dotm-rs 2.1.1

Dotfile manager with composable roles, templates, and host-specific overrides
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
use anyhow::Result;
use std::path::Path;

#[derive(Debug, Clone)]
pub struct DirtyFile {
    pub path: String,
    pub status: DirtyStatus,
}

#[derive(Debug, Clone, PartialEq)]
pub enum DirtyStatus {
    Modified,
    Added,
    Deleted,
    Untracked,
}

#[derive(Debug)]
pub enum PushResult {
    Success,
    NoRemote,
    Rejected(String),
    Error(String),
}

#[derive(Debug)]
pub enum PullResult {
    Success,
    NoRemote,
    AlreadyUpToDate,
    Conflicts(Vec<String>),
    Error(String),
}

#[derive(Debug)]
pub struct GitSummary {
    pub branch: Option<String>,
    pub dirty_count: usize,
    pub untracked_count: usize,
    pub modified_count: usize,
    pub ahead_behind: Option<(usize, usize)>,
}

pub struct GitRepo {
    repo: gix::Repository,
}

impl GitRepo {
    /// Attempt to open (discover) a git repository at or above `path`.
    /// Returns `None` if `path` is not inside a git repository.
    pub fn open(path: &Path) -> Option<Self> {
        let repo = gix::discover(path).ok()?;
        Some(Self { repo })
    }

    /// Returns the current branch name, or `None` if HEAD is detached.
    pub fn branch_name(&self) -> Result<Option<String>> {
        let head = self.repo.head()?;
        let name = head
            .referent_name()
            .map(|full| full.shorten().to_string());
        Ok(name)
    }

    /// Returns a high-level summary of the repository state: branch, dirty counts, ahead/behind.
    pub fn summary(&self) -> Result<GitSummary> {
        let branch = self.branch_name()?;
        let dirty = self.dirty_files()?;

        let untracked_count = dirty
            .iter()
            .filter(|f| matches!(f.status, DirtyStatus::Untracked))
            .count();
        let modified_count = dirty
            .iter()
            .filter(|f| !matches!(f.status, DirtyStatus::Untracked))
            .count();

        let ahead_behind = self.ahead_behind()?;

        Ok(GitSummary {
            branch,
            dirty_count: dirty.len(),
            untracked_count,
            modified_count,
            ahead_behind,
        })
    }

    /// Returns true if the working tree has any uncommitted changes or untracked files.
    pub fn is_dirty(&self) -> Result<bool> {
        let files = self.dirty_files()?;
        Ok(!files.is_empty())
    }

    /// Returns (ahead, behind) counts relative to the upstream tracking branch.
    /// Returns None if there's no tracking branch configured or HEAD is detached.
    pub fn ahead_behind(&self) -> Result<Option<(usize, usize)>> {
        let workdir = self
            .repo
            .workdir()
            .ok_or_else(|| anyhow::anyhow!("bare repository has no working directory"))?;

        let output = std::process::Command::new("git")
            .args(["rev-list", "--left-right", "--count", "HEAD...@{upstream}"])
            .current_dir(workdir)
            .output()?;

        if !output.status.success() {
            // No upstream configured, detached HEAD, etc.
            return Ok(None);
        }

        let stdout = String::from_utf8(output.stdout)?;
        let parts: Vec<&str> = stdout.trim().split('\t').collect();
        if parts.len() != 2 {
            return Ok(None);
        }

        let ahead = parts[0].parse::<usize>().unwrap_or(0);
        let behind = parts[1].parse::<usize>().unwrap_or(0);

        Ok(Some((ahead, behind)))
    }

    /// Stage all changes and create a commit. Errors if there's nothing to commit.
    pub fn commit_all(&self, message: &str) -> Result<()> {
        if !self.is_dirty()? {
            anyhow::bail!("nothing to commit — working tree is clean");
        }

        let workdir = self
            .repo
            .workdir()
            .ok_or_else(|| anyhow::anyhow!("bare repository has no working directory"))?;

        let status = std::process::Command::new("git")
            .args(["add", "-A"])
            .current_dir(workdir)
            .status()?;

        if !status.success() {
            anyhow::bail!("git add failed with exit code {}", status);
        }

        let status = std::process::Command::new("git")
            .args(["commit", "-m", message])
            .current_dir(workdir)
            .status()?;

        if !status.success() {
            anyhow::bail!("git commit failed with exit code {}", status);
        }

        Ok(())
    }

