]> git.lizzy.rs Git - rust.git/blob - src/tools/build-manifest/src/versions.rs
build-manifest: refactor detecting package versions
[rust.git] / src / tools / build-manifest / src / versions.rs
1 use anyhow::{Context, Error};
2 use flate2::read::GzDecoder;
3 use std::collections::HashMap;
4 use std::fs::File;
5 use std::io::Read;
6 use std::path::{Path, PathBuf};
7 use tar::Archive;
8
9 const DEFAULT_TARGET: &str = "x86_64-unknown-linux-gnu";
10
11 #[derive(Debug, Hash, Eq, PartialEq, Clone)]
12 pub(crate) enum PkgType {
13     Rust,
14     RustSrc,
15     Cargo,
16     Rls,
17     RustAnalyzer,
18     Clippy,
19     Rustfmt,
20     LlvmTools,
21     Miri,
22     Other(String),
23 }
24
25 impl PkgType {
26     pub(crate) fn from_component(component: &str) -> Self {
27         match component {
28             "rust" => PkgType::Rust,
29             "rust-src" => PkgType::RustSrc,
30             "cargo" => PkgType::Cargo,
31             "rls" | "rls-preview" => PkgType::Rls,
32             "rust-analyzer" | "rust-analyzer-preview" => PkgType::RustAnalyzer,
33             "clippy" | "clippy-preview" => PkgType::Clippy,
34             "rustfmt" | "rustfmt-preview" => PkgType::Rustfmt,
35             "llvm-tools" | "llvm-tools-preview" => PkgType::LlvmTools,
36             "miri" | "miri-preview" => PkgType::Miri,
37             other => PkgType::Other(other.into()),
38         }
39     }
40
41     fn rust_monorepo_path(&self) -> Option<&'static str> {
42         match self {
43             PkgType::Cargo => Some("src/tools/cargo"),
44             PkgType::Rls => Some("src/tools/rls"),
45             PkgType::RustAnalyzer => Some("src/tools/rust-analyzer/crates/rust-analyzer"),
46             PkgType::Clippy => Some("src/tools/clippy"),
47             PkgType::Rustfmt => Some("src/tools/rustfmt"),
48             PkgType::Miri => Some("src/tools/miri"),
49             PkgType::Rust => None,
50             PkgType::RustSrc => None,
51             PkgType::LlvmTools => None,
52             PkgType::Other(_) => None,
53         }
54     }
55
56     fn tarball_component_name(&self) -> &str {
57         match self {
58             PkgType::Rust => "rust",
59             PkgType::RustSrc => "rust-src",
60             PkgType::Cargo => "cargo",
61             PkgType::Rls => "rls",
62             PkgType::RustAnalyzer => "rust-analyzer",
63             PkgType::Clippy => "clippy",
64             PkgType::Rustfmt => "rustfmt",
65             PkgType::LlvmTools => "llvm-tools",
66             PkgType::Miri => "miri",
67             PkgType::Other(component) => component,
68         }
69     }
70
71     fn should_use_rust_version(&self) -> bool {
72         match self {
73             PkgType::Cargo => false,
74             PkgType::Rls => false,
75             PkgType::RustAnalyzer => false,
76             PkgType::Clippy => false,
77             PkgType::Rustfmt => false,
78             PkgType::LlvmTools => false,
79             PkgType::Miri => false,
80
81             PkgType::Rust => true,
82             PkgType::RustSrc => true,
83             PkgType::Other(_) => true,
84         }
85     }
86 }
87
88 #[derive(Debug, Default, Clone)]
89 pub(crate) struct VersionInfo {
90     pub(crate) version: Option<String>,
91     pub(crate) git_commit: Option<String>,
92     pub(crate) present: bool,
93 }
94
95 pub(crate) struct Versions {
96     channel: String,
97     rustc_version: String,
98     monorepo_root: PathBuf,
99     dist_path: PathBuf,
100     package_versions: HashMap<PkgType, String>,
101     versions: HashMap<PkgType, VersionInfo>,
102 }
103
104 impl Versions {
105     pub(crate) fn new(
106         channel: &str,
107         dist_path: &Path,
108         monorepo_root: &Path,
109     ) -> Result<Self, Error> {
110         Ok(Self {
111             channel: channel.into(),
112             rustc_version: std::fs::read_to_string(monorepo_root.join("src").join("version"))
113                 .context("failed to read the rustc version from src/version")?
114                 .trim()
115                 .to_string(),
116             monorepo_root: monorepo_root.into(),
117             dist_path: dist_path.into(),
118             package_versions: HashMap::new(),
119             versions: HashMap::new(),
120         })
121     }
122
123     pub(crate) fn channel(&self) -> &str {
124         &self.channel
125     }
126
127     pub(crate) fn version(&mut self, mut package: &PkgType) -> Result<VersionInfo, Error> {
128         if package.should_use_rust_version() {
129             package = &PkgType::Rust;
130         }
131
132         match self.versions.get(package) {
133             Some(version) => Ok(version.clone()),
134             None => {
135                 let version_info = self.load_version_from_tarball(package)?;
136                 self.versions.insert(package.clone(), version_info.clone());
137                 Ok(version_info)
138             }
139         }
140     }
141
142     fn load_version_from_tarball(&mut self, package: &PkgType) -> Result<VersionInfo, Error> {
143         let tarball_name = self.tarball_name(package, DEFAULT_TARGET)?;
144         let tarball = self.dist_path.join(tarball_name);
145
146         let file = match File::open(&tarball) {
147             Ok(file) => file,
148             Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
149                 // Missing tarballs do not return an error, but return empty data.
150                 return Ok(VersionInfo::default());
151             }
152             Err(err) => return Err(err.into()),
153         };
154         let mut tar = Archive::new(GzDecoder::new(file));
155
156         let mut version = None;
157         let mut git_commit = None;
158         for entry in tar.entries()? {
159             let mut entry = entry?;
160
161             let dest;
162             match entry.path()?.components().nth(1).and_then(|c| c.as_os_str().to_str()) {
163                 Some("version") => dest = &mut version,
164                 Some("git-commit-hash") => dest = &mut git_commit,
165                 _ => continue,
166             }
167             let mut buf = String::new();
168             entry.read_to_string(&mut buf)?;
169             *dest = Some(buf);
170
171             // Short circuit to avoid reading the whole tar file if not necessary.
172             if version.is_some() && git_commit.is_some() {
173                 break;
174             }
175         }
176
177         Ok(VersionInfo { version, git_commit, present: true })
178     }
179
180     pub(crate) fn disable_version(&mut self, package: &PkgType) {
181         match self.versions.get_mut(package) {
182             Some(version) => {
183                 *version = VersionInfo::default();
184             }
185             None => {
186                 self.versions.insert(package.clone(), VersionInfo::default());
187             }
188         }
189     }
190
191     pub(crate) fn tarball_name(
192         &mut self,
193         package: &PkgType,
194         target: &str,
195     ) -> Result<String, Error> {
196         Ok(format!(
197             "{}-{}-{}.tar.gz",
198             package.tarball_component_name(),
199             self.package_version(package).with_context(|| format!(
200                 "failed to get the package version for component {:?}",
201                 package,
202             ))?,
203             target
204         ))
205     }
206
207     pub(crate) fn package_version(&mut self, package: &PkgType) -> Result<String, Error> {
208         match self.package_versions.get(package) {
209             Some(release) => Ok(release.clone()),
210             None => {
211                 let version = match package.rust_monorepo_path() {
212                     Some(path) => {
213                         let path = self.monorepo_root.join(path).join("Cargo.toml");
214                         let cargo_toml: CargoToml = toml::from_slice(&std::fs::read(path)?)?;
215                         cargo_toml.package.version
216                     }
217                     None => self.rustc_version.clone(),
218                 };
219
220                 let release = match self.channel.as_str() {
221                     "stable" => version,
222                     "beta" => "beta".into(),
223                     "nightly" => "nightly".into(),
224                     _ => format!("{}-dev", version),
225                 };
226
227                 self.package_versions.insert(package.clone(), release.clone());
228                 Ok(release)
229             }
230         }
231     }
232 }
233
234 #[derive(serde::Deserialize)]
235 struct CargoToml {
236     package: CargoTomlPackage,
237 }
238
239 #[derive(serde::Deserialize)]
240 struct CargoTomlPackage {
241     version: String,
242 }