Skip to content

Commit e90ad79

Browse files
committed
Refactor.
1 parent c935985 commit e90ad79

File tree

1 file changed

+15
-19
lines changed

1 file changed

+15
-19
lines changed

Diff for: src/file_context.rs

+15-19
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use crate::{Error, SourceFile, SourceName, SourcePos};
2+
use std::borrow::Cow;
23
use std::path::{Path, PathBuf};
34

45
/// A file context manages finding and loading files.
@@ -55,15 +56,8 @@ pub trait FileContext: Sized + std::fmt::Debug {
5556
];
5657
// Note: Should a "full stack" of bases be used here?
5758
// Or is this fine?
58-
let base = from.file_url();
59-
if let Some((path, mut file)) = base
60-
.rfind('/')
61-
.map(|p| base.split_at(p + 1).0)
62-
.map(|base| {
63-
do_find_file(self, &format!("{}{}", base, url), names)
64-
})
65-
.unwrap_or_else(|| do_find_file(self, url, names))?
66-
{
59+
let url = relative(from.file_url(), url);
60+
if let Some((path, mut file)) = do_find_file(self, &url, names)? {
6761
let source = SourceName::imported(path, from);
6862
Ok(Some(SourceFile::read(&mut file, source)?))
6963
} else {
@@ -89,15 +83,8 @@ pub trait FileContext: Sized + std::fmt::Debug {
8983
];
9084
// Note: Should a "full stack" of bases be used here?
9185
// Or is this fine?
92-
let base = from.file_url();
93-
if let Some((path, mut file)) = base
94-
.rfind('/')
95-
.map(|p| base.split_at(p + 1).0)
96-
.map(|base| {
97-
do_find_file(self, &format!("{}{}", base, url), names)
98-
})
99-
.unwrap_or_else(|| do_find_file(self, url, names))?
100-
{
86+
let url = relative(from.file_url(), url);
87+
if let Some((path, mut file)) = do_find_file(self, &url, names)? {
10188
let source = SourceName::used(path, from);
10289
Ok(Some(SourceFile::read(&mut file, source)?))
10390
} else {
@@ -119,7 +106,16 @@ pub trait FileContext: Sized + std::fmt::Debug {
119106
) -> Result<Option<(String, Self::File)>, Error>;
120107
}
121108

122-
/// Find a file for `@use`
109+
/// Make a url relative to a given base.
110+
fn relative<'a>(base: &str, url: &'a str) -> Cow<'a, str> {
111+
base.rfind('/')
112+
.map(|p| base.split_at(p + 1).0)
113+
.map(|base| format!("{}{}", base, url).into())
114+
.unwrap_or_else(|| url.into())
115+
}
116+
117+
/// Find a file in a given filecontext matching a url over a set of
118+
/// name rules.
123119
fn do_find_file<FC: FileContext>(
124120
ctx: &FC,
125121
url: &str,

0 commit comments

Comments
 (0)