    /// Returns a list of dirty files with their statuses.
    /// Uses `git status --porcelain` for reliable results across all repo states.
    pub fn dirty_files(&self) -> Result<Vec<DirtyFile>> {
        let workdir = self
            .repo
            .workdir()
            .ok_or_else(|| anyhow::anyhow!("bare repository has no working directory"))?;

        let output = std::process::Command::new("git")
            .args(["status", "--porcelain"])
            .current_dir(workdir)
            .output()?;

        anyhow::ensure!(
            output.status.success(),
            "git status failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );

        let stdout = String::from_utf8(output.stdout)?;
        let mut files = Vec::new();

        for line in stdout.lines() {
            if line.len() < 4 {
                continue;
            }
            let index_status = line.as_bytes()[0];
            let worktree_status = line.as_bytes()[1];
            let path = line[3..].to_string();

            let status = match (index_status, worktree_status) {
                (b'?', b'?') => DirtyStatus::Untracked,
                (b'A', _) | (_, b'A') => DirtyStatus::Added,
                (b'D', _) | (_, b'D') => DirtyStatus::Deleted,
                _ => DirtyStatus::Modified,
            };

            files.push(DirtyFile { path, status });
        }

        Ok(files)
    }

    fn has_remote(&self) -> bool {
        self.repo.remote_names().first().is_some()
    }

    pub fn push(&self) -> Result<PushResult> {
        if !self.has_remote() {
            return Ok(PushResult::NoRemote);
        }

        let workdir = self
            .repo
            .workdir()
            .ok_or_else(|| anyhow::anyhow!("bare repository has no working directory"))?;

        let output = std::process::Command::new("git")
            .args(["push"])
            .current_dir(workdir)
            .output()?;

        if output.status.success() {
            Ok(PushResult::Success)
        } else {
            let stderr = String::from_utf8_lossy(&output.stderr).to_string();
            if stderr.contains("rejected") {
                Ok(PushResult::Rejected(stderr))
            } else {
                Ok(PushResult::Error(stderr))
            }
        }
    }

    pub fn pull(&self) -> Result<PullResult> {
        if !self.has_remote() {
            return Ok(PullResult::NoRemote);
        }

        let workdir = self
            .repo
            .workdir()
            .ok_or_else(|| anyhow::anyhow!("bare repository has no working directory"))?;

        let output = std::process::Command::new("git")
            .args(["pull"])
            .current_dir(workdir)
            .output()?;

        if output.status.success() {
            let stdout = String::from_utf8_lossy(&output.stdout);
            if stdout.contains("Already up to date") {
                Ok(PullResult::AlreadyUpToDate)
            } else {
                Ok(PullResult::Success)
            }
        } else {
            let stdout = String::from_utf8_lossy(&output.stdout);
            let stderr = String::from_utf8_lossy(&output.stderr);
            if stdout.contains("CONFLICT") || stderr.contains("CONFLICT") {
                let conflicts = self.list_conflicted_files()?;
                Ok(PullResult::Conflicts(conflicts))
            } else {
                Ok(PullResult::Error(stderr.to_string()))
            }
        }
    }

    fn list_conflicted_files(&self) -> Result<Vec<String>> {
        let workdir = self
            .repo
            .workdir()
            .ok_or_else(|| anyhow::anyhow!("bare repository has no working directory"))?;

        let output = std::process::Command::new("git")
            .args(["diff", "--name-only", "--diff-filter=U"])
            .current_dir(workdir)
            .output()?;

        let files = String::from_utf8_lossy(&output.stdout)
            .lines()
            .map(|l| l.to_string())
            .collect();

        Ok(files)
    }
}

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

    #[test]
    fn open_returns_none_for_non_repo() {
        let dir = TempDir::new().unwrap();
        assert!(GitRepo::open(dir.path()).is_none());
    }

    #[test]
    fn open_returns_some_for_git_repo() {
        let dir = TempDir::new().unwrap();
        gix::init(dir.path()).unwrap();
        assert!(GitRepo::open(dir.path()).is_some());
    }

    #[test]
    fn branch_name_on_fresh_repo() {
        let dir = TempDir::new().unwrap();
        gix::init(dir.path()).unwrap();
        let repo = GitRepo::open(dir.path()).unwrap();
        let name = repo.branch_name().unwrap();
        assert_eq!(name, Some("main".to_string()));
    }

