magoo 0.2.2

A wrapper for git submodule that simplifies the workflows
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
666
667
668
669
670
671
672
673
674
675
676
677
678
//! Low level integration with git
use std::borrow::Cow;
use std::cell::OnceCell;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
use std::process::{Command, ExitStatus, Stdio};
use std::time::Duration;

use fs4::fs_std::FileExt;

use crate::print::{
    self, println_error, println_hint, println_info, println_verbose, println_warn,
};
use crate::version;

/// Context for running git commands
pub struct GitContext {
    /// The absolute path of the working directory to run the git commands
    working_dir: PathBuf,

    /// The path to the .git directory
    ///
    /// This is retrieved from `git rev-parse --git-dir` and cached.
    git_dir_cell: OnceCell<PathBuf>,

    /// The path to the top level directory
    ///
    /// This is retrieved from `git rev-parse --show-toplevel` and cached.
    top_level_cell: OnceCell<PathBuf>,
}

/// Implementation for basic operations
impl GitContext {
    /// Create a new GitContext for running git commands in the given working directory
    pub fn try_from<S>(working_dir: S) -> Result<Self, GitError>
    where
        S: AsRef<Path>,
    {
        if which::which("git").is_err() {
            return Err(GitError::NotInstalled);
        }
        Ok(Self {
            working_dir: working_dir.as_ref().canonicalize_git()?,
            git_dir_cell: OnceCell::new(),
            top_level_cell: OnceCell::new(),
        })
    }

    /// Return a guard that locks the repository until dropped. Other magoo processes cannot access
    /// the repository while the guard is alive.
    pub fn lock(&self) -> Result<Guard, GitError> {
        let git_dir = self.git_dir()?;
        let lock_path = git_dir.join("magoo.lock");
        Guard::new(lock_path)
    }

    /// Check if the version is supported. If print is true, it will print the info when the
    /// version is supported. Otherwise only print if it's not supported
    pub fn check_version(&self, print: bool) -> Result<(), GitError> {
        let out = self.run_git_command(&["--version"], false)?.join("");
        let version = version::parse_git_version(&out).ok_or_else(|| {
            GitError::UnsupportedVersion("nnable to parse git version".to_string())
        })?;
        if !version::is_supported(&version) {
            println_error!("Magoo does not support your git version!");
            println_error!("Your version is: {}", version);
            println_hint!(
                "Supported versions are: {}",
                version::get_supported_versions()
            );
            println_hint!(
                "Please upgrade your git to a supported version or use `magoo --allow-unsupported COMMAND`"
            );
            return Err(GitError::UnsupportedVersion(version.to_string()));
        }
        if print {
            println_info!("Magoo supports your git version.");
            println_info!("Your version is: {}", version);
            println_info!(
                "Supported versions are: {}",
                version::get_supported_versions()
            );
        }
        Ok(())
    }

    /// Get the absolute path to the .git directory
    pub fn git_dir(&self) -> Result<&PathBuf, GitError> {
        if let Some(git_dir) = self.git_dir_cell.get() {
            return Ok(git_dir);
        }

        let git_dir_path = match self.git_dir_raw()? {
            Some(x) => x,
            None => {
                return Err(GitError::UnexpectedOutput(
                    "git did not return the .git directory".to_string(),
                ));
            }
        };
        let path = self.working_dir.join(git_dir_path).canonicalize_git()?;

        self.git_dir_cell.set(path).unwrap();
        Ok(self.git_dir_cell.get().unwrap())
    }

    /// Return the raw output of `git rev-parse --git-dir`
    pub fn git_dir_raw(&self) -> Result<Option<String>, GitError> {
        let output = self.run_git_command(&["rev-parse", "--git-dir"], false)?;
        Ok(output.into_iter().next())
    }

