-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathconfigure_projects.go
More file actions
514 lines (458 loc) · 14 KB
/
configure_projects.go
File metadata and controls
514 lines (458 loc) · 14 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
package cmd
import (
"encoding/json"
"fmt"
"os"
"strings"
"time"
"github.com/DevExpGBB/gh-devlake/internal/devlake"
"github.com/DevExpGBB/gh-devlake/internal/prompt"
"github.com/spf13/cobra"
)
// ProjectOpts holds options for the project command.
type ProjectOpts struct {
ProjectName string
Connections string // "plugin:connID,plugin:connID" for flag-driven mode
TimeAfter string
Cron string
SkipSync bool
Wait bool
Timeout time.Duration
// Pre-resolved fields set by orchestrators (full, init)
Client *devlake.Client
StatePath string
State *devlake.State
}
func newConfigureProjectsCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "project",
Aliases: []string{"projects"},
Short: "Manage DevLake projects",
Long: `Manage DevLake projects.
Use subcommands to add, list, or delete projects.`,
}
cmd.AddCommand(newProjectAddCmd(), newProjectListCmd(), newProjectDeleteCmd())
return cmd
}
// connChoice represents a discovered connection for the interactive picker.
type connChoice struct {
plugin string
id int
label string
enterprise string
}
// addedConnection tracks a connection whose scopes are included in the project.
type addedConnection struct {
plugin string
connID int
label string
summary string
bpConn devlake.BlueprintConnection
repos []string
}
func runConfigureProjects(cmd *cobra.Command, args []string, opts *ProjectOpts) error {
printBanner("DevLake \u2014 Project Setup")
fmt.Println()
fmt.Println(" A DevLake project groups data from multiple connections into a")
fmt.Println(" single view with DORA metrics. Think of it as one project per")
fmt.Println(" team or business unit.")
client := opts.Client
statePath := opts.StatePath
state := opts.State
// Discover DevLake if not pre-resolved by an orchestrator
if client == nil {
var disc *devlake.DiscoveryResult
var err error
client, disc, err = discoverClient(cfgURL)
if err != nil {
return err
}
statePath, state = devlake.FindStateFile(disc.URL, disc.GrafanaURL)
}
// Project name — derive default from state connections
defaultName := "my-project"
if state != nil {
for _, c := range state.Connections {
if c.Organization != "" {
defaultName = c.Organization
break
}
}
}
projectName := opts.ProjectName
if projectName == "" {
custom := prompt.ReadLine(fmt.Sprintf("\nProject name [%s]", defaultName))
if custom != "" {
projectName = custom
} else {
projectName = defaultName
}
}
// Discover connections
fmt.Println("\n🔍 Discovering connections...")
choices := discoverConnections(client, state)
if len(choices) == 0 {
return fmt.Errorf("no connections found — run 'gh devlake configure connection add' first")
}
// Iterative connection addition loop
var added []addedConnection
remaining := make([]connChoice, len(choices))
copy(remaining, choices)
for {
if len(remaining) == 0 {
if len(added) == 0 {
return fmt.Errorf("at least one connection is required")
}
fmt.Println("\n All available connections have been added.")
break
}
var picked connChoice
if len(added) > 0 {
fmt.Println()
fmt.Println(" " + strings.Repeat("\u2500", 44))
fmt.Println(" Added so far:")
for _, a := range added {
fmt.Printf(" \u2705 %s\n", a.summary)
}
fmt.Println(" " + strings.Repeat("\u2500", 44))
}
fmt.Println()
fmt.Println(" Choose a connection to add to this project.")
fmt.Println()
labels := make([]string, len(remaining))
for i, c := range remaining {
labels[i] = c.label
}
chosen := prompt.Select("Add connection", labels)
if chosen == "" {
if len(added) == 0 {
return fmt.Errorf("at least one connection is required")
}
break
}
for _, c := range remaining {
if c.label == chosen {
picked = c
break
}
}
// List existing scopes on the picked connection
ac, err := listConnectionScopes(client, picked)
if err != nil {
fmt.Printf(" \u26a0\ufe0f Could not list scopes for %s: %v\n", picked.label, err)
fmt.Println(" Run 'gh devlake configure scope' to add scopes first.")
remaining = removeChoice(remaining, picked)
continue
}
added = append(added, *ac)
remaining = removeChoice(remaining, picked)
if len(remaining) == 0 {
fmt.Println("\n All available connections have been added.")
break
}
if !prompt.Confirm("\nWould you like to add another connection?") {
break
}
}
if len(added) == 0 {
return fmt.Errorf("at least one connection is required")
}
// Accumulate results
var connections []devlake.BlueprintConnection
var allRepos []string
var pluginNames []string
for _, a := range added {
connections = append(connections, a.bpConn)
allRepos = append(allRepos, a.repos...)
pluginNames = append(pluginNames, pluginDisplayName(a.plugin))
}
// Show what will happen
fmt.Println()
fmt.Println(" Ready to finalize:")
for _, a := range added {
fmt.Printf(" \u2022 %s\n", a.summary)
}
fmt.Println(" \u2022 Create project with DORA metrics")
fmt.Println(" \u2022 Configure daily sync schedule")
if !opts.SkipSync {
fmt.Println(" \u2022 Trigger the first data collection")
}
// Finalize
return finalizeProject(finalizeProjectOpts{
Client: client,
StatePath: statePath,
State: state,
ProjectName: projectName,
Connections: connections,
Repos: allRepos,
PluginNames: pluginNames,
Cron: opts.Cron,
TimeAfter: opts.TimeAfter,
SkipSync: opts.SkipSync,
Wait: opts.Wait,
Timeout: opts.Timeout,
})
}
// listConnectionScopes lists existing scopes on a connection and builds an
// addedConnection from them. Returns an error if no scopes are found.
func listConnectionScopes(client *devlake.Client, c connChoice) (*addedConnection, error) {
fmt.Printf("\n📦 Listing scopes on %s...\n", c.label)
resp, err := client.ListScopes(c.plugin, c.id)
if err != nil {
return nil, fmt.Errorf("could not list scopes: %w", err)
}
if resp == nil || len(resp.Scopes) == 0 {
return nil, fmt.Errorf("no scopes found on connection %d \u2014 run 'gh devlake configure scope' first", c.id)
}
var bpScopes []devlake.BlueprintScope
var repos []string
def := FindConnectionDef(c.plugin)
for _, w := range resp.Scopes {
// Generic scope ID extraction using the plugin's configured ScopeIDField.
var scopeID string
if def != nil && def.ScopeIDField != "" {
scopeID = devlake.ExtractScopeID(w.RawScope, def.ScopeIDField)
}
fullName := w.ScopeFullName()
scopeName := fullName
if scopeName == "" {
scopeName = w.ScopeName()
}
if scopeID == "" {
scopeID = scopeName
}
bpScopes = append(bpScopes, devlake.BlueprintScope{
ScopeID: scopeID,
ScopeName: scopeName,
})
if def != nil && def.HasRepoScopes && fullName != "" {
repos = append(repos, fullName)
}
fmt.Printf(" %s (ID: %s)\n", scopeName, scopeID)
}
fmt.Printf(" \u2705 Found %d scope(s)\n", len(bpScopes))
summary := fmt.Sprintf("%s (ID: %d, %d scope(s))", pluginDisplayName(c.plugin), c.id, len(bpScopes))
return &addedConnection{
plugin: c.plugin,
connID: c.id,
label: c.label,
summary: summary,
bpConn: devlake.BlueprintConnection{
PluginName: c.plugin,
ConnectionID: c.id,
Scopes: bpScopes,
},
repos: repos,
}, nil
}
// finalizeProjectOpts holds the parameters for finalizeProject.
type finalizeProjectOpts struct {
Client *devlake.Client
StatePath string
State *devlake.State
ProjectName string
Org string
Connections []devlake.BlueprintConnection
Repos []string
PluginNames []string // display names of active plugins
Cron string
TimeAfter string
SkipSync bool
Wait bool
Timeout time.Duration
}
// finalizeProject creates the project, patches the blueprint with all
// accumulated connections, triggers the first sync, and saves state.
func finalizeProject(opts finalizeProjectOpts) error {
timeAfter := opts.TimeAfter
if timeAfter == "" {
timeAfter = time.Now().AddDate(0, -6, 0).Format("2006-01-02T00:00:00Z")
}
cron := opts.Cron
if cron == "" {
cron = "0 0 * * *"
}
fmt.Println("\n🏗️ Creating DevLake project...")
blueprintID, err := ensureProjectWithFlags(opts.Client, opts.ProjectName, opts.PluginNames)
if err != nil {
return fmt.Errorf("failed to create project: %w", err)
}
fmt.Printf(" Project: %s, Blueprint ID: %d\n", opts.ProjectName, blueprintID)
fmt.Println("\n📋 Configuring blueprint...")
enable := true
patch := &devlake.BlueprintPatch{
Enable: &enable,
Mode: "NORMAL",
CronConfig: cron,
TimeAfter: timeAfter,
Connections: opts.Connections,
}
_, err = opts.Client.PatchBlueprint(blueprintID, patch)
if err != nil {
return fmt.Errorf("failed to configure blueprint: %w", err)
}
fmt.Printf(" \u2705 Blueprint configured with %d connection(s)\n", len(opts.Connections))
fmt.Printf(" Schedule: %s | Data since: %s\n", cron, timeAfter)
if !opts.SkipSync {
fmt.Println("\n🚀 Triggering first data sync...")
fmt.Println(" Depending on data volume and history, this may take 5\u201330 minutes.")
if err := triggerAndPoll(opts.Client, blueprintID, opts.Wait, opts.Timeout); err != nil {
fmt.Printf(" \u26a0\ufe0f %v\n", err)
}
}
// Update state file
opts.State.Project = &devlake.StateProject{
Name: opts.ProjectName,
BlueprintID: blueprintID,
Repos: opts.Repos,
Organization: opts.Org,
}
opts.State.ScopesConfiguredAt = time.Now().Format(time.RFC3339)
if err := devlake.SaveState(opts.StatePath, opts.State); err != nil {
fmt.Fprintf(os.Stderr, "\u26a0\ufe0f Could not update state file: %v\n", err)
} else {
fmt.Printf("\n💾 State saved to %s\n", opts.StatePath)
}
fmt.Println("\n" + strings.Repeat("\u2500", 40))
fmt.Println("\u2705 Project configured successfully!")
fmt.Printf(" Project: %s\n", opts.ProjectName)
if len(opts.Repos) > 0 {
printWrappedList(" Repos:", opts.Repos, 100)
}
for _, pn := range opts.PluginNames {
fmt.Printf(" Plugin: %s\n", pn)
}
fmt.Println(strings.Repeat("\u2500", 40))
fmt.Println()
return nil
}
func printWrappedList(label string, items []string, maxWidth int) {
if len(items) == 0 {
return
}
if maxWidth <= 0 {
maxWidth = 100
}
indent := " "
sep := ", "
prefixFirst := indent + label + " "
prefixNext := indent + strings.Repeat(" ", len(label)+1)
line := prefixFirst
for i, item := range items {
part := item
if i > 0 {
part = sep + part
}
if len(line)+len(part) > maxWidth && line != prefixFirst {
fmt.Println(line)
line = prefixNext + item
continue
}
line += part
}
if strings.TrimSpace(line) != "" {
fmt.Println(line)
}
}
// ensureProjectWithFlags creates a project or returns an existing one's blueprint ID.
func ensureProjectWithFlags(client *devlake.Client, name string, pluginNames []string) (int, error) {
desc := fmt.Sprintf("DevLake metrics for %s", name)
if len(pluginNames) > 0 {
desc = fmt.Sprintf("DevLake metrics for %s (%s)", name, strings.Join(pluginNames, ", "))
}
project := &devlake.Project{
Name: name,
Description: desc,
Metrics: []devlake.ProjectMetric{
{PluginName: "dora", Enable: true},
},
}
result, err := client.CreateProject(project)
if err == nil && result.Blueprint != nil {
return result.Blueprint.ID, nil
}
existing, getErr := client.GetProject(name)
if getErr != nil {
return 0, fmt.Errorf("create failed: %v; get failed: %v", err, getErr)
}
if existing != nil && existing.Blueprint != nil {
return existing.Blueprint.ID, nil
}
return 0, fmt.Errorf("project %q has no blueprint", name)
}
// triggerAndPoll triggers a blueprint sync and monitors progress.
func triggerAndPoll(client *devlake.Client, blueprintID int, wait bool, timeout time.Duration) error {
pipeline, err := client.TriggerBlueprint(blueprintID)
if err != nil {
return fmt.Errorf("could not trigger sync: %w", err)
}
fmt.Printf(" Pipeline started (ID: %d)\n", pipeline.ID)
if !wait {
return nil
}
if timeout == 0 {
timeout = 5 * time.Minute
}
fmt.Println(" Monitoring progress...")
deadline := time.Now().Add(timeout)
start := time.Now()
// clearLine erases the current in-place status line so subsequent output
// (completion banners, error messages) appears on a clean line.
clearLine := func() {
fmt.Printf("\r%s\r", strings.Repeat(" ", progressLineWidth))
}
ticker := time.NewTicker(10 * time.Second)
defer ticker.Stop()
for range ticker.C {
p, err := client.GetPipeline(pipeline.ID)
elapsed := time.Since(start).Truncate(time.Second)
if err != nil {
fmt.Printf("\r %-*s", progressLineWidth-3, fmt.Sprintf("⚠️ Could not check status (%s elapsed)", elapsed))
} else {
bar := renderBar(p.FinishedTasks, p.TotalTasks, progressBarWidth)
fmt.Printf("\r %-*s", progressLineWidth-3, fmt.Sprintf("%s %d/%d tasks — %s (%s elapsed)", bar, p.FinishedTasks, p.TotalTasks, p.Status, elapsed))
switch p.Status {
case "TASK_COMPLETED":
clearLine()
fmt.Println(" ✅ Data sync completed!")
return nil
case "TASK_FAILED":
clearLine()
return fmt.Errorf("pipeline failed — check DevLake logs")
}
}
if time.Now().After(deadline) {
clearLine()
fmt.Println(" ⚠️ Monitoring timed out. Pipeline is still running.")
fmt.Printf(" Check status: GET /pipelines/%d\n", pipeline.ID)
return nil
}
}
return nil
}
// marshalJSON is available for debug output.
func marshalJSON(v any) string {
b, _ := json.MarshalIndent(v, "", " ")
return string(b)
}
// removeChoice returns choices with the specified entry removed.
func removeChoice(choices []connChoice, remove connChoice) []connChoice {
var out []connChoice
for _, c := range choices {
if c.plugin == remove.plugin && c.id == remove.id {
continue
}
out = append(out, c)
}
return out
}
// filterChoicesByPlugin returns only the connections matching the given plugin slug.
func filterChoicesByPlugin(choices []connChoice, plugin string) []connChoice {
var out []connChoice
for _, c := range choices {
if c.plugin == plugin {
out = append(out, c)
}
}
return out
}