git-sync-rs 0.7.7

Automatic git repository synchronization with file watching
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
use crate::error::{Result, SyncError};
use std::path::Path;
use std::process::{Command, Output};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CommitOutcome {
    Created,
    NoChanges,
}

pub trait GitTransport: Send + Sync {
    fn fetch_branch(&self, repo_path: &Path, remote: &str, branch: &str) -> Result<()>;
    fn push_refspec(&self, repo_path: &Path, remote: &str, refspec: &str) -> Result<()>;
    fn push_branch_upstream(&self, repo_path: &Path, remote: &str, branch: &str) -> Result<()>;
    fn commit(&self, repo_path: &Path, message: &str, skip_hooks: bool) -> Result<CommitOutcome>;
}

#[derive(Debug, Default)]
pub struct CommandGitTransport;

impl CommandGitTransport {
    fn run_commit_command(
        &self,
        repo_path: &Path,
        message: &str,
        skip_hooks: bool,
        identity: Option<(&str, &str)>,
    ) -> std::io::Result<Output> {
        let mut command = Command::new("git");
        command.arg("commit");
        if skip_hooks {
            command.arg("--no-verify");
        }
        command.arg("-m").arg(message).current_dir(repo_path);

        if let Some((name, email)) = identity {
            command
                .env("GIT_AUTHOR_NAME", name)
                .env("GIT_AUTHOR_EMAIL", email)
                .env("GIT_COMMITTER_NAME", name)
                .env("GIT_COMMITTER_EMAIL", email);
        }

        command.output()
    }

    fn is_missing_identity_error(output: &str) -> bool {
        let lower = output.to_lowercase();
        lower.contains("author identity unknown")
            || lower.contains("committer identity unknown")
            || lower.contains("please tell me who you are")
            || lower.contains("unable to auto-detect email address")
            || lower.contains("empty ident name")
            || lower.contains("empty ident email")
    }

    fn sanitize_email_component(value: &str) -> String {
        let mut out = String::with_capacity(value.len());
        for ch in value.chars() {
            if ch.is_ascii_alphanumeric() || ch == '.' || ch == '_' || ch == '-' {
                out.push(ch.to_ascii_lowercase());
            } else {
                out.push('-');
            }
        }
        out.trim_matches('-').to_string()
    }

    fn fallback_commit_identity() -> (String, String) {
        let user = std::env::var("USER")
            .ok()
            .filter(|u| !u.trim().is_empty())
            .unwrap_or_else(|| "git-sync-rs".to_string());
        let hostname = hostname::get()
            .ok()
            .map(|h| h.to_string_lossy().to_string())
            .filter(|h| !h.trim().is_empty())
            .unwrap_or_else(|| "localhost".to_string());

        let local = Self::sanitize_email_component(&user);
        let domain = Self::sanitize_email_component(&hostname);
        let local = if local.is_empty() {
            "git-sync-rs".to_string()
        } else {
            local
        };
        let domain = if domain.is_empty() {
            "localhost".to_string()
        } else {
            domain
        };

        ("git-sync-rs".to_string(), format!("{local}@{domain}"))
    }

    fn parse_commit_output(output: &Output) -> std::result::Result<CommitOutcome, String> {
        if output.status.success() {
            return Ok(CommitOutcome::Created);
        }

        let stderr = String::from_utf8_lossy(&output.stderr);
        let stdout = String::from_utf8_lossy(&output.stdout);
        let combined = format!("{stderr}\n{stdout}");
        let lower = combined.to_lowercase();

        if lower.contains("nothing to commit")
            || lower.contains("nothing added to commit")
            || lower.contains("no changes added to commit")
        {
            return Ok(CommitOutcome::NoChanges);
        }

        Err(combined)
    }

    fn classify_git_error(
        &self,
        command: &str,
        stderr: &str,
        remote: Option<&str>,
        branch: Option<&str>,
    ) -> SyncError {
        let stderr_lower = stderr.to_lowercase();

        if stderr.contains("couldn't find remote ref")
            || stderr.contains("fatal: couldn't find remote ref")
        {
            return SyncError::RemoteBranchNotFound {
                remote: remote.unwrap_or("origin").to_string(),
                branch: branch.unwrap_or("<unknown>").to_string(),
            };
        }

        if stderr_lower.contains("authentication failed")
            || stderr_lower.contains("permission denied")
            || stderr_lower.contains("could not read from remote repository")
        {
            return SyncError::AuthenticationFailed {
                operation: command.to_string(),
            };
        }

        if command.contains("commit")
            && (stderr_lower.contains("hook declined")
                || stderr_lower.contains("pre-commit")
                || stderr_lower.contains("pre-commit hook failed")
                || stderr_lower.contains("commit-msg")
                || stderr_lower.contains("commit-msg hook failed"))
        {
            return SyncError::HookRejected {
                details: stderr.trim().to_string(),
            };
        }

        SyncError::GitCommandFailed {
            command: command.to_string(),
            stderr: stderr.trim().to_string(),
        }
    }
}