    /// Get the absolute path to the top level directory
    pub fn top_level_dir(&self) -> Result<&PathBuf, GitError> {
        if let Some(top_level) = self.top_level_cell.get() {
            return Ok(top_level);
        }

        let output = self.run_git_command(&["rev-parse", "--show-toplevel"], false)?;
        let top_dir_path = output.first().ok_or_else(|| {
            GitError::UnexpectedOutput("git did not return the top level directory".to_string())
        })?;
        let path = self.working_dir.join(top_dir_path).canonicalize_git()?;

        self.top_level_cell.set(path).unwrap();
        Ok(self.top_level_cell.get().unwrap())
    }

    /// Get the path in `git -C <path> ...` to run the command in the top level directory
    pub fn get_top_level_switch(&self) -> Result<Option<String>, GitError> {
        let top_level_dir = self.top_level_dir()?;

        let command = match Path::new(".").canonicalize() {
            Ok(cwd) => {
                if &cwd == top_level_dir {
                    None
                } else {
                    let path = pathdiff::diff_paths(top_level_dir, &cwd)
                        .unwrap_or(top_level_dir.to_path_buf());
                    let diff = path.to_cmd_arg();
                    Some(quote_arg(&diff).to_string())
                }
            }
            Err(_) => {
                let top_level = top_level_dir.to_cmd_arg();
                Some(quote_arg(&top_level).to_string())
            }
        };

        Ok(command)
    }

    /// Run the git command from self's working directory. The output of the command will be returned as a vector of lines.
    fn run_git_command(&self, args: &[&str], print: bool) -> Result<Vec<String>, GitError> {
        let args_str = args
            .iter()
            .map(|x| {
                if x.contains(' ') {
                    format!("'{x}'")
                } else {
                    x.to_string()
                }
            })
            .collect::<Vec<_>>()
            .join(" ");
        let command = format!("git {args_str}");
        println_verbose!("Running `{command}`");

        let mut child = Command::new("git")
            .args(args)
            .current_dir(&self.working_dir)
            .stdout(Stdio::piped())
            .stderr(if !print {
                Stdio::piped()
            } else {
                Stdio::inherit()
            })
            .spawn()
            .map_err(|e| {
                GitError::CommandFailed(command.clone(), "failed to spawn process".to_string(), e)
            })?;

        let mut output = Vec::new();
        if let Some(stdout) = child.stdout.take() {
            let reader = BufReader::new(stdout);
            for line in reader.lines() {
                let line = line.map_err(|e| {
                    GitError::CommandFailed(command.clone(), "failed to read output".to_string(), e)
                })?;
                if print {
                    println_info!("{line}");
                }
                output.push(line);
            }
        }

        if print::is_verbose() {
            if let Some(stderr) = child.stderr.take() {
                let reader = BufReader::new(stderr);
                for line in reader.lines().map_while(Result::ok) {
                    println_verbose!("{line}");
                }
            }
        }
        let status = child.wait().map_err(|e| {
            GitError::CommandFailed(
                command.clone(),
                "command did not finish normally".to_string(),
                e,
            )
        })?;
        println_verbose!("Git command finished: {}", status);
        if status.success() {
            Ok(output)
        } else {
            Err(GitError::ExitStatus(command, status))
        }
    }
}

/// Wrapper implementation for git commands
impl GitContext {
    /// Run `git status` and print the status
    pub fn status(&self) -> Result<(), GitError> {
        self.run_git_command(&["status"], true)?;
        Ok(())
    }

    /// Run `git -C top_level ls-files ...`
    pub fn ls_files(&self, extra_args: &[&str]) -> Result<Vec<String>, GitError> {
        let top_level_dir = self.top_level_dir()?.to_cmd_arg();
        let mut args = vec!["-C", &top_level_dir, "ls-files"];
        args.extend_from_slice(extra_args);
        self.run_git_command(&args, false)
    }

    /// Run `git describe --all <commit>` and return the first output
    pub fn describe(&self, commit: &str) -> Option<String> {
        self.run_git_command(&["describe", "--all", commit], false)
            .ok()
            .and_then(|x| x.into_iter().next())
    }

    /// Run `git rev-parse HEAD`
    pub fn head(&self) -> Result<Option<String>, GitError> {
        let output = self.run_git_command(&["rev-parse", "HEAD"], false)?;
        Ok(output.into_iter().next())
    }

