forked from iwarapter/gpg-commit-mcp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit.go
More file actions
49 lines (45 loc) · 1.55 KB
/
Copy pathgit.go
File metadata and controls
49 lines (45 loc) · 1.55 KB
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
package main
import (
"bytes"
"context"
"fmt"
"os"
"os/exec"
"strings"
)
// resolveRepo returns the repo directory, defaulting to cwd, and validates it is a git repo.
func resolveRepo(ctx context.Context, repoDir string) (string, error) {
if repoDir == "" {
var err error
repoDir, err = os.Getwd()
if err != nil {
return "", fmt.Errorf("failed to get current directory: %w", err)
}
}
out, err := exec.CommandContext(ctx, "git", "-C", repoDir, "rev-parse", "--git-dir").CombinedOutput()
if err != nil {
return "", fmt.Errorf("not a git repository: %s", strings.TrimSpace(string(out)))
}
return repoDir, nil
}
// resolveGitDir returns the absolute path to the .git directory for repoDir.
func resolveGitDir(ctx context.Context, repoDir string) (string, error) {
out, err := exec.CommandContext(ctx, "git", "-C", repoDir, "rev-parse", "--absolute-git-dir").Output()
if err != nil {
return "", fmt.Errorf("failed to resolve git dir: %w", err)
}
return strings.TrimSpace(string(out)), nil
}
// runGit runs a git command with the full user environment and stdin connected
// to the controlling TTY, so ssh-agent / gpg-agent / pinentry work correctly.
// Stdout and stderr are captured and returned.
func runGit(ctx context.Context, args ...string) (stdout, stderr string, err error) {
cmd := exec.CommandContext(ctx, "git", args...)
cmd.Env = os.Environ()
cmd.Stdin = os.Stdin
var outBuf, errBuf bytes.Buffer
cmd.Stdout = &outBuf
cmd.Stderr = &errBuf
err = cmd.Run()
return strings.TrimSpace(outBuf.String()), strings.TrimSpace(errBuf.String()), err
}