nuts_tool/cli/archive/get.rs
1// MIT License
2//
3// Copyright (c) 2023,2024 Robin Doer
4//
5// Permission is hereby granted, free of charge, to any person obtaining a copy
6// of this software and associated documentation files (the "Software"), to
7// deal in the Software without restriction, including without limitation the
8// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
9// sell copies of the Software, and to permit persons to whom the Software is
10// furnished to do so, subject to the following conditions:
11//
12// The above copyright notice and this permission notice shall be included in
13// all copies or substantial portions of the Software.
14//
15// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21// IN THE SOFTWARE.
22
23use anyhow::{anyhow, Result};
24use clap::{ArgAction, Args};
25use log::{debug, trace};
26
27use crate::cli::archive::open_archive;
28use crate::format::Format;
29use crate::say::is_quiet;
30
31#[derive(Args, Debug)]
32pub struct ArchiveGetArgs {
33 /// The name of the entry to print
34 name: String,
35
36 /// Specifies the format of the output
37 #[clap(short, long, value_parser, default_value = "raw")]
38 format: Format,
39
40 /// Starts the migration when the container/archive is opened
41 #[clap(long, action = ArgAction::SetTrue)]
42 pub migrate: bool,
43
44 /// Specifies the name of the container
45 #[clap(short, long, env = "NUTS_CONTAINER")]
46 container: String,
47}
48
49impl ArchiveGetArgs {
50 pub fn run(&self) -> Result<()> {
51 debug!("args: {:?}", self);
52
53 let mut archive = open_archive(&self.container, self.migrate)?;
54 let block_size = archive.as_ref().block_size() as usize;
55
56 let entry = match archive.lookup(&self.name) {
57 Some(Ok(e)) => e,
58 Some(Err(err)) => return Err(err.into()),
59 None => return Err(anyhow!("no such entry: {}", self.name)),
60 };
61
62 if let Some(mut file) = entry.into_file() {
63 let mut buf = vec![0; block_size];
64 let mut writer = self.format.create_writer();
65
66 loop {
67 let n = file.read(&mut buf)?;
68 trace!("{} bytes read from {}", n, self.name);
69
70 if n > 0 {
71 if !is_quiet() {
72 writer.print(&buf[..n])?;
73 }
74 } else {
75 break;
76 }
77 }
78
79 if !is_quiet() {
80 writer.flush()?;
81 }
82 }
83
84 Ok(())
85 }
86}