Skip to content
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
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,14 @@ seam --sexp <<< '(hello (%define subject world) %subject)'
#stdout:
# (hello world)
```
To run a file only for what its macros do, such as writing files with
`%write`, use `seam run`, which reports each action like `make` does:
```sh
seam run build.sex
#stdout:
# write public/index.html
# ...
```

## Checklist
- [x] Literate mode for parser+lexer, where string nodes are not escaped and parentheses are converted to symbols.
Expand All @@ -106,6 +114,8 @@ seam --sexp <<< '(hello (%define subject world) %subject)'
- [x] Shell-style `${var:...}` string manipulation, written `%{var:...}`.
- [x] `%while`, `%take`, `%drop`, `%split` on symbols in lists, `%intercalate`.
- [x] `(%basename :suffix "txt" /path/file.txt)` (-> `file`), `(%dirname /path/file.txt)` (-> `/path`) and `(%extension /path/file.txt)` (-> `txt`), macros for paths.
- [x] `%path/...` macros: `cwd`, `this`, `here`, `join`, `split`, `stem`, `with-extension`, `normalise`, `canonical`, `absolute`, `relative`, `exists`, `is-file` and `is-directory`.
- [x] `seam run file.sex`, running a file for its side effects (`%write`, `%exec`), reported on STDOUT like `make`.
- [x] Math operators: `+`, `-`, `*`, `/`, `mod`, `pow`, `exp`, `sqrt`, `ln`, `log2`, `log10`, `hypot` (`%log` already logs),
along with comparisons, `%if`, `%and`, `%or`, `%not` and `%range`.
- [x] User `(%error msg)` macro for aborting compilation.
Expand Down
57 changes: 51 additions & 6 deletions USAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,24 @@ Literate mode is enabled with:
Elements produced by macros within Markdown are written as HTML.
Frontmatter and content are expanded separately, so `:only frontmatter`
or `:only content` expands just that part, and the content can use the
frontmatter's definitions.
frontmatter's definitions. Macro calls inside code (blocks and spans) are
shown as written, not expanded.

### Running build scripts

`seam run file.sex` expands a file only for what its macros *do*, such as
writing files with `%write` or running programs with `%exec`, and discards
the document it would otherwise generate. Like `make`, it reports each action
on STDOUT as it happens, and `%log` prints there too:
```sh
seam run build.sex
#stdout:
# write public/index.html
# write public/posts/hello-world.html
# exec git rev-parse --short HEAD
# log Built 3 posts.
```
No target format is given, and the other options (`-I`, `--literate`) work as usual.

## Macros

Expand All @@ -106,18 +123,22 @@ will be treated as macros.
- `%ifdef` checks if a symbol is defined, e.g. `(ifdef username (span Hello %username))`,
or with an else-clause: `(ifdef title (title My Blog - %title) (title My Blog))`.
- `%include` will include an entire file's contents into another, e.g.
`(%include "components/footer.sex")`.
`(%include "components/footer.sex")`. Paths are looked up relative to the
including file first, then in each include directory (`-I`, and the
working directory). `%embed` finds files the same way.
- `%date` standard `strftime` function, works of current system time, e.g.
`(span :id timestamp Uploaded on (%date "%Y-%m-%d"))`.
- `%log` will simply log any information to STDERR, e.g. `(%log Hello, World!)`.
- `%log` will simply log any information to STDERR (STDOUT under `seam run`),
e.g. `(%log Hello, World!)`.
- `%with` overrides top-level definitions for everything within it, e.g.
`(%with (:title "Pound Cake") (%layout))` (see [Scoping](#scoping)).
- `%let` binds patterns for its body, each seeing the ones before it, e.g.
`(%let ((n 2) ((a b) (x y))) %n %a %b)`.

#### Conditions and arithmetic
- `(%if condition then else)` expands only the chosen branch. Nothing, `()`,
`false` and `""` are false; anything else is true.
`false` (or `"false"`, as YAML and TOML booleans arrive) and `""` are false;
anything else is true.
- `%not`, `%and` and `%or`, where `%and` and `%or` stop expanding their
arguments as soon as the answer is known.
- Comparisons `%=`, `%!=`, `%<`, `%>`, `%<=` and `%>=` (numbers by value,
Expand All @@ -137,17 +158,37 @@ will be treated as macros.
- `(%split , "a,b")` gives `("a" "b")`; `(%split | (a b | c))` gives `((a b) (c))`.
- `(%intercalate ", " %tags)` puts the separator between the items (unwrapped).
- `(%length list)` counts items, or the characters of a string.
- `(%unique list)` drops repeated items; `(%contains item list)` tests membership.
- `(%items dict)`, `(%keys dict)` and `(%values dict)` for keyword lists:
`(%for (key value) in (%items (:a 1 :b 2)) ...)`.
- `%for` iterates over the items of the list its expression gives
(or over all the nodes it gives), e.g. `(%for post in %posts ...)`.

#### Paths, files and programs
- `(%basename :suffix md posts/hi.md)` → `hi`, `(%dirname posts/hi.md)` →
`posts`, `(%extension posts/hi.md)` → `md`.
`posts`, `(%extension posts/hi.md)` → `md` (also `%path/basename`,
`%path/dirname` and `%path/extension`).
- `(%path/cwd)` is the (absolute) directory seam is run from, and
`(%path/this)` is the absolute path of the file the call is written in, and
`(%path/here)` is its directory (the current directory, for
source read from STDIN). Relative paths given to `%glob`, `%write`, `%exec`
and the like are from the current directory, so
`(%path/join (%path/here) posts)` refers to `posts` next to the
file wherever seam is run from.
- `(%path/join a b/c d.txt)` → `a/b/c/d.txt`, and `(%path/split /a/b.md)` →
`("/" a b.md)`.
- `(%path/stem a/b.tar.gz)` → `b.tar`, `(%path/with-extension a/b.md html)` →
`a/b.html` (an empty extension removes it).
- `(%path/normalise a/./b/../c)` → `a/c`, without looking at the file system,
while `(%path/canonical path)` resolves links too, and the file must exist.
- `(%path/absolute path :from dir)` resolves a path from a directory (by default,
the current one), and `(%path/relative path :from dir)` gives the way to a path
from a directory: `(%path/relative /a/b/c :from /a/d)` → `../b/c`.
- `(%path/exists path)`, `(%path/is-file path)` and `(%path/is-directory path)`
are `true` or `false`.
- `(%write path content...)` writes the content's text to a file (making
directories as needed), expanding to nothing. With the formatter macros
below, one source file can generate a whole site.
below, one source file can generate a whole site, run with `seam run`.
- `(%exec program arguments... :stdin text)` runs a program and gives its
output, e.g. `(%exec git rev-parse --short HEAD)`.

Expand Down Expand Up @@ -299,3 +340,7 @@ let tree = expander.expand()?;
This way you can easily construct websites with reusable components,
cut down on copy-pasting, and generate it statically. Ideal for a blog,
especially using the `(%markdown ...)` macro.

See [`samples/blog`](samples/blog) for a whole blog: Markdown posts with
frontmatter, a shared layout, a tags page and an RSS feed, all generated by
`seam run build.sex` with `%write` and the formatter macros.
7 changes: 5 additions & 2 deletions crates/seam/src/assemble/css.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,13 @@ impl<'a> CSSFormatter<'a> {
and property-value pairs, wrapped in parentheses.",
&site.to_owned()));
},
// Raw text (e.g. hand-written CSS around literate macro calls) is written as it is.
ParseNode::Raw(node) => {
write!(f, "{leading}{}", node.value)?;
},
ParseNode::Symbol(node)
| ParseNode::Number(node)
| ParseNode::String(node)
| ParseNode::Raw(node) => {
| ParseNode::String(node) => {
let site = node.site;
return Err(GenerationError::new("CSS",
"Symbolic node not expected here, CSS documents \
Expand Down
6 changes: 5 additions & 1 deletion crates/seam/src/assemble/xml.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ impl<'a> XMLFormatter<'a> {
write!(f, "{leading}")?;
write_escaped(f, &node.value)?;
},
// Raw text (e.g. the text of literate source) is written as it is.
ParseNode::Raw(node) => {
write!(f, "{leading}{}", node.value)?;
},
ParseNode::List { nodes: list, end_token, .. } => {
write!(f, "{leading}")?;
let head = list.first();
Expand Down Expand Up @@ -110,7 +114,7 @@ impl<'a> XMLFormatter<'a> {

write!(f, "</{tag}>")?;
},
_ => return Err(GenerationError::new("XML",
ParseNode::Attribute { .. } => return Err(GenerationError::new("XML",
&format!("Unexpected {} node when generating.", node.node_type()),
node.site()))
}
Expand Down
25 changes: 21 additions & 4 deletions crates/seam/src/bin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,13 @@ fn argument_fatal(msg: impl std::fmt::Display) -> ! {
const SUPPORTED_TARGETS: [&str; 5] = ["text", "sexp", "html", "xml", "css"];

fn main() -> Result<(), Box<dyn Error>> {
let mut args = env::args();
let mut args = env::args().peekable();
let _ = args.next(); // Discard.

// `seam run file.sex` expands a file only for its side effects
// (`%write`, `%exec`, ...), which are reported on STDOUT instead.
let run = args.next_if(|arg| arg == "run").is_some();

// Command line flags and options.
let mut files = Vec::new();
let mut target = String::new();
Expand Down Expand Up @@ -74,7 +78,11 @@ fn main() -> Result<(), Box<dyn Error>> {
if files.is_empty() {
from_stdin = true;
}
if target.is_empty() {
if run {
if !target.is_empty() {
argument_fatal(format!("`seam run' takes no target format, but `--{target}' was given."));
}
} else if target.is_empty() {
argument_fatal("No such target format exists / \
no target format given.");
}
Expand All @@ -84,19 +92,28 @@ fn main() -> Result<(), Box<dyn Error>> {
let context = seam::Context::new();
let builder = seam::tree_builder_stream(&context, &mut stdin, literate)?;
builder.add_includes(include_dirs.iter());
generate_and_print(builder, &target, is_doc);
if run { execute(builder) } else { generate_and_print(builder, &target, is_doc) }
}

for file in files {
let context = seam::Context::new();
let builder = seam::tree_builder_file(&context, &file, literate)?;
builder.add_includes(include_dirs.iter());
generate_and_print(builder, &target, is_doc);
if run { execute(builder) } else { generate_and_print(builder, &target, is_doc) }
}

Ok(())
}

/// Expand a file only for its side effects, discarding the document.
fn execute(expander: seam::parse::expander::Expander) {
expander.set_echo(true);
if let Err(e) = expander.expand() {
eprintln!("{e}");
std::process::exit(1);
}
}

fn generate_and_print(expander: seam::parse::expander::Expander, target: &str, is_doc: bool) {
let tree = match expander.expand() {
Ok(tree) => tree,
Expand Down
Loading
Loading