skif-cli 0.2.0

Command-line interface for skif, a dependency and package-manager linter for JS/TS monorepos.
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
//! Writing a `FixPlan` to disk: every target is validated first, every new content is staged in a temporary file
//! next to its target, and only then is anything renamed into place, so a failure leaves the tree as it was.

use std::fs::{self, OpenOptions};
use std::io::{self, Write};
use std::path::{Component, Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};

use skif::{FileChange, FixPlan};

use crate::error::{CliError, Kind};

/// What the plan does to one validated file.
enum Job<'a> {
    Write {
        target: PathBuf,
        bytes: &'a [u8],
        /// The previous contents of a modified file; `None` for a created one.
        original: Option<Vec<u8>>,
    },
    Remove {
        target: PathBuf,
        original: Vec<u8>,
    },
}

/// How to put a file back if a later step fails.
enum Undo {
    Restore { target: PathBuf, bytes: Vec<u8> },
    Remove { target: PathBuf },
}

/// A temporary file that is deleted unless it was renamed into place.
struct Temp(Option<PathBuf>);

impl Drop for Temp {
    fn drop(&mut self) {
        if let Some(path) = self.0.take() {
            let _ = fs::remove_file(path);
        }
    }
}

/// Directories created for new files; removed again (when still empty) unless the plan was written.
#[derive(Default)]
struct CreatedDirs {
    dirs: Vec<PathBuf>,
    keep: bool,
}

impl Drop for CreatedDirs {
    fn drop(&mut self) {
        if !self.keep {
            for dir in self.dirs.iter().rev() {
                let _ = fs::remove_dir(dir);
            }
        }
    }
}

/// Applies `plan` under `root`. Every path in the plan is resolved against `root`, never the working directory.
///
/// All targets are validated before the first byte is written, new contents are staged next to their targets and
/// renamed into place together, and a failure while doing so restores the files already replaced.
pub fn write_plan(plan: &FixPlan, root: &Path) -> Result<(), CliError> {
    let root = root
        .canonicalize()
        .map_err(|error| CliError::io("cannot resolve", root, &error))?;
    let jobs = plan
        .changes
        .iter()
        .map(|change| prepare(plan, change, &root))
        .collect::<Result<Vec<_>, _>>()?;

    let mut dirs = CreatedDirs::default();
    let mut staged: Vec<(Temp, &Job<'_>)> = Vec::new();
    for job in &jobs {
        if let Job::Write {
            target,
            bytes,
            original,
        } = job
        {
            let temp = stage(target, bytes, original.is_none(), &mut dirs)
                .map_err(|error| CliError::io("cannot write", target, &error))?;
            staged.push((temp, job));
        }
    }

    let mut undo: Vec<Undo> = Vec::new();
    let committed = commit(&mut staged, &jobs, &mut undo);
    if let Err(error) = committed {
        rollback(undo);
        return Err(error);
    }
    dirs.keep = true;
    for job in &jobs {
        sync_parent(match job {
            Job::Write { target, .. } | Job::Remove { target, .. } => target,
        });
    }
    Ok(())
}

/// Flushes the directory entry of `target`, so a rename or removal survives a crash. Best effort: not every
/// platform can open a directory, and the data itself was synced before the rename.
fn sync_parent(target: &Path) {
    if let Some(parent) = target.parent() {
        let _ = fs::File::open(parent).and_then(|dir| dir.sync_all());
    }
}

fn commit(staged: &mut [(Temp, &Job<'_>)], jobs: &[Job<'_>], undo: &mut Vec<Undo>) -> Result<(), CliError> {
    for (temp, job) in staged.iter_mut() {
        let Job::Write { target, original, .. } = job else {
            continue;
        };
        let Some(path) = temp.0.take() else {
            continue;
        };
        if let Err(error) = fs::rename(&path, target) {
            temp.0 = Some(path);
            return Err(CliError::io("cannot write", target, &error));
        }
        undo.push(match original {
            Some(bytes) => Undo::Restore {
                target: target.clone(),
                bytes: bytes.clone(),
            },
            None => Undo::Remove { target: target.clone() },
        });
    }
    for job in jobs {
        if let Job::Remove { target, original } = job {
            match fs::remove_file(target) {
                Ok(()) => {}
                Err(error) if error.kind() == io::ErrorKind::NotFound => {}
                Err(error) => return Err(CliError::io("cannot delete", target, &error)),
            }
            undo.push(Undo::Restore {
                target: target.clone(),
                bytes: original.clone(),
            });
        }
    }
    Ok(())
}

fn rollback(undo: Vec<Undo>) {
    for step in undo.into_iter().rev() {
        let _ = match step {
            Undo::Restore { target, bytes } => fs::write(target, bytes),
            Undo::Remove { target } => fs::remove_file(target),
        };
    }
}

/// Validates one change and reads what a rollback would need.
fn prepare<'a>(plan: &FixPlan, change: &'a FileChange, root: &Path) -> Result<Job<'a>, CliError> {
    match change {
        FileChange::Modify { path, new_contents, .. } => {
            let target = target(root, path)?;
            let original = fs::read(&target).map_err(|error| CliError::io("cannot read", path, &error))?;
            refuse_if_stale(plan, path, &original, "modify")?;
            Ok(Job::Write {
                target,
                bytes: new_contents.as_bytes(),
                original: Some(original),
            })
        }
        FileChange::Create { path, contents } => {
            let target = target(root, path)?;
            if fs::symlink_metadata(&target).is_ok() {
                return Err(CliError::new(
                    Kind::Io,
                    format!("refusing to create {}: it already exists", path.display()),
                ));
            }
            Ok(Job::Write {
                target,
                bytes: contents.as_bytes(),
                original: None,
            })
        }
        FileChange::Delete { path } => {
            let target = target(root, path)?;
            match fs::read(&target) {
                Ok(original) => {
                    refuse_if_stale(plan, path, &original, "delete")?;
                    Ok(Job::Remove { target, original })
                }
                Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(Job::Remove {
                    target,
                    original: Vec::new(),
                }),
                Err(error) => Err(CliError::io("cannot read", path, &error)),
            }
        }
        _ => Err(CliError::new(
            Kind::Io,
            "the fix plan holds a change this skif cannot write",
        )),
    }
}