    /// Run `git config -f config_path --get key`
    ///
    /// The config path is resolved relative to the working directory of this context.
    pub fn get_config<S>(&self, config_path: S, key: &str) -> Result<Option<String>, GitError>
    where
        S: AsRef<Path>,
    {
        let config_path = config_path.to_cmd_arg();
        let value = self
            .run_git_command(&["config", "-f", &config_path, "--get", key], false)?
            .into_iter()
            .next();
        Ok(value)
    }

    /// Calls `git config -f config_path ... --get-regexp regexp` to get (key, value) pairs in the config file
    ///
    /// The config path is resolved relative to the working directory of this context.
    pub fn get_config_regexp<S>(
        &self,
        config_path: S,
        regexp: &str,
    ) -> Result<Vec<(String, String)>, GitError>
    where
        S: AsRef<Path>,
    {
        let config_path = config_path.to_cmd_arg();
        let name_and_values = self.run_git_command(
            &["config", "-f", &config_path, "--get-regexp", regexp],
            false,
        )?;
        let name_only = self.run_git_command(
            &[
                "config",
                "-f",
                &config_path,
                "--name-only",
                "--get-regexp",
                regexp,
            ],
            false,
        )?;

        let mut name_values = Vec::new();
        for (name, name_and_value) in name_only.iter().zip(name_and_values.iter()) {
            match name_and_value.strip_prefix(name) {
                Some(value) => {
                    name_values.push((name.trim().to_string(), value.trim().to_string()));
                }
                None => {
                    return Err(GitError::InvalidConfig(
                        "unexpected config key mismatch in git output.".to_string(),
                    ));
                }
            }
        }

        Ok(name_values)
    }

    /// Calls `git config` to set or remove a config from a config file.
    ///
    /// The config path is resolved relative to the working directory of this context.
    pub fn set_config<S>(
        &self,
        config_path: S,
        key: &str,
        value: Option<&str>,
    ) -> Result<(), GitError>
    where
        S: AsRef<Path>,
    {
        let config_path = config_path.to_cmd_arg();
        let mut args = vec!["config", "-f", &config_path];
        match value {
            Some(v) => {
                args.push(key);
                args.push(v);
            }
            None => {
                args.push("--unset");
                args.push(key);
            }
        }
        self.run_git_command(&args, false)?;
        Ok(())
    }

    /// Remove a config section from a config file.
    ///
    /// The config path is resolved relative to the working directory of this context.
    pub fn remove_config_section<S>(&self, config_path: S, section: &str) -> Result<(), GitError>
    where
        S: AsRef<Path>,
    {
        let config_path = config_path.to_cmd_arg();
        self.run_git_command(
            &["config", "-f", &config_path, "--remove-section", section],
            false,
        )?;
        Ok(())
    }

    /// Remove an object from the index and stage the change. The path should be relative from repo top level
    pub fn remove_from_index(&self, path: &str) -> Result<(), GitError> {
        let top_level_dir = self.top_level_dir()?.to_cmd_arg();

        // ignore the error because the file might not be in the index
        let _ = self.run_git_command(&["-C", &top_level_dir, "rm", path], false);

        let _ = self.run_git_command(&["-C", &top_level_dir, "add", path], false);
        Ok(())
    }

    /// Run `git add`
    pub fn add(&self, path: &str) -> Result<(), GitError> {
        let top_level_dir = self.top_level_dir()?.to_cmd_arg();

        self.run_git_command(&["-C", &top_level_dir, "add", path], false)?;
        Ok(())
    }

    /// Runs `git submodule deinit [-- <path>]`. Path should be from top level
    pub fn submodule_deinit(&self, path: Option<&str>, force: bool) -> Result<(), GitError> {
        let top_level_dir = self.top_level_dir()?.to_cmd_arg();
        let mut args = vec!["-C", &top_level_dir, "submodule", "deinit"];

        if force {
            args.push("--force");
        }

        if let Some(path) = path {
            args.push("--");
            args.push(path);
        } else {
            args.push("--all");
        }
        self.run_git_command(&args, true)?;

        Ok(())
    }

