git-shadow 0.0.3

Standalone shadow copies of git repos (or parts of them) in a working directory.
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
//! End-to-end tests that drive the compiled `git-shadow` binary against
//! real git repositories in a temporary directory, with the config
//! directory isolated per test via the platform's config env var.

use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};

const BIN: &str = env!("CARGO_BIN_EXE_git-shadow");
const PARENT_ORIGIN: &str = "git@github.com:example/parent.git";

struct TestEnv {
    root: tempfile::TempDir,
}

impl TestEnv {
    /// A parent repo with `PARENT_ORIGIN` as origin, plus a local bare
    /// repo (`shadow.git`) to clone shadows from.
    fn new() -> Self {
        let env = TestEnv {
            root: tempfile::tempdir().unwrap(),
        };

        let src = env.path("shadow-src");
        fs::create_dir(&src).unwrap();
        git(&src, &["init", "-q"]);
        git(
            &src,
            &[
                "-c",
                "user.email=test@example.com",
                "-c",
                "user.name=test",
                "commit",
                "-q",
                "--allow-empty",
                "-m",
                "init",
            ],
        );
        git(
            env.root.path(),
            &[
                "clone",
                "-q",
                "--bare",
                src.to_str().unwrap(),
                env.shadow_remote().to_str().unwrap(),
            ],
        );

        let parent = env.parent();
        fs::create_dir(&parent).unwrap();
        git(&parent, &["init", "-q"]);
        git(&parent, &["remote", "add", "origin", PARENT_ORIGIN]);

        env
    }

    fn path(&self, name: &str) -> PathBuf {
        self.root.path().join(name)
    }

    fn parent(&self) -> PathBuf {
        self.path("parent")
    }

    /// Local bare repo used as the shadow's remote; derives the default
    /// nickname "shadow".
    fn shadow_remote(&self) -> PathBuf {
        self.path("shadow.git")
    }

    /// Runs the binary in `dir` with the config directory redirected into
    /// this test's temp root.
    fn run_in(&self, dir: &Path, args: &[&str]) -> Output {
        let mut cmd = Command::new(BIN);
        cmd.args(args).current_dir(dir);

        let config_home = self.path("config-home");
        #[cfg(target_os = "windows")]
        cmd.env("APPDATA", &config_home);
        #[cfg(target_os = "macos")]
        cmd.env("HOME", &config_home);
        #[cfg(all(unix, not(target_os = "macos")))]
        cmd.env("XDG_CONFIG_HOME", &config_home);

        cmd.output().unwrap()
    }

    fn run(&self, args: &[&str]) -> Output {
        self.run_in(&self.parent(), args)
    }

    /// The config file the binary should use for the parent repo's origin.
    fn config_file(&self) -> PathBuf {
        #[cfg(target_os = "macos")]
        let base = self
            .path("config-home")
            .join("Library")
            .join("Application Support");
        #[cfg(not(target_os = "macos"))]
        let base = self.path("config-home");

        base.join("git-shadow")
            .join("github.com")
            .join("example")
            .join("parent")
            .join("config.toml")
    }

    fn exclude_file(&self) -> PathBuf {
        self.parent().join(".git").join("info").join("exclude")
    }
}

fn git(dir: &Path, args: &[&str]) {
    let status = Command::new("git")
        .args(args)
        .current_dir(dir)
        .status()
        .unwrap();
    assert!(status.success(), "git {args:?} failed in {}", dir.display());
}

fn stdout(output: &Output) -> String {
    String::from_utf8_lossy(&output.stdout).into_owned()
}

fn stderr(output: &Output) -> String {
    String::from_utf8_lossy(&output.stderr).into_owned()
}

/// `git status --porcelain` output for the parent repo.
fn parent_status(env: &TestEnv) -> String {
    let output = Command::new("git")
        .args(["status", "--porcelain"])
        .current_dir(env.parent())
        .output()
        .unwrap();
    String::from_utf8_lossy(&output.stdout).into_owned()
}

#[test]
fn no_arguments_prints_usage() {
    let env = TestEnv::new();

    let output = env.run(&[]);

    assert!(!output.status.success());
    assert!(stderr(&output).contains("Usage: git shadow"));
}