/// Fails when the plan recorded the contents `path` had and `current` differs: the file changed after planning.
fn refuse_if_stale(plan: &FixPlan, path: &Path, current: &[u8], action: &str) -> Result<(), CliError> {
    if plan
        .base_hash(path)
        .is_some_and(|base| skif::content_hash(current) != base)
    {
        return Err(CliError::new(
            Kind::Io,
            format!(
                "refusing to {action} {}: it changed after the fixes were planned",
                path.display()
            ),
        ));
    }
    Ok(())
}

/// The absolute target of a workspace-relative `relative` path, which must stay inside `root`: no `..`, no
/// absolute paths, no symlink at the target and no symlinked directory leading out of the root.
fn target(root: &Path, relative: &Path) -> Result<PathBuf, CliError> {
    let outside = || {
        CliError::new(
            Kind::Io,
            format!("refusing to write outside the workspace: {}", relative.display()),
        )
    };
    if relative.as_os_str().is_empty()
        || !relative
            .components()
            .all(|component| matches!(component, Component::Normal(_)))
    {
        return Err(outside());
    }
    let target = root.join(relative);
    let nearest = target
        .ancestors()
        .skip(1)
        .find(|dir| dir.exists())
        .ok_or_else(outside)?
        .canonicalize()
        .map_err(|error| CliError::io("cannot resolve", relative, &error))?;
    if !nearest.starts_with(root) {
        return Err(outside());
    }
    if fs::symlink_metadata(&target).is_ok_and(|metadata| metadata.file_type().is_symlink()) {
        return Err(CliError::new(
            Kind::Io,
            format!("refusing to write through a symlink: {}", relative.display()),
        ));
    }
    Ok(target)
}

static COUNTER: AtomicUsize = AtomicUsize::new(0);

/// A fresh sibling of `target` that nothing else can have created: exclusive creation, process id and a counter. The
/// name does not carry the target's, so a file name at the length limit still stages.
fn temp_path(target: &Path) -> PathBuf {
    let sequence = COUNTER.fetch_add(1, Ordering::Relaxed);
    target.with_file_name(format!(".{}.{sequence}.skif-tmp", std::process::id()))
}

fn create_parents(target: &Path, dirs: &mut CreatedDirs) -> io::Result<()> {
    let missing: Vec<&Path> = target
        .ancestors()
        .skip(1)
        .take_while(|dir| !dir.as_os_str().is_empty() && !dir.exists())
        .collect();
    for dir in missing.into_iter().rev() {
        fs::create_dir(dir)?;
        dirs.dirs.push(dir.to_path_buf());
    }
    Ok(())
}