    /// Runs `git submodule init [-- <path>]`. Path should be from top level
    pub fn submodule_init(&self, path: Option<&str>) -> Result<(), GitError> {
        let top_level_dir = self.top_level_dir()?.to_cmd_arg();
        let mut args = vec!["-C", &top_level_dir, "submodule", "init"];

        if let Some(path) = path {
            args.push("--");
            args.push(path);
        }
        self.run_git_command(&args, true)?;

        Ok(())
    }

    /// Runs `git submodule sync [-- <path>]`. Path should be from top level
    pub fn submodule_sync(&self, path: Option<&str>, recursive: bool) -> Result<(), GitError> {
        let top_level_dir = self.top_level_dir()?.to_cmd_arg();
        let mut args = vec!["-C", &top_level_dir, "submodule", "sync"];

        if recursive {
            args.push("--recursive");
        }

        if let Some(path) = path {
            args.push("--");
            args.push(path);
        }
        self.run_git_command(&args, true)?;

        Ok(())
    }

    /// Runs `git submodule set-branch`. Path should be from top level
    ///
    /// Note: Pre git 2.43, there's a bug treating the argument as name instead of path.
    pub fn submodule_set_branch(&self, path: &str, branch: Option<&str>) -> Result<(), GitError> {
        let top_level_dir = self.top_level_dir()?.to_cmd_arg();
        let mut args = vec!["-C", &top_level_dir, "submodule", "set-branch"];
        match branch {
            Some(branch) => {
                args.push("--branch");
                args.push(branch);
            }
            None => {
                args.push("--default");
            }
        }
        args.push("--");
        args.push(path);
        self.run_git_command(&args, true)?;
        Ok(())
    }

    /// Runs `git submodule set-url`.
    ///
    /// Note: Pre git 2.43, there's a bug treating the argument as name instead of path.
    pub fn submodule_set_url(&self, path: &str, url: &str) -> Result<(), GitError> {
        let top_level_dir = self.top_level_dir()?.to_cmd_arg();
        self.run_git_command(
            &[
                "-C",
                &top_level_dir,
                "submodule",
                "set-url",
                "--",
                path,
                url,
            ],
            true,
        )?;
        Ok(())
    }

    /// Runs `git submodule update [-- <path>]`. Path should be from top level
    pub fn submodule_update(
        &self,
        path: Option<&str>,
        force: bool,
        remote: bool,
        recursive: bool,
    ) -> Result<(), GitError> {
        let top_level_dir = self.top_level_dir()?.to_cmd_arg();
        let mut args = vec!["-C", &top_level_dir, "submodule", "update"];

        if force {
            args.push("--force");
        }

        if remote {
            args.push("--remote");
        }

        if recursive {
            args.push("--init");
            args.push("--recursive");
        }

        if let Some(path) = path {
            args.push("--");
            args.push(path);
        }
        self.run_git_command(&args, true)?;

        Ok(())
    }

    /// Runs `git submodule add`. Path should be from top level
    pub fn submodule_add(
        &self,
        url: &str,
        path: Option<&str>,
        branch: Option<&str>,
        name: Option<&str>,
        depth: Option<usize>,
        force: bool,
    ) -> Result<(), GitError> {
        let top_level_dir = self.top_level_dir()?.to_cmd_arg();
        let mut args = vec!["-C", &top_level_dir, "submodule", "add"];
        if force {
            args.push("--force");
        }
        if let Some(branch) = branch {
            args.push("--branch");
            args.push(branch);
        }
        if let Some(name) = name {
            args.push("--name");
            args.push(name);
        }
        let depth = depth.map(|x| x.to_string());
        if let Some(depth) = &depth {
            args.push("--depth");
            args.push(depth);
        }
        args.push("--");
        args.push(url);
        if let Some(path) = path {
            args.push(path);
        }
        self.run_git_command(&args, true)?;
        Ok(())
    }
}

/// Guard that uses file locking to ensure only one process are manipulating
/// the submodules at a time.
#[derive(Debug)]
pub struct Guard(pub File, pub PathBuf);

