Skip to content

Commit 372e3e4

Browse files
structwafelpaolobarbolini
authored andcommitted
refactor!: replace ignore_dirs with ignore_paths
1 parent c505c6b commit 372e3e4

File tree

4 files changed

+44
-120
lines changed

4 files changed

+44
-120
lines changed

README.md

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,9 +50,7 @@ This will:
5050

5151
- `compress = false` - compress static files with zstd and gzip, true or false (defaults to false)
5252

53-
- `ignore_dirs = ["my_ignore_dir", "other_ignore_dir"]` - a bracketed list of `&str`s of the paths/subdirectories inside the target directory, which should be ignored and not included. (If this parameter is missing, no subdirectories will be ignored)
54-
55-
- `ignore_files = ["my_ignore_file.txt", "other_ignore_file.js"]` - a bracketed list of `&str`s of the specific files inside the target directory, which should be ignored and not included. (If this parameter is missing, no files will be ignored)
53+
- `ignore_paths = ["my_ignore_dir", "other_ignore_dir", "my_ignore_file.txt"]` - a bracketed list of `&str`s of paths/subdirectories/files inside the target directory, which should be ignored and not included. (If this parameter is missing, no paths/subdirectories/files will be ignored)
5654

5755
- `strip_html_ext = false` - strips the `.html` or `.htm` from all HTML files included. If the filename is `index.html` or `index.htm`, the `index` part will also be removed, leaving just the root (defaults to false)
5856

