haz-cli 0.2.0

Command-line task runner: tracks task DAGs across a workspace of projects, executes them with caching.
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
//! Commit pass for `haz init` per `AUX-005`..`AUX-006`.
//!
//! Once the interactive flow has finalised a selection in
//! [`super::model::Tree`], the commit pass:
//!
//! 1. Computes the project-root set (`AUX-005` step 1, delegated
//!    to the tree).
//! 2. Sanitises each project root's basename to an
//!    `ID-001..ID-005`-valid `ProjectName` (`AUX-005` step 2).
//! 3. Renders the final `.haz/workspace.yml` body and the per-
//!    project `haz.yml` bodies (`AUX-005` step 3 listing data;
//!    the UI prompt for confirmation lives in the TUI driver).
//! 4. Applies the plan to disk via `AUX-006` rename-into-place,
//!    writing every `haz.yml` first and `.haz/workspace.yml`
//!    last so an interrupted run never leaves a workspace
//!    referencing a non-existent `haz.yml`.
//!
//! Existing `haz.yml` files are not overwritten per `AUX-005`
//! step 2 ("for each path... that does not contain a `haz.yml`").

use std::collections::BTreeSet;
use std::fs;
use std::path::{Component, Path, PathBuf};

use miette::{IntoDiagnostic, Result, WrapErr};
use snafu::Snafu;

use super::atomic_write;
use super::model::{Node, SelectionState, Tree};

/// A single entry that will land in `.haz/workspace.yml`'s
/// `projects:` list. Ordering is byte-ascending on
/// [`Self::text`] so the AUX-005 step 3 listing and the eventual
/// `workspace.yml` are byte-stable across runs.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct ProjectsEntry {
    /// The workspace-absolute string form (a literal `/<dir>`
    /// per [`SelectionState::Project`] or a glob `/<dir>/*` per
    /// [`SelectionState::ProjectsParent`]).
    pub text: String,
}

impl ProjectsEntry {
    fn literal(path: &Path) -> Self {
        Self {
            text: workspace_absolute_str(path),
        }
    }
    fn glob_under(path: &Path) -> Self {
        let mut text = workspace_absolute_str(path);
        text.push_str("/*");
        Self { text }
    }
}

/// A new `haz.yml` file to scaffold per `AUX-005` step 2.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScaffoldedHazYml {
    /// Workspace-absolute directory the file will land under.
    pub project_root: PathBuf,
    /// Sanitised `ProjectName` per `AUX-005` step 2 and
    /// `ID-001..ID-005`.
    pub sanitised_name: String,
    /// Complete file body.
    pub body: String,
}

/// The full commit plan derived from a finalised [`Tree`].
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct CommitPlan {
    /// Final `.haz/workspace.yml` body (already-rendered YAML).
    pub workspace_yml_body: String,
    /// `haz.yml` files to scaffold, ordered by `project_root`.
    /// Projects whose root already contains a `haz.yml` are
    /// omitted per `AUX-005` step 2.
    pub project_ymls: Vec<ScaffoldedHazYml>,
}

/// Sanitisation failure surfaced during [`plan_commit`].
///
/// `AUX-005` step 2 names this as the one user-facing failure
/// mode of the planning step; filesystem I/O failures live in
/// [`apply_commit`].
#[derive(Debug, Snafu)]
pub enum CommitPlanError {
    /// `AUX-005` step 2: sanitising a directory's basename
    /// produced an empty string or a name that violates one of
    /// the `ID-001`..`ID-005` rules.
    #[snafu(display(
        "could not derive a valid project name from directory `{directory}` (sanitised: `{sanitised}`)"
    ))]
    SanitisationFailed {
        /// Workspace-absolute directory string for diagnostics.
        directory: String,
        /// The sanitised string that failed validation.
        sanitised: String,
    },
}

