Skip to content

fix(serve): Work with custom config #1179

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Apr 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions crates/config/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,9 @@ impl Config {

let mut root = path;
root.pop(); // Remove filename
if root == std::path::Path::new("") {
root = std::path::Path::new(".").to_owned();
}
config.root = root;

Ok(config)
Expand Down
6 changes: 2 additions & 4 deletions src/bin/cobalt/args.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use std::env;
use std::io::Write;
use std::path;

Expand Down Expand Up @@ -32,11 +31,10 @@ impl ConfigArgs {
// Fetch config information if available
let mut config = if let Some(config_path) = config_path {
cobalt_config::Config::from_file(config_path).with_context(|| {
anyhow::format_err!("Error reading config file {:?}", config_path)
anyhow::format_err!("Error reading config file {}", config_path.display())
})?
} else {
let cwd = env::current_dir().unwrap_or_default();
cobalt_config::Config::from_cwd(cwd)?
cobalt_config::Config::from_cwd(".")?
};

config.abs_dest = self
Expand Down
13 changes: 6 additions & 7 deletions src/bin/cobalt/new.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use std::collections;
use std::env;
use std::fs;
use std::io::Write;
use std::path;
Expand Down Expand Up @@ -58,7 +57,7 @@ impl NewArgs {

let title = self.title.as_deref();

let mut file = env::current_dir().unwrap_or_default();
let mut file = path::Path::new(".").to_owned();
if let Some(rel_file) = self.file.as_deref() {
file.push(rel_file)
}
Expand Down Expand Up @@ -100,7 +99,7 @@ impl RenameArgs {

let title = self.title.as_ref();

let mut file = env::current_dir().unwrap_or_default();
let mut file = path::Path::new(".").to_owned();
if let Some(rel_file) = self.file.as_deref() {
file.push(rel_file)
}
Expand Down Expand Up @@ -130,7 +129,7 @@ impl PublishArgs {
let config = cobalt::cobalt_model::Config::from_config(config)?;

let filename = self.filename.as_path();
let mut file = env::current_dir().unwrap_or_default();
let mut file = path::Path::new(".").to_owned();
file.push(path::Path::new(filename));

publish_document(&config, &file)
Expand Down Expand Up @@ -248,7 +247,7 @@ pub fn create_new_document(
let interim_path = cobalt_core::SourcePath::from_root(&config.source, &interim_path)
.ok_or_else(|| {
anyhow::format_err!(
"New file {} not project directory ({})",
"New file {} not in project in directory ({})",
file.display(),
config.source.display()
)
Expand Down Expand Up @@ -369,7 +368,7 @@ pub fn rename_document(

let target = cobalt_core::SourcePath::from_root(&config.source, &target).ok_or_else(|| {
anyhow::format_err!(
"New file {} not project directory ({})",
"New file {} not in project directory ({})",
target.display(),
config.source.display()
)
Expand Down Expand Up @@ -484,7 +483,7 @@ pub fn publish_document(config: &cobalt_model::Config, file: &path::Path) -> Res
let file = move_from_drafts_to_posts(config, file)?;
let file = cobalt_core::SourcePath::from_root(&config.source, &file).ok_or_else(|| {
anyhow::format_err!(
"New file {} not project directory ({})",
"New file {} not in project directory ({})",
file.display(),
config.source.display()
)
Expand Down
17 changes: 11 additions & 6 deletions src/bin/cobalt/serve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ impl ServeArgs {

dest.close()?;
} else {
info!("Watching {:?} for changes", &config.source);
info!("Watching {} for changes", &config.source.display());
thread::spawn(move || {
let e = serve(&server);
if let Some(e) = e.err() {
Expand Down Expand Up @@ -105,22 +105,27 @@ fn open_browser(url: String) -> Result<()> {
fn watch(config: &cobalt_model::Config) -> Result<()> {
// canonicalize is to ensure there is no question that `watcher`s paths come back safe for
// Files::includes_file
let source = dunce::canonicalize(path::Path::new(&config.source))
.with_context(|| anyhow::format_err!("Failed in processing source"))?;
let source = dunce::canonicalize(path::Path::new(&config.source)).with_context(|| {
anyhow::format_err!("Failed in processing source `{}`", config.source.display())
})?;

// Also canonicalize the destination folder. In particular for Windows, notify-rs
// generates the absolute path by prepending the above source path.
// On Windows canonicalize() adds a \\?\ to the start of the path.
let destination = dunce::canonicalize(&config.destination)
.with_context(|| anyhow::format_err!("Failed to canonicalize destination folder"))?;
let destination = dunce::canonicalize(&config.destination).with_context(|| {
anyhow::format_err!(
"Failed to canonicalize destination folder `{}`",
config.destination.display()
)
})?;

let (tx, rx) = channel();
let mut watcher =
notify::recommended_watcher(tx).with_context(|| anyhow::format_err!("Notify error"))?;
watcher
.watch(&source, notify::RecursiveMode::Recursive)
.with_context(|| anyhow::format_err!("Notify error"))?;
info!("Watching {:?} for changes", &config.source);
info!("Watching {} for changes", config.source.display());

for event in rx {
let event = event.with_context(|| anyhow::format_err!("Notify error"))?;
Expand Down
12 changes: 8 additions & 4 deletions src/cobalt_model/files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,11 @@ impl FilesBuilder {
}

pub fn add_ignore(&mut self, line: &str) -> Result<&mut Self> {
trace!("{:?}: adding '{}' ignore pattern", self.root_dir, line);
trace!(
"{}: adding '{}' ignore pattern",
self.root_dir.display(),
line
);
self.ignore.push(line.to_owned());
Ok(self)
}
Expand All @@ -55,7 +59,7 @@ impl FilesBuilder {
}

pub fn add_extension(&mut self, ext: &str) -> Result<&mut FilesBuilder> {
trace!("{:?}: adding '{}' extension", self.root_dir, ext);
trace!("{}: adding '{}' extension", self.root_dir.display(), ext);
self.extensions.push(ext.into());
Ok(self)
}
Expand Down Expand Up @@ -211,11 +215,11 @@ impl Files {
match self.ignore.matched(path, is_dir) {
Match::None => true,
Match::Ignore(glob) => {
trace!("{:?}: ignored {:?}", path, glob.original());
trace!("{}: ignored {:?}", path.display(), glob.original());
false
}
Match::Whitelist(glob) => {
trace!("{:?}: allowed {:?}", path, glob.original());
trace!("{}: allowed {:?}", path.display(), glob.original());
true
}
}
Expand Down
16 changes: 8 additions & 8 deletions src/cobalt_model/site.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,8 @@ fn deep_insert(
for part in path.iter() {
let key = part.to_str().ok_or_else(|| {
anyhow::format_err!(
"The data from {:?} can't be loaded as it contains non utf-8 characters",
path
"The data from `{}` can't be loaded as it contains non utf-8 characters",
path.display()
)
})?;
let cur_map = map;
Expand All @@ -116,8 +116,8 @@ fn deep_insert(
.as_object_mut()
.ok_or_else(|| {
anyhow::format_err!(
"Aborting: Duplicate in data tree. Would overwrite {:?} ",
path
"Aborting: Duplicate in data tree. Would overwrite {} ",
path.display()
)
})?;
}
Expand All @@ -129,8 +129,8 @@ fn deep_insert(
match target_map.insert(target_key.into(), data) {
None => Ok(()),
_ => Err(anyhow::format_err!(
"The data from {:?} can't be loaded: the key already exists",
file_path
"The data from {} can't be loaded: the key already exists",
file_path.display()
)),
}
}
Expand All @@ -151,9 +151,9 @@ fn load_data(data_path: &path::Path) -> Result<liquid::model::Value> {
data = toml::from_str(&text)?;
} else {
anyhow::bail!(
"Failed to load of data {:?}: unknown file type '{:?}'.\n\
"Failed to load of data `{}`: unknown file type '{:?}'.\n\
Supported data files extensions are: yml, yaml, json and toml.",
data_path,
data_path.display(),
ext
);
}
Expand Down
6 changes: 3 additions & 3 deletions src/document.rs
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ impl Document {
rel_path: &relative_path::RelativePath,
default_front: cobalt_config::Frontmatter,
) -> Result<Document> {
trace!("Parsing {:?}", rel_path);
trace!("Parsing `{}`", rel_path);
let content = files::read_file(src_path)?;
let builder = cobalt_config::Document::parse(&content)?;
let (front, content) = builder.into_parts();
Expand Down Expand Up @@ -379,10 +379,10 @@ impl Document {
let template = context
.parser
.parse(layout_data_ref)
.with_context(|| anyhow::format_err!("Failed to parse layout {:?}", layout))?;
.with_context(|| anyhow::format_err!("Failed to parse layout `{}`", layout))?;
let content_html = template
.render(context.globals)
.with_context(|| anyhow::format_err!("Failed to render layout {:?}", layout))?;
.with_context(|| anyhow::format_err!("Failed to render layout `{}`", layout))?;
let content_html = minify_if_enabled(content_html, context, &self.file_path)?;
Ok(content_html)
} else {
Expand Down
2 changes: 1 addition & 1 deletion tests/cmd/clean.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ Clean no-op
```console
$ cobalt -v clean
WARN: No _cobalt.yml file found in current directory, using default config.
DEBUG: No `[CWD]/_site` to clean
DEBUG: No `./_site` to clean
DEBUG: [..]

```
Expand Down
14 changes: 7 additions & 7 deletions tests/cmd/copy_files.md
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
```console
$ cobalt -v build --destination _dest
DEBUG: Using config file `[CWD]/_cobalt.yml`
Building from `[CWD]` into `[CWD]/_dest`
DEBUG: Using config file `./_cobalt.yml`
Building from `.` into `[CWD]/_dest`
DEBUG: glob converted to regex: Glob { glob: "**/.*", re: "(?-u)^(?:/?|.*/)//.[^/]*$", opts: GlobOptions { case_insensitive: false, literal_separator: true, backslash_escape: true }, tokens: Tokens([RecursivePrefix, Literal('.'), ZeroOrMore]) }
DEBUG: glob converted to regex: Glob { glob: "**/_*", re: "(?-u)^(?:/?|.*/)_[^/]*$", opts: GlobOptions { case_insensitive: false, literal_separator: true, backslash_escape: true }, tokens: Tokens([RecursivePrefix, Literal('_'), ZeroOrMore]) }
DEBUG: built glob set; 6 literals, 0 basenames, 0 extensions, 0 prefixes, 0 suffixes, 0 required extensions, 2 regexes
DEBUG: Loading data from `[CWD]/_data`
DEBUG: built glob set; 5 literals, 0 basenames, 0 extensions, 0 prefixes, 0 suffixes, 0 required extensions, 2 regexes
DEBUG: Loading data from `./_data`
DEBUG: glob converted to regex: Glob { glob: "**/.*", re: "(?-u)^(?:/?|.*/)//.[^/]*$", opts: GlobOptions { case_insensitive: false, literal_separator: true, backslash_escape: true }, tokens: Tokens([RecursivePrefix, Literal('.'), ZeroOrMore]) }
DEBUG: glob converted to regex: Glob { glob: "**/_*", re: "(?-u)^(?:/?|.*/)_[^/]*$", opts: GlobOptions { case_insensitive: false, literal_separator: true, backslash_escape: true }, tokens: Tokens([RecursivePrefix, Literal('_'), ZeroOrMore]) }
DEBUG: built glob set; 0 literals, 0 basenames, 0 extensions, 0 prefixes, 0 suffixes, 0 required extensions, 2 regexes
DEBUG: Loading snippets from `[CWD]/_includes`
DEBUG: Copying `[CWD]/some.js` to `[CWD]/_dest/some.js`
DEBUG: Copying `[CWD]/style/blog.css` to `[CWD]/_dest/style/blog.css`
DEBUG: Loading snippets from `./_includes`
DEBUG: Copying `./some.js` to `[CWD]/_dest/some.js`
DEBUG: Copying `./style/blog.css` to `[CWD]/_dest/style/blog.css`
Build successful

```
2 changes: 2 additions & 0 deletions tests/cmd/custom_config.in/_cobalt_testing.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
syntax_highlight:
enabled: false
12 changes: 12 additions & 0 deletions tests/cmd/custom_config.in/_layouts/default.liquid
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<h1>{{ page.permalink }}</h1>

{{ page.content }}
</body>
</html>

10 changes: 10 additions & 0 deletions tests/cmd/custom_config.in/_layouts/posts.liquid
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<!DOCTYPE html>
<html>
<head>
<title>My blog - {{ page.permalink }}</title>
</head>
<body>
{{ page.content }}
</body>
</html>

8 changes: 8 additions & 0 deletions tests/cmd/custom_config.in/index.liquid
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
layout: default.liquid
---
This is my Index page!

{% for post in collections.posts.pages %}
<a href="{{post.permalink}}">{{ post.title }}</a>
{% endfor %}
10 changes: 10 additions & 0 deletions tests/cmd/custom_config.in/no-post.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
layout: posts.liquid

title: Custom paths are available to non-posts
published_date: 2014-08-22 15:36:20 +0100
permalink: /test/hello.html
---
# {{ page.title }}

This asserts that you can specify custom file paths
10 changes: 10 additions & 0 deletions tests/cmd/custom_config.in/posts/all_date_variables.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
layout: posts.liquid

title: All date variables
published_date: 2015-05-03 01:05:20 +0100
permalink: /{{year}}/{{month}}/{{i_month}}/{{day}}/{{i_day}}/{{hour}}/{{minute}}/{{second}}/
---
# {{ page.title }}

This checks that all date variables are interpolated correctly into the path.
10 changes: 10 additions & 0 deletions tests/cmd/custom_config.in/posts/custom-leading-slash.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
layout: posts.liquid

title: Custom paths with leading slash
published_date: 2015-05-03 02:05:20 +0100
permalink: /test/thing2.html
---
# {{ page.title }}

This asserts that you can specify custom file paths with a leading slash and it doesn't make a difference.
10 changes: 10 additions & 0 deletions tests/cmd/custom_config.in/posts/custom.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
layout: posts.liquid

title: Custom paths
published_date: 2015-05-03 03:05:20 +0100
permalink: /test/thing.html
---
# {{ page.title }}

This asserts that you can specify custom file paths
12 changes: 12 additions & 0 deletions tests/cmd/custom_config.in/posts/date_variables.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
layout: posts.liquid

title: Date variables
published_date: 2015-05-03 04:05:20 +0100
permalink: /{{year}}/{{data.thing}}/
data:
thing: hello
---
# {{ page.title }}

This asserts interpolation of date variables and other variables.
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
layout: posts.liquid

title: Boom without trailing slash
published_date: 2015-05-03 05:05:20 +0100
permalink: /test/thing4
---
# {{ page.title }}

This asserts that custom paths without a file extension get made into a folder with an index.html file, even when the user did not specify a trailing slash.
10 changes: 10 additions & 0 deletions tests/cmd/custom_config.in/posts/explodes-urls.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
layout: posts.liquid

title: Boom
published_date: 2015-05-03 06:05:20 +0100
permalink: /test/thing3/
---
# {{ page.title }}

This asserts that custom paths without a file extension get made into a folder with an index.html file.
9 changes: 9 additions & 0 deletions tests/cmd/custom_config.in/posts/no-path.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
layout: posts.liquid

title: Custom paths
published_date: 2015-05-03 07:05:20 +0100
---
# {{ page.title }}

This asserts that you can have normal and custom file paths side by side.
Loading
Loading