static-serve-macro/src/error.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,8 @@ pub(crate) enum Error {
2121
FilePathIsNotUtf8,
2222
#[error("Invalid unicode in directory name")]
2323
InvalidUnicodeInDirectoryName,
24-
#[error("Cannot canonicalize ignore directory")]
25-
CannotCanonicalizeIgnoreDir(#[source] io::Error),
24+
#[error("Cannot canonicalize ignore path")]
25+
CannotCanonicalizeIgnorePath(#[source] io::Error),
2626
#[error("Invalid unicode in directory name")]
2727
InvalidUnicodeInEntryName,
2828
#[error("Error while compressing with gzip")]

static-serve-macro/src/lib.rs

Lines changed: 32 additions & 106 deletions
Original file line numberDiff line numberDiff line change
@@ -155,8 +155,7 @@ impl ToTokens for EmbedAsset {
155155

156156
struct EmbedAssets {
157157
assets_dir: AssetsDir,
158-
validated_ignore_dirs: IgnoreDirs,
159-
validated_ignore_files: IgnoreFiles,
158+
validated_ignore_paths: IgnorePaths,
160159
should_compress: ShouldCompress,
161160
should_strip_html_ext: ShouldStripHtmlExt,
162161
cache_busted_paths: CacheBustedPaths,
@@ -168,8 +167,7 @@ impl Parse for EmbedAssets {
168167

169168
// Default to no compression
170169
let mut maybe_should_compress = None;
171-
let mut maybe_ignore_dirs = None;
172-
let mut maybe_ignore_files = None;
170+
let mut maybe_ignore_paths = None;
173171
let mut maybe_should_strip_html_ext = None;
174172
let mut maybe_cache_busted_paths = None;
175173

@@ -183,13 +181,9 @@ impl Parse for EmbedAssets {
183181
let value = input.parse()?;
184182
maybe_should_compress = Some(value);
185183
}
186-
"ignore_dirs" => {
184+
"ignore_paths" => {
187185
let value = input.parse()?;
188-
maybe_ignore_dirs = Some(value);
189-
}
190-
"ignore_files" => {
191-
let value = input.parse()?;
192-
maybe_ignore_files = Some(value);
186+
maybe_ignore_paths = Some(value);
193187
}
194188
"strip_html_ext" => {
195189
let value = input.parse()?;
@@ -202,7 +196,7 @@ impl Parse for EmbedAssets {
202196
_ => {
203197
return Err(syn::Error::new(
204198
key.span(),
205-
"Unknown key in embed_assets! macro. Expected `compress`, `ignore_dirs`, `ignore_files`, `strip_html_ext`, or `cache_busted_paths`",
199+
"Unknown key in embed_assets! macro. Expected `compress`, `ignore_paths`, `strip_html_ext`, or `cache_busted_paths`",
206200
));
207201
}
208202
}
@@ -222,11 +216,8 @@ impl Parse for EmbedAssets {
222216
})
223217
});
224218

225-
let ignore_dirs_with_span = maybe_ignore_dirs.unwrap_or(IgnoreDirsWithSpan(vec![]));
226-
let validated_ignore_dirs = validate_ignore_dirs(ignore_dirs_with_span, &assets_dir.0)?;
227-
228-
let ignore_files_with_span = maybe_ignore_files.unwrap_or(IgnoreFilesWithSpan(vec![]));
229-
let validated_ignore_files = validate_ignore_files(ignore_files_with_span, &assets_dir.0)?;
219+
let ignore_paths_with_span = maybe_ignore_paths.unwrap_or(IgnorePathsWithSpan(vec![]));
220+
let validated_ignore_paths = validate_ignore_paths(ignore_paths_with_span, &assets_dir.0)?;
230221

231222
let maybe_cache_busted_paths =
232223
maybe_cache_busted_paths.unwrap_or(CacheBustedPathsWithSpan(vec![]));
@@ -235,8 +226,7 @@ impl Parse for EmbedAssets {
235226

236227
Ok(Self {
237228
assets_dir,
238-
validated_ignore_dirs,
239-
validated_ignore_files,
229+
validated_ignore_paths,
240230
should_compress,
241231
should_strip_html_ext,
242232
cache_busted_paths,
@@ -247,16 +237,14 @@ impl Parse for EmbedAssets {
247237
impl ToTokens for EmbedAssets {
248238
fn to_tokens(&self, tokens: &mut TokenStream) {
249239
let AssetsDir(assets_dir) = &self.assets_dir;
250-
let ignore_dirs = &self.validated_ignore_dirs;
251-
let ignore_files = &self.validated_ignore_files;
240+
let ignore_paths = &self.validated_ignore_paths;
252241
let ShouldCompress(should_compress) = &self.should_compress;
253242
let ShouldStripHtmlExt(should_strip_html_ext) = &self.should_strip_html_ext;
254243
let cache_busted_paths = &self.cache_busted_paths;
255244

256245
let result = generate_static_routes(
257246
assets_dir,
258-
ignore_dirs,
259-
ignore_files,
247+
ignore_paths,
260248
should_compress,
261249
should_strip_html_ext,
262250
cache_busted_paths,
@@ -314,100 +302,46 @@ impl Parse for AssetsDir {
314302
}
315303
}
316304

317-
struct IgnoreDirs(Vec<PathBuf>);
305+
struct IgnorePaths(Vec<PathBuf>);
318306

319-
struct IgnoreDirsWithSpan(Vec<(PathBuf, Span)>);
307+
struct IgnorePathsWithSpan(Vec<(PathBuf, Span)>);
320308

321-
struct IgnoreFiles(Vec<PathBuf>);
322-
323-
struct IgnoreFilesWithSpan(Vec<(PathBuf, Span)>);
324-
325-
impl Parse for IgnoreDirsWithSpan {
309+
impl Parse for IgnorePathsWithSpan {
326310
fn parse(input: ParseStream) -> syn::Result<Self> {
327311
let dirs = parse_dirs(input)?;
328312

329-
Ok(IgnoreDirsWithSpan(dirs))
330-
}
331-
}
332-
333-
impl Parse for IgnoreFilesWithSpan {
334-
fn parse(input: ParseStream) -> syn::Result<Self> {
335-
let files = parse_dirs(input)?; // reuse parse_dirs since it's just parsing paths
336-
337-
Ok(IgnoreFilesWithSpan(files))
313+
Ok(IgnorePathsWithSpan(dirs))
338314
}
339315
}
340316

341-
fn validate_ignore_dirs(
342-
ignore_dirs: IgnoreDirsWithSpan,
317+
fn validate_ignore_paths(
318+
ignore_paths: IgnorePathsWithSpan,
343319
assets_dir: &LitStr,
344-
) -> syn::Result<IgnoreDirs> {
345-
let mut valid_ignore_dirs = Vec::new();
346-
for (dir, span) in ignore_dirs.0 {
320+
) -> syn::Result<IgnorePaths> {
321+
let mut valid_ignore_paths = Vec::new();
322+
for (dir, span) in ignore_paths.0 {
347323
let full_path = PathBuf::from(assets_dir.value()).join(&dir);
348324
match fs::metadata(&full_path) {
349-
Ok(meta) if !meta.is_dir() => {
350-
return Err(syn::Error::new(
351-
span,
352-
"The specified ignored directory is not a directory",
353-
));
354-
}
355-
Ok(_) => valid_ignore_dirs.push(full_path),
325+
Ok(_) => valid_ignore_paths.push(full_path),
356326
Err(e) if matches!(e.kind(), std::io::ErrorKind::NotFound) => {
357327
return Err(syn::Error::new(
358328
span,
359-
"The specified ignored directory does not exist",
329+
"The specified ignored path does not exist",
360330
))
361331
}
362332
Err(e) => {
363333
return Err(syn::Error::new(
364334
span,
365335
format!(
366-
"Error reading ignored directory {}: {}",
336+
"Error reading ignored path {}: {}",
367337
dir.to_string_lossy(),
368338
DisplayFullError(&e)
369339
),
370340
))
371341
}
372342
}
373343
}
374-
Ok(IgnoreDirs(valid_ignore_dirs))
375-
}
376-
377-
fn validate_ignore_files(
378-
ignore_files: IgnoreFilesWithSpan,
379-
assets_dir: &LitStr,
380-
) -> syn::Result<IgnoreFiles> {
381-
let mut valid_ignore_files = Vec::new();
382-
for (file, span) in ignore_files.0 {
383-
let full_path = PathBuf::from(assets_dir.value()).join(&file);
384-
match fs::metadata(&full_path) {
385-
Ok(meta) if meta.is_dir() => {
386-
return Err(syn::Error::new(
387-
span,
388-
"The specified ignored file is a directory. Use ignore_dirs instead.",
389-
));
390-
}
391-
Ok(_) => valid_ignore_files.push(full_path),
392-
Err(e) if matches!(e.kind(), std::io::ErrorKind::NotFound) => {
393-
return Err(syn::Error::new(
394-
span,
395-
"The specified ignored file does not exist",
396-
))
397-
}
398-
Err(e) => {
399-
return Err(syn::Error::new(
400-
span,
401-
format!(
402-
"Error reading ignored file {}: {}",
403-
file.to_string_lossy(),
404-
DisplayFullError(&e)
405-
),
406-
))
407-
}
408-
}
409-
}
410-
Ok(IgnoreFiles(valid_ignore_files))
344+
Ok(IgnorePaths(valid_ignore_paths))
411345
}
412346

413347
struct ShouldCompress(LitBool);
@@ -512,8 +446,7 @@ fn parse_dirs(input: ParseStream) -> syn::Result<Vec<(PathBuf, Span)>> {
512446

513447
fn generate_static_routes(
514448
assets_dir: &LitStr,
515-
ignore_dirs: &IgnoreDirs,
516-
ignore_files: &IgnoreFiles,
449+
ignore_paths: &IgnorePaths,
517450
should_compress: &LitBool,
518451
should_strip_html_ext: &LitBool,
519452
cache_busted_paths: &CacheBustedPaths,
@@ -524,15 +457,13 @@ fn generate_static_routes(
524457
let assets_dir_abs_str = assets_dir_abs
525458
.to_str()
526459
.ok_or(Error::InvalidUnicodeInDirectoryName)?;
527-
let canon_ignore_dirs = ignore_dirs
528-
.0
529-
.iter()
530-
.map(|d| d.canonicalize().map_err(Error::CannotCanonicalizeIgnoreDir))
531-
.collect::<Result<Vec<_>, _>>()?;
532-
let canon_ignore_files = ignore_files
460+
let canon_ignore_paths = ignore_paths
533461
.0
534462
.iter()
535-
.map(|f| f.canonicalize().map_err(Error::CannotCanonicalizeFile))
463+
.map(|d| {
464+
d.canonicalize()
465+
.map_err(Error::CannotCanonicalizeIgnorePath)
466+
})
536467
.collect::<Result<Vec<_>, _>>()?;
537468
let canon_cache_busted_dirs = cache_busted_paths
538469
.dirs
@@ -556,19 +487,14 @@ fn generate_static_routes(
556487
continue;
557488
}
558489

559-
// Skip `entry`s which are located in ignored subdirectories
560-
if canon_ignore_dirs
490+
// Skip `entry`s which are located in ignored paths
491+
if canon_ignore_paths
561492
.iter()
562-
.any(|ignore_dir| entry.starts_with(ignore_dir))
493+
.any(|ignore_path| entry.starts_with(ignore_path))
563494
{
564495
continue;
565496
}
566497

567-
// Skip `entry`s which are explicitly ignored files
568-
if canon_ignore_files.contains(&entry) {
569-
continue;
570-
}
571-
572498
let mut is_entry_cache_busted = false;
573499
if canon_cache_busted_dirs
574500
.iter()

static-serve/tests/tests.rs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -208,8 +208,8 @@ async fn router_created_compressed_zstd_or_gzip_accepted() {
208208
}
209209

210210
#[tokio::test]
211-
async fn router_created_ignore_dirs_one() {
212-
embed_assets!("../static-serve/test_assets", ignore_dirs = ["dist"]);
211+
async fn router_created_ignore_paths_one() {
212+
embed_assets!("../static-serve/test_assets", ignore_paths = ["dist"]);
213213
let router: Router<()> = static_router();
214214
assert!(router.has_routes());
215215

@@ -230,10 +230,10 @@ async fn router_created_ignore_dirs_one() {
230230
}
231231

232232
#[tokio::test]
233-
async fn router_created_ignore_dirs_three() {
233+
async fn router_created_ignore_paths_three() {
234234
embed_assets!(
235235
"../static-serve/test_assets",
236-
ignore_dirs = ["big", "small", "dist", "with_html"]
236+
ignore_paths = ["big", "small", "dist", "with_html"]
237237
);
238238
let router: Router<()> = static_router();
239239
// all directories ignored, so router has no routes
@@ -1084,20 +1084,20 @@ async fn handles_dir_with_cache_control_on_filename_and_dir() {
10841084
async fn router_created_ignore_files() {
10851085
embed_assets!(
10861086
"../static-serve/test_assets/small",
1087-
ignore_files = ["app.js"]
1087+
ignore_paths = ["app.js"]
10881088
);
10891089
let router: Router<()> = static_router();
10901090

10911091
// app.js should be ignored, but styles.css should be available
10921092
assert!(router.has_routes());
10931093

1094-
// Request for app.js should succeed
1094+
// Request for styles.css should succeed
10951095
let request = create_request("/styles.css", &Compression::None);
10961096
let response = get_response(router.clone(), request).await;
10971097
let (parts, _) = response.into_parts();
10981098
assert!(parts.status.is_success());
10991099

1100-
// Request for index.html should return 404 since it's ignored
1100+
// Request for app.js should return 404 since it's ignored
11011101
let request = create_request("/app.js", &Compression::None);
11021102
let response = get_response(router, request).await;
11031103
let (parts, _) = response.into_parts();
@@ -1108,11 +1108,11 @@ async fn router_created_ignore_files() {
11081108
async fn router_created_ignore_multiple_files() {
11091109
embed_assets!(
11101110
"../static-serve/test_assets/big",
1111-
ignore_files = ["app.js", "styles.css"]
1111+
ignore_paths = ["app.js", "styles.css"]
11121112
);
11131113
let router: Router<()> = static_router();
11141114

1115-
// All files in /big should be ignored, but files in /big/immutable should still be available
1115+
// app.js and styles.css at root should be ignored, but files in /big/immutable should still be available
11161116
assert!(router.has_routes());
11171117

11181118
// Request for ignored files should return 404

0 commit comments

Comments
 (0)