axbuild 0.5.0

An OS build lib toolkit used by arceos
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
use std::path::{Path, PathBuf};

use clap::{Args as ClapArgs, Subcommand};

use crate::{
    context::AppContext,
    rootfs::resize::{ResizeOptions, resize_ext_rootfs_image},
    support::download::file_sha256,
};

pub mod config;
pub mod registry;
pub mod spec;
pub mod storage;

use config::ImageConfig;
use spec::ImageSpecRef;
use storage::Storage;

#[derive(ClapArgs)]
pub struct ImageArgs {
    #[command(flatten)]
    pub overrides: ConfigOverrides,

    #[command(subcommand)]
    pub command: Command,
}

#[derive(ClapArgs, Debug, Clone, Default)]
pub struct ConfigOverrides {
    #[arg(short('R'), long, global = true)]
    pub registry: Option<String>,

    #[arg(short('D'), long, global = true)]
    pub download_dir: Option<PathBuf>,

    #[arg(short('E'), long, global = true)]
    pub extract_dir: Option<PathBuf>,
}

impl ConfigOverrides {
    pub fn apply_on(&self, config: &mut ImageConfig) {
        if let Some(registry) = self.registry.as_ref() {
            config.registry = registry.clone();
        }
        if let Some(download_dir) = self.download_dir.as_ref() {
            config.download_dir = download_dir.clone();
        }
        if let Some(extract_dir) = self.extract_dir.as_ref() {
            config.extract_dir = extract_dir.clone();
        }
    }
}

#[derive(Subcommand)]
pub enum Command {
    /// List available images from rcore-os/tgosimages registry.
    Ls(ArgsLs),
    /// Pull an image and verify its sha256 checksum.
    Pull(ArgsPull),
    /// Resize an ext rootfs image, optionally copying it first.
    Resize(ArgsResize),
    /// Print and optionally verify the sha256 of a local image.
    Check(ArgsCheck),
}

#[derive(ClapArgs)]
pub struct ArgsLs {
    #[arg(short, long)]
    pub verbose: bool,

    pub pattern: Option<String>,
}

#[derive(ClapArgs)]
pub struct ArgsPull {
    /// Rootfs image name, optionally with `:<version>`.
    ///
    /// Examples: `rootfs-riscv64-alpine.img`, `rootfs-aarch64-alpine.img:v0.0.5`.
    pub image: Option<String>,

    /// Pull the default Starry/ArceOS rootfs for this architecture.
    #[arg(long)]
    pub arch: Option<String>,

    /// Keep only the downloaded archive for generic images.
    #[arg(long)]
    pub no_extract: bool,
}

#[derive(ClapArgs)]
pub struct ArgsCheck {
    pub image: PathBuf,

    #[arg(long)]
    pub sha256: Option<String>,
}

#[derive(ClapArgs)]
pub struct ArgsResize {
    /// Rootfs image to resize.
    pub image: PathBuf,

    /// Output image path. When omitted, resize IMAGE in place.
    #[arg(short, long)]
    pub output: Option<PathBuf>,

    /// Final image size in MiB. Shrinking is rejected.
    #[arg(long = "size-mib", value_name = "MIB")]
    pub size_mib: u64,
}

pub(crate) async fn run(args: ImageArgs) -> anyhow::Result<()> {
    execute(args).await
}

async fn execute(args: ImageArgs) -> anyhow::Result<()> {
    let app = AppContext::new()?;
    match args.command {
        Command::Ls(ls) => list_images(app.workspace_root(), &args.overrides, ls).await,
        Command::Pull(pull) => pull_image(app.workspace_root(), &args.overrides, pull).await,
        Command::Resize(resize) => resize_image(resize),
        Command::Check(check) => {
            let path = to_absolute_path(&check.image)?;
            let ok = check_image(&path, check.sha256.as_deref())?;
            if ok {
                Ok(())
            } else {
                anyhow::bail!("checksum mismatch for {}", path.display())
            }
        }
    }
}

fn check_image(path: &Path, expected_sha256: Option<&str>) -> anyhow::Result<bool> {
    let actual = file_sha256(path)?;
    if let Some(expected) = expected_sha256 {
        let matches = actual == expected;
        println!(
            "{}  {}{}",
            actual,
            path.display(),
            if matches { "" } else { " (mismatch)" }
        );
        return Ok(matches);
    }

    println!("{actual}  {}", path.display());
    Ok(true)
}