impl GitTransport for CommandGitTransport {
    fn fetch_branch(&self, repo_path: &Path, remote: &str, branch: &str) -> Result<()> {
        let output = Command::new("git")
            .arg("fetch")
            .arg(remote)
            .arg(branch)
            .current_dir(repo_path)
            .output()
            .map_err(|e| SyncError::Other(format!("Failed to run git fetch: {}", e)))?;

        if output.status.success() {
            return Ok(());
        }

        let stderr = String::from_utf8_lossy(&output.stderr);
        Err(self.classify_git_error(
            &format!("git fetch {} {}", remote, branch),
            &stderr,
            Some(remote),
            Some(branch),
        ))
    }

    fn push_refspec(&self, repo_path: &Path, remote: &str, refspec: &str) -> Result<()> {
        let output = Command::new("git")
            .arg("push")
            .arg(remote)
            .arg(refspec)
            .current_dir(repo_path)
            .output()
            .map_err(|e| SyncError::Other(format!("Failed to run git push: {}", e)))?;

        if output.status.success() {
            return Ok(());
        }

        let stderr = String::from_utf8_lossy(&output.stderr);
        Err(self.classify_git_error(
            &format!("git push {} {}", remote, refspec),
            &stderr,
            Some(remote),
            None,
        ))
    }

    fn push_branch_upstream(&self, repo_path: &Path, remote: &str, branch: &str) -> Result<()> {
        let output = Command::new("git")
            .arg("push")
            .arg("-u")
            .arg(remote)
            .arg(branch)
            .current_dir(repo_path)
            .output()
            .map_err(|e| SyncError::Other(format!("Failed to run git push: {}", e)))?;

        if output.status.success() {
            return Ok(());
        }

        let stderr = String::from_utf8_lossy(&output.stderr);
        Err(self.classify_git_error(
            &format!("git push -u {} {}", remote, branch),
            &stderr,
            Some(remote),
            Some(branch),
        ))
    }

