Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,16 @@ and listed with their assets on the

## [Unreleased]

### Added

- **`prepare.link`** (ADR-0044, #159): directories `prepare` installs in a
lane's copy (`link = ["web/node_modules"]`) are linked into the lane's
worktree, a junction on Windows, so git hooks there (`npx eslint` in a
pre-commit hook) find them without a second `npm ci`. Only where the
worktree has nothing of that name; only when git ignores the link (write
`node_modules`, not `node_modules/`); removed when the lane stops. Stop the
lane before `git worktree remove`, which on Windows trips over a junction.

### Fixed

- Docs: a viewer of a shared lane reads its containers' logs, as it has
Expand Down
17 changes: 17 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ http-body-util = "0.1"
hyper = { version = "1", features = ["client", "server", "http1"] }
hyper-util = { version = "0.1", features = ["tokio"] }
include_dir = "0.7"
junction = { version = "2", default-features = false }
jiff = "0.2"
libc = "0.2"
notify = "8"
Expand Down
6 changes: 6 additions & 0 deletions crates/devstack-config/src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -618,6 +618,12 @@ pub struct Prepare {
/// empty: once per copy.
#[serde(default)]
pub inputs: Vec<String>,
/// Directories it installs that a lane's worktree gets linked to, e.g.
/// `["web/node_modules"]` (ADR-0044): the worktree's git hooks and
/// editor find them there. Relative to the repository; only where the
/// worktree has nothing of that name, and removed when the lane stops.
#[serde(default)]
pub link: Vec<String>,
}

/// Hot-reload mode of a built service: the toolchain's own watcher, from
Expand Down
13 changes: 13 additions & 0 deletions crates/devstack-config/src/validate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -493,6 +493,19 @@ pub fn validate(stack: &Stack) -> Vec<Issue> {
c.repo_path(&format!("{p}.prepare.cwd"), d);
}
c.globs(&format!("{p}.prepare.inputs"), &prep.inputs);
for l in &prep.link {
let at = format!("{p}.prepare.link");
c.literal(&at, l);
c.repo_path(&at, l);
if l.trim_matches(['/', '\\', '.']).is_empty() {
c.err(
&at,
format!(
"`{l}`: a directory below the repository, not the repository itself"
),
);
}
}
}
if svc.kind == Kind::Job && (svc.port.is_some() || svc.health.is_some()) {
c.err(
Expand Down
33 changes: 33 additions & 0 deletions crates/devstack-config/tests/stack_files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -664,6 +664,39 @@ fn a_dev_server_with_a_port_of_its_own_is_fronted() {
);
}

#[test]
fn prepare_links_are_directories_inside_the_repository() {
let ok = MINIMAL.replace(
"port = 5000",
"port = 5000
prepare = { run = \"npm ci\", link = [\"web/node_modules\"] }",
);
let stack = from_str(&ok, Path::new("test.toml")).expect("loads");
let link = &stack.services["api"].prepare.as_ref().unwrap().link;
assert_eq!(link, &["web/node_modules"]);
for bad in [
"../node_modules",
"/abs",
"C:/x",
".",
"{repo}/node_modules",
] {
let issues = invalid(&MINIMAL.replace(
"port = 5000",
&format!(
"port = 5000
prepare = {{ run = \"npm ci\", link = [\"{bad}\"] }}"
),
));
assert!(
issues
.iter()
.any(|i| i.contains("services.api.prepare.link")),
"{bad}: {issues:?}"
);
}
}

#[test]
fn working_directories_and_the_output_stay_inside_the_repository() {
let issues = invalid(&format!(
Expand Down
3 changes: 3 additions & 0 deletions crates/devstack-daemon/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ tokio.workspace = true
tokio-stream.workspace = true
ureq.workspace = true

[target.'cfg(windows)'.dependencies]
junction.workspace = true

[dev-dependencies]
tempfile.workspace = true

Expand Down
1 change: 1 addition & 0 deletions crates/devstack-daemon/src/lanes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1832,6 +1832,7 @@ impl Lanes {
let lanes: Vec<Arc<Lane>> = self.map.lock().unwrap().values().cloned().collect();
for l in lanes {
l.sup.down(false);
l.sup.unlink_prepared();
}
// A daemon that stops releases its lanes on nodes (ADR-0025 point 7).
let remote: Vec<Arc<RemoteLane>> = std::mem::take(&mut *self.remote.lock().unwrap())
Expand Down
1 change: 1 addition & 0 deletions crates/devstack-daemon/src/supervisor/artifacts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@ impl Supervisor {
self.run_prepare(name, job, cancel)?;
snap = self.snapshot.lock().unwrap();
}
self.link_prepared(name, svc);
let t0 = Instant::now();
let mut running = self
.builder
Expand Down
189 changes: 184 additions & 5 deletions crates/devstack-daemon/src/supervisor/copy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use devstack_build::Snapshot;
use devstack_config::model::Service;
use devstack_proc::Spec;
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;

Expand Down Expand Up @@ -58,7 +58,11 @@ impl Supervisor {
}
let key = h.finalize().to_hex().to_string();
let mark = self.layout.lane("main").join("prepared").join(name);
if std::fs::read_to_string(&mark).is_ok_and(|k| k == key) {
// A linked directory that is gone (a `git worktree remove` followed
// the link into it, ADR-0044) is prepared again.
let linked_there =
!self.links_prepared() || p.link.iter().all(|l| snap.dir.join(l).is_dir());
if linked_there && std::fs::read_to_string(&mark).is_ok_and(|k| k == key) {
return Ok(None);
}
Ok(Some(PrepareJob {
Expand Down Expand Up @@ -132,9 +136,99 @@ impl Supervisor {
snap.sync().map_err(|e| e.to_string())?;
self.prepare_job(name, svc, &snap)?
};
match job {
Some(job) => self.run_prepare(name, job, cancel),
None => Ok(()),
if let Some(job) = job {
self.run_prepare(name, job, cancel)?;
}
self.link_prepared(name, svc);
Ok(())
}

/// Whether what `prepare` installs is linked into the worktree
/// (ADR-0044): in a lane on this machine. The main tree runs in place
/// with its own; a lane on a node has no worktree there.
fn links_prepared(&self) -> bool {
!self.lane.is_empty() && !crate::remote_lane()
}

/// After `prepare` of `svc`: each of its `link` paths the worktree does
/// not have, linked to the prepared directory in the copy (a junction on
/// Windows, which needs no privilege), so the worktree's git hooks find
/// it (ADR-0044). What the worktree has already, a developer's own
/// install or a link of before, stays as it is. A link git does not
/// ignore is taken away again: `git add -A` would commit it.
pub(super) fn link_prepared(&self, name: &str, svc: &Service) {
let Some(p) = &svc.prepare else {
return;
};
if !self.links_prepared() {
return;
}
let copy = self.run_root();
for rel in &p.link {
let (link, target) = (self.repo.join(rel), copy.join(rel));
if std::fs::symlink_metadata(&link).is_ok() {
continue;
}
let not_linked = |why: String| {
crate::diag::warn(
"prepare_not_linked",
serde_json::json!({ "lane": self.lane, "service": name, "path": rel, "why": why }),
);
};
if !target.is_dir() {
not_linked(format!(
"`prepare` made no directory `{rel}` in the lane's copy"
));
continue;
}
if !link.parent().is_some_and(Path::is_dir) {
not_linked("its parent directory is not in the worktree".into());
continue;
}
if let Err(e) = make_link(&target, &link) {
not_linked(e.to_string());
continue;
}
if !git_ignores(&self.repo, rel) {
let _ = remove_link(&link);
not_linked(format!(
"git does not ignore `{rel}` as a link: ignore it without a trailing slash (`node_modules`, not `node_modules/`)"
));
continue;
}
crate::diag::info(
"prepare_linked",
serde_json::json!({ "lane": self.lane, "service": name, "path": rel }),
);
}
}

/// The links [`Self::link_prepared`] made, removed: a lane that stops
/// leaves no link in its worktree for `git worktree remove` to follow
/// into its copy (ADR-0044). Only links to the copy; anything else at
/// those paths is the developer's.
pub(crate) fn unlink_prepared(&self) {
if !self.links_prepared() {
return;
}
let copy = self.run_root();
for rel in self
.stack
.services
.values()
.filter_map(|s| s.prepare.as_ref())
.flat_map(|p| &p.link)
{
let link = self.repo.join(rel);
if !links_to(&link, &copy.join(rel)) {
continue;
}
let r = remove_link(&link);
crate::diag::info(
"prepare_unlinked",
serde_json::json!({ "lane": self.lane, "path": rel,
"error": r.err().map(|e| e.to_string()) }),
);
}
}

Expand Down Expand Up @@ -210,3 +304,88 @@ pub(super) struct PrepareJob {
cwd: PathBuf,
run: String,
}

/// A directory link at `link` to `target`: a junction on Windows (no
/// privilege needed, unlike a symbolic link), a symbolic link elsewhere.
fn make_link(target: &Path, link: &Path) -> std::io::Result<()> {
#[cfg(windows)]
return junction::create(target, link);
#[cfg(not(windows))]
return std::os::unix::fs::symlink(target, link);
}

/// Removes the link itself, never what it points to.
fn remove_link(link: &Path) -> std::io::Result<()> {
// A junction is a directory to Windows; removing it leaves its target.
if cfg!(windows) {
std::fs::remove_dir(link)
} else {
std::fs::remove_file(link)
}
}

/// Is `link` a link (a junction on Windows) to `target`?
fn links_to(link: &Path, target: &Path) -> bool {
let is_link = std::fs::symlink_metadata(link).is_ok_and(|m| m.file_type().is_symlink());
let norm = |p: &Path| {
let s = p.to_string_lossy().replace('\\', "/");
let s = s
.strip_prefix("//?/")
.or_else(|| s.strip_prefix("/??/"))
.unwrap_or(&s)
.trim_end_matches('/')
.to_string();
if cfg!(windows) { s.to_lowercase() } else { s }
};
is_link && std::fs::read_link(link).is_ok_and(|t| norm(&t) == norm(target))
}

/// Does git ignore `rel` in `repo` as it is now? Unknown counts as no.
fn git_ignores(repo: &Path, rel: &str) -> bool {
std::process::Command::new("git")
.args(["ls-files", "-o", "--exclude-standard", "-z", "--", rel])
.current_dir(repo)
.output()
.is_ok_and(|o| o.status.success() && o.stdout.is_empty())
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn a_link_points_at_its_target_and_goes_without_it() {
let d = tempfile::tempdir().unwrap();
let target = d.path().join("copy").join("node_modules");
std::fs::create_dir_all(&target).unwrap();
std::fs::write(target.join("x.js"), "1").unwrap();
let link = d.path().join("node_modules");
make_link(&target, &link).unwrap();
assert!(link.join("x.js").is_file());
assert!(links_to(&link, &target));
assert!(!links_to(&link, &d.path().join("elsewhere")));
assert!(!links_to(&target, &target), "a directory is no link");
remove_link(&link).unwrap();
assert!(std::fs::symlink_metadata(&link).is_err());
assert!(target.join("x.js").is_file(), "the target stays");
}

#[test]
fn a_link_git_does_not_ignore_is_seen() {
let d = tempfile::tempdir().unwrap();
let (repo, target) = (d.path().join("repo"), d.path().join("copy"));
std::fs::create_dir_all(repo.join("web")).unwrap();
std::fs::create_dir_all(&target).unwrap();
std::fs::write(target.join("x.js"), "1").unwrap();
let init = std::process::Command::new("git")
.args(["init", "-q"])
.current_dir(&repo)
.status()
.unwrap();
assert!(init.success());
make_link(&target, &repo.join("web/node_modules")).unwrap();
assert!(!git_ignores(&repo, "web/node_modules"));
std::fs::write(repo.join(".gitignore"), "node_modules\n").unwrap();
assert!(git_ignores(&repo, "web/node_modules"));
}
}
1 change: 1 addition & 0 deletions crates/devstack-daemon/src/supervisor/handover.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ impl Supervisor {
/// A removed lane: stop its services, release its ports, end its threads.
pub(crate) fn close(&self) {
self.down(false);
self.unlink_prepared();
self.closed.store(true, Ordering::SeqCst);
for (_, p) in std::mem::take(&mut *self.proxies.lock().unwrap()) {
p.close();
Expand Down
Loading