-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathsnapshot.go
More file actions
180 lines (154 loc) · 4.41 KB
/
snapshot.go
File metadata and controls
180 lines (154 loc) · 4.41 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
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
package preflight
import (
"fmt"
"os"
"strings"
"github.com/google/uuid"
)
// FileChange represents a single file changed in the snapshot.
type FileChange struct {
Status string // e.g. "M", "A", "D", "R"
Path string
}
// SnapshotResult holds the output of a successful snapshot operation.
type SnapshotResult struct {
Commit string
Ref string
Branch string
Files []FileChange
PushSkipped bool
}
func (r SnapshotResult) ShortCommit() string {
if len(r.Commit) >= 10 {
return r.Commit[:10]
}
return r.Commit
}
// StatusSymbol returns a human-readable symbol for the file change status.
func (f FileChange) StatusSymbol() string {
switch f.Status {
case "A":
return "+"
case "D":
return "-"
default:
return "~"
}
}
type snapshotConfig struct {
debug bool
}
// SnapshotOption configures Snapshot behavior.
type SnapshotOption func(*snapshotConfig)
// WithDebug enables verbose git output on failure.
func WithDebug() SnapshotOption {
return func(cfg *snapshotConfig) { cfg.debug = true }
}
// Snapshot pushes the current working tree state to a remote preflight ref.
// It always creates a distinct commit on top of HEAD (even when the worktree
// is clean) without touching the real git index.
func Snapshot(dir string, preflightID uuid.UUID, opts ...SnapshotOption) (*SnapshotResult, error) {
cfg := &snapshotConfig{}
for _, opt := range opts {
opt(cfg)
}
tmp, err := os.CreateTemp("", "git-index-*")
if err != nil {
return nil, fmt.Errorf("create temp index: %w", err)
}
tmpIndex := tmp.Name()
tmp.Close()
defer os.Remove(tmpIndex)
env := tempIndexEnv(tmpIndex)
// Seed the temp index from HEAD.
if err := gitRun(dir, env, cfg.debug, "read-tree", "HEAD"); err != nil {
return nil, err
}
// Stage the entire worktree into the temp index.
if err := gitRun(dir, env, cfg.debug, "add", "-A"); err != nil {
return nil, err
}
// Diff the temp index against HEAD to find changed files.
files, err := diffFiles(dir, env, cfg.debug)
if err != nil {
return nil, err
}
head, err := gitOutput(dir, env, cfg.debug, "rev-parse", "HEAD")
if err != nil {
return nil, err
}
branch := fmt.Sprintf("bk/preflight/%s", preflightID.String())
ref := fmt.Sprintf("refs/heads/%s", branch)
// Always write a tree and create a new commit, even when there are no
// local changes. This ensures the preflight branch always points to a
// distinct commit (not shared with HEAD), which allows commit statuses to
// be attributed to the preflight run rather than the base commit.
tree, err := gitOutput(dir, env, cfg.debug, "write-tree")
if err != nil {
return nil, err
}
msg := fmt.Sprintf("Preflight snapshot\n\nPreflight Run ID: %s\nBase Commit: %s", preflightID, head)
commit, err := gitOutput(dir, env, cfg.debug, "commit-tree", tree, "-p", head, "-m", msg)
if err != nil {
return nil, err
}
var pushSkipped bool
if _, err := gitOutput(dir, env, cfg.debug, "remote", "get-url", "origin"); err != nil {
pushSkipped = true
} else {
// Push the commit to the remote branch.
refspec := fmt.Sprintf("%s:%s", commit, ref)
if err := gitRun(dir, env, cfg.debug, "push", "origin", refspec); err != nil {
return nil, err
}
}
return &SnapshotResult{
Commit: commit,
Ref: ref,
Branch: branch,
Files: files,
PushSkipped: pushSkipped,
}, nil
}
// diffFiles returns the list of files changed between HEAD and the temp index.
// It uses -z for null-terminated output to correctly handle renames, copies,
// and filenames containing spaces or special characters.
func diffFiles(dir string, env []string, debug bool) ([]FileChange, error) {
out, err := gitOutput(dir, env, debug, "diff-index", "--cached", "--name-status", "-z", "-M", "HEAD")
if err != nil {
return nil, err
}
if out == "" {
return nil, nil
}
// With -z, git outputs NUL-separated tokens:
// status \0 path \0 — for M, A, D, etc.
// status \0 old_path \0 new_path \0 — for R (rename) and C (copy)
tokens := strings.Split(out, "\x00")
var files []FileChange
for i := 0; i < len(tokens); i++ {
status := tokens[i]
if status == "" {
continue
}
code := status[:1]
i++
if i >= len(tokens) {
break
}
path := tokens[i]
if code == "R" || code == "C" {
// Skip old path, use the new path.
i++
if i >= len(tokens) {
break
}
path = tokens[i]
}
files = append(files, FileChange{
Status: code,
Path: path,
})
}
return files, nil
}