/// Writes `bytes` to a new temporary sibling of `target` (with its permissions, when it exists) and syncs it.
fn stage(target: &Path, bytes: &[u8], create: bool, dirs: &mut CreatedDirs) -> io::Result<Temp> {
    if create {
        create_parents(target, dirs)?;
    }
    let path = temp_path(target);
    let mut file = OpenOptions::new().write(true).create_new(true).open(&path)?;
    let temp = Temp(Some(path));
    file.write_all(bytes)?;
    if let Ok(metadata) = fs::metadata(target) {
        let _ = file.set_permissions(metadata.permissions());
    }
    file.sync_all()?;
    Ok(temp)
}

/// Writes `bytes` to `target`.
///
/// A regular file is replaced atomically through a temporary sibling that is renamed over it; a symlink to a regular
/// file is followed, so the link stays a link. Anything that is not a regular file (`/dev/stdout`, a pipe) cannot be
/// replaced without destroying it, so the bytes are written through it instead.
pub fn write_atomic(target: &Path, bytes: &[u8]) -> io::Result<()> {
    let destination = match fs::metadata(target) {
        Ok(metadata) if metadata.is_file() => fs::canonicalize(target)?,
        Ok(_) => return write_through(target, bytes),
        Err(error) if error.kind() == io::ErrorKind::NotFound => target.to_path_buf(),
        Err(error) => return Err(error),
    };
    let mut dirs = CreatedDirs::default();
    let mut temp = stage(&destination, bytes, false, &mut dirs)?;
    let path = temp.0.take().unwrap_or_default();
    fs::rename(&path, &destination).inspect_err(|_| {
        let _ = fs::remove_file(&path);
    })?;
    sync_parent(&destination);
    Ok(())
}