#[test]
fn help_flag_documents_the_subcommands() {
    let env = TestEnv::new();

    let output = env.run(&["--help"]);

    assert!(output.status.success());
    let out = stdout(&output);
    for subcommand in ["list", "sync", "clone", "remove"] {
        assert!(out.contains(subcommand), "help must mention '{subcommand}'");
    }
}

#[test]
fn shadow_name_without_git_command_prints_usage() {
    let env = TestEnv::new();

    let output = env.run(&["lonely-name"]);

    assert!(!output.status.success());
    assert!(stderr(&output).contains("usage: git shadow <shadow-name> <git-command>"));
}

#[test]
fn list_without_config_reports_no_shadows() {
    let env = TestEnv::new();

    let output = env.run(&["list"]);

    assert!(output.status.success());
    assert!(
        stdout(&output).contains("no shadows configured for git@github.com:example/parent.git")
    );
}

#[test]
fn list_rejects_unknown_flags() {
    let env = TestEnv::new();

    let output = env.run(&["list", "--bogus"]);

    assert!(!output.status.success());
    assert!(stderr(&output).contains("unexpected argument '--bogus'"));
}

#[test]
fn clone_registers_shadow_and_updates_exclude() {
    let env = TestEnv::new();

    let output = env.run(&["clone", env.shadow_remote().to_str().unwrap()]);

    assert!(output.status.success(), "stderr: {}", stderr(&output));
    let out = stdout(&output);
    assert!(out.contains("registered shadow 'shadow'"));
    assert!(out.contains("added '/shadow/'"));

    let config = fs::read_to_string(env.config_file()).unwrap();
    assert!(config.contains("version = 1"));
    assert!(config.contains("[shadows.shadow]"));
    assert!(config.contains("mapping = \"shadow/\""));

    let exclude = fs::read_to_string(env.exclude_file()).unwrap();
    assert!(exclude.contains("# >>> git-shadow (managed) >>>"));
    assert!(exclude.contains("/shadow/"));

    assert!(env.parent().join("shadow").join(".git").exists());
    assert_eq!(parent_status(&env), "", "shadow dir must be excluded");
}

#[test]
fn clone_refuses_duplicate_nickname() {
    let env = TestEnv::new();
    let remote = env.shadow_remote();

    assert!(
        env.run(&["clone", remote.to_str().unwrap()])
            .status
            .success()
    );
    let output = env.run(&["clone", remote.to_str().unwrap()]);

    assert!(!output.status.success());
    assert!(stderr(&output).contains("shadow 'shadow' already exists"));
}

#[test]
fn clone_refuses_non_empty_target_directory() {
    let env = TestEnv::new();
    let busy = env.parent().join("busy");
    fs::create_dir(&busy).unwrap();
    fs::write(busy.join("file.txt"), "").unwrap();

    let output = env.run(&[
        "clone",
        env.shadow_remote().to_str().unwrap(),
        "busy",
        "--name",
        "busy",
    ]);

    assert!(!output.status.success());
    assert!(stderr(&output).contains("exists and is not empty"));
    assert!(!env.config_file().exists(), "config must not be created");
}

#[test]
fn clone_from_subdirectory_stores_mapping_relative_to_repo_root() {
    let env = TestEnv::new();
    let sub = env.parent().join("sub");
    fs::create_dir(&sub).unwrap();

    let output = env.run_in(
        &sub,
        &[
            "clone",
            env.shadow_remote().to_str().unwrap(),
            "vendor/fb",
            "--name",
            "fb",
        ],
    );

    assert!(output.status.success(), "stderr: {}", stderr(&output));
    let config = fs::read_to_string(env.config_file()).unwrap();
    assert!(config.contains("mapping = \"sub/vendor/fb/\""));
    assert!(env.parent().join("sub/vendor/fb/.git").exists());
}

#[test]
fn list_shows_registered_shadows() {
    let env = TestEnv::new();
    assert!(
        env.run(&["clone", env.shadow_remote().to_str().unwrap()])
            .status
            .success()
    );

    let output = env.run(&["list"]);

    assert!(output.status.success());
    let out = stdout(&output);
    assert!(out.contains("shadow"));
    assert!(out.contains("shadow/"));
}

