-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup.go
More file actions
561 lines (530 loc) · 17 KB
/
Copy pathsetup.go
File metadata and controls
561 lines (530 loc) · 17 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
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
package app
import (
"context"
"crypto/sha256"
"errors"
"fmt"
"os"
"os/exec"
"runtime"
"strings"
"github.com/morluto/gitcontribute/internal/cli"
"github.com/morluto/gitcontribute/internal/domain"
"github.com/morluto/gitcontribute/internal/managedbinary"
clientsetup "github.com/morluto/gitcontribute/internal/setup"
"github.com/morluto/gitcontribute/internal/terminalinstall"
)
// Setup initializes local state for one of three access modes. MCP-only setup
// copies the running native executable into a private product-owned directory;
// CLI-only setup installs the published command globally through npm; Both
// registers that verified global executable with selected coding clients.
// Installation failures stop before later configuration writes.
//
// Dry-run setup validates and reports the same access-mode plan without invoking
// npm or writing local state. Setup performs no GitHub access and never executes
// repository-controlled code.
func (s *Service) Setup(ctx context.Context, opts cli.SetupOptions) (*cli.SetupReport, error) {
return s.setup(ctx, opts, nil)
}
// SetupWithProgress applies setup while reporting phase changes to an optional
// observer owned by the interactive CLI adapter.
func (s *Service) SetupWithProgress(ctx context.Context, opts cli.SetupOptions, observer cli.SetupObserver) (*cli.SetupReport, error) {
return s.setup(ctx, opts, observer)
}
func (s *Service) setup(ctx context.Context, opts cli.SetupOptions, observer cli.SetupObserver) (*cli.SetupReport, error) {
run, err := s.newSetupRun(ctx, opts, observer)
if err != nil {
return nil, err
}
if stop, err := run.preflightClients(); err != nil || stop {
return run.report, err
}
if err := run.setupRuntime(); err != nil {
return nil, err
}
if run.report.HasFailures() {
return run.report, nil
}
if run.operation == clientsetup.Configure {
run.configure()
}
if err := run.registerClients(); err != nil {
return nil, err
}
run.addRepository()
run.verify()
return run.report, nil
}
type setupRun struct {
service *Service
ctx context.Context
opts cli.SetupOptions
observer cli.SetupObserver
operation clientsetup.Operation
report *cli.SetupReport
clientOptions clientsetup.Options
clientReport clientsetup.Report
managedRuntime string
installedExecutable string
mcpCommandPending bool
configurationOK bool
}
func (s *Service) newSetupRun(ctx context.Context, opts cli.SetupOptions, observer cli.SetupObserver) (*setupRun, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
if opts.Version == "" {
opts.Version = s.version
}
operation := clientsetup.Configure
if opts.Remove {
operation = clientsetup.Remove
}
if opts.Remove && opts.Mode != "" {
return nil, errors.New("an access mode is not supported by remove")
}
if operation == clientsetup.Configure && opts.Mode != cli.SetupModeMCP && opts.Mode != cli.SetupModeCLI && opts.Mode != cli.SetupModeBoth {
return nil, errors.New("setup has no selected access mode")
}
if operation == clientsetup.Configure && opts.Mode == cli.SetupModeCLI && (len(opts.Clients) > 0 || opts.AllClients) {
return nil, errors.New("CLI mode cannot configure MCP clients")
}
clients, err := s.setupClients(opts)
if err != nil {
return nil, err
}
if strings.TrimSpace(opts.Repository) != "" {
if _, err := setupRepoRef(opts.Repository); err != nil {
return nil, err
}
}
run := &setupRun{
service: s, ctx: ctx, opts: opts, observer: observer, operation: operation,
report: &cli.SetupReport{Operation: string(operation), DryRun: opts.DryRun},
clientOptions: clientsetup.Options{
Operation: operation, Clients: clients, All: opts.AllClients, DryRun: opts.DryRun,
Home: s.paths.HomeDir(), Executable: opts.Executable,
},
configurationOK: true,
}
if operation == clientsetup.Configure && opts.Mode == cli.SetupModeMCP {
dataDir, err := s.paths.DataDir()
if err != nil {
return nil, err
}
run.managedRuntime, err = managedbinary.Destination(dataDir, opts.Version)
if err != nil {
return nil, err
}
run.clientOptions.Executable = run.managedRuntime
} else if operation == clientsetup.Configure && opts.Mode == cli.SetupModeBoth {
run.mcpCommandPending = true
}
return run, nil
}
func (s *Service) setupClients(opts cli.SetupOptions) ([]clientsetup.Client, error) {
if !opts.Remove && !opts.Mode.ConfiguresMCP() {
return nil, nil
}
clients := make([]clientsetup.Client, 0, len(opts.Clients))
for _, value := range opts.Clients {
clients = append(clients, clientsetup.Client(strings.ToLower(strings.TrimSpace(value))))
}
if len(clients) == 0 && !opts.AllClients {
return nil, errors.New("no coding-agent targets selected; pass --codex, --claude, or --all-clients")
}
return clients, nil
}
func (r *setupRun) preflightClients() (bool, error) {
if !r.configuresClients() {
return false, nil
}
planOptions := r.clientOptions
planOptions.DryRun = true
report, err := clientsetup.Run(planOptions)
if err != nil {
return false, err
}
r.setClientReport(report)
for _, result := range report.Results {
if result.Error != "" {
r.appendClientResults()
return true, nil
}
}
return false, nil
}
func (r *setupRun) setupRuntime() error {
if r.operation != clientsetup.Configure {
return nil
}
if !r.opts.Mode.InstallsCLI() {
return r.installManagedRuntime()
}
setupStarted(r.observer, cli.SetupPhaseCLI)
step, executable := installCLI(r.ctx, r.opts.Version, r.opts.DryRun)
r.report.Steps = append(r.report.Steps, step)
setupCompleted(r.observer, step)
r.installedExecutable = executable
if executable == "" {
if !r.opts.DryRun {
r.mcpCommandPending = false
r.report.MCPCommandPending = false
}
return nil
}
if !r.opts.Mode.ConfiguresMCP() {
return nil
}
r.mcpCommandPending = false
r.clientOptions.Executable = executable
planOptions := r.clientOptions
planOptions.DryRun = true
report, err := clientsetup.Run(planOptions)
if err != nil {
return err
}
r.setClientReport(report)
return nil
}
func (r *setupRun) installManagedRuntime() error {
step := cli.SetupStep{Name: "mcp-runtime", Path: r.managedRuntime, Status: "installed"}
if r.opts.DryRun {
step.Status = "would install"
r.report.Steps = append(r.report.Steps, step)
return nil
}
setupStarted(r.observer, cli.SetupPhaseMCPRuntime)
r.installedExecutable = r.managedRuntime
source := r.opts.Executable
if source == "" {
var err error
source, err = os.Executable()
if err != nil {
return fmt.Errorf("resolve packaged executable: %w", err)
}
}
installed, err := managedbinary.Install(source, r.managedRuntime)
if err != nil {
step.Status = "failed"
step.Message = err.Error()
} else if !installed {
step.Status = "already installed"
}
r.report.Steps = append(r.report.Steps, step)
setupCompleted(r.observer, step)
return nil
}
func (r *setupRun) configure() {
setupStarted(r.observer, cli.SetupPhaseConfiguration)
configPath, pathErr := r.service.paths.ConfigFile()
configExisted := pathErr == nil
if configExisted {
_, statErr := os.Stat(configPath)
configExisted = statErr == nil
}
tokenSource := strings.TrimSpace(r.opts.TokenSource)
if tokenSource == "" {
tokenSource = autoTokenSource()
}
if tokenSource == "env" && strings.TrimSpace(r.opts.TokenSourceKey) == "" {
r.opts.TokenSourceKey = "GITHUB_TOKEN"
}
r.report.Authentication = &cli.SetupAuthentication{Method: tokenSource, Key: r.opts.TokenSourceKey}
options := cli.ConfigureOptions{DryRun: r.opts.DryRun, TokenSource: &tokenSource}
if r.opts.TokenSourceKey != "" {
options.TokenSourceKey = &r.opts.TokenSourceKey
}
configured, err := r.service.Configure(r.ctx, options)
step := configurationStep(configured, err, configExisted, r.opts.DryRun)
r.report.Steps = append(r.report.Steps, step)
setupCompleted(r.observer, step)
if err != nil {
r.configurationOK = false
}
r.initializeCorpus(err == nil)
}
func configurationStep(configured *cli.ConfigureResult, err error, existed, dryRun bool) cli.SetupStep {
step := cli.SetupStep{Name: "configuration", Status: "configured"}
if configured != nil {
step.Path = configured.Path
if dryRun && (!existed || configured.Changed) {
step.Status = "would configure"
} else if existed && !configured.Changed {
step.Status = "already configured"
}
}
if err != nil {
step.Status = "failed"
step.Message = err.Error()
}
return step
}
func (r *setupRun) initializeCorpus(configured bool) {
if r.opts.DryRun {
r.report.Steps = append(r.report.Steps, cli.SetupStep{Name: "corpus", Status: "would initialize"})
return
}
if !configured {
return
}
setupStarted(r.observer, cli.SetupPhaseCorpus)
initialized, err := r.service.Init(r.ctx)
step := cli.SetupStep{Name: "corpus", Status: "initialized"}
if initialized != nil {
step.Path = initialized.Path
step.Message = initialized.Message
}
if err != nil {
step.Status = "failed"
step.Message = err.Error()
r.configurationOK = false
}
r.report.Steps = append(r.report.Steps, step)
setupCompleted(r.observer, step)
}
func (r *setupRun) registerClients() error {
if !r.configuresClients() {
return nil
}
if !r.opts.DryRun && r.configurationOK {
setupStarted(r.observer, cli.SetupPhaseClients)
r.clientOptions.DryRun = false
report, err := clientsetup.Run(r.clientOptions)
if err != nil {
return err
}
r.setClientReport(report)
}
r.appendClientResults()
return nil
}
func (r *setupRun) configuresClients() bool {
return r.operation == clientsetup.Remove || r.opts.Mode.ConfiguresMCP()
}
func (r *setupRun) setClientReport(report clientsetup.Report) {
r.clientReport = report
if r.mcpCommandPending {
r.report.MCPCommand = nil
r.report.MCPCommandPending = true
return
}
r.report.MCPCommand = &cli.SetupMCPCommand{
Command: report.Launcher.Command,
Args: append([]string(nil), report.Launcher.Args...),
}
r.report.MCPCommandPending = false
}
func (r *setupRun) appendClientResults() {
for _, result := range r.clientReport.Results {
step := cli.SetupStep{Name: string(result.Client), Path: result.Path, Status: result.Status, Message: result.Error}
r.report.Steps = append(r.report.Steps, step)
if !r.opts.DryRun && r.operation == clientsetup.Configure && (result.Status == "configured" || result.Status == "updated") {
r.report.RestartClients = append(r.report.RestartClients, string(result.Client))
}
setupCompleted(r.observer, step)
}
}
func (r *setupRun) addRepository() {
if r.operation != clientsetup.Configure || strings.TrimSpace(r.opts.Repository) == "" {
return
}
setupStarted(r.observer, cli.SetupPhaseRepository)
ref, err := setupRepoRef(r.opts.Repository)
step := cli.SetupStep{Name: "repository", Status: "added", Message: r.opts.Repository}
if err != nil {
step.Status = "failed"
step.Message = err.Error()
} else if r.opts.DryRun {
step.Status = "would add"
} else if _, err := r.service.AddRepoSource(r.ctx, setupSourceName(ref), []cli.RepoRef{ref}); err != nil {
step.Status = "failed"
step.Message = err.Error()
}
r.report.Steps = append(r.report.Steps, step)
setupCompleted(r.observer, step)
}
func (r *setupRun) verify() {
if r.operation != clientsetup.Configure || r.opts.DryRun {
return
}
setupStarted(r.observer, cli.SetupPhaseVerification)
step := cli.SetupStep{Name: "verification", Status: "verified"}
if err := r.verifyAppliedSetup(); err != nil {
step.Status = "failed"
step.Message = err.Error()
}
r.report.Steps = append(r.report.Steps, step)
setupCompleted(r.observer, step)
}
func (r *setupRun) verifyAppliedSetup() error {
failures := make([]string, 0, 5)
if executableErr := verifySetupExecutable(r.installedExecutable); executableErr != nil {
failures = append(failures, "executable: "+executableErr.Error())
}
c, err := r.service.openCorpus(r.ctx)
if err != nil {
failures = append(failures, "database: "+err.Error())
} else {
current, target, schemaErr := c.SchemaVersions(r.ctx)
if schemaErr != nil {
failures = append(failures, "schema: "+schemaErr.Error())
} else if current != target {
failures = append(failures, fmt.Sprintf("schema: database version %d does not match expected version %d", current, target))
}
integrityCtx, cancel := context.WithTimeout(r.ctx, databaseIntegrityTimeout)
integrityErr := c.CheckIntegrity(integrityCtx)
cancel()
if integrityErr != nil {
failures = append(failures, "database_integrity: "+integrityErr.Error())
}
}
if gitErr := commandAvailable(r.ctx, "git", "--version"); gitErr != nil {
failures = append(failures, "git: "+redactDiagnostic(gitErr.Error()))
}
if r.configuresClients() {
opts := r.clientOptions
opts.DryRun = true
report, clientErr := clientsetup.Run(opts)
if clientErr != nil {
failures = append(failures, "mcp registration: "+clientErr.Error())
} else {
for _, result := range report.Results {
if result.Error != "" {
failures = append(failures, string(result.Client)+": "+result.Error)
} else if result.Status != "already configured" {
failures = append(failures, fmt.Sprintf("%s: registration does not match the configured MCP command", result.Client))
}
}
}
}
if len(failures) == 0 {
return nil
}
return errors.New(strings.Join(failures, "; "))
}
func verifySetupExecutable(path string) error {
if strings.TrimSpace(path) == "" {
return errors.New("installed command path is unavailable")
}
info, err := os.Stat(path)
if err != nil {
return fmt.Errorf("inspect installed command: %w", err)
}
if !info.Mode().IsRegular() {
return fmt.Errorf("installed command is not a regular file: %s", path)
}
if runtime.GOOS != "windows" && info.Mode().Perm()&0o111 == 0 {
return fmt.Errorf("installed command is not executable: %s", path)
}
return nil
}
func setupStarted(observer cli.SetupObserver, phase cli.SetupPhase) {
if observer != nil {
observer.SetupStarted(phase)
}
}
func setupCompleted(observer cli.SetupObserver, step cli.SetupStep) {
if observer != nil {
observer.SetupCompleted(step)
}
}
// DiscoverSetup inspects local onboarding state without writes, network access,
// credential resolution, or process execution.
func (s *Service) DiscoverSetup(ctx context.Context) (*cli.SetupDiscovery, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
home := s.paths.HomeDir()
detected := make(map[clientsetup.Client]bool)
for _, client := range clientsetup.Detect(home) {
detected[client] = true
}
result := &cli.SetupDiscovery{Version: s.version}
for _, client := range clientsetup.AllClients {
registered, path, err := clientsetup.CheckRegistration(client, home)
item := cli.SetupClientDiscovery{
Name: string(client),
Path: path,
Detected: detected[client],
Registered: registered,
}
if err != nil {
item.Error = err.Error()
}
result.Clients = append(result.Clients, item)
}
configPath, err := s.paths.ConfigFile()
if err != nil {
return nil, err
}
cfg, err := s.persistedConfig(configPath)
if err != nil {
return nil, err
}
result.ConfiguredTokenSource = cfg.TokenSource.Method
result.ConfiguredTokenKey = cfg.TokenSource.Key
_, ghErr := exec.LookPath("gh")
result.GitHubCLIAvailable = ghErr == nil
envKey := cfg.TokenSource.Key
if envKey == "" {
envKey = "GITHUB_TOKEN"
}
if s.paths.Env != nil {
_, result.EnvironmentKeyPresent = s.paths.Env.Vars[envKey]
} else {
_, result.EnvironmentKeyPresent = os.LookupEnv(envKey)
}
return result, nil
}
// installCLI converts the requested release into a safe npm package
// specifier and reports installation as an independent setup step. The returned
// path is non-empty only after npm succeeded and the command shim was verified.
func installCLI(ctx context.Context, version string, dryRun bool) (cli.SetupStep, string) {
resolvedVersion, err := clientsetup.ResolveNPMVersion(version)
step := cli.SetupStep{Name: "cli", Status: "installed", Message: "npm install --global gitcontribute@" + resolvedVersion}
if err != nil {
step.Status = "failed"
step.Message = err.Error()
return step, ""
}
if dryRun {
step.Status = "would install"
return step, ""
}
commandPath, err := terminalinstall.GlobalNPM(ctx, "gitcontribute@"+resolvedVersion)
if err != nil {
step.Status = "failed"
step.Message = err.Error()
return step, ""
}
step.Path = commandPath
return step, commandPath
}
func setupSourceName(ref cli.RepoRef) string {
name := strings.ToLower(ref.Owner + "-" + ref.Repo)
if len(name) <= 64 {
return name
}
sum := sha256.Sum256([]byte(ref.String()))
return fmt.Sprintf("%s-%x", name[:55], sum[:4])
}
func autoTokenSource() string {
if _, err := exec.LookPath("gh"); err == nil {
return "gh-cli"
}
return "none"
}
func setupRepoRef(value string) (cli.RepoRef, error) {
value = strings.TrimSpace(strings.TrimSuffix(value, "/"))
value = strings.TrimPrefix(value, "https://github.com/")
parts := strings.Split(value, "/")
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
return cli.RepoRef{}, fmt.Errorf("repository must be OWNER/REPO")
}
ref := cli.RepoRef{Owner: parts[0], Repo: strings.TrimSuffix(parts[1], ".git")}
if err := (domain.RepoRef{Owner: ref.Owner, Repo: ref.Repo}).Validate(); err != nil {
return cli.RepoRef{}, err
}
return ref, nil
}