android_tools/aapt2/
convert.rs

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