summaryrefslogtreecommitdiff
path: root/src/image.rs
blob: e0b5a982435e37b61d6d57e9a76ec47a0f1bbf2c (plain)
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
use std::fs::copy;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::result::Result;

#[derive(Debug, thiserror::Error)]
pub enum ImageError {
    #[error("qemu-img resize failed: {0}")]
    ResizeError(String),

    #[error(transparent)]
    IoError(#[from] std::io::Error),

    #[error(transparent)]
    StringError(#[from] std::string::FromUtf8Error),
}

pub struct VirtualMachineImage {
    filename: PathBuf,
}

impl VirtualMachineImage {
    pub fn new_from_base(base_image: &Path, image: &Path) -> Result<Self, ImageError> {
        copy(base_image, image)?;
        Ok(Self {
            filename: image.to_path_buf(),
        })
    }

    pub fn filename(&self) -> &Path {
        &self.filename
    }

    pub fn resize(&self, new_size: usize) -> Result<(), ImageError> {
        let r = Command::new("qemu-img")
            .arg("resize")
            .arg("-f")
            .arg(self.filename())
            .arg(format!("{}", new_size))
            .output()?;
        if !r.status.success() {
            let stderr = String::from_utf8(r.stderr)?;
            return Err(ImageError::ResizeError(stderr));
        }
        Ok(())
    }
}