grass/src/parse/import.rs

102 lines
3.3 KiB
Rust
Raw Normal View History

use std::{ffi::OsStr, fs, path::Path};
2020-06-16 22:34:01 -04:00
use codemap::Spanned;
2020-06-16 22:34:01 -04:00
use peekmore::PeekMore;
use crate::{common::QuoteKind, error::SassResult, lexer::Lexer, value::Value, Token};
2020-06-16 22:34:01 -04:00
use super::{Parser, Stmt};
impl<'a> Parser<'a> {
pub(super) fn import(&mut self) -> SassResult<Vec<Stmt>> {
self.whitespace();
match self.toks.peek() {
Some(Token { kind: '\'', .. })
| Some(Token { kind: '"', .. })
| Some(Token { kind: 'u', .. }) => {}
Some(Token { pos, .. }) => return Err(("Expected string.", *pos).into()),
2020-07-06 12:55:34 -04:00
None => return Err(("expected more input.", self.span_before).into()),
2020-06-16 22:34:01 -04:00
};
let Spanned {
node: file_name_as_value,
span,
} = self.parse_value()?;
let file_name = match file_name_as_value {
Value::String(s, QuoteKind::Quoted) => {
if s.ends_with(".css") || s.starts_with("http://") || s.starts_with("https://") {
return Ok(vec![Stmt::Import(format!("\"{}\"", s))]);
} else {
s
}
2020-06-16 22:34:01 -04:00
}
Value::String(s, QuoteKind::None) => {
if s.starts_with("url(") {
return Ok(vec![Stmt::Import(s)]);
} else {
s
}
2020-06-16 22:34:01 -04:00
}
_ => return Err(("Expected string.", span).into()),
};
2020-06-16 22:34:01 -04:00
self.whitespace();
let path: &Path = file_name.as_ref();
let path_buf = if path.is_absolute() {
// todo: test for absolute path imports
path.into()
} else {
self.path
.parent()
.unwrap_or_else(|| Path::new(""))
.join(path)
};
let name = path_buf.file_name().unwrap_or_else(|| OsStr::new(".."));
2020-06-16 22:34:01 -04:00
let paths = [
path_buf.with_file_name(name).with_extension("scss"),
2020-06-22 11:08:28 -04:00
path_buf
.with_file_name(format!("_{}", name.to_str().unwrap()))
.with_extension("scss"),
path_buf.clone(),
path_buf.join("index.scss"),
path_buf.join("_index.scss"),
2020-06-16 22:34:01 -04:00
];
2020-06-16 22:34:01 -04:00
for name in &paths {
if name.is_file() {
let file = self.map.add_file(
name.to_string_lossy().into(),
String::from_utf8(fs::read(name)?)?,
);
return Parser {
2020-06-16 22:34:01 -04:00
toks: &mut Lexer::new(&file)
.collect::<Vec<Token>>()
.into_iter()
.peekmore(),
2020-06-22 03:19:16 -04:00
map: self.map,
2020-06-16 22:34:01 -04:00
path: name.as_ref(),
2020-06-22 03:19:16 -04:00
scopes: self.scopes,
global_scope: self.global_scope,
2020-06-16 22:34:01 -04:00
super_selectors: self.super_selectors,
span_before: file.span.subspan(0, 0),
2020-06-26 01:02:06 -04:00
content: self.content,
2020-07-05 19:16:44 +08:00
flags: self.flags,
2020-06-16 22:34:01 -04:00
at_root: self.at_root,
at_root_has_selector: self.at_root_has_selector,
2020-06-18 16:56:03 -04:00
extender: self.extender,
2020-07-08 17:52:37 -04:00
content_scopes: self.content_scopes,
2020-06-16 22:34:01 -04:00
}
.parse();
2020-06-16 22:34:01 -04:00
}
}
Err(("Can't find stylesheet to import.", span).into())
2020-06-16 22:34:01 -04:00
}
}