/// Compute the [`CommitPlan`] for `tree`, anchoring relative
/// paths against `cwd_host_root`.
///
/// The function consults the filesystem only to test whether a
/// `haz.yml` already exists under each project root; it never
/// writes anything (that's [`apply_commit`]'s job).
///
/// # Errors
///
/// Returns [`CommitPlanError::SanitisationFailed`] when a project
/// root's basename cannot be sanitised to a valid `ProjectName`.
pub fn plan_commit(tree: &Tree, cwd_host_root: &Path) -> Result<CommitPlan, CommitPlanError> {
    let workspace_yml_body = render_workspace_yml(&projects_yml_entries(tree));

    let mut project_ymls: Vec<ScaffoldedHazYml> = Vec::new();
    for project_root_ws in &tree.project_root_set() {
        let host_dir = host_join(cwd_host_root, project_root_ws);
        if host_dir.join("haz.yml").exists() {
            continue;
        }
        let basename = project_root_ws
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_default();
        let sanitised = sanitise_project_name(&basename);
        if !is_valid_project_name(&sanitised) {
            return Err(CommitPlanError::SanitisationFailed {
                directory: workspace_absolute_str(project_root_ws),
                sanitised,
            });
        }
        let body = format!("name: {sanitised}\ntasks: {{}}\n");
        project_ymls.push(ScaffoldedHazYml {
            project_root: project_root_ws.clone(),
            sanitised_name: sanitised,
            body,
        });
    }
    Ok(CommitPlan {
        workspace_yml_body,
        project_ymls,
    })
}

/// Apply `plan` to disk per `AUX-006`: write every `haz.yml`
/// first, then `.haz/workspace.yml` last, each via the
/// rename-into-place pattern.
///
/// `cwd_host_root` is the host filesystem location that becomes
/// the workspace root; the function joins workspace-absolute
/// paths from `plan` against it to compute host paths.
///
/// # Errors
///
/// Returns a [`miette::Report`] on any filesystem failure (mkdir,
/// tmp write, fsync, rename). The function makes no attempt to
/// roll back files written earlier in the sequence; the
/// `haz.yml`-then-`workspace.yml` ordering is itself the
/// safety property `AUX-006` names: an interrupted run leaves a
/// consistent state because workspace.yml never references
/// missing `haz.yml`s.
pub fn apply_commit(plan: &CommitPlan, cwd_host_root: &Path) -> Result<()> {
    for scaffold in &plan.project_ymls {
        let host_dir = host_join(cwd_host_root, &scaffold.project_root);
        fs::create_dir_all(&host_dir)
            .into_diagnostic()
            .wrap_err_with(|| format!("failed to create directory `{}`", host_dir.display()))?;
        atomic_write(&host_dir.join("haz.yml"), scaffold.body.as_bytes())?;
    }
    let haz_dir = cwd_host_root.join(".haz");
    fs::create_dir_all(&haz_dir)
        .into_diagnostic()
        .wrap_err_with(|| format!("failed to create directory `{}`", haz_dir.display()))?;
    atomic_write(
        &haz_dir.join("workspace.yml"),
        plan.workspace_yml_body.as_bytes(),
    )?;
    Ok(())
}

/// Render the `projects:` block of `.haz/workspace.yml` from a
/// pre-collected, ordered set of entries.
///
/// Empty input yields the literal `projects: []\n` form per
/// `AUX-007`. Non-empty input yields one indented list item per
/// entry.
fn render_workspace_yml(entries: &BTreeSet<ProjectsEntry>) -> String {
    if entries.is_empty() {
        return "projects: []\n".to_owned();
    }
    let mut out = String::from("projects:\n");
    for entry in entries {
        out.push_str("  - ");
        out.push_str(&entry.text);
        out.push('\n');
    }
    out
}

/// Collect every `Project` and `ProjectsParent` node in `tree`
/// into the ordered set of `projects:` entries.
fn projects_yml_entries(tree: &Tree) -> BTreeSet<ProjectsEntry> {
    let mut out: BTreeSet<ProjectsEntry> = BTreeSet::new();
    collect_entries(tree.root(), &mut out);
    out
}

