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 semver::Version;
23 use thiserror::Error;
24
25 mod android_bp;
26 mod crate_collection;
27 mod crate_type;
28 mod crates_io;
29 mod license;
30 mod managed_crate;
31 mod managed_repo;
32 mod patch;
33 mod pseudo_crate;
34 mod upgradable;
35
36 pub use self::android_bp::maybe_build_cargo_embargo;
37 pub use self::managed_repo::ManagedRepo;
38
39 #[derive(Error, Debug)]
40 pub enum CrateError {
41 #[error("Virtual crate: {0}")]
42 VirtualCrate(PathBuf),
43
44 #[error("Duplicate crate version: {0} {1}")]
45 DuplicateCrateVersion(String, Version),
46 }
47
default_repo_root() -> Result<PathBuf>48 pub fn default_repo_root() -> Result<PathBuf> {
49 let cwd = current_dir().context("Could not get current working directory")?;
50 for cur in cwd.ancestors() {
51 for e in cur.read_dir()? {
52 if e?.file_name() == ".repo" {
53 return Ok(cur.to_path_buf());
54 }
55 }
56 }
57 Err(anyhow!(".repo directory not found in any ancestor of {}", cwd.display()))
58 }
59
ensure_exists_and_empty(dir: impl AsRef<Path>) -> Result<()>60 pub fn ensure_exists_and_empty(dir: impl AsRef<Path>) -> Result<()> {
61 let dir = dir.as_ref();
62 if dir.exists() {
63 remove_dir_all(dir).context(format!("Failed to remove {}", dir.display()))?;
64 }
65 create_dir_all(dir).context(format!("Failed to create {}", dir.display()))
66 }
67
68 pub trait RunQuiet {
run_quiet_and_expect_success(&mut self) -> Result<Output>69 fn run_quiet_and_expect_success(&mut self) -> Result<Output>;
70 }
71 impl RunQuiet for Command {
run_quiet_and_expect_success(&mut self) -> Result<Output>72 fn run_quiet_and_expect_success(&mut self) -> Result<Output> {
73 self.output()
74 .context(format!("Failed to run {:?}", self))?
75 .success_or_error()
76 .context(format!("Failed to run {:?}", self))
77 }
78 }
79
80 pub trait SuccessOrError {
success_or_error(self) -> Result<Self> where Self: std::marker::Sized81 fn success_or_error(self) -> Result<Self>
82 where
83 Self: std::marker::Sized;
84 }
85 impl SuccessOrError for ExitStatus {
success_or_error(self) -> Result<Self>86 fn success_or_error(self) -> Result<Self> {
87 if !self.success() {
88 let exit_code =
89 self.code().map(|code| format!("{}", code)).unwrap_or("(unknown)".to_string());
90 Err(anyhow!("Process failed with exit code {}", exit_code))
91 } else {
92 Ok(self)
93 }
94 }
95 }
96 impl SuccessOrError for Output {
success_or_error(self) -> Result<Self>97 fn success_or_error(self) -> Result<Self> {
98 (&self).success_or_error()?;
99 Ok(self)
100 }
101 }
102 impl SuccessOrError for &Output {
success_or_error(self) -> Result<Self>103 fn success_or_error(self) -> Result<Self> {
104 if !self.status.success() {
105 let exit_code = self
106 .status
107 .code()
108 .map(|code| format!("{}", code))
109 .unwrap_or("(unknown)".to_string());
110 Err(anyhow!(
111 "Process failed with exit code {}\nstdout:\n{}\nstderr:\n{}",
112 exit_code,
113 from_utf8(&self.stdout)?,
114 from_utf8(&self.stderr)?
115 ))
116 } else {
117 Ok(self)
118 }
119 }
120 }
121
122 // The copy_dir crate doesn't handle symlinks.
copy_dir(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> Result<()>123 pub fn copy_dir(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> Result<()> {
124 Command::new("cp")
125 .arg("--archive")
126 .arg(src.as_ref())
127 .arg(dst.as_ref())
128 .run_quiet_and_expect_success()?;
129 Ok(())
130 }
131