xref: /aosp_15_r20/external/toolchain-utils/llvm_tools/patch_sync/src/android_utils.rs (revision 760c253c1ed00ce9abd48f8546f08516e57485fe)
1 // Copyright 2022 The ChromiumOS Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 use std::path::Path;
6 use std::process::Command;
7 
8 use anyhow::{bail, ensure, Result};
9 
10 const LLVM_ANDROID_REL_PATH: &str = "toolchain/llvm_android";
11 
12 /// Return the Android checkout's current llvm version.
13 ///
14 /// This uses android_version.get_svn_revision_number, a python function
15 /// that can't be executed directly. We spawn a Python3 program
16 /// to run it and get the result from that.
get_android_llvm_version(android_checkout: &Path) -> Result<String>17 pub fn get_android_llvm_version(android_checkout: &Path) -> Result<String> {
18     let mut command = new_android_cmd(android_checkout, "python3")?;
19     command.args([
20         "-c",
21         "import android_version; print(android_version.get_svn_revision_number(), end='')",
22     ]);
23     let output = command.output()?;
24     if !output.status.success() {
25         bail!(
26             "could not get android llvm version: {}",
27             String::from_utf8_lossy(&output.stderr)
28         );
29     }
30     let out_string = String::from_utf8(output.stdout)?.trim().to_string();
31     Ok(out_string)
32 }
33 
34 /// Sort the Android patches using the cherrypick_cl.py Android utility.
35 ///
36 /// This assumes that:
37 ///   1. There exists a python script called cherrypick_cl.py
38 ///   2. That calling it with the given arguments sorts the PATCHES.json file.
39 ///   3. Calling it does nothing besides sorting the PATCHES.json file.
40 ///
41 /// We aren't doing our own sorting because we shouldn't have to update patch_sync along
42 /// with cherrypick_cl.py any time they change the __lt__ implementation.
sort_android_patches(android_checkout: &Path) -> Result<()>43 pub fn sort_android_patches(android_checkout: &Path) -> Result<()> {
44     let mut command = new_android_cmd(android_checkout, "python3")?;
45     command.args(["cherrypick_cl.py", "--reason", "patch_sync sorting"]);
46     let output = command.output()?;
47     if !output.status.success() {
48         bail!(
49             "could not sort: {}",
50             String::from_utf8_lossy(&output.stderr)
51         );
52     }
53     Ok(())
54 }
55 
new_android_cmd(android_checkout: &Path, cmd: &str) -> Result<Command>56 fn new_android_cmd(android_checkout: &Path, cmd: &str) -> Result<Command> {
57     let mut command = Command::new(cmd);
58     let llvm_android_dir = android_checkout.join(LLVM_ANDROID_REL_PATH);
59     ensure!(
60         llvm_android_dir.is_dir(),
61         "can't make android command; {} is not a directory",
62         llvm_android_dir.display()
63     );
64     command.current_dir(llvm_android_dir);
65     Ok(command)
66 }
67