fn collect_entries(node: &Node, out: &mut BTreeSet<ProjectsEntry>) {
    match node.state {
        SelectionState::None => {}
        SelectionState::Project => {
            out.insert(ProjectsEntry::literal(&node.path));
        }
        SelectionState::ProjectsParent => {
            out.insert(ProjectsEntry::glob_under(&node.path));
        }
    }
    for child in &node.children {
        collect_entries(child, out);
    }
}

/// Render a workspace-absolute path (a [`PathBuf`] starting with
/// `RootDir`) as its `/<segment>/<segment>...` string form.
fn workspace_absolute_str(path: &Path) -> String {
    let mut out = String::new();
    for component in path.components() {
        match component {
            Component::RootDir => out.push('/'),
            Component::Normal(seg) => {
                if !out.ends_with('/') {
                    out.push('/');
                }
                out.push_str(&seg.to_string_lossy());
            }
            // `CurDir` / `ParentDir` / `Prefix` are excluded by
            // the path grammar of PATH-002; the tree model never
            // produces them. Skip defensively.
            _ => {}
        }
    }
    if out.is_empty() {
        out.push('/');
    }
    out
}

/// Join a workspace-absolute path onto `cwd_host_root` to recover
/// the host filesystem location.
fn host_join(cwd_host_root: &Path, workspace_absolute: &Path) -> PathBuf {
    let mut host = cwd_host_root.to_path_buf();
    for component in workspace_absolute.components() {
        if let Component::Normal(seg) = component {
            host.push(seg);
        }
    }
    host
}

/// Sanitise `raw` to an `ID-001..ID-005` candidate per `AUX-005`
/// step 2: replace non-alphabet runs with `-` and trim leading
/// non-`[A-Za-z0-9]` characters. The caller validates the
/// result with [`is_valid_project_name`].
fn sanitise_project_name(raw: &str) -> String {
    // Per ID-001 the identifier alphabet is [A-Za-z0-9_-]. Any
    // codepoint outside that set is replaced with `-`.
    let replaced: String = raw
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '_' || c == '-' {
                c
            } else {
                '-'
            }
        })
        .collect();
    // Collapse runs of `-` so a long stretch of forbidden chars
    // becomes a single separator instead of `------`.
    let mut collapsed = String::with_capacity(replaced.len());
    let mut prev_dash = false;
    for ch in replaced.chars() {
        if ch == '-' {
            if !prev_dash {
                collapsed.push('-');
            }
            prev_dash = true;
        } else {
            collapsed.push(ch);
            prev_dash = false;
        }
    }
    // Trim leading non-[A-Za-z0-9] (i.e., '-' and '_').
    collapsed
        .trim_start_matches(|c: char| !c.is_ascii_alphanumeric())
        .to_owned()
}

/// Validate `s` against `ID-001..ID-005` for use as a
/// `ProjectName`.
fn is_valid_project_name(s: &str) -> bool {
    if s.is_empty() || s.len() > 64 {
        return false;
    }
    let mut chars = s.chars();
    let first = chars.next().expect("non-empty");
    if !first.is_ascii_alphanumeric() {
        return false;
    }
    chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
}

/// Convenience accessor for tests / callers that want to inspect
/// the `projects:` entries without forcing a string render.
#[must_use]
pub fn projects_entries(tree: &Tree) -> Vec<ProjectsEntry> {
    projects_yml_entries(tree).into_iter().collect()
}

#[cfg(test)]
mod tests {
    use std::ffi::OsString;
    use std::fs;
    use std::path::{Path, PathBuf};

    use tempfile::TempDir;

    use super::{
        CommitPlanError, ProjectsEntry, apply_commit, host_join, is_valid_project_name,
        plan_commit, projects_entries, render_workspace_yml, sanitise_project_name,
        workspace_absolute_str,
    };
    use crate::commands::init::model::{Node, SelectionState, Tree};

    fn node(name: &str, path: &str, state: SelectionState, children: Vec<Node>) -> Node {
        let mut n = Node::new(OsString::from(name), PathBuf::from(path));
        n.state = state;
        n.children = children;
        n.children_loaded = true;
        n
    }

    // --- sanitise_project_name --------------------------------

