android_tools_rs/aapt2/
convert.rs

1use crate::error::{CommandExt, Result};
2use std::{
3    path::{Path, PathBuf},
4    process::Command,
5};
6
7#[derive(Default)]
8pub struct Aapt2Convert {
9    output_path: PathBuf,
10    output_format: Option<OutputFormat>,
11    enable_sparse_encoding: bool,
12    keep_raw_values: bool,
13    verbose: bool,
14    help: bool,
15}
16
17impl Aapt2Convert {
18    /// Initialize struct Aapt2Convert and then specifies output path to convert
19    pub fn new(output_path: &Path) -> Self {
20        Self {
21            output_path: output_path.to_owned(),
22            ..Default::default()
23        }
24    }
25
26    /// Format of the output. Accepted values are 'proto' and 'binary'. When not set,
27    /// defaults to 'binary'
28    pub fn output_format(&mut self, output_format: OutputFormat) -> &mut Self {
29        self.output_format = Some(output_format);
30        self
31    }
32
33    /// Enables encoding sparse entries using a binary search tree. This decreases APK
34    /// size at the cost of resource retrieval performance
35    pub fn enable_sparse_encoding(&mut self, enable_sparse_encoding: bool) -> &mut Self {
36        self.enable_sparse_encoding = enable_sparse_encoding;
37        self
38    }
39
40    /// Preserve raw attribute values in xml files when using the 'binary' output format
41    pub fn keep_raw_values(&mut self, keep_raw_values: bool) -> &mut Self {
42        self.keep_raw_values = keep_raw_values;
43        self
44    }
45
46    /// Enables verbose logging
47    pub fn verbose(&mut self, verbose: bool) -> &mut Self {
48        self.verbose = verbose;
49        self
50    }
51
52    /// Displays this help menu
53    pub fn help(&mut self, help: bool) -> &mut Self {
54        self.help = help;
55        self
56    }
57
58    /// Opens the command line and launches aapt2 convert with arguments
59    pub fn run(&self) -> Result<()> {
60        let mut aapt2 = Command::new("aapt2");
61        aapt2.arg("convert");
62        aapt2.arg("-o").arg(&self.output_path);
63        if let Some(output_format) = &self.output_format {
64            aapt2.arg("--output-format").arg(output_format.to_string());
65        }
66        if self.enable_sparse_encoding {
67            aapt2.arg("--enable-sparse-encoding");
68        }
69        if self.keep_raw_values {
70            aapt2.arg("--keep-raw-values");
71        }
72        if self.verbose {
73            aapt2.arg("-v");
74        }
75        if self.help {
76            aapt2.arg("-h");
77        }
78        aapt2.output_err(true)?;
79        Ok(())
80    }
81}
82
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub enum OutputFormat {
85    Proto,
86    Binary,
87}
88
89impl std::fmt::Display for OutputFormat {
90    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91        match *self {
92            Self::Proto => write!(f, "proto"),
93            Self::Binary => write!(f, "binary"),
94        }
95    }
96}