local-ci 0.20.0

Run the GitHub Actions jobs a branch would trigger, locally, in an isolated worktree, and print a short report
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
//! What one attempt (one call of [`crate::run`] or [`crate::execute_plan`])
//! needs from its host: the environment it sees, where it keeps its files, and
//! the handle that stops it.
//!
//! Nothing in the library reads the process environment; the caller builds an
//! [`ExecContext`] (the `local-ci` binary builds it from `std::env`). Give each
//! attempt its own context: the processes and containers an attempt starts are
//! tracked in its [`CancelHandle`], so cancelling one attempt leaves the others
//! running.

use std::collections::BTreeMap;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, OnceLock};

#[derive(Default)]
struct CancelState {
    cancelled: AtomicBool,
    pgids: Mutex<Vec<i32>>,
    native_uncertain: Mutex<Vec<u32>>,
    containers: Mutex<Vec<String>>,
    creation_candidates: Mutex<Vec<String>>,
    unverified_compose: Mutex<Vec<String>>,
    pending_ports: Mutex<Vec<PathBuf>>,
    external_executor: AtomicBool,
    compose_projects: Mutex<Vec<String>>,
}

/// Cancellation and child tracking owned by one attempt. Cloning shares the
/// state, so a signal handler can hold a clone while the attempt runs.
#[derive(Clone, Default)]
pub struct CancelHandle(Arc<CancelState>);

impl CancelHandle {
    pub fn new() -> Self {
        Self::default()
    }

    /// Stop the processes this attempt started and make it report as
    /// cancelled. Safe to call from a signal handler thread, and more than once.
    pub fn cancel(&self) {
        self.0.cancelled.store(true, Ordering::SeqCst);
        for &pg in self.0.pgids.lock().unwrap().iter() {
            // SAFETY: a plain signal to a process group this attempt started.
            unsafe {
                libc::killpg(pg, libc::SIGTERM);
            }
        }
    }

    pub fn is_cancelled(&self) -> bool {
        self.0.cancelled.load(Ordering::SeqCst)
    }

    /// Make [`CancelHandle::cancel`] signal this process group until it is
    /// untracked. `pg` must be the pid of a process group leader and greater
    /// than 1: anything else is ignored, so that `killpg(0)` or `killpg(1)`
    /// can never signal local-ci's own group or init's.
    pub fn track_pgid(&self, pg: i32) {
        if pg <= 1 {
            return;
        }
        self.0.pgids.lock().unwrap().push(pg);
    }

    pub fn untrack_pgid(&self, pg: i32) {
        self.0.pgids.lock().unwrap().retain(|&p| p != pg);
    }

    pub(crate) fn record_native_uncertain(&self, leader: u32) {
        let mut ids = self.0.native_uncertain.lock().unwrap();
        ids.push(leader);
    }

    #[cfg(test)]
    pub(crate) fn native_group_count(&self) -> usize {
        self.0.pgids.lock().unwrap().len()
    }

    #[cfg(test)]
    pub(crate) fn native_uncertain(&self) -> Vec<u32> {
        self.0.native_uncertain.lock().unwrap().clone()
    }

    pub(crate) fn track_container(&self, name: String) {
        self.0.containers.lock().unwrap().push(name);
    }

    pub(crate) fn untrack_containers(&self, names: &std::collections::HashSet<&String>) {
        self.0
            .containers
            .lock()
            .unwrap()
            .retain(|n| !names.contains(n));
    }

    pub(crate) fn track_compose(&self, project: String) {
        self.0.compose_projects.lock().unwrap().push(project);
    }

    pub(crate) fn untrack_compose(&self, projects: &[String]) {
        self.0
            .compose_projects
            .lock()
            .unwrap()
            .retain(|p| !projects.contains(p));
    }