fn write_through(target: &Path, bytes: &[u8]) -> io::Result<()> {
    let mut file = OpenOptions::new().write(true).open(target)?;
    file.write_all(bytes)?;
    file.flush()
}

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

    fn modify(path: &str, contents: &str) -> FileChange {
        FileChange::Modify {
            path: path.into(),
            edits: Vec::new(),
            new_contents: contents.to_owned(),
        }
    }

    fn plan(changes: Vec<FileChange>) -> FixPlan {
        let mut plan = FixPlan::default();
        plan.changes = changes;
        plan
    }

    fn leftovers(dir: &Path) -> Vec<String> {
        fs::read_dir(dir)
            .unwrap()
            .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
            .filter(|name| name.ends_with(".skif-tmp"))
            .collect()
    }

    #[test]
    fn atomic_write_replaces_the_file_and_leaves_no_temporary() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join("a.json"), "old").unwrap();
        write_atomic(&dir.path().join("a.json"), b"new").unwrap();
        assert_eq!(fs::read_to_string(dir.path().join("a.json")).unwrap(), "new");
        assert_eq!(leftovers(dir.path()), [] as [std::string::String; 0]);
    }

    #[cfg(unix)]
    #[test]
    fn atomic_write_keeps_a_symlink_and_updates_its_target() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join("real.json"), "old").unwrap();
        std::os::unix::fs::symlink("real.json", dir.path().join("link.json")).unwrap();
        write_atomic(&dir.path().join("link.json"), b"new").unwrap();
        assert!(
            fs::symlink_metadata(dir.path().join("link.json"))
                .unwrap()
                .file_type()
                .is_symlink()
        );
        assert_eq!(fs::read_to_string(dir.path().join("real.json")).unwrap(), "new");
        assert_eq!(leftovers(dir.path()), [] as [std::string::String; 0]);
    }

    #[cfg(unix)]
    #[test]
    fn atomic_write_goes_through_a_device_instead_of_replacing_it() {
        write_atomic(Path::new("/dev/null"), b"discarded").unwrap();
        assert!(!fs::metadata("/dev/null").unwrap().is_file());
    }

    #[test]
    fn rejects_paths_that_escape_the_root() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().canonicalize().unwrap();
        assert!(target(&root, Path::new("../x")).is_err());
        assert!(target(&root, Path::new("/abs")).is_err());
        assert!(target(&root, Path::new("")).is_err());
        assert_eq!(
            target(&root, Path::new("a/b.json")).unwrap(),
            root.join("a").join("b.json")
        );
    }

    #[test]
    fn one_bad_target_writes_nothing() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join("a.json"), "old").unwrap();
        let bad = plan(vec![modify("a.json", "new"), modify("../escape.json", "x")]);
        assert!(write_plan(&bad, dir.path()).is_err());
        assert_eq!(fs::read_to_string(dir.path().join("a.json")).unwrap(), "old");
        assert_eq!(leftovers(dir.path()), [] as [std::string::String; 0]);
    }

    #[test]
    fn a_failure_while_staging_leaves_the_tree_untouched() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join("a.json"), "old").unwrap();
        fs::write(dir.path().join("blocker"), "file").unwrap();
        let failing = plan(vec![
            modify("a.json", "new"),
            FileChange::Create {
                path: Path::new("blocker").join("nested").join("b.json"),
                contents: "{}".to_owned(),
            },
        ]);
        assert!(write_plan(&failing, dir.path()).is_err());
        assert_eq!(fs::read_to_string(dir.path().join("a.json")).unwrap(), "old");
        assert_eq!(leftovers(dir.path()), [] as [std::string::String; 0]);
    }

    #[test]
    fn a_file_that_changed_after_planning_is_refused() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join("a.json"), "edited since").unwrap();
        let stale = plan(vec![modify("a.json", "new")]).with_base_hash("a.json", skif::content_hash(b"as planned"));
        let error = write_plan(&stale, dir.path()).unwrap_err();
        assert!(
            error.to_string().contains("changed after the fixes were planned"),
            "{error}"
        );
        assert_eq!(fs::read_to_string(dir.path().join("a.json")).unwrap(), "edited since");

        let fresh = plan(vec![modify("a.json", "new")]).with_base_hash("a.json", skif::content_hash(b"edited since"));
        write_plan(&fresh, dir.path()).unwrap();
        assert_eq!(fs::read_to_string(dir.path().join("a.json")).unwrap(), "new");
    }

    #[test]
    fn a_deleted_file_that_changed_after_planning_is_refused() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join("gone.json"), "edited since").unwrap();
        let delete = |hash_of: &[u8]| {
            plan(vec![FileChange::Delete {
                path: "gone.json".into(),
            }])
            .with_base_hash("gone.json", skif::content_hash(hash_of))
        };
        let error = write_plan(&delete(b"as planned"), dir.path()).unwrap_err();
        assert!(error.to_string().contains("refusing to delete"), "{error}");
        assert!(dir.path().join("gone.json").exists());

        write_plan(&delete(b"edited since"), dir.path()).unwrap();
        assert!(!dir.path().join("gone.json").exists());
    }

    #[test]
    fn creating_over_an_existing_file_is_refused() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join("a.json"), "old").unwrap();
        let create = plan(vec![FileChange::Create {
            path: "a.json".into(),
            contents: "new".to_owned(),
        }]);
        assert!(write_plan(&create, dir.path()).is_err());
        assert_eq!(fs::read_to_string(dir.path().join("a.json")).unwrap(), "old");
    }

    #[test]
    fn created_files_get_their_directories() {
        let dir = tempfile::tempdir().unwrap();
        let create = plan(vec![FileChange::Create {
            path: Path::new("new").join("deep").join("c.json"),
            contents: "{}".to_owned(),
        }]);
        write_plan(&create, dir.path()).unwrap();
        assert_eq!(
            fs::read_to_string(dir.path().join("new").join("deep").join("c.json")).unwrap(),
            "{}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn symlinks_out_of_the_root_are_not_followed() {
        let outside = tempfile::tempdir().unwrap();
        fs::write(outside.path().join("secret.json"), "secret").unwrap();
        let dir = tempfile::tempdir().unwrap();
        std::os::unix::fs::symlink(outside.path().join("secret.json"), dir.path().join("link.json")).unwrap();
        std::os::unix::fs::symlink(outside.path(), dir.path().join("linked-dir")).unwrap();

        let through_file = plan(vec![modify("link.json", "pwned")]);
        assert!(write_plan(&through_file, dir.path()).is_err());
        let through_dir = plan(vec![modify("linked-dir/secret.json", "pwned")]);
        assert!(write_plan(&through_dir, dir.path()).is_err());
        assert_eq!(
            fs::read_to_string(outside.path().join("secret.json")).unwrap(),
            "secret"
        );
    }
}