async fn list_images(
    workspace_root: &Path,
    overrides: &ConfigOverrides,
    args: ArgsLs,
) -> anyhow::Result<()> {
    let mut config = ImageConfig::read_config(workspace_root)?;
    overrides.apply_on(&mut config);
    let storage = Storage::new_from_config(&config).await?;
    storage
        .image_registry
        .print(args.verbose, args.pattern.as_deref());
    Ok(())
}

async fn pull_image(
    workspace_root: &Path,
    overrides: &ConfigOverrides,
    args: ArgsPull,
) -> anyhow::Result<()> {
    let image_path = match (args.image.as_deref(), args.arch.as_deref()) {
        (Some(image), None) if !args.no_extract => {
            let mut config = ImageConfig::read_config(workspace_root)?;
            overrides.apply_on(&mut config);
            let storage = Storage::new_from_config(&config).await?;
            match storage.pull_rootfs_image(ImageSpecRef::parse(image)).await {
                Ok(path) => path,
                Err(rootfs_err) => storage
                    .pull_image(ImageSpecRef::parse(image), true)
                    .await
                    .map_err(|generic_err| {
                        anyhow::anyhow!(
                            "failed to pull `{image}` as managed rootfs ({rootfs_err}) or generic \
                             image ({generic_err})"
                        )
                    })?,
            }
        }
        (Some(image), None) => {
            let mut config = ImageConfig::read_config(workspace_root)?;
            overrides.apply_on(&mut config);
            let storage = Storage::new_from_config(&config).await?;
            storage
                .pull_image(ImageSpecRef::parse(image), !args.no_extract)
                .await?
        }
        (None, Some(arch)) if !args.no_extract => {
            let mut config = ImageConfig::read_config(workspace_root)?;
            overrides.apply_on(&mut config);
            let image = storage::default_rootfs_image(arch).ok_or_else(|| {
                anyhow::anyhow!("no managed rootfs image available for arch `{arch}`")
            })?;
            let storage = Storage::new_from_config(&config).await?;
            storage.pull_rootfs_image(image.into()).await?
        }
        (None, Some(_)) => {
            anyhow::bail!("`--arch` managed rootfs pulls do not accept `--no-extract`")
        }
        (None, None) => {
            anyhow::bail!("provide an image name or use `--arch <ARCH>`")
        }
        (Some(_), Some(_)) => {
            anyhow::bail!(
                "`cargo xtask image pull` accepts either an image name or `--arch`, not both"
            )
        }
    };

    println!("image ready at {}", image_path.display());
    Ok(())
}

fn resize_image(args: ArgsResize) -> anyhow::Result<()> {
    let input = to_absolute_path(&args.image)?;
    let output = args.output.as_deref().map(to_absolute_path).transpose()?;
    let image = resize_ext_rootfs_image(ResizeOptions {
        input,
        output,
        size_mib: args.size_mib,
    })?;

    println!("rootfs image resized at {}", image.display());
    Ok(())
}

fn to_absolute_path(path: &Path) -> anyhow::Result<PathBuf> {
    Ok(if path.is_absolute() {
        path.to_path_buf()
    } else {
        std::env::current_dir()?.join(path)
    })
}

#[cfg(test)]
mod tests {
    use clap::Parser;

    use super::*;

    #[derive(Parser)]
    struct Cli {
        #[command(flatten)]
        overrides: ConfigOverrides,

        #[command(subcommand)]
        command: Command,
    }

    #[test]
    fn parses_separate_image_directories() {
        let cli = Cli::try_parse_from([
            "image",
            "--download-dir",
            "downloads",
            "--extract-dir",
            "rootfs",
            "ls",
        ])
        .unwrap();

        assert_eq!(cli.overrides.download_dir, Some(PathBuf::from("downloads")));
        assert_eq!(cli.overrides.extract_dir, Some(PathBuf::from("rootfs")));
    }

    #[test]
    fn rejects_removed_storage_options() {
        assert!(Cli::try_parse_from(["image", "--local-storage", "images", "ls"]).is_err());
        assert!(Cli::try_parse_from(["image", "--no-auto-sync", "ls"]).is_err());
        assert!(Cli::try_parse_from(["image", "--auto-sync-threshold", "60", "ls"]).is_err());
    }