    pub(crate) fn creation_started(&self, name: String) {
        self.0.creation_candidates.lock().unwrap().push(name);
    }
    pub(crate) fn creation_acknowledged(&self, name: &str, id: String) {
        self.track_container(id);
        // A later successful operation with the same requested name cannot
        // erase an earlier ambiguous creation operation.
        let mut candidates = self.0.creation_candidates.lock().unwrap();
        if let Some(index) = candidates.iter().rposition(|n| n == name) {
            candidates.remove(index);
        }
    }
    pub(crate) fn track_unverified_compose(&self, name: String) {
        let mut names = self.0.unverified_compose.lock().unwrap();
        if !names.contains(&name) {
            names.push(name);
        }
    }
    pub(crate) fn external_execution_started(&self) {
        self.0.external_executor.store(true, Ordering::SeqCst);
    }
    pub(crate) fn port_release_pending(&self, path: &std::path::Path) {
        let mut paths = self.0.pending_ports.lock().unwrap();
        if !paths.iter().any(|p| p == path) {
            paths.push(path.into());
        }
    }
    pub(crate) fn port_release_confirmed(&self, path: &std::path::Path) {
        self.0.pending_ports.lock().unwrap().retain(|p| p != path);
    }
    pub(crate) fn pending_ownership(&self) -> crate::execution_outcome::PendingOwnership {
        crate::execution_outcome::PendingOwnership {
            native_groups: self.0.pgids.lock().unwrap().len(),
            native_uncertain: self.0.native_uncertain.lock().unwrap().clone(),
            external_executor: self.0.external_executor.load(Ordering::SeqCst),
            containers: self.0.containers.lock().unwrap().clone(),
            creation_candidates: self.0.creation_candidates.lock().unwrap().clone(),
            compose: self.0.compose_projects.lock().unwrap().clone(),
            unverified_compose: self.0.unverified_compose.lock().unwrap().clone(),
            port_paths: self.0.pending_ports.lock().unwrap().clone(),
        }
    }
    pub(crate) fn cleanup_projects(
        &self,
        ctx: &ExecContext,
        projects: &[String],
    ) -> Vec<crate::cleanup::CleanupIncomplete> {
        #[cfg(test)]
        crate::exec::finalization_test::inspect("resource cleanup");
        let unverified = self.0.unverified_compose.lock().unwrap().clone();
        let allowed: Vec<String> = projects
            .iter()
            .filter(|p| !unverified.contains(p))
            .cloned()
            .collect();
        let mut errors = crate::cleanup::compose_down(ctx, &allowed);
        if errors.is_empty() {
            self.untrack_compose(&allowed);
        }
        if projects.iter().any(|p| unverified.contains(p)) {
            errors.push(crate::cleanup::CleanupIncomplete(
                "unverified Compose namespace retained".into(),
            ));
        }
        errors
    }
    pub(crate) fn cleanup_owned(
        &self,
        ctx: &ExecContext,
    ) -> crate::execution_outcome::CleanupOutcome {
        let projects = self.0.compose_projects.lock().unwrap().clone();
        let mut diagnostics = self.cleanup_projects(ctx, &projects);
        let ids = self.0.containers.lock().unwrap().clone();
        let removed = crate::cleanup::remove_tracked_containers(ctx, &ids);
        if removed.is_empty() {
            self.untrack_containers(&ids.iter().collect());
        }
        diagnostics.extend(removed);
        let pending = self.pending_ownership();
        if !pending.creation_candidates.is_empty() {
            diagnostics.push(crate::cleanup::CleanupIncomplete(
                "unconfirmed container creation retained".into(),
            ));
        }
        if !pending.unverified_compose.is_empty()
            && !diagnostics
                .iter()
                .any(|d| d.0 == "unverified Compose namespace retained")
        {
            diagnostics.push(crate::cleanup::CleanupIncomplete(
                "unverified Compose namespace retained".into(),
            ));
        }
        crate::execution_outcome::CleanupOutcome {
            diagnostics,
            pending,
        }
    }
    /// Legacy caller projection: warnings are separate from business results.
    /// Failed/unknown references remain available to the owned outcome API.
    pub(crate) fn remove_containers(&self, ctx: &ExecContext) {
        for diagnostic in self.cleanup_owned(ctx).diagnostics {
            eprintln!("local-ci: warning: {diagnostic}");
        }
    }
}

/// The environment and the cancel handle of one attempt.
pub struct ExecContext {
    env: BTreeMap<String, String>,
    /// Stops this attempt; see [`CancelHandle`].
    pub cancel: CancelHandle,
    github_token: OnceLock<Option<String>>,
}

