hugr_cli/
extensions.rs

1//! Dump standard extensions in serialized form.
2use anyhow::Result;
3use clap::Parser;
4use hugr::extension::ExtensionRegistry;
5use std::{io::Write, path::PathBuf};
6
7/// Dump the standard extensions.
8#[derive(Parser, Debug)]
9#[clap(version = "1.0", long_about = None)]
10#[clap(about = "Write standard extensions.")]
11#[group(id = "hugr")]
12#[non_exhaustive]
13pub struct ExtArgs {
14    /// Output directory
15    #[arg(
16        default_value = ".",
17        short,
18        long,
19        value_name = "OUTPUT",
20        help = "Output directory."
21    )]
22    pub outdir: PathBuf,
23}
24
25impl ExtArgs {
26    /// Write out the standard extensions in serialized form.
27    /// Qualified names of extensions used to generate directories under the specified output directory.
28    /// E.g. extension "foo.bar.baz" will be written to "OUTPUT/foo/bar/baz.json".
29    pub fn run_dump(&self, registry: &ExtensionRegistry) -> Result<()> {
30        let base_dir = &self.outdir;
31
32        for ext in registry {
33            let mut path = base_dir.clone();
34            for part in ext.name().split('.') {
35                path.push(part);
36            }
37            path.set_extension("json");
38
39            std::fs::create_dir_all(path.clone().parent().unwrap())?;
40            // file buffer
41            let mut file = std::fs::File::create(&path)?;
42
43            serde_json::to_writer_pretty(&mut file, &ext)?;
44
45            // write newline, for pre-commit end of file check that edits the file to
46            // add newlines if missing.
47            file.write_all(b"\n")?;
48        }
49
50        Ok(())
51    }
52}