    #[test]
    fn is_dirty_on_clean_repo() {
        let dir = TempDir::new().unwrap();
        gix::init(dir.path()).unwrap();
        let repo = GitRepo::open(dir.path()).unwrap();
        assert!(!repo.is_dirty().unwrap());
    }

    #[test]
    fn is_dirty_with_untracked_file() {
        let dir = TempDir::new().unwrap();
        gix::init(dir.path()).unwrap();
        std::fs::write(dir.path().join("hello.txt"), "hello").unwrap();
        let repo = GitRepo::open(dir.path()).unwrap();
        assert!(repo.is_dirty().unwrap());
    }

    #[test]
    fn dirty_files_lists_changes() {
        let dir = TempDir::new().unwrap();
        gix::init(dir.path()).unwrap();
        std::fs::write(dir.path().join("a.txt"), "aaa").unwrap();
        std::fs::write(dir.path().join("b.txt"), "bbb").unwrap();
        let repo = GitRepo::open(dir.path()).unwrap();
        let files = repo.dirty_files().unwrap();
        assert_eq!(files.len(), 2);
        assert!(files.iter().all(|f| f.status == DirtyStatus::Untracked));
    }

    #[test]
    fn ahead_behind_returns_none_without_remote() {
        let dir = TempDir::new().unwrap();
        gix::init(dir.path()).unwrap();
        let repo = GitRepo::open(dir.path()).unwrap();
        let result = repo.ahead_behind().unwrap();
        assert_eq!(result, None);
    }

    /// Configure a minimal git identity in the given repo so `git commit` works.
    fn configure_test_identity(dir: &Path) {
        for (key, value) in [
            ("user.name", "Test User"),
            ("user.email", "test@test.com"),
        ] {
            std::process::Command::new("git")
                .args(["config", key, value])
                .current_dir(dir)
                .status()
                .unwrap();
        }
    }

    #[test]
    fn commit_all_creates_commit() {
        let dir = TempDir::new().unwrap();
        gix::init(dir.path()).unwrap();
        configure_test_identity(dir.path());
        std::fs::write(dir.path().join("file.txt"), "content").unwrap();

        let repo = GitRepo::open(dir.path()).unwrap();
        repo.commit_all("test commit").unwrap();

        let gix_repo = gix::open(dir.path()).unwrap();
        let head = gix_repo.head_commit().unwrap();
        let msg = head.message_raw_sloppy();
        assert!(
            msg.starts_with(b"test commit"),
            "commit message should match"
        );
    }

    #[test]
    fn commit_all_errors_when_nothing_to_commit() {
        let dir = TempDir::new().unwrap();
        gix::init(dir.path()).unwrap();
        let repo = GitRepo::open(dir.path()).unwrap();
        let result = repo.commit_all("empty commit");
        assert!(result.is_err());
    }

    #[test]
    fn push_returns_no_remote_without_remote() {
        let dir = TempDir::new().unwrap();
        gix::init(dir.path()).unwrap();
        let repo = GitRepo::open(dir.path()).unwrap();
        let result = repo.push().unwrap();
        assert!(matches!(result, PushResult::NoRemote));
    }

    #[test]
    fn pull_returns_no_remote_without_remote() {
        let dir = TempDir::new().unwrap();
        gix::init(dir.path()).unwrap();
        let repo = GitRepo::open(dir.path()).unwrap();
        let result = repo.pull().unwrap();
        assert!(matches!(result, PullResult::NoRemote));
    }

    #[test]
    fn summary_clean_repo() {
        let dir = TempDir::new().unwrap();
        gix::init(dir.path()).unwrap();
        let repo = GitRepo::open(dir.path()).unwrap();
        let summary = repo.summary().unwrap();
        assert!(summary.branch.is_some());
        assert_eq!(summary.dirty_count, 0);
        assert!(summary.ahead_behind.is_none());
    }

    #[test]
    fn summary_with_dirty_files() {
        let dir = TempDir::new().unwrap();
        gix::init(dir.path()).unwrap();
        std::fs::write(dir.path().join("file.txt"), "content").unwrap();
        let repo = GitRepo::open(dir.path()).unwrap();
        let summary = repo.summary().unwrap();
        assert!(summary.dirty_count > 0);
    }
}