-
-
Notifications
You must be signed in to change notification settings - Fork 174
Expand file tree
/
Copy pathexecutor.go
More file actions
337 lines (293 loc) · 10.8 KB
/
Copy pathexecutor.go
File metadata and controls
337 lines (293 loc) · 10.8 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
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
package git
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
errUtils "github.com/cloudposse/atmos/errors"
atmosgit "github.com/cloudposse/atmos/pkg/git"
"github.com/cloudposse/atmos/pkg/perf"
"github.com/cloudposse/atmos/pkg/ui"
"github.com/cloudposse/atmos/pkg/ui/spinner"
)
// testProviderOverride, when non-nil, is used by providerForName() instead of
// looking up the real registry. Set only from tests via setTestProvider().
var testProviderOverride atmosgit.Provider
// setTestProvider installs a test-double provider that all provider lookups
// will use instead of the real registry. Returns a cleanup function that
// restores the previous value.
func setTestProvider(p atmosgit.Provider) func() {
prev := testProviderOverride
testProviderOverride = p
return func() { testProviderOverride = prev }
}
// Executor holds the resolved inputs for a single Git operation and delegates
// to an injected Provider. This enables unit testing without invoking real git
// subprocesses: tests pass a stub provider; production passes the real one.
type Executor struct {
provider atmosgit.Provider
}
// newExecutor builds an Executor using the named provider from the registry.
// Pass an empty string to use the default "cli" provider.
func newExecutor(providerName string) (*Executor, error) {
p, err := atmosgit.NewProvider(providerName)
if err != nil {
return nil, err
}
return &Executor{provider: p}, nil
}
// newExecutorWithProvider builds an Executor using an already-constructed
// Provider (used in tests).
func newExecutorWithProvider(p atmosgit.Provider) *Executor {
return &Executor{provider: p}
}
// Init delegates to the provider.
func (e *Executor) Init(ctx context.Context, opts *atmosgit.InitOptions, label string) error {
defer perf.Track(nil, "git.Executor.Init")()
reconcile := initWillReconcile(opts)
progressMsg := initProgressMessage(label, opts, reconcile)
completedMsg := initCompletedMessage(label, opts, reconcile)
stderr, err := atmosgit.CaptureStderr(e.provider, func() error {
return spinner.ExecWithSpinner(progressMsg, completedMsg, func() error {
return e.provider.Init(ctx, opts)
})
})
return atmosgit.WrapOperationError(
fmt.Sprintf("initialize Git repository %q", label),
opts.Workdir,
stderr,
err,
"Run 'atmos git list' to confirm the configured URI, branch, and resolved workdir.",
)
}
// initWillReconcile reports whether init will reconcile an already-initialized
// repository in place (the workdir already contains a ".git", and --force was
// not given) rather than creating or seeding a fresh one. It only phrases the
// output; the provider makes the authoritative decision.
func initWillReconcile(opts *atmosgit.InitOptions) bool {
if opts.Force {
return false
}
_, err := os.Stat(filepath.Join(opts.Workdir, ".git"))
return err == nil
}
// initProgressMessage builds the spinner progress line, naming the seed source
// when init is seeding from another repository.
func initProgressMessage(label string, opts *atmosgit.InitOptions, reconcile bool) string {
switch {
case reconcile:
return fmt.Sprintf("Reconciling Git repository %s", label)
case opts.FromURI != "":
return fmt.Sprintf("Initializing Git repository %s from %s", label, opts.FromURI)
default:
return fmt.Sprintf("Initializing Git repository %s", label)
}
}
// initCompletedMessage builds a mode-aware init success message so the output
// reflects whether the Git repository was created, seeded (and how), or
// reconciled, mirroring the dry-run, and makes clear that a Git repository (not
// a deployment) was acted on. The verb reflects --force, which deletes and
// re-creates from scratch.
func initCompletedMessage(label string, opts *atmosgit.InitOptions, reconcile bool) string {
if reconcile {
return fmt.Sprintf("Reconciled Git repository %s in %s.", label, opts.Workdir)
}
verb := "Initialized"
if opts.Force {
verb = "Re-initialized"
}
switch {
case opts.FromURI == "":
return fmt.Sprintf("%s empty Git repository %s in %s.", verb, label, opts.Workdir)
case opts.KeepHistory:
return fmt.Sprintf("%s Git repository %s in %s from %s (history preserved; source kept as 'upstream').", verb, label, opts.Workdir, opts.FromURI)
default:
return fmt.Sprintf("%s Git repository %s in %s from %s (fresh history).", verb, label, opts.Workdir, opts.FromURI)
}
}
// Clone delegates to the provider.
func (e *Executor) Clone(ctx context.Context, opts *atmosgit.CloneOptions, label string) error {
defer perf.Track(nil, "git.Executor.Clone")()
progressMsg := fmt.Sprintf("Cloning %s", label)
completedMsg := fmt.Sprintf("Cloned %s into %s.", label, opts.Workdir)
stderr, err := atmosgit.CaptureStderr(e.provider, func() error {
return spinner.ExecWithSpinner(progressMsg, completedMsg, func() error {
return e.provider.Clone(ctx, opts)
})
})
return wrapCloneError(label, opts.Workdir, stderr, err)
}
func (e *Executor) CloneWithoutSpinner(ctx context.Context, opts *atmosgit.CloneOptions, label string) error {
defer perf.Track(nil, "git.Executor.CloneWithoutSpinner")()
stderr, err := atmosgit.CaptureStderr(e.provider, func() error {
return e.provider.Clone(ctx, opts)
})
if err != nil {
return wrapCloneError(label, opts.Workdir, stderr, err)
}
ui.Successf("Cloned %s into %s.", label, opts.Workdir)
return nil
}
func wrapCloneError(label, workdir, stderr string, err error) error {
return atmosgit.WrapOperationError(
fmt.Sprintf("clone Git repository %q", label),
workdir,
stderr,
err,
"Run 'atmos git list' to confirm the configured URI, branch, and resolved workdir.",
)
}
// Pull delegates to the provider.
func (e *Executor) Pull(ctx context.Context, opts *atmosgit.PullOptions) error {
defer perf.Track(nil, "git.Executor.Pull")()
stderr, err := atmosgit.CaptureStderr(e.provider, func() error {
return e.provider.Pull(ctx, opts)
})
if errors.Is(err, errUtils.ErrGitNoTrackingBranch) {
return errUtils.Build(errUtils.ErrGitNoTrackingBranch).
WithExplanation(fmt.Sprintf("The repository at %s has no branch to pull: its current branch has no upstream, and no branch is configured for it.", opts.Workdir)).
WithHint("Set 'branch:' for this repository under git.repositories so Atmos pulls that branch explicitly.").
WithHint("Or name the remote and branch after the '--' separator, e.g. 'atmos git pull myrepo -- origin main'.").
WithExitCode(2).
Err()
}
if err != nil {
return atmosgit.WrapOperationError(
"pull Git repository",
opts.Workdir,
stderr,
err,
"Run 'atmos git list' to confirm the configured branch and resolved workdir.",
)
}
ui.Successf("Pulled repository at %s.", opts.Workdir)
return nil
}
// Status delegates to the provider and prints the result.
func (e *Executor) Status(ctx context.Context, opts *atmosgit.StatusOptions) (*atmosgit.StatusResult, error) {
defer perf.Track(nil, "git.Executor.Status")()
var result *atmosgit.StatusResult
stderr, err := atmosgit.CaptureStderr(e.provider, func() error {
var opErr error
result, opErr = e.provider.Status(ctx, opts)
return opErr
})
if err != nil {
return nil, atmosgit.WrapOperationError("read Git status", opts.Workdir, stderr, err, "")
}
return result, nil
}
// Diff delegates to the provider.
func (e *Executor) Diff(ctx context.Context, opts *atmosgit.DiffOptions) (*atmosgit.DiffResult, error) {
defer perf.Track(nil, "git.Executor.Diff")()
var result *atmosgit.DiffResult
stderr, err := atmosgit.CaptureStderr(e.provider, func() error {
var opErr error
result, opErr = e.provider.Diff(ctx, opts)
return opErr
})
if err != nil {
return nil, atmosgit.WrapOperationError("show Git diff", opts.Workdir, stderr, err, "")
}
return result, nil
}
// Commit delegates to the provider.
func (e *Executor) Commit(ctx context.Context, opts *atmosgit.CommitOptions) (*atmosgit.CommitResult, error) {
defer perf.Track(nil, "git.Executor.Commit")()
var result *atmosgit.CommitResult
stderr, err := atmosgit.CaptureStderr(e.provider, func() error {
var opErr error
result, opErr = e.provider.Commit(ctx, opts)
return opErr
})
if err != nil {
return nil, atmosgit.WrapOperationError("commit Git changes", opts.Workdir, stderr, err, "")
}
return result, nil
}
// Push delegates to the provider.
func (e *Executor) Push(ctx context.Context, opts *atmosgit.PushOptions) error {
defer perf.Track(nil, "git.Executor.Push")()
stderr, err := atmosgit.CaptureStderr(e.provider, func() error {
return e.provider.Push(ctx, opts)
})
if err != nil {
return atmosgit.WrapOperationError(
"push Git repository",
opts.Workdir,
stderr,
err,
"Run 'atmos git status' and 'atmos git pull' before retrying the push.",
)
}
ui.Successf("Pushed %s to %s/%s.", opts.Workdir, opts.Remote, opts.Branch)
return nil
}
// executeStatusAndPrint runs status and prints results.
func executeStatusAndPrint(ctx context.Context, exec *Executor, workdir string, env []string) error {
defer perf.Track(nil, "git.executeStatusAndPrint")()
result, err := exec.Status(ctx, &atmosgit.StatusOptions{
RepoContext: atmosgit.RepoContext{
Workdir: workdir,
Env: env,
},
})
if err != nil {
return err
}
return printStatus(workdir, result)
}
// executeDiffAndPrint runs diff and prints results.
func executeDiffAndPrint(ctx context.Context, exec *Executor, workdir string, env, paths []string) error {
defer perf.Track(nil, "git.executeDiffAndPrint")()
result, err := exec.Diff(ctx, &atmosgit.DiffOptions{
RepoContext: atmosgit.RepoContext{
Workdir: workdir,
Env: env,
},
Paths: paths,
})
if err != nil {
return err
}
return printDiff(workdir, result)
}
// executeCommitWithResult runs commit and reports outcome.
func executeCommitWithResult(ctx context.Context, exec *Executor, opts *atmosgit.CommitOptions) error {
defer perf.Track(nil, "git.executeCommitWithResult")()
result, err := exec.Commit(ctx, opts)
if err != nil {
return err
}
if !result.Committed {
ui.Info("Nothing to commit; working tree is clean.")
return nil
}
ui.Successf("Committed %s in %s.", result.SHA, opts.Workdir)
return nil
}
// buildRepoContext assembles a RepoContext from resolved values and composed env.
func buildRepoContext(workdir, remote, branch string, env []string) atmosgit.RepoContext {
return atmosgit.RepoContext{
Workdir: workdir,
Remote: remote,
Branch: branch,
Env: env,
}
}
// providerForName looks up the named provider from the registry and wraps it
// in an Executor. Pass an empty string to use the default "cli" provider.
// When testProviderOverride is non-nil (set via setTestProvider in tests), it
// is returned directly without consulting the registry, allowing unit tests to
// run without a real Git subprocess.
func providerForName(name string) (*Executor, error) {
if testProviderOverride != nil {
return newExecutorWithProvider(testProviderOverride), nil
}
exec, err := newExecutor(name)
if err != nil {
return nil, fmt.Errorf("initializing git provider %q: %w", name, err)
}
return exec, nil
}