    #[test]
    fn parses_pull_by_image_name() {
        let cli = Cli::try_parse_from(["image", "pull", "rootfs-riscv64-alpine.img"]).unwrap();

        match cli.command {
            Command::Pull(args) => {
                assert_eq!(args.image.as_deref(), Some("rootfs-riscv64-alpine.img"));
                assert!(args.arch.is_none());
                assert!(!args.no_extract);
            }
            _ => panic!("expected pull command"),
        }
    }

    #[test]
    fn parses_pull_by_arch() {
        let cli = Cli::try_parse_from(["image", "pull", "--arch", "x86_64"]).unwrap();

        match cli.command {
            Command::Pull(args) => {
                assert!(args.image.is_none());
                assert_eq!(args.arch.as_deref(), Some("x86_64"));
            }
            _ => panic!("expected pull command"),
        }
    }

    #[test]
    fn parses_pull_without_extracting() {
        let cli = Cli::try_parse_from(["image", "pull", "demo-x86_64", "--no-extract"]).unwrap();

        match cli.command {
            Command::Pull(args) => {
                assert_eq!(args.image.as_deref(), Some("demo-x86_64"));
                assert!(args.no_extract);
            }
            _ => panic!("expected pull command"),
        }
    }

    #[test]
    fn parses_pull_with_extract_dir_after_image() {
        let cli = Cli::try_parse_from([
            "image",
            "pull",
            "qemu-x86_64",
            "--extract-dir",
            "tmp/axbuild/images",
        ])
        .unwrap();

        assert_eq!(
            cli.overrides.extract_dir,
            Some(PathBuf::from("tmp/axbuild/images"))
        );
        assert!(matches!(cli.command, Command::Pull(_)));
    }

    #[test]
    fn ci_image_pull_commands_do_not_use_removed_output_dir() {
        let workflow = include_str!("../../../.github/workflows/ci.yml");

        for command in workflow
            .lines()
            .filter(|line| line.contains("cargo xtask image pull"))
        {
            assert!(
                !command.contains("--output-dir"),
                "CI still uses removed image option: {command}"
            );
        }

        // The modular check definitions under `.github/ci/checks/*.toml` are the
        // actual source of the commands CI runs. Scan them too, so a regressed
        // `--output-dir` anywhere is caught instead of only in `ci.yml`.
        let checks_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.github/ci/checks");
        for entry in std::fs::read_dir(&checks_dir).expect("read checks dir") {
            let path = entry.expect("check entry").path();
            if path.extension().and_then(|e| e.to_str()) != Some("toml") {
                continue;
            }
            let content = std::fs::read_to_string(&path).expect("read check toml");
            for command in content
                .lines()
                .filter(|line| line.contains("cargo xtask image pull"))
            {
                assert!(
                    !command.contains("--output-dir"),
                    "CI check {} still uses removed image option: {command}",
                    path.display()
                );
            }
        }
    }

    #[test]
    fn parses_check_with_expected_sha256() {
        let cli = Cli::try_parse_from([
            "image",
            "check",
            ".tgos-images/rootfs-riscv64-alpine.img",
            "--sha256",
            "abc",
        ])
        .unwrap();

        match cli.command {
            Command::Check(args) => {
                assert_eq!(
                    args.image,
                    PathBuf::from(".tgos-images/rootfs-riscv64-alpine.img")
                );
                assert_eq!(args.sha256.as_deref(), Some("abc"));
            }
            _ => panic!("expected check command"),
        }
    }

    #[test]
    fn parses_resize_with_output() {
        let cli = Cli::try_parse_from([
            "image",
            "resize",
            "rootfs.img",
            "--size-mib",
            "16384",
            "--output",
            "selfbuild.img",
        ])
        .unwrap();

        match cli.command {
            Command::Resize(args) => {
                assert_eq!(args.image, PathBuf::from("rootfs.img"));
                assert_eq!(args.output, Some(PathBuf::from("selfbuild.img")));
                assert_eq!(args.size_mib, 16384);
            }
            _ => panic!("expected resize command"),
        }
    }
}