| @@ -0,0 +1,429 @@ |
| 1 | +//! tilcayo packages (ADR 0020). A package is a directory holding a |
| 2 | +//! `tilcayo.toml` ([`manifest`]), its modules under `src/` and its tests |
| 3 | +//! under `test/`. This crate finds a package ([`find_package_root`]) and |
| 4 | +//! resolves it ([`resolve`]): from a root package to every package of the |
| 5 | +//! build, with git dependencies checked out ([`git`]) at the commits the |
| 6 | +//! lockfile records ([`lock`]). It knows nothing of tilcayo code: |
| 7 | +//! `tilc_db` loads the packages' modules, and `tilc_build` builds their |
| 8 | +//! native dependencies. |
| 9 | +//! |
| 10 | +//! **One version per package.** The modules of a dependency are named after |
| 11 | +//! it (`json`, `json/...`) in a single namespace, so a build holds at most |
| 12 | +//! one package per name, and one commit per git URL. Requirements that |
| 13 | +//! disagree are an error that names both requesters; nothing is chosen |
| 14 | +//! silently. |
| 15 | + |
| 16 | +pub mod git; |
| 17 | +pub mod lock; |
| 18 | +pub mod manifest; |
| 19 | + |
| 20 | +use std::collections::VecDeque; |
| 21 | +use std::path::{Path, PathBuf}; |
| 22 | + |
| 23 | +use lock::{LOCKFILE, Lock, Locked, short}; |
| 24 | +use manifest::{Dependency, GitRef, Manifest, NativeDep, Source}; |
| 25 | + |
| 26 | +/// Marks a package root. |
| 27 | +pub const MANIFEST: &str = "tilcayo.toml"; |
| 28 | + |
| 29 | +/// The nearest ancestor of `start` (inclusive) containing `tilcayo.toml`. |
| 30 | +pub fn find_package_root(start: &Path) -> Option<PathBuf> { |
| 31 | + let start = if start.is_file() { |
| 32 | + start.parent()? |
| 33 | + } else { |
| 34 | + start |
| 35 | + }; |
| 36 | + start |
| 37 | + .ancestors() |
| 38 | + .find(|dir| dir.join(MANIFEST).is_file()) |
| 39 | + .map(Path::to_path_buf) |
| 40 | +} |
| 41 | + |
| 42 | +/// How to resolve. |
| 43 | +#[derive(Debug, Clone, Default)] |
| 44 | +pub struct Options { |
| 45 | + /// Use the cache only; never run `git fetch`. |
| 46 | + pub offline: bool, |
| 47 | + pub lock: LockMode, |
| 48 | + pub update: Update, |
| 49 | + /// The cache's parent directory (default: see [`git::Cache::new`]). |
| 50 | + pub home: Option<PathBuf>, |
| 51 | +} |
| 52 | + |
| 53 | +impl Options { |
| 54 | + /// What the language server uses: the lockfile and the cache as they |
| 55 | + /// are, without fetching or writing anything. |
| 56 | + pub fn cached() -> Options { |
| 57 | + Options { |
| 58 | + offline: true, |
| 59 | + lock: LockMode::ReadOnly, |
| 60 | + ..Options::default() |
| 61 | + } |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +/// What to do when the resolved commits differ from the lockfile. |
| 66 | +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 67 | +pub enum LockMode { |
| 68 | + /// Write the new lockfile. |
| 69 | + #[default] |
| 70 | + Write, |
| 71 | + /// Fail (`--locked`, for CI). |
| 72 | + Check, |
| 73 | + /// Leave it. |
| 74 | + ReadOnly, |
| 75 | +} |
| 76 | + |
| 77 | +/// Which git dependencies ignore their locked commit (`tilc update`). |
| 78 | +#[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 79 | +pub enum Update { |
| 80 | + #[default] |
| 81 | + None, |
| 82 | + All, |
| 83 | + Only(String), |
| 84 | +} |
| 85 | + |
| 86 | +/// Every package of a build. |
| 87 | +#[derive(Debug)] |
| 88 | +pub struct Resolution { |
| 89 | + /// The root package first, then its dependencies, breadth first. |
| 90 | + pub packages: Vec<Package>, |
| 91 | + /// What changed in the lockfile, one line per package. |
| 92 | + pub changes: Vec<String>, |
| 93 | +} |
| 94 | + |
| 95 | +#[derive(Debug)] |
| 96 | +pub struct Package { |
| 97 | + /// The name its modules have: the root's `[package] name`, else the |
| 98 | + /// dependency's name. |
| 99 | + pub name: String, |
| 100 | + /// Its root is the checkout of a git dependency. |
| 101 | + pub manifest: Manifest, |
| 102 | +} |
| 103 | + |
| 104 | +impl Resolution { |
| 105 | + pub fn root(&self) -> &Package { |
| 106 | + &self.packages[0] |
| 107 | + } |
| 108 | + |
| 109 | + /// The native dependencies of every package (ADR 0005). |
| 110 | + pub fn natives(&self) -> Vec<NativeDep> { |
| 111 | + self.packages |
| 112 | + .iter() |
| 113 | + .flat_map(|p| p.manifest.native.iter().cloned()) |
| 114 | + .collect() |
| 115 | + } |
| 116 | +} |
| 117 | + |
| 118 | +/// Resolve the package at `root` and its dependencies, transitively. |
| 119 | +/// Depending on `opts`, this fetches git repositories and writes the |
| 120 | +/// lockfile. |
| 121 | +pub fn resolve(root: &Path, opts: &Options) -> Result<Resolution, String> { |
| 122 | + let manifest = manifest::load(root)?; |
| 123 | + let lock_path = root.join(LOCKFILE); |
| 124 | + let old = Lock::read(&lock_path)?; |
| 125 | + let mut resolver = Resolver { |
| 126 | + opts, |
| 127 | + old: old.clone().unwrap_or_default(), |
| 128 | + new: Lock::default(), |
| 129 | + cache: None, |
| 130 | + fetched: Vec::new(), |
| 131 | + seen: Vec::new(), |
| 132 | + packages: Vec::new(), |
| 133 | + }; |
| 134 | + resolver.walk(manifest)?; |
| 135 | + let mut new = resolver.new; |
| 136 | + new.packages.sort(); |
| 137 | + if let Update::Only(name) = &opts.update |
| 138 | + && !new.packages.iter().any(|p| p.name == *name) |
| 139 | + { |
| 140 | + return Err(format!("no git dependency is named `{name}`")); |
| 141 | + } |
| 142 | + let old = old.unwrap_or_default(); |
| 143 | + let changes = old.changes(&new); |
| 144 | + if !changes.is_empty() { |
| 145 | + match opts.lock { |
| 146 | + LockMode::Write => new.write(&lock_path)?, |
| 147 | + LockMode::Check => { |
| 148 | + return Err(format!( |
| 149 | + "{LOCKFILE} is out of date, and --locked forbids updating it:\n {}\nbuild without --locked, or run `tilc update`, then commit {LOCKFILE}", |
| 150 | + changes.join("\n ") |
| 151 | + )); |
| 152 | + } |
| 153 | + LockMode::ReadOnly => {} |
| 154 | + } |
| 155 | + } |
| 156 | + Ok(Resolution { |
| 157 | + packages: resolver.packages, |
| 158 | + changes, |
| 159 | + }) |
| 160 | +} |
| 161 | + |
| 162 | +struct Resolver<'a> { |
| 163 | + opts: &'a Options, |
| 164 | + old: Lock, |
| 165 | + new: Lock, |
| 166 | + cache: Option<git::Cache>, |
| 167 | + /// (URL, whether `HEAD` was fetched too): each is fetched once per run. |
| 168 | + fetched: Vec<(String, bool)>, |
| 169 | + /// `seen[i]` describes `packages[i]`. |
| 170 | + seen: Vec<Seen>, |
| 171 | + packages: Vec<Package>, |
| 172 | +} |
| 173 | + |
| 174 | +/// A package already in the build, and who asked for it. |
| 175 | +struct Seen { |
| 176 | + name: String, |
| 177 | + identity: Identity, |
| 178 | + required_by: String, |
| 179 | + /// The request, as the user wrote it (`tag v1`, `path ../x`). |
| 180 | + request: String, |
| 181 | + /// The checkout it lives in, if it came from git: its path dependencies |
| 182 | + /// must stay inside. |
| 183 | + checkout: Option<PathBuf>, |
| 184 | +} |
| 185 | + |
| 186 | +#[derive(Clone, PartialEq, Eq)] |
| 187 | +enum Identity { |
| 188 | + /// The canonical package root. |
| 189 | + Path(PathBuf), |
| 190 | + Git { |
| 191 | + url: String, |
| 192 | + commit: String, |
| 193 | + }, |
| 194 | +} |
| 195 | + |
| 196 | +impl Identity { |
| 197 | + /// Whether both are the same package, at any version. |
| 198 | + fn same_package(&self, other: &Identity) -> bool { |
| 199 | + match (self, other) { |
| 200 | + (Identity::Git { url: a, .. }, Identity::Git { url: b, .. }) => a == b, |
| 201 | + _ => self == other, |
| 202 | + } |
| 203 | + } |
| 204 | + |
| 205 | + fn describe(&self) -> String { |
| 206 | + match self { |
| 207 | + Identity::Path(p) => p.display().to_string(), |
| 208 | + Identity::Git { url, commit } => format!("{url} at {}", short(commit)), |
| 209 | + } |
| 210 | + } |
| 211 | +} |
| 212 | + |
| 213 | +impl Resolver<'_> { |
| 214 | + fn walk(&mut self, root: Manifest) -> Result<(), String> { |
| 215 | + let identity = Identity::Path(canonical(&root.root)?); |
| 216 | + self.seen.push(Seen { |
| 217 | + name: root.name.clone(), |
| 218 | + identity, |
| 219 | + required_by: String::new(), |
| 220 | + request: "the root package".into(), |
| 221 | + checkout: None, |
| 222 | + }); |
| 223 | + self.packages.push(Package { |
| 224 | + name: root.name.clone(), |
| 225 | + manifest: root, |
| 226 | + }); |
| 227 | + let mut queue = VecDeque::from([0]); |
| 228 | + while let Some(index) = queue.pop_front() { |
| 229 | + let parent = &self.packages[index]; |
| 230 | + let (parent_name, checkout) = (parent.name.clone(), self.seen[index].checkout.clone()); |
| 231 | + for dep in parent.manifest.dependencies.clone() { |
| 232 | + if let Some(added) = self.add(&dep, &parent_name, checkout.as_deref())? { |
| 233 | + queue.push_back(added); |
| 234 | + } |
| 235 | + } |
| 236 | + } |
| 237 | + Ok(()) |
| 238 | + } |
| 239 | + |
| 240 | + /// Add the dependency `dep` of package `parent` (whose files are in the |
| 241 | + /// git checkout `checkout`, if any). Returns its index if it is new. |
| 242 | + fn add( |
| 243 | + &mut self, |
| 244 | + dep: &Dependency, |
| 245 | + parent: &str, |
| 246 | + checkout: Option<&Path>, |
| 247 | + ) -> Result<Option<usize>, String> { |
| 248 | + let (identity, root, request, dep_checkout) = match &dep.source { |
| 249 | + Source::Path(path) => { |
| 250 | + let c = canonical(path) |
| 251 | + .map_err(|e| format!("dependency `{}` of `{parent}`: {e}", dep.name))?; |
| 252 | + if let Some(checkout) = checkout |
| 253 | + && !c.starts_with(checkout) |
| 254 | + { |
| 255 | + return Err(format!( |
| 256 | + "dependency `{}` of `{parent}`: the path {} leaves the git repository `{parent}` comes from", |
| 257 | + dep.name, |
| 258 | + path.display() |
| 259 | + )); |
| 260 | + } |
| 261 | + let request = format!("path {}", path.display()); |
| 262 | + ( |
| 263 | + Identity::Path(c), |
| 264 | + path.clone(), |
| 265 | + request, |
| 266 | + checkout.map(Path::to_path_buf), |
| 267 | + ) |
| 268 | + } |
| 269 | + Source::Git { url, reference } => { |
| 270 | + let commit = self.commit(&dep.name, url, reference)?; |
| 271 | + let dir = self.cache()?.repo(url).checkout(&commit)?; |
| 272 | + let identity = Identity::Git { |
| 273 | + url: url.clone(), |
| 274 | + commit, |
| 275 | + }; |
| 276 | + let request = reference.to_string(); |
| 277 | + (identity, dir.clone(), request, Some(canonical(&dir)?)) |
| 278 | + } |
| 279 | + }; |
| 280 | + if let Some(seen) = self |
| 281 | + .seen |
| 282 | + .iter() |
| 283 | + .find(|s| s.name == dep.name || s.identity.same_package(&identity)) |
| 284 | + { |
| 285 | + if seen.name == dep.name && seen.identity == identity { |
| 286 | + return Ok(None); |
| 287 | + } |
| 288 | + return Err(self.conflict(seen, dep, parent, &request, &identity)); |
| 289 | + } |
| 290 | + let manifest = manifest::load(&root)?; |
| 291 | + self.seen.push(Seen { |
| 292 | + name: dep.name.clone(), |
| 293 | + identity, |
| 294 | + required_by: parent.to_owned(), |
| 295 | + request, |
| 296 | + checkout: dep_checkout, |
| 297 | + }); |
| 298 | + self.packages.push(Package { |
| 299 | + name: dep.name.clone(), |
| 300 | + manifest, |
| 301 | + }); |
| 302 | + Ok(Some(self.packages.len() - 1)) |
| 303 | + } |
| 304 | + |
| 305 | + fn conflict( |
| 306 | + &self, |
| 307 | + seen: &Seen, |
| 308 | + dep: &Dependency, |
| 309 | + parent: &str, |
| 310 | + request: &str, |
| 311 | + identity: &Identity, |
| 312 | + ) -> String { |
| 313 | + let requirement = |by: &str, request: &str, identity: &Identity| { |
| 314 | + if by.is_empty() { |
| 315 | + format!("the root package is {}", identity.describe()) |
| 316 | + } else { |
| 317 | + format!("`{by}` requires {request}: {}", identity.describe()) |
| 318 | + } |
| 319 | + }; |
| 320 | + let both = format!( |
| 321 | + " {}\n {}", |
| 322 | + requirement(&seen.required_by, &seen.request, &seen.identity), |
| 323 | + requirement(parent, request, identity) |
| 324 | + ); |
| 325 | + let headline = if seen.name != dep.name { |
| 326 | + format!( |
| 327 | + "the same package is required under two names, `{}` and `{}`", |
| 328 | + seen.name, dep.name |
| 329 | + ) |
| 330 | + } else if seen.identity.same_package(identity) { |
| 331 | + format!("conflicting versions of `{}`", dep.name) |
| 332 | + } else { |
| 333 | + format!("two different packages are named `{}`", dep.name) |
| 334 | + }; |
| 335 | + format!( |
| 336 | + "{headline}:\n{both}\na build holds one version of each package: make these requirements agree (ADR 0020)" |
| 337 | + ) |
| 338 | + } |
| 339 | + |
| 340 | + /// The commit a git dependency uses: the locked one, unless it is being |
| 341 | + /// updated or the request changed; otherwise what the reference names |
| 342 | + /// now. |
| 343 | + fn commit(&mut self, name: &str, url: &str, reference: &GitRef) -> Result<String, String> { |
| 344 | + // The same request, made again by another package. |
| 345 | + if let Some(commit) = self.new.find(name, url, reference) { |
| 346 | + return Ok(commit.to_owned()); |
| 347 | + } |
| 348 | + let updating = match &self.opts.update { |
| 349 | + Update::None => false, |
| 350 | + Update::All => true, |
| 351 | + Update::Only(n) => n == name, |
| 352 | + }; |
| 353 | + let locked = if updating { |
| 354 | + None |
| 355 | + } else { |
| 356 | + self.old.find(name, url, reference).map(str::to_owned) |
| 357 | + }; |
| 358 | + let offline = self.opts.offline; |
| 359 | + let commit = match locked { |
| 360 | + Some(commit) => { |
| 361 | + if !self.cache()?.repo(url).has_commit(&commit) { |
| 362 | + self.fetch(url, reference)?; |
| 363 | + } |
| 364 | + if !self.cache()?.repo(url).has_commit(&commit) { |
| 365 | + return Err(if offline { |
| 366 | + format!( |
| 367 | + "`{name}`: the locked commit {commit} of {url} is not in the cache, and --offline forbids fetching it" |
| 368 | + ) |
| 369 | + } else { |
| 370 | + format!( |
| 371 | + "`{name}`: {url} has no commit {commit}, which {LOCKFILE} records; `tilc update {name}` re-resolves it" |
| 372 | + ) |
| 373 | + }); |
| 374 | + } |
| 375 | + commit |
| 376 | + } |
| 377 | + None => { |
| 378 | + // A commit id never moves: no need to fetch one already here. |
| 379 | + let cached = matches!(reference, GitRef::Rev(_)) |
| 380 | + && self.cache()?.repo(url).resolve(reference)?.is_some(); |
| 381 | + if !cached { |
| 382 | + self.fetch(url, reference)?; |
| 383 | + } |
| 384 | + self.cache()? |
| 385 | + .repo(url) |
| 386 | + .resolve(reference)? |
| 387 | + .ok_or_else(|| { |
| 388 | + if offline { |
| 389 | + format!( |
| 390 | + "`{name}`: {reference} of {url} is not in the cache, and --offline forbids fetching it" |
| 391 | + ) |
| 392 | + } else { |
| 393 | + format!("`{name}`: {url} has no {reference}") |
| 394 | + } |
| 395 | + })? |
| 396 | + } |
| 397 | + }; |
| 398 | + self.new.packages.push(Locked { |
| 399 | + name: name.to_owned(), |
| 400 | + url: url.to_owned(), |
| 401 | + reference: reference.clone(), |
| 402 | + commit: commit.clone(), |
| 403 | + }); |
| 404 | + Ok(commit) |
| 405 | + } |
| 406 | + |
| 407 | + /// Fetch `url` once per run, unless offline. |
| 408 | + fn fetch(&mut self, url: &str, reference: &GitRef) -> Result<(), String> { |
| 409 | + let key = (url.to_owned(), *reference == GitRef::DefaultBranch); |
| 410 | + if self.opts.offline || self.fetched.contains(&key) { |
| 411 | + return Ok(()); |
| 412 | + } |
| 413 | + self.cache()?.repo(url).fetch(reference)?; |
| 414 | + self.fetched.push(key); |
| 415 | + Ok(()) |
| 416 | + } |
| 417 | + |
| 418 | + fn cache(&mut self) -> Result<&git::Cache, String> { |
| 419 | + if self.cache.is_none() { |
| 420 | + self.cache = Some(git::Cache::new(self.opts.home.as_deref())?); |
| 421 | + } |
| 422 | + Ok(self.cache.as_ref().expect("just set")) |
| 423 | + } |
| 424 | +} |
| 425 | + |
| 426 | +fn canonical(path: &Path) -> Result<PathBuf, String> { |
| 427 | + path.canonicalize() |
| 428 | + .map_err(|e| format!("cannot read {}: {e}", path.display())) |
| 429 | +} |