nuts_tool/cli/container/
write.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::Result;
24use clap::Args;
25use log::{debug, trace};
26use std::cmp;
27use std::io::{self, Read};
28
29use crate::cli::open_container;
30
31fn fill_buf(buf: &mut [u8]) -> Result<usize> {
32    let mut nread = 0;
33
34    while nread < buf.len() {
35        let n = io::stdin().read(&mut buf[nread..])?;
36        trace!("read {} bytes: nread: {}, max: {}", n, nread, buf.len());
37
38        if n > 0 {
39            nread += n;
40        } else {
41            break;
42        }
43    }
44
45    Ok(nread)
46}
47
48#[derive(Args, Debug)]
49pub struct ContainerWriteArgs {
50    /// The id of the block to write. If not specified, aquire a new block
51    id: Option<String>,
52
53    /// Writes up to SIZE bytes. If not specified, write the whole block
54    #[clap(short, long, id = "SIZE")]
55    max_bytes: Option<u64>,
56
57    /// Specifies the name of the container
58    #[clap(short, long, env = "NUTS_CONTAINER")]
59    container: String,
60}
61
62impl ContainerWriteArgs {
63    pub fn run(&self) -> Result<()> {
64        debug!("args: {:?}", self);
65
66        let mut container = open_container(&self.container)?;
67
68        let block_size = container.block_size();
69        let max_bytes = self.max_bytes.unwrap_or(u64::MAX);
70        let max_bytes = cmp::min(max_bytes, block_size as u64) as usize;
71
72        debug!("block_size: {} => max_bytes: {}", block_size, max_bytes);
73
74        let id = match self.id.as_ref() {
75            Some(s) => {
76                let id = s.parse()?;
77                debug!("use id from cmdline: {}", id);
78                id
79            }
80            None => {
81                let id = container.aquire()?;
82                debug!("aquire new id: {}", id);
83                id
84            }
85        };
86
87        let mut buf = vec![0; max_bytes];
88        let n = fill_buf(&mut buf)?;
89
90        debug!("{} bytes read from stdin", n);
91
92        container.write(&id, &buf[..n])?;
93
94        println!("{} bytes written into {}", n, id);
95        Ok(())
96    }
97}