android_tools/error.rs
1//! Contains `Error` type and `CommandExt` impl used by `android-tools-rs`.
2
3use displaydoc::Display;
4use std::{path::PathBuf, process::Command};
5use thiserror::Error;
6
7pub type Result<T> = std::result::Result<T, Error>;
8
9#[derive(Display, Debug, Error)]
10pub enum Error {
11 /// Android SDK or Android NDK is not found. Check the installation path or use crossbundle install command to install it
12 AndroidToolNotFound,
13 /// Android SDK is not found. Check the installation path or use crossbundle install command to install it
14 AndroidSdkNotFound,
15 /// Bundletool is not found. Check the installation path or use crossbundle install command to install it
16 BundletoolNotFound,
17 /// Unable to access to home directory or home directory doesn't exists
18 UnableToAccessHomeDirectory,
19 /// Path {0:?} doesn't exists
20 PathNotFound(PathBuf),
21 /// Command {0} is not found
22 CmdNotFound(String),
23 /// Command had a non-zero exit code. Stdout: {0} Stderr: {1}
24 CmdFailed(String, String),
25 /// Compiled resources is not found
26 CompiledResourcesNotFound,
27 /// IO error
28 Io(#[from] std::io::Error),
29}
30
31/// Extension trait for [`Command`] that helps
32/// to wrap output and print logs from command execution.
33///
34/// [`Command`](std::process::Command)
35pub trait CommandExt {
36 /// Executes the command as a child process, then captures an output and return it.
37 /// If command termination wasn't successful wraps an output into error and return it
38 fn output_err(self, print_logs: bool) -> Result<std::process::Output>;
39}
40
41impl CommandExt for Command {
42 fn output_err(mut self, print_logs: bool) -> Result<std::process::Output> {
43 // Enables log print during command execution
44 let output = match print_logs {
45 true => self.spawn().and_then(|p| p.wait_with_output())?,
46 false => self.output()?,
47 };
48 if !output.status.success() {
49 return Err(Error::CmdFailed(
50 String::from_utf8_lossy(&output.stdout).to_string(),
51 String::from_utf8_lossy(&output.stderr).to_string(),
52 ));
53 }
54 Ok(output)
55 }
56}