• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (C) 2023 The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 use std::env::current_dir;
16 use std::fs::{create_dir_all, remove_dir_all};
17 use std::path::{Path, PathBuf};
18 use std::process::{Command, ExitStatus, Output};
19 use std::str::from_utf8;
20 
21 use anyhow::{anyhow, Context, Result};
22 use thiserror::Error;
23 
24 mod android_bp;
25 mod crate_collection;
26 mod crate_type;
27 mod crates_io;
28 mod license;
29 mod managed_crate;
30 mod managed_repo;
31 mod patch;
32 mod pseudo_crate;
33 mod upgradable;
34 
35 pub use self::android_bp::maybe_build_cargo_embargo;
36 pub use self::managed_repo::ManagedRepo;
37 pub use self::upgradable::SemverCompatibilityRule;
38 
39 #[derive(Error, Debug)]
40 pub enum CrateError {
41     #[error("Virtual crate: {0}")]
42     VirtualCrate(PathBuf),
43 }
44 
default_repo_root() -> Result<PathBuf>45 pub fn default_repo_root() -> Result<PathBuf> {
46     let cwd = current_dir().context("Could not get current working directory")?;
47     for cur in cwd.ancestors() {
48         for e in cur.read_dir()? {
49             if e?.file_name() == ".repo" {
50                 return Ok(cur.to_path_buf());
51             }
52         }
53     }
54     Err(anyhow!(".repo directory not found in any ancestor of {}", cwd.display()))
55 }
56 
ensure_exists_and_empty(dir: impl AsRef<Path>) -> Result<()>57 pub fn ensure_exists_and_empty(dir: impl AsRef<Path>) -> Result<()> {
58     let dir = dir.as_ref();
59     if dir.exists() {
60         remove_dir_all(dir).context(format!("Failed to remove {}", dir.display()))?;
61     }
62     create_dir_all(dir).context(format!("Failed to create {}", dir.display()))
63 }
64 
65 pub trait RunQuiet {
run_quiet_and_expect_success(&mut self) -> Result<Output>66     fn run_quiet_and_expect_success(&mut self) -> Result<Output>;
67 }
68 impl RunQuiet for Command {
run_quiet_and_expect_success(&mut self) -> Result<Output>69     fn run_quiet_and_expect_success(&mut self) -> Result<Output> {
70         self.output()
71             .context(format!("Failed to run {:?}", self))?
72             .success_or_error()
73             .context(format!("Failed to run {:?}", self))
74     }
75 }
76 
77 pub trait SuccessOrError {
success_or_error(self) -> Result<Self> where Self: std::marker::Sized78     fn success_or_error(self) -> Result<Self>
79     where
80         Self: std::marker::Sized;
81 }
82 impl SuccessOrError for ExitStatus {
success_or_error(self) -> Result<Self>83     fn success_or_error(self) -> Result<Self> {
84         if !self.success() {
85             let exit_code =
86                 self.code().map(|code| format!("{}", code)).unwrap_or("(unknown)".to_string());
87             Err(anyhow!("Process failed with exit code {}", exit_code))
88         } else {
89             Ok(self)
90         }
91     }
92 }
93 impl SuccessOrError for Output {
success_or_error(self) -> Result<Self>94     fn success_or_error(self) -> Result<Self> {
95         (&self).success_or_error()?;
96         Ok(self)
97     }
98 }
99 impl SuccessOrError for &Output {
success_or_error(self) -> Result<Self>100     fn success_or_error(self) -> Result<Self> {
101         if !self.status.success() {
102             let exit_code = self
103                 .status
104                 .code()
105                 .map(|code| format!("{}", code))
106                 .unwrap_or("(unknown)".to_string());
107             Err(anyhow!(
108                 "Process failed with exit code {}\nstdout:\n{}\nstderr:\n{}",
109                 exit_code,
110                 from_utf8(&self.stdout)?,
111                 from_utf8(&self.stderr)?
112             ))
113         } else {
114             Ok(self)
115         }
116     }
117 }
118 
119 // The copy_dir crate doesn't handle symlinks.
copy_dir(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> Result<()>120 pub fn copy_dir(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> Result<()> {
121     Command::new("cp")
122         .arg("--archive")
123         .arg(src.as_ref())
124         .arg(dst.as_ref())
125         .run_quiet_and_expect_success()?;
126     Ok(())
127 }
128