    fn commit(&self, repo_path: &Path, message: &str, skip_hooks: bool) -> Result<CommitOutcome> {
        let output = self
            .run_commit_command(repo_path, message, skip_hooks, None)
            .map_err(|e| SyncError::Other(format!("Failed to run git commit: {}", e)))?;

        match Self::parse_commit_output(&output) {
            Ok(outcome) => Ok(outcome),
            Err(combined) => {
                if Self::is_missing_identity_error(&combined) {
                    let (name, email) = Self::fallback_commit_identity();
                    let retry = self
                        .run_commit_command(repo_path, message, skip_hooks, Some((&name, &email)))
                        .map_err(|e| {
                            SyncError::Other(format!("Failed to rerun git commit: {}", e))
                        })?;

                    return match Self::parse_commit_output(&retry) {
                        Ok(outcome) => Ok(outcome),
                        Err(retry_combined) => {
                            let combined_errors = format!(
                                "git commit failed due to missing identity, fallback identity retry also failed.\n\ninitial:\n{}\n\nfallback retry:\n{}",
                                combined.trim(),
                                retry_combined.trim()
                            );
                            Err(self.classify_git_error("git commit", &combined_errors, None, None))
                        }
                    };
                }

                Err(self.classify_git_error("git commit", &combined, None, None))
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{CommandGitTransport, CommitOutcome, GitTransport};
    use crate::error::SyncError;
    use std::process::Command;
    use std::sync::{Mutex, OnceLock};
    use tempfile::tempdir;

    static ENV_LOCK: OnceLock<Mutex<()>> = OnceLock::new();

    #[test]
    fn classifies_missing_remote_ref_errors() {
        let transport = CommandGitTransport;
        let err = transport.classify_git_error(
            "git fetch origin feature",
            "fatal: couldn't find remote ref feature",
            Some("origin"),
            Some("feature"),
        );
        assert!(matches!(
            err,
            SyncError::RemoteBranchNotFound {
                ref remote,
                ref branch
            } if remote == "origin" && branch == "feature"
        ));
    }

    #[test]
    fn classifies_authentication_errors() {
        let transport = CommandGitTransport;
        let err = transport.classify_git_error(
            "git push origin main:main",
            "Permission denied (publickey).",
            Some("origin"),
            Some("main"),
        );
        assert!(matches!(err, SyncError::AuthenticationFailed { .. }));
    }

    #[test]
    fn classifies_hook_rejections() {
        let transport = CommandGitTransport;
        let err = transport.classify_git_error(
            "git commit",
            "error: failed to push some refs\npre-commit hook failed",
            None,
            None,
        );
        assert!(matches!(err, SyncError::HookRejected { .. }));
    }

    #[test]
    fn detects_missing_identity_errors() {
        assert!(CommandGitTransport::is_missing_identity_error(
            "Author identity unknown\nfatal: unable to auto-detect email address"
        ));
        assert!(CommandGitTransport::is_missing_identity_error(
            "Please tell me who you are."
        ));
        assert!(CommandGitTransport::is_missing_identity_error(
            "fatal: empty ident name (for <>) not allowed"
        ));
        assert!(!CommandGitTransport::is_missing_identity_error(
            "nothing to commit, working tree clean"
        ));
    }

    #[test]
    fn commit_retries_with_fallback_identity_when_git_identity_missing() {
        let _guard = ENV_LOCK
            .get_or_init(|| Mutex::new(()))
            .lock()
            .expect("acquire environment mutation lock");

        let temp = tempdir().expect("create tempdir");
        let repo_path = temp.path().join("repo");
        std::fs::create_dir(&repo_path).expect("create repo dir");

        run_git(
            temp.path(),
            &["init", repo_path.to_str().expect("path utf8")],
        );
        std::fs::write(repo_path.join("file.txt"), "hello\n").expect("write test file");
        run_git(&repo_path, &["add", "file.txt"]);

        let old_home = std::env::var("HOME").ok();
        let old_xdg_config_home = std::env::var("XDG_CONFIG_HOME").ok();
        let old_git_config_global = std::env::var("GIT_CONFIG_GLOBAL").ok();
        let old_git_config_nosystem = std::env::var("GIT_CONFIG_NOSYSTEM").ok();
        let old_author_name = std::env::var("GIT_AUTHOR_NAME").ok();
        let old_author_email = std::env::var("GIT_AUTHOR_EMAIL").ok();
        let old_committer_name = std::env::var("GIT_COMMITTER_NAME").ok();
        let old_committer_email = std::env::var("GIT_COMMITTER_EMAIL").ok();

        let no_config_home = temp.path().join("empty-home");
        std::fs::create_dir(&no_config_home).expect("create empty HOME");
        std::env::set_var("HOME", &no_config_home);
        std::env::set_var("XDG_CONFIG_HOME", &no_config_home);
        std::env::set_var("GIT_CONFIG_GLOBAL", "/dev/null");
        std::env::set_var("GIT_CONFIG_NOSYSTEM", "1");
        std::env::remove_var("GIT_AUTHOR_NAME");
        std::env::remove_var("GIT_AUTHOR_EMAIL");
        std::env::remove_var("GIT_COMMITTER_NAME");
        std::env::remove_var("GIT_COMMITTER_EMAIL");

        let transport = CommandGitTransport;
        let expected_identity = CommandGitTransport::fallback_commit_identity();
        let result = transport
            .commit(&repo_path, "auto commit message", false)
            .expect("commit should succeed with fallback identity");
        assert_eq!(result, CommitOutcome::Created);

        let log_out = Command::new("git")
            .args(["log", "-1", "--pretty=format:%an|%ae"])
            .current_dir(&repo_path)
            .output()
            .expect("read commit identity");
        assert!(log_out.status.success(), "git log failed");
        let observed = String::from_utf8_lossy(&log_out.stdout).trim().to_string();
        assert_eq!(
            observed,
            format!("{}|{}", expected_identity.0, expected_identity.1)
        );

        restore_env("HOME", old_home);
        restore_env("XDG_CONFIG_HOME", old_xdg_config_home);
        restore_env("GIT_CONFIG_GLOBAL", old_git_config_global);
        restore_env("GIT_CONFIG_NOSYSTEM", old_git_config_nosystem);
        restore_env("GIT_AUTHOR_NAME", old_author_name);
        restore_env("GIT_AUTHOR_EMAIL", old_author_email);
        restore_env("GIT_COMMITTER_NAME", old_committer_name);
        restore_env("GIT_COMMITTER_EMAIL", old_committer_email);
    }

    fn run_git(cwd: &std::path::Path, args: &[&str]) {
        let output = Command::new("git")
            .args(args)
            .current_dir(cwd)
            .output()
            .expect("run git command");
        assert!(
            output.status.success(),
            "git {} failed: {}",
            args.join(" "),
            String::from_utf8_lossy(&output.stderr)
        );
    }

    fn restore_env(name: &str, value: Option<String>) {
        if let Some(v) = value {
            std::env::set_var(name, v);
        } else {
            std::env::remove_var(name);
        }
    }
}