impl ExecContext {
    /// A context over `env` (the variables `PATH`, `HOME`, `LOCAL_CI_HOME` and
    /// `XDG_CACHE_HOME` matter; steps run with exactly these variables plus
    /// their own).
    pub fn new(env: BTreeMap<String, String>) -> Self {
        ExecContext {
            env,
            cancel: CancelHandle::new(),
            github_token: OnceLock::new(),
        }
    }

    /// The same environment with a handle of its own: for a second attempt
    /// that must not be cancelled with this one. (Not `Clone`: a plain clone
    /// would share the handle and so the cancellation.)
    pub fn fresh_attempt(&self) -> Self {
        ExecContext {
            env: self.env.clone(),
            cancel: CancelHandle::new(),
            github_token: OnceLock::new(),
        }
    }

    /// A command that sees exactly this context's environment (not the
    /// process's).
    pub(crate) fn command(&self, program: impl AsRef<std::ffi::OsStr>) -> Command {
        #[allow(clippy::disallowed_methods)] // the one place; the environment is cleared next
        let mut c = Command::new(program);
        c.env_clear().envs(&self.env);
        c
    }

    /// The GitHub token of the machine this runs on (`gh auth token`), for
    /// steps that read `github.token` or `secrets.GITHUB_TOKEN`. Asked once,
    /// and only when a step needs it; `None` when `gh` is missing or not
    /// logged in.
    pub fn github_token(&self) -> Option<&str> {
        self.github_token
            .get_or_init(|| {
                let gh = self.find_tool("gh")?;
                let out = self
                    .command(gh)
                    .args(["auth", "token"])
                    .stdin(Stdio::null())
                    .stderr(Stdio::null())
                    .output()
                    .ok()?;
                let t = String::from_utf8_lossy(&out.stdout).trim().to_string();
                (out.status.success() && !t.is_empty()).then_some(t)
            })
            .as_deref()
    }

    /// The token, if it has been asked for already (to mask it in output).
    pub(crate) fn github_token_if_fetched(&self) -> Option<&str> {
        self.github_token.get()?.as_deref()
    }

    pub fn env(&self) -> &BTreeMap<String, String> {
        &self.env
    }

    pub fn var(&self, key: &str) -> Option<&str> {
        self.env.get(key).map(String::as_str)
    }

    /// `HOME`, when set and not empty.
    pub fn home(&self) -> Option<&str> {
        self.var("HOME").filter(|h| !h.is_empty())
    }

    /// Where runs, results, worktrees and locks live by default
    /// (`LOCAL_CI_HOME`, else the platform cache directory).
    ///
    /// Only an absolute path: local-ci deletes what it left in this
    /// directory, and a path that is empty or relative names a different
    /// directory wherever local-ci is started.
    pub fn cache_dir(&self) -> anyhow::Result<PathBuf> {
        if let Some(d) = self.var("LOCAL_CI_HOME") {
            if !std::path::Path::new(d).is_absolute() {
                anyhow::bail!("LOCAL_CI_HOME must be an absolute path (it is `{d}`)");
            }
            return Ok(PathBuf::from(d));
        }
        let home = PathBuf::from(self.var("HOME").unwrap_or("/tmp"));
        let dir = if cfg!(target_os = "macos") {
            home.join("Library/Caches/local-ci")
        } else {
            match self.var("XDG_CACHE_HOME") {
                Some(x) if !x.is_empty() => PathBuf::from(x).join("local-ci"),
                _ => home.join(".cache/local-ci"),
            }
        };
        if !dir.is_absolute() {
            anyhow::bail!(
                "the cache directory `{}` is not an absolute path: set LOCAL_CI_HOME to one",
                dir.display()
            );
        }
        Ok(dir)
    }

