Skip to main content

abbaye/
main.rs

1//! # Abbaye
2//!
3//! ![logo](logo-wordmark.svg)
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//! ├── repository/ # the directory containing the repository UI (if enabled in config)
16//! ├── repository.git # Clonable git repository
17//! ├── latest -> v2.0.0 # symlink to the latest version (biggest version number)
18//! ├── v1.0.0/ # the directory containing the version 1.0.0 of the software
19//! │   ├── index.html # the main page of the version 1.0.0, from the README.md file.
20//! │   │   # Contains a sidebar with links to the documentation and distribution.
21//! │   │   # After the readme content, A changelog is displayed.
22//! │   ├── docs/ # the directory containing the documentation of the version 1.0.0
23//! │   │   ├── index.html # the main page of the documentation of the version 1.0.0
24//! │   │   └── …
25//! │   ├── docs.tar.gz # the tarball containing the documentation of the version 1.0.0
26//! │   └── dist/ # the directory containing the distribution of the version 1.0.0
27//! │       ├── source.tgz # the source code of the version 1.0.0
28//! │       ├── mybin-v1.0.0-x86_64-unknown-linux-gnu
29//! │       └── mybin-v1.0.0-x86_64-unknown-linux-musl
30//! └── v2.0.0/ # the directory containing the version 2.0.0 of the software
31//!     ├── index.html # the main page of the version 2.0.0
32//!     ├── …
33//!     └── …
34//! ```
35//!
36//! ## Why ?
37//!
38//! This piece of software is for people that can't or won't use a full-featured forge such as GitHub, GitLab, ForgeJo & others.
39//! These forges provide "release pages" that allow you to upload and distribute your software, as well as get a changelog.
40//!
41//! Abbaye is made to be a simple, lightweight alternative to these forges, for the release/documentation parts.
42//!
43//! ### Why "Abbaye" ?
44//!
45//! [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.
46//!
47//! Anyway, that's where you store and display your relics (your software releases).
48//!
49//! ## Installation
50//!
51//! ### Pre-built binaries
52//!
53//! You can grab a pre-built binary from the [releases page](http://vit.am/~ololduck/abbaye/latest).
54//!
55//! 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).
56//!
57//! ### From source
58//!
59//! To build from source, you need to have Rust installed. You can install Rust using [rustup](https://rustup.rs/).
60//!
61//! 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 .`
62//!
63//! ## Usage
64//!
65//! Run `abbaye init` in your project's directory to create a `abbaye.toml` configuration file. You can then customize the configuration to your liking.
66//! Here's an example configuration file to get you started:
67//!
68//! ```toml
69//! [site]
70//! name = "Abbaye"
71//! # required for Atom feed generation (canonical URLs are used for feed items)
72//! base_url = "http://vit.am/~ololduck/abbaye/"
73//!
74//! [version_extractor]
75//! type = "git" # extract version from git tags
76//! tag_prefix = "v"
77//!
78//! [changelog] # use the default changelog parser (Keepachangelog format in CHANGELOG.md)
79//!
80//! [[builders]]  # builds the project using cargo build --release
81//! type = "cargo"
82//! targets = ["x86_64-unknown-linux-gnu", "x86_64-unknown-linux-musl"]
83//!
84//! [[builders]]  # generates documentation using cargo doc
85//! type = "cargo_doc"
86//! no_deps = true  # Don't include dependencies in the documentation
87//!
88//! [[builders]]
89//! # creates a compressed tarball of the source code (can be of anything, really)
90//! type = "archive"
91//!
92//! [[builders]]
93//! # Just an example dumb script to showcase the `script` builder type
94//! type = "script"
95//! script = [
96//!  "echo $ABBAYE_BUILDING_VERSION > .version",
97//! ]
98//! outputs = [".version"]
99//! ```
100//!
101//! Then run `abbaye build` to build the site. The site will be generated in the `public/` directory by default.
102//! Now you can copy the contents of `public/` to your web server to deploy the site. For instance, with rsync:
103//! `rsync --progress -avz --links --perms --update public/ ololduck@vit.am:public_html/abbaye/`
104//!
105//! To have a look at all the available configuration options, please refer to the documentation of [`config::AbbayeConfig`].
106//!
107//! ### A note on the repository UI
108//!
109//! The repository UI is **NOT** enabled by default. It must be enabled explicitly in the configuration with the following:
110//!
111//! ```toml
112//! [git_ui] # only this section is needed to enable the repository UI
113//! ```
114//! It has multiple options (each presented with their defaults, if any):
115//!
116//! ```toml
117//! [git_ui]
118//! default_branch = "main"
119//! max_commits = 200
120//! repo_path = "."
121//! clone_url = "{{ site.base_url }}/repository.git"
122//! ```
123//!
124//! When the git UI is enabled, pages permitting browsing the tree of the repository are available, _but only for the branches tips and the tags_, as to not generate too much content. It already is quite a lot of content to generate for a simple repository UI (about 10MBs for Abbaye's repository at the time of writing).
125//!
126//! ### ✨ Customization ✨
127//!
128//! You can dump the default theme/templates to your local filesystem with `abbaye dump-theme`.
129//!
130//! This will create a `.abbaye/theme/` directory in your current directory with the default templates, which you can then ✨customize✨.
131//!
132//! If you don't want to customize every template, simply delete the ones you don't want to change.
133//!
134//! In `.abbaye/theme/static/`, you will find the CSS sheet used by the default theme, across all templates. Editing this file will change the look and feel of all your site's pages.
135//!
136//! ## Future plans
137//!
138//! - [x] Add support for theming
139//! - [ ] Add support for more site variables, such as the site title, description, and author, or even a custom footer and stuff.
140//!   - I added OpenGraph support, does that count?
141//! - [x] 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`.
142//!
143//! ## Contributing
144//!
145//! 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.
146//!
147//! 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}.
148
149use std::path::PathBuf;
150
151use clap::CommandFactory;
152use clap::Parser;
153use human_panic::setup_panic;
154use miette::{IntoDiagnostic, Result};
155use tokio::fs::create_dir_all;
156use tracing::{info, warn};
157
158use crate::{
159    builders::{AnyBuilder, BuilderEntry, archive::ArchiveBuilderConfig},
160    changelog::ChangelogConfig,
161    config::{AbbayeConfig, SiteConfig},
162    version_extractors::{AnyVersionExtractor, git::GitVersionConfig},
163};
164
165/// All builders for the site (ex: cargo build, cargo doc, etc.).
166pub mod builders;
167/// Parses the changelog file and generates a changelog page for the site.
168pub mod changelog;
169/// Stuff related to the CLI interface. Also contains colour escape codes for terminal output.
170pub mod cli;
171/// Handles the `abbaye.toml` configuration file.
172pub mod config;
173/// Generates a static git web UI and clonable bare repository.
174pub mod git_ui;
175/// Generates the site from the configuration and builds it.
176pub mod site;
177/// Self-update logic: fetches the release feed and replaces the binary when a newer version exists.
178mod updater;
179/// Extracts current version information from different sources (ex: git tags, cargo metadata, etc.).
180pub mod version_extractors;
181
182/// Build the full website for every git tag, sorted from the lowest semver
183/// version to the highest.
184///
185/// For each tag the function:
186/// 1. Runs `git checkout <tag>` to switch the working tree.
187/// 2. Loads `abbaye.toml` from the checked-out revision (falling back to the
188///    config that was active before the loop if the file is absent).
189/// 3. Calls [`site::build_site`] to produce the version page and update the
190///    root index and Atom feed.
191///
192/// The original HEAD (branch or commit) is always restored after the loop,
193/// even when an error occurs.
194async fn build_all() -> Result<()> {
195    // Load the current config to discover the version extractor settings.
196    let base_config = config::load_config()?;
197
198    // `git for-each-ref --sort=version:refname` returns tags in semver order,
199    // lowest first, which is exactly the order we want.
200    let all_versions = base_config.version_extractor.extract_all().await?;
201    if all_versions.is_empty() {
202        info!("No tagged versions found – nothing to build.");
203        return Ok(());
204    }
205
206    // Remember where we are so we can restore it when we're done.
207    // Prefer the branch name (symbolic ref) so that checking it out
208    // afterwards leaves the user on their branch rather than in a
209    // detached-HEAD state.  Fall back to the raw commit SHA when HEAD
210    // is already detached.
211    let symref_out = tokio::process::Command::new("git")
212        .args(["symbolic-ref", "--short", "HEAD"])
213        .output()
214        .await
215        .into_diagnostic()?;
216    let original_head = if symref_out.status.success() {
217        // On a branch.
218        String::from_utf8(symref_out.stdout)
219            .into_diagnostic()?
220            .trim()
221            .to_owned()
222    } else {
223        // Detached HEAD — fall back to the commit SHA.
224        let sha_out = tokio::process::Command::new("git")
225            .args(["rev-parse", "HEAD"])
226            .output()
227            .await
228            .into_diagnostic()?;
229        if !sha_out.status.success() {
230            return Err(miette::miette!("Could not determine current HEAD"));
231        }
232        String::from_utf8(sha_out.stdout)
233            .into_diagnostic()?
234            .trim()
235            .to_owned()
236    };
237
238    let total = all_versions.len();
239    info!("Building {} version(s) …", total);
240
241    // Run the build loop; capture the result so we can restore HEAD first.
242    let loop_result = async {
243        for (i, version_info) in all_versions.iter().enumerate() {
244            let tag = base_config
245                .version_extractor
246                .tag_name(&version_info.version);
247
248            info!("[{}/{}] Checking out {} …", i + 1, total, tag);
249
250            let checkout = tokio::process::Command::new("git")
251                .args(["checkout", &tag])
252                .output()
253                .await
254                .into_diagnostic()?;
255            if !checkout.status.success() {
256                let stderr = String::from_utf8_lossy(&checkout.stderr);
257                return Err(miette::miette!("git checkout {tag} failed:\n{stderr}"));
258            }
259
260            // Reload `abbaye.toml` from the checked-out revision so the build
261            // uses that version's own configuration (builders, readme path,
262            // etc.).  If the file does not exist in this revision, fall back
263            // to the config we loaded before the loop.
264            let version_config = config::load_config().unwrap_or_else(|_| base_config.clone());
265
266            info!(
267                "[{}/{}] Building version {} …",
268                i + 1,
269                total,
270                version_info.version
271            );
272
273            site::build_site(version_config).await?;
274        }
275        Ok(())
276    }
277    .await;
278
279    // Always restore HEAD, regardless of whether the loop succeeded.
280    let restore = tokio::process::Command::new("git")
281        .args(["checkout", &original_head])
282        .output()
283        .await
284        .into_diagnostic()?;
285    if !restore.status.success() {
286        let stderr = String::from_utf8_lossy(&restore.stderr);
287        warn!("Could not restore HEAD to {original_head}:\n{stderr}");
288    }
289
290    loop_result?;
291
292    // Build the git repository UI once, now that HEAD is restored.
293    if let Some(git_ui_cfg) = &base_config.git_ui {
294        git_ui::build_git_repository_ui(&base_config, git_ui_cfg).await?;
295    }
296
297    info!("Done. Built {total} version(s).");
298    Ok(())
299}
300
301#[tokio::main]
302async fn main() -> Result<()> {
303    setup_panic!();
304    let cli_args = cli::CliArgs::parse();
305
306    tracing_subscriber::fmt()
307        .with_timer(tracing_subscriber::fmt::time::SystemTime)
308        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
309        .init();
310
311    match cli_args.command {
312        cli::CliCommand::Init { path } => {
313            let base_path = if let Some(path) = path {
314                path
315            } else {
316                std::env::current_dir().into_diagnostic()?
317            };
318            if base_path.join("abbaye.toml").exists() {
319                return Err(miette::miette!(
320                    "abbaye.toml already exists in this directory"
321                ));
322            }
323            let abbaye_config = AbbayeConfig {
324                site: SiteConfig {
325                    name: "MyProject Release Page".to_string(),
326                    ..Default::default()
327                },
328                version_extractor: AnyVersionExtractor::Git(GitVersionConfig {
329                    tag_prefix: Some("v".to_string()),
330                    dirty_suffix: "-dirty".to_string(),
331                }),
332                builders: vec![BuilderEntry {
333                    builder: AnyBuilder::Archive(ArchiveBuilderConfig {
334                        source_dir: None,
335                        output: None,
336                        prefix: None,
337                        ignore_patterns: vec![".git/".to_string(), "*.tar.gz".to_string()],
338                    }),
339                    id: None,
340                    depends_on: vec![],
341                }],
342                changelog: ChangelogConfig {
343                    ..Default::default()
344                },
345                git_ui: None,
346            };
347            let config_path = base_path.join("abbaye.toml");
348            let toml = toml::to_string_pretty(&abbaye_config).into_diagnostic()?;
349            tokio::fs::write(&config_path, toml)
350                .await
351                .into_diagnostic()?;
352        }
353        cli::CliCommand::Build { repository_only } => {
354            let config = config::load_config()?;
355            if repository_only {
356                match &config.git_ui {
357                    Some(git_ui_cfg) => {
358                        git_ui::build_git_repository_ui(&config, git_ui_cfg).await?;
359                    }
360                    None => {
361                        return Err(miette::miette!(
362                            "--repository-only requires [git_ui] to be configured in abbaye.toml"
363                        ));
364                    }
365                }
366            } else {
367                site::build_site(config.clone()).await?;
368                if let Some(git_ui_cfg) = &config.git_ui {
369                    git_ui::build_git_repository_ui(&config, git_ui_cfg).await?;
370                }
371            }
372        }
373        cli::CliCommand::BuildAll => {
374            build_all().await?;
375        }
376        cli::CliCommand::DumpSchema => {
377            // Emit a JSON Schema draft-07 document rather than the 2020-12
378            // default.  Taplo (and most TOML LSP tooling) validates against
379            // draft-07, which treats `$ref` as exclusive — it ignores any
380            // sibling keywords.  Draft-07 output from schemars wraps `$ref`
381            // in `allOf` instead, keeping the `const` type-discriminators
382            // visible to the validator and resolving `oneOf` ambiguity.
383            let generator = schemars::generate::SchemaSettings::draft07().into_generator();
384            let schema = generator.into_root_schema_for::<config::AbbayeConfig>();
385            println!(
386                "{}",
387                serde_json::to_string_pretty(&schema).into_diagnostic()?
388            );
389        }
390        cli::CliCommand::SelfUpdate { check } => {
391            updater::self_update(check).await?;
392        }
393        cli::CliCommand::UsageSpec => {
394            let mut cmd = cli::CliArgs::command();
395            clap_usage::generate(&mut cmd, "abbaye", &mut std::io::stdout());
396        }
397        cli::CliCommand::DumpTheme => {
398            let theme_path = PathBuf::from(".abbaye").join("theme");
399            create_dir_all(&theme_path).await.into_diagnostic()?;
400            tokio::fs::write(
401                theme_path.join("root_index.html.j2"),
402                site::TEMPLATE_ROOT_INDEX,
403            )
404            .await
405            .into_diagnostic()?;
406            tokio::fs::write(
407                theme_path.join("version_index.html.j2"),
408                site::TEMPLATE_VERSION_INDEX,
409            )
410            .await
411            .into_diagnostic()?;
412            tokio::fs::write(
413                theme_path.join("markdown.html.j2"),
414                builders::markdown::TEMPLATE_MARKDOWN,
415            )
416            .await
417            .into_diagnostic()?;
418            tokio::fs::write(theme_path.join("git_log.html.j2"), git_ui::TEMPLATE_GIT_LOG)
419                .await
420                .into_diagnostic()?;
421            tokio::fs::write(
422                theme_path.join("git_commit.html.j2"),
423                git_ui::TEMPLATE_GIT_COMMIT,
424            )
425            .await
426            .into_diagnostic()?;
427            tokio::fs::write(
428                theme_path.join("git_refs.html.j2"),
429                git_ui::TEMPLATE_GIT_REFS,
430            )
431            .await
432            .into_diagnostic()?;
433            {
434                let static_dir = theme_path.join("static");
435                create_dir_all(&static_dir).await.into_diagnostic()?;
436                tokio::fs::write(static_dir.join("site.css"), site::SITE_CSS)
437                    .await
438                    .into_diagnostic()?;
439            }
440            tokio::fs::write(
441                theme_path.join("git_tree.html.j2"),
442                git_ui::TEMPLATE_GIT_TREE,
443            )
444            .await
445            .into_diagnostic()?;
446            tokio::fs::write(
447                theme_path.join("git_blob.html.j2"),
448                git_ui::TEMPLATE_GIT_BLOB,
449            )
450            .await
451            .into_diagnostic()?;
452        }
453    }
454    Ok(())
455}