-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdag_ascii.go
More file actions
643 lines (565 loc) · 18.1 KB
/
Copy pathdag_ascii.go
File metadata and controls
643 lines (565 loc) · 18.1 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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
package probe
import (
"path/filepath"
"slices"
"strings"
)
const (
// Node border characters (string)
nodeTopLeft = "╭"
nodeTopRight = "╮"
nodeBottomLeft = "╰"
nodeBottomRight = "╯"
nodeHorizontal = "─"
nodeVertical = "│"
nodeTeeRight = "├"
nodeTeeDown = "┬"
nodeTeeUp = "┴"
nodeTeeLeft = "┤"
nodeCross = "┼"
arrowDown = "↓"
stepBullet = "○"
stepBulletEmbedded = "↗"
ellipsis = "…"
// Tree characters for embedded steps
treeBranch = "├"
treeEnd = "└"
// ANSI escape codes for dim text
ansiDim = "\033[2m"
ansiReset = "\033[0m"
// Connection line characters (rune)
connVertical = '│'
connHorizontal = '─'
connTeeRight = '├'
connTeeLeft = '┤'
connTeeDown = '┬'
connTeeUp = '┴'
connCross = '┼'
connCornerTopLeft = '┌'
connCornerTopRight = '┐'
connCornerBottomLeft = '└'
connCornerBottomRight = '┘'
// Node dimensions
fixedNodeWidth = 25
)
// DagAsciiJobNode represents a rendered job node
type DagAsciiJobNode struct {
Job *Job
JobID string
Level int // Depth in DAG (0 = root)
Width int // Box width
Lines []string // Rendered lines
CenterX int // X coordinate of center (for connections)
HasChildren bool // Whether this job has dependent jobs
}
// DagAsciiRenderer renders detailed workflow graphs with job nodes and steps
type DagAsciiRenderer struct {
DagRendererBase
nodes []*DagAsciiJobNode
levels [][]int // levels[level] = []jobIndex
jobIDToIdx map[string]int // jobID -> index in workflow.Jobs
children map[string][]string // jobID -> list of child jobIDs (jobs that depend on this job)
parents map[string][]string // jobID -> list of parent jobIDs (jobs this job depends on)
}
// NewDagAsciiRenderer creates a new DagAsciiRenderer
func NewDagAsciiRenderer(w *Workflow) *DagAsciiRenderer {
r := &DagAsciiRenderer{
DagRendererBase: NewDagRendererBase(w),
nodes: make([]*DagAsciiJobNode, len(w.Jobs)),
jobIDToIdx: make(map[string]int),
children: make(map[string][]string),
parents: make(map[string][]string),
}
// Build job ID to index mapping
for i, job := range w.Jobs {
id := job.ID
if id == "" {
id = job.Name
}
r.jobIDToIdx[id] = i
}
// Build parent-child relationships
for _, job := range w.Jobs {
jobID := job.ID
if jobID == "" {
jobID = job.Name
}
for _, need := range job.Needs {
r.children[need] = append(r.children[need], jobID)
r.parents[jobID] = append(r.parents[jobID], need)
}
}
return r
}
// Render generates the detailed ASCII art graph
func (r *DagAsciiRenderer) Render() string {
if len(r.workflow.Jobs) == 0 {
return ""
}
r.calculateLevels()
r.createNodes()
var result []string
for level := 0; level < len(r.levels); level++ {
// Render connection lines from previous level
if level > 0 {
connections := r.renderConnections(level - 1)
result = append(result, connections...)
}
// Render nodes at this level
levelLines := r.renderLevel(level)
result = append(result, levelLines...)
}
return strings.Join(result, "\n") + "\n"
}
// calculateLevels assigns each job to a level based on dependencies (Sugiyama-style)
func (r *DagAsciiRenderer) calculateLevels() {
jobLevels := make(map[string]int)
// Calculate level for each job
var calcLevel func(jobID string) int
calcLevel = func(jobID string) int {
if level, exists := jobLevels[jobID]; exists {
return level
}
idx, ok := r.jobIDToIdx[jobID]
if !ok {
return 0
}
job := r.workflow.Jobs[idx]
if len(job.Needs) == 0 {
jobLevels[jobID] = 0
return 0
}
maxParentLevel := -1
for _, need := range job.Needs {
parentLevel := calcLevel(need)
if parentLevel > maxParentLevel {
maxParentLevel = parentLevel
}
}
level := maxParentLevel + 1
jobLevels[jobID] = level
return level
}
// Calculate levels for all jobs
maxLevel := 0
for _, job := range r.workflow.Jobs {
jobID := job.ID
if jobID == "" {
jobID = job.Name
}
level := calcLevel(jobID)
if level > maxLevel {
maxLevel = level
}
}
// Group jobs by level
r.levels = make([][]int, maxLevel+1)
for i, job := range r.workflow.Jobs {
jobID := job.ID
if jobID == "" {
jobID = job.Name
}
level := jobLevels[jobID]
r.levels[level] = append(r.levels[level], i)
}
// Sort jobs within each level: jobs with children first, then jobs without children
for level := range r.levels {
jobIndices := r.levels[level]
withChildren := []int{}
withoutChildren := []int{}
for _, idx := range jobIndices {
job := r.workflow.Jobs[idx]
jobID := job.ID
if jobID == "" {
jobID = job.Name
}
if len(r.children[jobID]) > 0 {
withChildren = append(withChildren, idx)
} else {
withoutChildren = append(withoutChildren, idx)
}
}
r.levels[level] = append(withChildren, withoutChildren...)
}
}
// createNodes creates DagAsciiJobNode for each job
func (r *DagAsciiRenderer) createNodes() {
for i, job := range r.workflow.Jobs {
jobID := job.ID
if jobID == "" {
jobID = job.Name
}
// Check if this job has children (other jobs depend on it)
hasChildren := len(r.children[jobID]) > 0
node := &DagAsciiJobNode{
Job: &r.workflow.Jobs[i],
JobID: jobID,
Width: fixedNodeWidth, // Use fixed width for all nodes
HasChildren: hasChildren,
}
// Find level for this job
for level, jobIndices := range r.levels {
if slices.Contains(jobIndices, i) {
node.Level = level
}
}
node.Lines = r.renderDagAsciiJobNode(node)
r.nodes[i] = node
}
}
// renderDagAsciiJobNode renders a single job node
func (r *DagAsciiRenderer) renderDagAsciiJobNode(node *DagAsciiJobNode) []string {
var lines []string
width := node.Width
innerWidth := width - 2 // Width inside borders
// Top border
lines = append(lines, nodeTopLeft+strings.Repeat(nodeHorizontal, innerWidth)+nodeTopRight)
// Job name (centered, truncate with ellipsis if too long)
name := truncateWithEllipsis(node.Job.Name, innerWidth-2) // -2 for padding
padding := innerWidth - runeWidth(name)
leftPad := padding / 2
rightPad := padding - leftPad
lines = append(lines, nodeVertical+strings.Repeat(" ", leftPad)+name+strings.Repeat(" ", rightPad)+nodeVertical)
// Separator
lines = append(lines, nodeTeeRight+strings.Repeat(nodeHorizontal, innerWidth)+nodeTeeLeft)
// Steps
for _, step := range node.Job.Steps {
stepName := step.Name
if stepName == "" {
stepName = step.Uses
}
// Use different bullet for embedded actions
bullet := stepBullet
if step.Uses == "embedded" {
bullet = stepBulletEmbedded
}
// Format: " ○ stepname" or " ↗ stepname" with truncation
prefix := " " + bullet + " "
prefixWidth := runeWidth(prefix)
maxStepNameWidth := innerWidth - prefixWidth
truncatedStepName := truncateWithEllipsis(stepName, maxStepNameWidth)
stepLine := prefix + truncatedStepName
// Pad to inner width
stepLineWidth := runeWidth(stepLine)
if stepLineWidth < innerWidth {
stepLine = stepLine + strings.Repeat(" ", innerWidth-stepLineWidth)
}
lines = append(lines, nodeVertical+stepLine+nodeVertical)
// Render embedded steps if this is an embedded action
if step.Uses == "embedded" {
if pathVal, ok := step.With["path"]; ok {
if pathStr, ok := pathVal.(string); ok {
// Expand template variables in path and resolve relative to workflow directory
expandedPath := r.ExpandPath(pathStr)
resolvedPath := r.ResolvePath(expandedPath)
embeddedJob, err := LoadEmbeddedJob(resolvedPath)
if err == nil && len(embeddedJob.Steps) > 0 {
// Render each embedded step with tree characters
for i, embStep := range embeddedJob.Steps {
embStepName := embStep.Name
if embStepName == "" {
embStepName = embStep.Uses
}
// Use ├ for non-last items, └ for last item
var treeChar string
if i == len(embeddedJob.Steps)-1 {
treeChar = treeEnd
} else {
treeChar = treeBranch
}
// Format: " ├ stepname" or " └ stepname"
embPrefix := " " + treeChar + " "
embPrefixWidth := runeWidth(embPrefix)
maxEmbStepNameWidth := innerWidth - embPrefixWidth
truncatedEmbStepName := truncateWithEllipsis(embStepName, maxEmbStepNameWidth)
embStepLine := embPrefix + truncatedEmbStepName
// Pad to inner width
embStepLineWidth := runeWidth(embStepLine)
if embStepLineWidth < innerWidth {
embStepLine = embStepLine + strings.Repeat(" ", innerWidth-embStepLineWidth)
}
lines = append(lines, nodeVertical+embStepLine+nodeVertical)
}
// Add filename at the end with dim color (aligned with tree characters)
filename := filepath.Base(expandedPath)
filePrefix := " "
filePrefixWidth := runeWidth(filePrefix)
maxFilenameWidth := innerWidth - filePrefixWidth
truncatedFilename := truncateWithEllipsis(filename, maxFilenameWidth)
// Apply dim color
dimFilename := ansiDim + truncatedFilename + ansiReset
// Calculate padding based on non-colored text length
fileLine := filePrefix + dimFilename
actualWidth := filePrefixWidth + runeWidth(truncatedFilename)
if actualWidth < innerWidth {
fileLine = filePrefix + dimFilename + strings.Repeat(" ", innerWidth-actualWidth)
}
lines = append(lines, nodeVertical+fileLine+nodeVertical)
}
}
}
}
}
// Bottom border - use ┬ in center if job has children
if node.HasChildren {
leftWidth := (innerWidth - 1) / 2
rightWidth := innerWidth - 1 - leftWidth
bottomBorder := nodeBottomLeft + strings.Repeat(nodeHorizontal, leftWidth) + nodeTeeDown + strings.Repeat(nodeHorizontal, rightWidth) + nodeBottomRight
lines = append(lines, bottomBorder)
} else {
lines = append(lines, nodeBottomLeft+strings.Repeat(nodeHorizontal, innerWidth)+nodeBottomRight)
}
return lines
}
// truncateWithEllipsis truncates a string to maxLen runes, adding ellipsis if truncated
func truncateWithEllipsis(s string, maxLen int) string {
runes := []rune(s)
if len(runes) <= maxLen {
return s
}
if maxLen <= 1 {
return string(runes[:maxLen])
}
return string(runes[:maxLen-1]) + ellipsis
}
// runeWidth returns the display width of a string (counting runes)
func runeWidth(s string) int {
return len([]rune(s))
}
// flagsToChar converts connection flags to the appropriate box-drawing character
// Flags: 1=from_above, 2=to_below, 4=from_left, 8=to_right
func flagsToChar(flags int) rune {
fromAbove := flags&1 != 0
toBelow := flags&2 != 0
fromLeft := flags&4 != 0
toRight := flags&8 != 0
switch {
case fromAbove && toBelow && fromLeft && toRight:
return connCross
case fromAbove && toBelow && fromLeft:
return connTeeLeft
case fromAbove && toBelow && toRight:
return connTeeRight
case fromAbove && fromLeft && toRight:
return connTeeUp
case toBelow && fromLeft && toRight:
return connTeeDown
case fromAbove && toBelow:
return connVertical
case fromLeft && toRight:
return connHorizontal
case fromAbove && toRight:
return connCornerBottomLeft
case fromAbove && fromLeft:
return connCornerBottomRight
case toBelow && toRight:
return connCornerTopLeft
case toBelow && fromLeft:
return connCornerTopRight
case fromAbove:
return connVertical
case toBelow:
return connVertical
case fromLeft, toRight:
return connHorizontal
default:
return ' '
}
}
// renderLevel renders all nodes at a given level side by side
func (r *DagAsciiRenderer) renderLevel(level int) []string {
jobIndices := r.levels[level]
if len(jobIndices) == 0 {
return nil
}
// Get nodes for this level
var levelNodes []*DagAsciiJobNode
for _, idx := range jobIndices {
levelNodes = append(levelNodes, r.nodes[idx])
}
// Find max height
maxHeight := 0
for _, node := range levelNodes {
if len(node.Lines) > maxHeight {
maxHeight = len(node.Lines)
}
}
// Calculate positions and set center X
spacing := 2
currentX := 0
for _, node := range levelNodes {
node.CenterX = currentX + node.Width/2
currentX += node.Width + spacing
}
// Render lines
var result []string
for lineIdx := 0; lineIdx < maxHeight; lineIdx++ {
var line strings.Builder
for i, node := range levelNodes {
if i > 0 {
line.WriteString(strings.Repeat(" ", spacing))
}
if lineIdx < len(node.Lines) {
line.WriteString(node.Lines[lineIdx])
} else {
// Node ended but other nodes continue - draw vertical line if this job has children
if node.HasChildren {
// Draw vertical line at center position
centerPos := node.Width / 2
line.WriteString(strings.Repeat(" ", centerPos))
line.WriteString("│")
line.WriteString(strings.Repeat(" ", node.Width-centerPos-1))
} else {
line.WriteString(strings.Repeat(" ", node.Width))
}
}
}
result = append(result, line.String())
}
return result
}
// renderConnections renders connection lines between levels
func (r *DagAsciiRenderer) renderConnections(fromLevel int) []string {
if fromLevel >= len(r.levels)-1 {
return nil
}
parentIndices := r.levels[fromLevel]
childIndices := r.levels[fromLevel+1]
if len(parentIndices) == 0 || len(childIndices) == 0 {
return nil
}
connections := r.buildConnectionMap(parentIndices, childIndices)
if len(connections) == 0 {
return nil
}
parentPositions, parentTotalWidth := r.calculateLevelPositions(parentIndices)
childPositions, childTotalWidth := r.calculateLevelPositions(childIndices)
totalWidth := max(parentTotalWidth, childTotalWidth)
parentsWithConnections := r.getConnectedParents(connections)
var result []string
result = append(result, r.renderVerticalLine(parentPositions, parentsWithConnections, totalWidth))
if r.needsRoutingLines(connections, parentPositions, childPositions) {
result = append(result, r.renderRoutingLine(connections, parentPositions, childPositions, totalWidth))
} else {
result = append(result, r.renderVerticalLine(parentPositions, parentsWithConnections, totalWidth))
}
result = append(result, r.renderArrowLine(childPositions, connections, totalWidth))
return result
}
// buildConnectionMap builds a map of childIdx -> []parentIdx for dependencies at the given level
func (r *DagAsciiRenderer) buildConnectionMap(parentIndices, childIndices []int) map[int][]int {
connections := make(map[int][]int)
for _, childIdx := range childIndices {
childNode := r.nodes[childIdx]
for _, parentIdx := range parentIndices {
parentNode := r.nodes[parentIdx]
if slices.Contains(childNode.Job.Needs, parentNode.JobID) {
connections[childIdx] = append(connections[childIdx], parentIdx)
}
}
}
return connections
}
// calculateLevelPositions calculates the center X positions for each job at a level
func (r *DagAsciiRenderer) calculateLevelPositions(jobIndices []int) (positions map[int]int, totalWidth int) {
const spacing = 2
positions = make(map[int]int)
currentX := 0
for _, idx := range jobIndices {
node := r.nodes[idx]
positions[idx] = currentX + node.Width/2
currentX += node.Width + spacing
}
if currentX > 0 {
totalWidth = currentX - spacing
}
return positions, totalWidth
}
// getConnectedParents returns a set of parent indices that have connections
func (r *DagAsciiRenderer) getConnectedParents(connections map[int][]int) map[int]bool {
parentsWithConnections := make(map[int]bool)
for _, parentList := range connections {
for _, parentIdx := range parentList {
parentsWithConnections[parentIdx] = true
}
}
return parentsWithConnections
}
// needsRoutingLines checks if routing lines are needed (when parent and child positions differ)
func (r *DagAsciiRenderer) needsRoutingLines(connections map[int][]int, parentPositions, childPositions map[int]int) bool {
for childIdx, parents := range connections {
childPos := childPositions[childIdx]
for _, parentIdx := range parents {
if parentPositions[parentIdx] != childPos {
return true
}
}
}
return false
}
// renderVerticalLine renders a line with vertical bars at the specified positions
func (r *DagAsciiRenderer) renderVerticalLine(positions map[int]int, connectedIndices map[int]bool, totalWidth int) string {
line := make([]rune, totalWidth)
for i := range line {
line[i] = ' '
}
for idx := range connectedIndices {
if pos, ok := positions[idx]; ok && pos < len(line) {
line[pos] = '│'
}
}
return string(line)
}
// renderRoutingLine renders the routing line with appropriate box-drawing characters
func (r *DagAsciiRenderer) renderRoutingLine(connections map[int][]int, parentPositions, childPositions map[int]int, totalWidth int) string {
// Collect connection flags for each position
// Flags: 1=from_above, 2=to_below, 4=from_left, 8=to_right
posFlags := make(map[int]int)
for childIdx, parents := range connections {
childPos := childPositions[childIdx]
for _, parentIdx := range parents {
parentPos := parentPositions[parentIdx]
if parentPos == childPos {
// Straight vertical
posFlags[parentPos] |= 1 | 2 // from_above | to_below
} else if parentPos < childPos {
// Parent is left of child
posFlags[parentPos] |= 1 | 8 // from_above | to_right
posFlags[childPos] |= 4 | 2 // from_left | to_below
for i := parentPos + 1; i < childPos; i++ {
posFlags[i] |= 4 | 8 // horizontal
}
} else {
// Parent is right of child
posFlags[childPos] |= 8 | 2 // to_right | to_below
posFlags[parentPos] |= 4 | 1 // from_left | from_above
for i := childPos + 1; i < parentPos; i++ {
posFlags[i] |= 4 | 8 // horizontal
}
}
}
}
line := make([]rune, totalWidth)
for i := range line {
line[i] = ' '
}
for pos, flags := range posFlags {
if pos < len(line) {
line[pos] = flagsToChar(flags)
}
}
return string(line)
}
// renderArrowLine renders the arrow line pointing to child positions
func (r *DagAsciiRenderer) renderArrowLine(childPositions map[int]int, connections map[int][]int, totalWidth int) string {
line := make([]rune, totalWidth)
for i := range line {
line[i] = ' '
}
for childIdx := range connections {
if pos, ok := childPositions[childIdx]; ok && pos < len(line) {
line[pos] = '↓'
}
}
return string(line)
}