Skip to content

Commit 94be6d2

Browse files
committed
refactor: find_file() - Switch conditional order
Shift the file exist check to come after the `format_hint` check. This change better co-locates the two distinct format types instead of interleaving them. Better to diverge initially based on the format type than if a file exists. - This adds slight complexity to the `format_hint.filter()` and regresses the simplicity of the happy path when both conditionals are true. - It is now however more easy to reason with the two distinct format types in mind; allowing to unify on return types (_which was previously a point of friction_), additionally reducing the four `Ok()` down to two.
1 parent b3aaae6 commit 94be6d2

File tree

1 file changed

+13
-18
lines changed

1 file changed

+13
-18
lines changed

src/file/source/file.rs

Lines changed: 13 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -37,37 +37,32 @@ impl FileSourceFile {
3737
// Ideally there is an exact filename match with a format hint, otherwise:
3838
// - Without a hint => Try to identify the format via the file extension
3939
// - Without an exact filename => Try to find a valid file by appending format extensions
40-
if filename.is_file() {
41-
return if let Some(format) = format_hint {
42-
Ok((filename, Box::new(format)))
43-
} else {
44-
let valid_format = {
45-
all_extensions().keys().cloned()
46-
.find(identify_format(&filename))
47-
.ok_or_else(|| self.error_invalid_format())?
48-
};
49-
50-
Ok((filename, Box::new(*valid_format)))
51-
};
52-
}
53-
5440
match format_hint {
5541
Some(_) => {
5642
let valid_format = format_hint
57-
.filter(file_exists_with_format(&mut filename))
43+
.filter(|format| {
44+
filename.is_file() || file_exists_with_format(&mut filename)(format)
45+
})
5846
.ok_or_else(|| self.error_invalid_path())?;
5947

6048
Ok((filename, Box::new(valid_format)))
6149
}
6250

51+
// Fallback to checking compatibility with internally supported formats (`FileFormat` enum):
6352
None => {
64-
let valid_format = {
65-
all_extensions().keys().cloned()
53+
let mut internal_formats = all_extensions().keys().cloned();
54+
55+
let valid_format = if filename.is_file() {
56+
internal_formats
57+
.find(identify_format(&filename))
58+
.ok_or_else(|| self.error_invalid_format())?
59+
} else {
60+
internal_formats
6661
.find(file_exists_with_format(&mut filename))
6762
.ok_or_else(|| self.error_invalid_path())?
6863
};
6964

70-
Ok((filename, Box::new(*valid_format)))
65+
Ok((filename, Box::new(valid_format)))
7166
}
7267
}
7368
}

0 commit comments

Comments
 (0)