impl Guard {
    /// Create a new guard with the given path as the file lock. Will block until
    /// the lock can be acquired.
    pub fn new<P>(path: P) -> Result<Self, GitError>
    where
        P: AsRef<Path>,
    {
        let path = path.as_ref();
        if path.exists() {
            println_warn!(
                "Waiting on file lock. If you are sure no other magoo processes are running, you can remove the lock file `{}`",
                path.to_cmd_arg()
            );
        }
        while path.exists() {
            println_verbose!("Waiting for lock file...");
            std::thread::sleep(Duration::from_millis(1000));
        }
        let file = std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .truncate(true)
            .open(path)
            .map_err(|e| GitError::LockFailed(path.to_cmd_arg(), e))?;
        file.lock_exclusive()
            .map_err(|e| GitError::LockFailed(path.to_cmd_arg(), e))?;
        println_verbose!("Acquired lock file `{}`", path.to_cmd_arg());
        Ok(Self(file, path.to_path_buf()))
    }
}

impl Drop for Guard {
    fn drop(&mut self) {
        let path = &self.1.to_cmd_arg();
        println_verbose!("Releasing lock file `{path}`");
        if <File as FileExt>::unlock(&self.0).is_err() {
            println_verbose!("Failed to unlock file `{path}`");
        }
        if std::fs::remove_file(&self.1).is_err() {
            println_verbose!("Failed to remove file `{path}`");
        }
    }
}

/// Error type for the program
#[derive(Debug, thiserror::Error)]
pub enum GitError {
    #[error("operation was successful")]
    Success,

    #[error("git is not installed or not in PATH")]
    NotInstalled,

    #[error("fail to read `{0}`: {1}")]
    CanonicalizeFail(String, std::io::Error),

    #[error("unexpected output: {0}")]
    UnexpectedOutput(String),

    #[error("failed to execute `{0}`: {1}: {2}")]
    CommandFailed(String, String, std::io::Error),

    #[error("command `{0}` finished with {1}")]
    ExitStatus(String, ExitStatus),

    #[error("cannot process config: {0}")]
    InvalidConfig(String),

    #[error("cannot process index: {0}")]
    InvalidIndex(String),

    #[error("cannot find module `{0}`")]
    ModuleNotFound(String),

    #[error("cannot lock `{0}`: {1}")]
    LockFailed(String, std::io::Error),

    #[error("fix the issues above and try again.")]
    NeedFix(bool /* should show fatal */),

    #[error("unsupported git version: {0}")]
    UnsupportedVersion(String),
}

/// Helper trait to canonicalize a path and return a [`GitError`] if failed
pub trait GitCanonicalize {
    fn canonicalize_git(&self) -> Result<PathBuf, GitError>;
}

impl<S> GitCanonicalize for S
where
    S: AsRef<Path>,
{
    fn canonicalize_git(&self) -> Result<PathBuf, GitError> {
        let s = self.as_ref();
        s.canonicalize()
            .map_err(|e| GitError::CanonicalizeFail(s.display().to_string(), e))
    }
}

/// Helper trait to clean a path to be used as command line argument
pub trait GitCmdPath {
    fn to_cmd_arg(&self) -> String;
}

impl<S> GitCmdPath for S
where
    S: AsRef<Path>,
{
    #[cfg(not(windows))]
    fn to_cmd_arg(&self) -> String {
        self.as_ref().display().to_string()
    }

    #[cfg(windows)]
    fn to_cmd_arg(&self) -> String {
        let s = self.as_ref().display().to_string();
        match s.strip_prefix(r"\\?\") {
            Some(x) => x.to_string(),
            None => s,
        }
    }
}

/// Quote the argument for shell.
pub fn quote_arg(s: &str) -> Cow<'_, str> {
    // note that this implementation doesn't work in a few edge cases
    // but atm I don't have enough time to thoroughly test it
    if s.is_empty() {
        Cow::Borrowed("''")
    } else if s.contains(' ') || s.contains('\'') {
        Cow::Owned(format!("'{s}'"))
    } else {
        Cow::Borrowed(s)
    }
}