hvctrl/
lib.rs

1// Copyright takubokudori.
2// This source code is licensed under the MIT or Apache-2.0 license.
3//! # HvCtrl
4//! A hypervisor controller library
5//!
6//! # Supported OS
7//! Windows only.
8//!
9//! # Supported hypervisor controller
10//!
11//! - [VirtualBox](https://www.virtualbox.org/)
12//!     - [VBoxManage](https://www.virtualbox.org/manual/ch08.html)
13//! - [VMWare Workstation Player](https://www.vmware.com/products/workstation-player.html)
14//!     - [VMRest](https://code.vmware.com/apis/413)
15//! - [Hyper-V](https://docs.microsoft.com/en-us/virtualization/hyper-v-on-windows/about/)
16//!     - [Hyper-V cmdlets](https://docs.microsoft.com/en-us/powershell/module/hyper-v/?view=win10-ps)
17//!
18//! # License
19//!
20//! This software is released under the MIT or Apache-2.0 License, see LICENSE-MIT or LICENSE-APACHE.
21#[macro_use]
22pub mod types;
23
24pub mod hyperv;
25pub mod virtualbox;
26pub mod vmware;
27
28use crate::types::{ErrorKind, VmError, VmResult};
29use serde::Deserialize;
30use std::process::Command;
31#[cfg(windows)]
32use windy::AString;
33
34#[allow(dead_code)]
35pub(crate) fn deserialize<'a, T: Deserialize<'a>>(s: &'a str) -> VmResult<T> {
36    serde_json::from_str(s)
37        .map_err(|x| vmerr!(@r ErrorKind::UnexpectedResponse(x.to_string())))
38}
39
40#[cfg(windows)]
41#[allow(dead_code)]
42pub(crate) fn exec_cmd_astr(cmd: &mut Command) -> VmResult<(String, String)> {
43    match cmd.output() {
44        Ok(o) => unsafe {
45            Ok((
46                AString::new_unchecked(o.stdout).to_string_lossy(),
47                AString::new_unchecked(o.stderr).to_string_lossy(),
48            ))
49        },
50        Err(x) => vmerr!(ErrorKind::ExecutionFailed(x.to_string())),
51    }
52}
53
54#[allow(dead_code)]
55pub(crate) fn exec_cmd(cmd: &mut Command) -> VmResult<(String, String)> {
56    #[cfg(windows)]
57    {
58        exec_cmd_astr(cmd)
59    }
60    #[cfg(not(windows))]
61    {
62        exec_cmd_utf8(cmd)
63    }
64}
65
66#[allow(dead_code)]
67/// Executes `cmd` and Returns `(stdout, stderr)`.
68pub(crate) fn exec_cmd_utf8(cmd: &mut Command) -> VmResult<(String, String)> {
69    match cmd.output() {
70        Ok(o) => Ok((
71            String::from_utf8(o.stdout)
72                .map_err(|e| VmError::from(ErrorKind::FromUtf8Error(e)))?,
73            String::from_utf8(o.stderr)
74                .map_err(|e| VmError::from(ErrorKind::FromUtf8Error(e)))?,
75        )),
76        Err(x) => vmerr!(ErrorKind::ExecutionFailed(x.to_string())),
77    }
78}