    /// An executable on this context's `PATH`, or in `~/.cargo/bin`.
    pub fn find_tool(&self, name: &str) -> Option<PathBuf> {
        for d in self.var("PATH").unwrap_or("").split(':') {
            if d.is_empty() {
                continue;
            }
            let p = PathBuf::from(d).join(name);
            if p.is_file() {
                return Some(p);
            }
        }
        let p = PathBuf::from(self.var("HOME").unwrap_or(""))
            .join(".cargo/bin")
            .join(name);
        p.is_file().then_some(p)
    }
}

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

    #[test]
    fn a_command_sees_the_context_env_and_not_the_processs() {
        let ctx = ExecContext::new([("ONLY".to_string(), "1".to_string())].into());
        let out = ctx.command("/usr/bin/env").output().unwrap();
        assert_eq!(String::from_utf8_lossy(&out.stdout), "ONLY=1\n");
    }

    #[test]
    fn only_a_group_leader_pid_above_one_is_tracked() {
        let c = CancelHandle::new();
        for pg in [i32::MIN, -1, 0, 1] {
            c.track_pgid(pg);
        }
        assert!(c.0.pgids.lock().unwrap().is_empty());
        c.track_pgid(2);
        assert_eq!(*c.0.pgids.lock().unwrap(), vec![2]);
        c.untrack_pgid(2);
        assert!(c.0.pgids.lock().unwrap().is_empty());
    }
    fn cleanup_fixture(body: &str) -> (tempfile::TempDir, ExecContext) {
        let root = tempfile::tempdir().unwrap();
        let docker = root.path().join("docker");
        crate::fake_exec::write_executable(
            &docker,
            format!("#!/bin/sh\necho \"$*\" >> \"$HOME/calls\"\n{body}\n"),
            0o700,
        );
        let ctx = ExecContext::new(
            [
                (
                    "PATH".into(),
                    format!("{}:/usr/bin:/bin", root.path().display()),
                ),
                ("HOME".into(), root.path().display().to_string()),
            ]
            .into(),
        );
        (root, ctx)
    }
    #[test]
    fn failed_owned_id_cleanup_is_retained_until_acknowledged_retry() {
        let id = "a".repeat(64);
        let script = format!(
            r#"case "$1" in
ps) [ -f "$HOME/removed" ] || echo '{id}';;
rm) [ -f "$HOME/allow" ] || exit 1; touch "$HOME/removed";;
esac
exit 0"#
        );
        let (root, ctx) = cleanup_fixture(&script);
        ctx.cancel.track_container(id.clone());
        let failed = ctx.cancel.cleanup_owned(&ctx);
        assert!(!failed.diagnostics.is_empty());
        assert_eq!(failed.pending.containers, vec![id.clone()]);
        std::fs::write(root.path().join("allow"), b"now").unwrap();
        let retried = ctx.cancel.cleanup_owned(&ctx);
        assert!(retried.diagnostics.is_empty());
        assert!(retried.pending.no_known_pending());
        // A repeated acknowledged-absent ID is cleared without rm by name.
        ctx.cancel.track_container(id.clone());
        assert!(ctx.cancel.cleanup_owned(&ctx).pending.no_known_pending());
        let calls = std::fs::read_to_string(root.path().join("calls")).unwrap();
        assert_eq!(calls.lines().filter(|l| l.starts_with("rm ")).count(), 2);
        assert!(calls.lines().all(|l| !l.contains("local-ci-")));
    }
    #[test]
    fn uncertain_creation_and_external_compose_names_never_authorize_deletion() {
        let (root, ctx) = cleanup_fixture("exit 0");
        ctx.cancel.creation_started("candidate-name".into());
        ctx.cancel.track_compose("shared-name".into());
        ctx.cancel.track_unverified_compose("shared-name".into());
        let outcome = ctx.cancel.cleanup_owned(&ctx);
        assert_eq!(outcome.pending.creation_candidates, vec!["candidate-name"]);
        assert_eq!(outcome.pending.unverified_compose, vec!["shared-name"]);
        assert!(!outcome.pending.no_known_pending());
        assert!(!root.path().join("calls").exists());
        let debug = format!("{:?}", outcome.pending);
        assert!(!debug.contains("candidate-name") && !debug.contains("shared-name"));
    }
    #[test]
    fn an_id_filtered_query_cannot_expand_cleanup_to_another_id() {
        let (root, ctx) = cleanup_fixture(&format!("echo '{}'\nexit 0", "b".repeat(64)));
        ctx.cancel.track_container("a".repeat(64));
        let outcome = ctx.cancel.cleanup_owned(&ctx);
        assert_eq!(outcome.pending.containers, vec!["a".repeat(64)]);
        assert!(!outcome.diagnostics.is_empty());
        assert!(!std::fs::read_to_string(root.path().join("calls"))
            .unwrap()
            .contains("rm "));
    }
}