#[test]
fn sync_clones_missing_shadow_and_restores_exclude() {
    let env = TestEnv::new();
    assert!(
        env.run(&["clone", env.shadow_remote().to_str().unwrap()])
            .status
            .success()
    );
    fs::remove_dir_all(env.parent().join("shadow")).unwrap();
    fs::remove_file(env.exclude_file()).unwrap();

    let output = env.run(&["sync"]);

    assert!(output.status.success(), "stderr: {}", stderr(&output));
    assert!(stdout(&output).contains("shadow: cloning"));
    assert!(env.parent().join("shadow").join(".git").exists());
    let exclude = fs::read_to_string(env.exclude_file()).unwrap();
    assert!(exclude.contains("/shadow/"));
}

#[test]
fn sync_reports_present_shadows_and_is_idempotent() {
    let env = TestEnv::new();
    assert!(
        env.run(&["clone", env.shadow_remote().to_str().unwrap()])
            .status
            .success()
    );

    let output = env.run(&["sync"]);

    assert!(output.status.success());
    let out = stdout(&output);
    assert!(out.contains("shadow: already present"));
    assert!(!out.contains("updated exclude entries"));
}

#[test]
fn sync_warns_and_fails_on_non_repo_mapping() {
    let env = TestEnv::new();
    assert!(
        env.run(&["clone", env.shadow_remote().to_str().unwrap()])
            .status
            .success()
    );
    let dir = env.parent().join("shadow");
    fs::remove_dir_all(&dir).unwrap();
    fs::create_dir(&dir).unwrap();
    fs::write(dir.join("unrelated.txt"), "").unwrap();

    let output = env.run(&["sync"]);

    assert!(!output.status.success());
    assert!(stderr(&output).contains("is not a git repository"));
}

#[test]
fn remove_unregisters_but_keeps_directory() {
    let env = TestEnv::new();
    assert!(
        env.run(&["clone", env.shadow_remote().to_str().unwrap()])
            .status
            .success()
    );

    let output = env.run(&["remove", "shadow"]);

    assert!(output.status.success(), "stderr: {}", stderr(&output));
    let config = fs::read_to_string(env.config_file()).unwrap();
    assert!(!config.contains("[shadows.shadow]"));
    let exclude = fs::read_to_string(env.exclude_file()).unwrap();
    assert!(!exclude.contains("/shadow/"));
    assert!(env.parent().join("shadow").join(".git").exists());
}

#[test]
fn rm_alias_with_delete_removes_directory() {
    let env = TestEnv::new();
    assert!(
        env.run(&["clone", env.shadow_remote().to_str().unwrap()])
            .status
            .success()
    );

    let output = env.run(&["rm", "shadow", "--delete"]);

    assert!(output.status.success(), "stderr: {}", stderr(&output));
    assert!(!env.parent().join("shadow").exists());
}

#[test]
fn remove_unknown_shadow_fails() {
    let env = TestEnv::new();
    assert!(
        env.run(&["clone", env.shadow_remote().to_str().unwrap()])
            .status
            .success()
    );

    let output = env.run(&["remove", "nope"]);

    assert!(!output.status.success());
    assert!(stderr(&output).contains("shadow 'nope' not found"));
}

#[test]
fn passthrough_runs_git_inside_the_shadow() {
    let env = TestEnv::new();
    assert!(
        env.run(&["clone", env.shadow_remote().to_str().unwrap()])
            .status
            .success()
    );

    let output = env.run(&["shadow", "rev-parse", "--show-toplevel"]);

    assert!(output.status.success(), "stderr: {}", stderr(&output));
    let toplevel = PathBuf::from(stdout(&output).trim().to_string());
    assert_eq!(
        toplevel.file_name().unwrap().to_str().unwrap(),
        "shadow",
        "git must run inside the shadow repo, got {}",
        toplevel.display()
    );
}

#[test]
fn passthrough_fails_for_unknown_shadow() {
    let env = TestEnv::new();
    assert!(
        env.run(&["clone", env.shadow_remote().to_str().unwrap()])
            .status
            .success()
    );

    let output = env.run(&["nope", "status"]);

    assert!(!output.status.success());
    assert!(stderr(&output).contains("shadow 'nope' not found"));
}