abbaye/main.rs
1//! # Abbaye
2//!
3//! 
4//!
5//! Abbaye is a Static Site Generator (SSG) for your software. As GitHub,
6//! Gitea, Forgejo and consorts offer, Abbaye can be used to generate a
7//! website with your software's presentation, documentation, and distribution, per version.
8//!
9//! Here's an example file structure:
10//!
11//! ```text
12//! .
13//! ├── index.html # the main page of the website, enabling choosing a version, defaults to "latest" (contains a list of available versions and a iframe to the selected version?)
14//! ├── releases.feed # the RSS feed of the releases
15//! ├── latest -> v2.0.0 # symlink to the latest version (biggest version number)
16//! ├── v1.0.0/ # the directory containing the version 1.0.0 of the software
17//! │ ├── index.html # the main page of the version 1.0.0, from the README.md file.
18//! │ │ # Contains a sidebar with links to the documentation and distribution.
19//! │ │ # After the readme content, A changelog is displayed.
20//! │ ├── docs/ # the directory containing the documentation of the version 1.0.0
21//! │ │ ├── index.html # the main page of the documentation of the version 1.0.0
22//! │ │ └── …
23//! │ ├── docs.tar.gz # the tarball containing the documentation of the version 1.0.0
24//! │ └── dist/ # the directory containing the distribution of the version 1.0.0
25//! │ ├── source.tgz # the source code of the version 1.0.0
26//! │ ├── mybin-v1.0.0-x86_64-unknown-linux-gnu
27//! │ └── mybin-v1.0.0-x86_64-unknown-linux-musl
28//! └── v2.0.0/ # the directory containing the version 2.0.0 of the software
29//! ├── index.html # the main page of the version 2.0.0
30//! ├── …
31//! └── …
32//! ```
33//!
34//! ## Why ?
35//!
36//! This piece of software is for people that can't or won't use a full-featured forge such as GitHub, GitLab, ForgeJo & others.
37//! These forges provide "release pages" that allow you to upload and distribute your software, as well as get a changelog.
38//!
39//! Abbaye is made to be a simple, lightweight alternative to these forges, for the release/documentation parts.
40//!
41//! ### Why "Abbaye" ?
42//!
43//! [Abbaye](https://en.wikipedia.org/wiki/Abbaye) is a French word for Abbey. An Abbey is a type of monastery, on the big-ish side, but still a small, quiet place.
44//!
45//! Anyway, that's where you store and display your relics (your software releases).
46//!
47//! ## Installation
48//!
49//! ### Pre-built binaries
50//!
51//! You can grab a pre-built binary from the [releases page](http://vit.am/~ololduck/abbaye/latest).
52//!
53//! The `-musl` binaries are statically linked and should run everywhere, while the `-gnu` binaries are dynamically linked and require a compatible system library(which is probably available if you're not using an exotic distribution).
54//!
55//! ### From source
56//!
57//! To build from source, you need to have Rust installed. You can install Rust using [rustup](https://rustup.rs/).
58//!
59//! You can clone the [repository](https://git.sr.ht/~ololduck/abbaye) and build the project using `cargo build --release`. The built binary will be located in `target/release/abbaye`. You can also install it directly using `cargo install --path .`
60//!
61//! ## Usage
62//!
63//! Run `abbaye init` in your project's directory to create a `abbaye.toml` configuration file. You can then customize the configuration to your liking.
64//! Here's an example configuration file to get you started:
65//!
66//! ```toml
67//! [site]
68//! name = "Abbaye"
69//! # required for Atom feed generation (canonical URLs are used for feed items)
70//! base_url = "http://vit.am/~ololduck/abbaye/"
71//!
72//! [version_extractor]
73//! type = "git" # extract version from git tags
74//! tag_prefix = "v"
75//!
76//! [changelog] # use the default changelog parser (Keepachangelog format in CHANGELOG.md)
77//!
78//! [[builders]] # builds the project using cargo build --release
79//! type = "cargo"
80//! targets = ["x86_64-unknown-linux-gnu", "x86_64-unknown-linux-musl"]
81//!
82//! [[builders]] # generates documentation using cargo doc
83//! type = "cargo_doc"
84//! no_deps = true # Don't include dependencies in the documentation
85//!
86//! [[builders]]
87//! type = "archive" # creates a compressed tarball of the source code (can be of anything, really)
88//!
89//! [[builders]]
90//! type = "script"
91//! script = [
92//! "echo $ABBAYE_BUILDING_VERSION > .version",
93//! ]
94//! outputs = [".version"]
95//! ```
96//!
97//! Then run `abbaye build` to build the site. The site will be generated in the `public/` directory by default.
98//! Now you can copy the contents of `public/` to your web server to deploy the site. For instance, with rsync:
99//! `rsync --progress -avz --links --perms --update public/ ololduck@vit.am:public_html/abbaye/`
100//!
101//! To have a look at all the available configuration options, please refer to the documentation of [`config::AbbayeConfig`].
102//!
103//! ### ✨ Customization ✨
104//!
105//! You can dump the default theme/templates to your local filesystem with `abbaye dump-theme`.
106//!
107//! This will create a `.abbaye/theme/` directory in your current directory with the default templates, which you can then ✨customize✨.
108//!
109//! If this directory contains a `static/` directory, it will be copied to the output directory. So you can add custom static assets to your site, and even use a separate CSS!
110//!
111//! ## Future plans
112//!
113//! - [x] Add support for theming
114//! - [ ] Add support for more site variables, such as the site title, description, and author, or even a custom footer and stuff.
115//! - [ ] Add support for a `self-update`-like command to update the abbaye binary to the latest version. The mechanisms put in place for this goal should be usable to any user of `abbaye`.
116//!
117//! ## Contributing
118//!
119//! Contributions are welcome! As i am mainly a rust developer, i am open to any contributions that improve the project, especially to support more artifacts builders/types.
120//!
121//! Just clone the repository and {send me an email,contact me on {IRC (ololduck@irc.libera.chat),the Fediverse (@ololduck@fosstodon.org)}} with {a link to your fork,a git patch,compliments and adoration}.
122
123use std::path::PathBuf;
124
125use clap::Parser;
126use human_panic::setup_panic;
127use miette::{IntoDiagnostic, Result};
128use tokio::fs::create_dir_all;
129use tracing::{info, warn};
130
131use crate::{
132 builders::{AnyBuilder, archive::ArchiveBuilderConfig},
133 changelog::ChangelogConfig,
134 config::{AbbayeConfig, SiteConfig},
135 version_extractors::{AnyVersionExtractor, git::GitVersionConfig},
136};
137
138/// All builders for the site (ex: cargo build, cargo doc, etc.).
139pub mod builders;
140/// Parses the changelog file and generates a changelog page for the site.
141pub mod changelog;
142mod cli;
143/// Handles the `abbaye.toml` configuration file.
144pub mod config;
145/// Generates the site from the configuration and builds it.
146pub mod site;
147/// Extracts current version information from different sources (ex: git tags, cargo metadata, etc.).
148pub mod version_extractors;
149
150/// Build the full website for every git tag, sorted from the lowest semver
151/// version to the highest.
152///
153/// For each tag the function:
154/// 1. Runs `git checkout <tag>` to switch the working tree.
155/// 2. Loads `abbaye.toml` from the checked-out revision (falling back to the
156/// config that was active before the loop if the file is absent).
157/// 3. Calls [`site::build_site`] to produce the version page and update the
158/// root index and Atom feed.
159///
160/// The original HEAD (branch or commit) is always restored after the loop,
161/// even when an error occurs.
162async fn build_all() -> Result<()> {
163 // Load the current config to discover the version extractor settings.
164 let base_config = config::load_config()?;
165
166 // `git for-each-ref --sort=version:refname` returns tags in semver order,
167 // lowest first, which is exactly the order we want.
168 let all_versions = base_config.version_extractor.extract_all().await?;
169 if all_versions.is_empty() {
170 info!("No tagged versions found – nothing to build.");
171 return Ok(());
172 }
173
174 // Remember where we are so we can restore it when we're done.
175 // Prefer the branch name (symbolic ref) so that checking it out
176 // afterwards leaves the user on their branch rather than in a
177 // detached-HEAD state. Fall back to the raw commit SHA when HEAD
178 // is already detached.
179 let symref_out = tokio::process::Command::new("git")
180 .args(["symbolic-ref", "--short", "HEAD"])
181 .output()
182 .await
183 .into_diagnostic()?;
184 let original_head = if symref_out.status.success() {
185 // On a branch.
186 String::from_utf8(symref_out.stdout)
187 .into_diagnostic()?
188 .trim()
189 .to_owned()
190 } else {
191 // Detached HEAD — fall back to the commit SHA.
192 let sha_out = tokio::process::Command::new("git")
193 .args(["rev-parse", "HEAD"])
194 .output()
195 .await
196 .into_diagnostic()?;
197 if !sha_out.status.success() {
198 return Err(miette::miette!("Could not determine current HEAD"));
199 }
200 String::from_utf8(sha_out.stdout)
201 .into_diagnostic()?
202 .trim()
203 .to_owned()
204 };
205
206 let total = all_versions.len();
207 info!("Building {} version(s) …", total);
208
209 // Run the build loop; capture the result so we can restore HEAD first.
210 let loop_result = async {
211 for (i, version_info) in all_versions.iter().enumerate() {
212 let tag = base_config
213 .version_extractor
214 .tag_name(&version_info.version);
215
216 info!("[{}/{}] Checking out {} …", i + 1, total, tag);
217
218 let checkout = tokio::process::Command::new("git")
219 .args(["checkout", &tag])
220 .output()
221 .await
222 .into_diagnostic()?;
223 if !checkout.status.success() {
224 let stderr = String::from_utf8_lossy(&checkout.stderr);
225 return Err(miette::miette!("git checkout {tag} failed:\n{stderr}"));
226 }
227
228 // Reload `abbaye.toml` from the checked-out revision so the build
229 // uses that version's own configuration (builders, readme path,
230 // etc.). If the file does not exist in this revision, fall back
231 // to the config we loaded before the loop.
232 let version_config = config::load_config().unwrap_or_else(|_| base_config.clone());
233
234 info!(
235 "[{}/{}] Building version {} …",
236 i + 1,
237 total,
238 version_info.version
239 );
240
241 site::build_site(version_config).await?;
242 }
243 Ok(())
244 }
245 .await;
246
247 // Always restore HEAD, regardless of whether the loop succeeded.
248 let restore = tokio::process::Command::new("git")
249 .args(["checkout", &original_head])
250 .output()
251 .await
252 .into_diagnostic()?;
253 if !restore.status.success() {
254 let stderr = String::from_utf8_lossy(&restore.stderr);
255 warn!("Could not restore HEAD to {original_head}:\n{stderr}");
256 }
257
258 loop_result?;
259 info!("Done. Built {total} version(s).");
260 Ok(())
261}
262
263#[tokio::main]
264async fn main() -> Result<()> {
265 setup_panic!();
266 let cli_args = cli::CliArgs::parse();
267
268 tracing_subscriber::fmt()
269 .with_timer(tracing_subscriber::fmt::time::SystemTime)
270 .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
271 .init();
272
273 match cli_args.command {
274 cli::CliCommand::Init { path } => {
275 let base_path = if let Some(path) = path {
276 path
277 } else {
278 std::env::current_dir().into_diagnostic()?
279 };
280 if base_path.join("abbaye.toml").exists() {
281 return Err(miette::miette!(
282 "abbaye.toml already exists in this directory"
283 ));
284 }
285 let abbaye_config = AbbayeConfig {
286 site: SiteConfig {
287 name: "MyProject Release Page".to_string(),
288 readme: None,
289 base_url: None,
290 repo_url: None,
291 lang: None,
292 fediverse_creator: None,
293 opengraph: None,
294 },
295 version_extractor: AnyVersionExtractor::Git(GitVersionConfig {
296 tag_prefix: Some("v".to_string()),
297 dirty_suffix: "-dirty".to_string(),
298 }),
299 builders: vec![AnyBuilder::Archive(ArchiveBuilderConfig {
300 source_dir: None,
301 output: None,
302 prefix: None,
303 ignore_patterns: vec![".git/".to_string(), "*.tar.gz".to_string()],
304 })],
305 changelog: ChangelogConfig {
306 ..Default::default()
307 },
308 output_dir: None,
309 };
310 let config_path = base_path.join("abbaye.toml");
311 let toml = toml::to_string_pretty(&abbaye_config).into_diagnostic()?;
312 tokio::fs::write(&config_path, toml)
313 .await
314 .into_diagnostic()?;
315 }
316 cli::CliCommand::Build => {
317 let config = config::load_config()?;
318 site::build_site(config).await?;
319 }
320 cli::CliCommand::BuildAll => {
321 build_all().await?;
322 }
323 cli::CliCommand::DumpSchema => {
324 // Emit a JSON Schema draft-07 document rather than the 2020-12
325 // default. Taplo (and most TOML LSP tooling) validates against
326 // draft-07, which treats `$ref` as exclusive — it ignores any
327 // sibling keywords. Draft-07 output from schemars wraps `$ref`
328 // in `allOf` instead, keeping the `const` type-discriminators
329 // visible to the validator and resolving `oneOf` ambiguity.
330 let generator = schemars::generate::SchemaSettings::draft07().into_generator();
331 let schema = generator.into_root_schema_for::<config::AbbayeConfig>();
332 println!(
333 "{}",
334 serde_json::to_string_pretty(&schema).into_diagnostic()?
335 );
336 }
337 cli::CliCommand::DumpTheme => {
338 let theme_path = PathBuf::from(".abbaye").join("theme");
339 create_dir_all(&theme_path).await.into_diagnostic()?;
340 tokio::fs::write(
341 theme_path.join("root_index.html.j2"),
342 site::TEMPLATE_ROOT_INDEX,
343 )
344 .await
345 .into_diagnostic()?;
346 tokio::fs::write(
347 theme_path.join("version_index.html.j2"),
348 site::TEMPLATE_VERSION_INDEX,
349 )
350 .await
351 .into_diagnostic()?;
352 }
353 }
354 Ok(())
355}