hugr_cli/
extensions.rs

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