    #[test]
    fn sanitise_preserves_valid_ascii_identifier_unchanged() {
        assert_eq!(sanitise_project_name("lib_core"), "lib_core");
        assert_eq!(sanitise_project_name("web-frontend"), "web-frontend");
        assert_eq!(sanitise_project_name("X42"), "X42");
    }

    #[test]
    fn sanitise_replaces_non_alphabet_runs_with_single_dash() {
        assert_eq!(sanitise_project_name("My Project"), "My-Project");
        assert_eq!(sanitise_project_name("a.b.c"), "a-b-c");
        // A run of forbidden chars collapses to a single `-`.
        assert_eq!(sanitise_project_name("a   b"), "a-b");
        assert_eq!(sanitise_project_name("a!@#b"), "a-b");
    }

    #[test]
    fn sanitise_trims_leading_dash_and_underscore() {
        assert_eq!(sanitise_project_name("-lib"), "lib");
        assert_eq!(sanitise_project_name("__lib"), "lib");
        assert_eq!(sanitise_project_name("--lib"), "lib");
    }

    #[test]
    fn sanitise_replaces_unicode_with_dashes() {
        // Non-ASCII codepoints are forbidden per ID-001; they
        // become `-`. Trailing dashes survive (only leading
        // non-alphanumeric characters are trimmed per AUX-005
        // step 2), and ID-002 only constrains the leading char.
        assert_eq!(sanitise_project_name("café"), "caf-");
        assert_eq!(sanitise_project_name("naïve-name"), "na-ve-name");
    }

    #[test]
    fn sanitise_yields_empty_when_basename_is_pure_punctuation() {
        assert_eq!(sanitise_project_name("..."), "");
        assert_eq!(sanitise_project_name("---"), "");
    }

    // --- is_valid_project_name --------------------------------

    #[test]
    fn is_valid_accepts_alphanumeric_underscore_hyphen() {
        assert!(is_valid_project_name("lib"));
        assert!(is_valid_project_name("lib_core"));
        assert!(is_valid_project_name("web-frontend"));
        assert!(is_valid_project_name("0snapshot"));
    }

    #[test]
    fn is_valid_rejects_empty_and_overlong() {
        assert!(!is_valid_project_name(""));
        let long = "a".repeat(65);
        assert!(!is_valid_project_name(&long));
    }

    #[test]
    fn is_valid_rejects_leading_dash_or_underscore() {
        assert!(!is_valid_project_name("-lib"));
        assert!(!is_valid_project_name("_lib"));
    }

    #[test]
    fn is_valid_rejects_forbidden_characters() {
        assert!(!is_valid_project_name("a.b"));
        assert!(!is_valid_project_name("a b"));
        assert!(!is_valid_project_name("a/b"));
    }

    // --- workspace_absolute_str / host_join -------------------

    #[test]
    fn workspace_absolute_str_renders_root_slash_segments() {
        assert_eq!(workspace_absolute_str(Path::new("/lib")), "/lib");
        assert_eq!(workspace_absolute_str(Path::new("/apps/web")), "/apps/web",);
    }

    #[test]
    fn host_join_appends_segments_to_cwd_root() {
        let cwd = PathBuf::from("/tmp/workspace");
        assert_eq!(
            host_join(&cwd, Path::new("/lib")),
            PathBuf::from("/tmp/workspace/lib"),
        );
        assert_eq!(
            host_join(&cwd, Path::new("/apps/web")),
            PathBuf::from("/tmp/workspace/apps/web"),
        );
    }

    // --- projects_entries on tree shapes -----------------------

    #[test]
    fn projects_entries_collects_literal_for_project_state() {
        let mut root = node("root", "/", SelectionState::None, Vec::new());
        root.children
            .push(node("lib", "/lib", SelectionState::Project, Vec::new()));
        let tree = Tree::new(root);
        let entries = projects_entries(&tree);
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].text, "/lib");
    }

    #[test]
    fn projects_entries_collects_glob_for_projects_parent_state() {
        let mut apps = node(
            "apps",
            "/apps",
            SelectionState::ProjectsParent,
            vec![node("api", "/apps/api", SelectionState::None, Vec::new())],
        );
        apps.expanded = true;
        let mut root = node("root", "/", SelectionState::None, vec![apps]);
        root.expanded = true;
        let tree = Tree::new(root);
        let entries = projects_entries(&tree);
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].text, "/apps/*");
    }

    #[test]
    fn projects_entries_mix_sorts_byte_ascending() {
        let mut apps = node(
            "apps",
            "/apps",
            SelectionState::ProjectsParent,
            vec![node("api", "/apps/api", SelectionState::None, Vec::new())],
        );
        apps.expanded = true;
        let mut lib = node("lib", "/lib", SelectionState::Project, Vec::new());
        lib.children_loaded = true;
        let mut root = node("root", "/", SelectionState::None, vec![apps, lib]);
        root.expanded = true;
        let tree = Tree::new(root);
        let entries = projects_entries(&tree);
        // `/apps/*` sorts before `/lib` lexicographically.
        assert_eq!(
            entries.iter().map(|e| e.text.clone()).collect::<Vec<_>>(),
            vec!["/apps/*".to_owned(), "/lib".to_owned()],
        );
    }

    // --- render_workspace_yml --------------------------------

    #[test]
    fn render_workspace_yml_empty_set_is_inline_empty_array() {
        let empty = std::collections::BTreeSet::new();
        assert_eq!(render_workspace_yml(&empty), "projects: []\n");
    }

    #[test]
    fn render_workspace_yml_one_entry_is_yaml_list() {
        let mut s = std::collections::BTreeSet::new();
        s.insert(ProjectsEntry {
            text: "/lib".to_owned(),
        });
        assert_eq!(render_workspace_yml(&s), "projects:\n  - /lib\n");
    }

    #[test]
    fn render_workspace_yml_multiple_entries_are_canonically_ordered() {
        let mut s = std::collections::BTreeSet::new();
        s.insert(ProjectsEntry {
            text: "/lib".to_owned(),
        });
        s.insert(ProjectsEntry {
            text: "/apps/*".to_owned(),
        });
        assert_eq!(
            render_workspace_yml(&s),
            "projects:\n  - /apps/*\n  - /lib\n",
        );
    }

    // --- plan_commit ------------------------------------------

    fn tree_with_one_project(name: &str, ws_path: &str) -> Tree {
        let mut root = node(
            "root",
            "/",
            SelectionState::None,
            vec![node(name, ws_path, SelectionState::Project, Vec::new())],
        );
        root.expanded = true;
        Tree::new(root)
    }

    #[test]
    fn plan_commit_scaffolds_haz_yml_for_each_project_root() {
        let tmp = TempDir::new().unwrap();
        fs::create_dir_all(tmp.path().join("lib")).unwrap();
        let tree = tree_with_one_project("lib", "/lib");
        let plan = plan_commit(&tree, tmp.path()).unwrap();
        assert_eq!(plan.workspace_yml_body, "projects:\n  - /lib\n");
        assert_eq!(plan.project_ymls.len(), 1);
        assert_eq!(plan.project_ymls[0].sanitised_name, "lib");
        assert_eq!(plan.project_ymls[0].body, "name: lib\ntasks: {}\n");
    }

    #[test]
    fn plan_commit_skips_project_root_with_pre_existing_haz_yml() {
        let tmp = TempDir::new().unwrap();
        fs::create_dir_all(tmp.path().join("lib")).unwrap();
        fs::write(tmp.path().join("lib/haz.yml"), "name: hand_written\n").unwrap();
        let tree = tree_with_one_project("lib", "/lib");
        let plan = plan_commit(&tree, tmp.path()).unwrap();
        assert_eq!(plan.workspace_yml_body, "projects:\n  - /lib\n");
        assert!(
            plan.project_ymls.is_empty(),
            "existing haz.yml must not be re-scaffolded: {:?}",
            plan.project_ymls,
        );
    }

    #[test]
    fn plan_commit_sanitises_basename_to_valid_project_name() {
        let tmp = TempDir::new().unwrap();
        fs::create_dir_all(tmp.path().join("My App")).unwrap();
        let mut root = node(
            "root",
            "/",
            SelectionState::None,
            vec![node(
                "My App",
                "/My App",
                SelectionState::Project,
                Vec::new(),
            )],
        );
        root.expanded = true;
        let tree = Tree::new(root);
        let plan = plan_commit(&tree, tmp.path()).unwrap();
        assert_eq!(plan.project_ymls.len(), 1);
        assert_eq!(plan.project_ymls[0].sanitised_name, "My-App");
    }

    #[test]
    fn plan_commit_errors_when_basename_sanitises_to_empty() {
        let tmp = TempDir::new().unwrap();
        // A directory whose basename is pure punctuation
        // sanitises to "" and fails validation.
        fs::create_dir_all(tmp.path().join("---")).unwrap();
        let mut root = node(
            "root",
            "/",
            SelectionState::None,
            vec![node("---", "/---", SelectionState::Project, Vec::new())],
        );
        root.expanded = true;
        let tree = Tree::new(root);
        let err = plan_commit(&tree, tmp.path()).unwrap_err();
        match err {
            CommitPlanError::SanitisationFailed {
                directory,
                sanitised,
            } => {
                assert_eq!(directory, "/---");
                assert_eq!(sanitised, "");
            }
        }
    }

    // --- apply_commit -----------------------------------------

    #[test]
    fn apply_commit_writes_haz_yml_then_workspace_yml() {
        let tmp = TempDir::new().unwrap();
        fs::create_dir_all(tmp.path().join("lib")).unwrap();
        let tree = tree_with_one_project("lib", "/lib");
        let plan = plan_commit(&tree, tmp.path()).unwrap();
        apply_commit(&plan, tmp.path()).unwrap();

        let haz_yml = fs::read_to_string(tmp.path().join("lib/haz.yml")).unwrap();
        assert_eq!(haz_yml, "name: lib\ntasks: {}\n");

        let workspace_yml = fs::read_to_string(tmp.path().join(".haz/workspace.yml")).unwrap();
        assert_eq!(workspace_yml, "projects:\n  - /lib\n");
    }

    #[test]
    fn apply_commit_creates_missing_haz_directory() {
        let tmp = TempDir::new().unwrap();
        fs::create_dir_all(tmp.path().join("lib")).unwrap();
        let tree = tree_with_one_project("lib", "/lib");
        let plan = plan_commit(&tree, tmp.path()).unwrap();
        assert!(!tmp.path().join(".haz").exists());
        apply_commit(&plan, tmp.path()).unwrap();
        assert!(tmp.path().join(".haz").exists());
    }

    #[test]
    fn apply_commit_creates_missing_project_root_directory() {
        // `projects-parent` semantics could in principle expand
        // to a subdirectory that the user named but doesn't yet
        // exist on disk; the executor MUST create it before
        // writing haz.yml.
        let tmp = TempDir::new().unwrap();
        let tree = tree_with_one_project("lib", "/lib");
        let plan = plan_commit(&tree, tmp.path()).unwrap();
        apply_commit(&plan, tmp.path()).unwrap();
        assert!(tmp.path().join("lib/haz.yml").exists());
    }

    #[test]
    fn apply_commit_with_empty_plan_writes_only_workspace_yml() {
        // `--yes`'s `projects: []` shape: no haz.ymls to
        // scaffold, just the workspace.yml.
        let tmp = TempDir::new().unwrap();
        let plan = super::CommitPlan {
            workspace_yml_body: "projects: []\n".to_owned(),
            project_ymls: Vec::new(),
        };
        apply_commit(&plan, tmp.path()).unwrap();
        let body = fs::read_to_string(tmp.path().join(".haz/workspace.yml")).unwrap();
        assert_eq!(body, "projects: []\n");
        // Only the `.haz/` directory was created.
        let top_entries: Vec<_> = fs::read_dir(tmp.path())
            .unwrap()
            .map(|e| e.unwrap().file_name())
            .collect();
        assert_eq!(top_entries, vec![std::ffi::OsString::from(".haz")]);
    }
}