-
Notifications
You must be signed in to change notification settings - Fork 356
Expand file tree
/
Copy pathadd_workflow_resolution.go
More file actions
265 lines (225 loc) · 8.75 KB
/
add_workflow_resolution.go
File metadata and controls
265 lines (225 loc) · 8.75 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
package cli
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/github/gh-aw/pkg/console"
"github.com/github/gh-aw/pkg/logger"
"github.com/github/gh-aw/pkg/parser"
"github.com/github/gh-aw/pkg/sliceutil"
)
var resolutionLog = logger.New("cli:add_workflow_resolution")
// ResolvedWorkflow contains metadata about a workflow that has been resolved and is ready to add
type ResolvedWorkflow struct {
// Spec is the parsed workflow specification
Spec *WorkflowSpec
// Content is the raw workflow content (convenience accessor, same as SourceInfo.Content)
Content []byte
// SourceInfo contains fetched workflow data including content, commit SHA, and source path
SourceInfo *FetchedWorkflow
// Description is the workflow description extracted from frontmatter
Description string
// Engine is the preferred engine extracted from frontmatter (empty if not specified)
Engine string
// HasWorkflowDispatch indicates if the workflow has workflow_dispatch trigger
HasWorkflowDispatch bool
// IsPrivate indicates if the workflow has private: true in its frontmatter
IsPrivate bool
}
// ResolvedWorkflows contains all resolved workflows ready to be added
type ResolvedWorkflows struct {
// Workflows is the list of resolved workflows
Workflows []*ResolvedWorkflow
// HasWildcard indicates if any of the original specs contained wildcards (local only)
HasWildcard bool
// HasWorkflowDispatch is true if any of the workflows has a workflow_dispatch trigger
HasWorkflowDispatch bool
}
// ResolveWorkflows resolves workflow specifications by parsing specs and fetching workflow content.
// For remote workflows, content is fetched directly from GitHub without cloning.
// Wildcards are only supported for local workflows (not remote repositories).
func ResolveWorkflows(ctx context.Context, workflows []string, verbose bool) (*ResolvedWorkflows, error) {
resolutionLog.Printf("Resolving workflows: count=%d", len(workflows))
if len(workflows) == 0 {
return nil, errors.New("at least one workflow name is required")
}
for i, workflow := range workflows {
if workflow == "" {
return nil, fmt.Errorf("workflow name cannot be empty (workflow %d)", i+1)
}
}
// Parse workflow specifications
parsedSpecs := make([]*WorkflowSpec, 0, len(workflows))
for _, workflow := range workflows {
spec, err := parseWorkflowSpec(workflow)
if err != nil {
return nil, fmt.Errorf("invalid workflow specification '%s': %w", workflow, err)
}
// Wildcards are only supported for local workflows
if spec.IsWildcard && !isLocalWorkflowPath(spec.WorkflowPath) {
return nil, fmt.Errorf("wildcards are only supported for local workflows, not remote repositories: %s", workflow)
}
parsedSpecs = append(parsedSpecs, spec)
}
// Check if any workflow is from the current repository
// Skip this check if we can't determine the current repository (e.g., not in a git repo)
currentRepoSlug, repoErr := GetCurrentRepoSlug()
if repoErr == nil {
resolutionLog.Printf("Current repository: %s", currentRepoSlug)
// We successfully determined the current repository, check all workflow specs
for _, spec := range parsedSpecs {
// Skip local workflow specs
if isLocalWorkflowPath(spec.WorkflowPath) {
continue
}
if spec.RepoSlug == currentRepoSlug {
return nil, fmt.Errorf("cannot add workflows from the current repository (%s). The 'add' command is for installing workflows from other repositories", currentRepoSlug)
}
}
} else {
resolutionLog.Printf("Could not determine current repository: %v", repoErr)
}
// If we can't determine the current repository, proceed without the check
// Check if any workflow specs contain wildcards (local only)
hasWildcard := sliceutil.Any(parsedSpecs, func(spec *WorkflowSpec) bool {
return spec.IsWildcard
})
// Expand wildcards for local workflows only
if hasWildcard {
var err error
parsedSpecs, err = expandLocalWildcardWorkflows(parsedSpecs, verbose)
if err != nil {
return nil, err
}
}
// Fetch workflow content and metadata for each workflow
resolvedWorkflows := make([]*ResolvedWorkflow, 0, len(parsedSpecs))
hasWorkflowDispatch := false
for _, spec := range parsedSpecs {
// Fetch workflow content - FetchWorkflowFromSource handles both local and remote
fetched, err := FetchWorkflowFromSourceWithContext(ctx, spec, verbose)
if err != nil {
return nil, fmt.Errorf("workflow '%s' not found: %w", spec.String(), err)
}
// Extract description from content
description := ExtractWorkflowDescription(string(fetched.Content))
// Extract engine from content (if specified in frontmatter)
engine := ExtractWorkflowEngine(string(fetched.Content))
// Check if workflow is private - private workflows cannot be added to other repositories
isPrivate := ExtractWorkflowPrivate(string(fetched.Content))
if isPrivate {
return nil, fmt.Errorf("workflow '%s' is private and cannot be added to other repositories", spec.String())
}
// Check for workflow_dispatch trigger in content
workflowHasDispatch := checkWorkflowHasDispatchFromContent(string(fetched.Content))
if workflowHasDispatch {
hasWorkflowDispatch = true
}
resolutionLog.Printf("Resolved workflow: spec=%s, engine=%s, has_dispatch=%t, content_size=%d bytes",
spec.String(), engine, workflowHasDispatch, len(fetched.Content))
resolvedWorkflows = append(resolvedWorkflows, &ResolvedWorkflow{
Spec: spec,
Content: fetched.Content,
SourceInfo: fetched,
Description: description,
Engine: engine,
HasWorkflowDispatch: workflowHasDispatch,
IsPrivate: isPrivate,
})
}
resolutionLog.Printf("Resolution complete: resolved=%d workflows, has_wildcard=%t, has_dispatch=%t",
len(resolvedWorkflows), hasWildcard, hasWorkflowDispatch)
return &ResolvedWorkflows{
Workflows: resolvedWorkflows,
HasWildcard: hasWildcard,
HasWorkflowDispatch: hasWorkflowDispatch,
}, nil
}
// expandLocalWildcardWorkflows expands wildcard workflow specifications for local workflows only.
func expandLocalWildcardWorkflows(specs []*WorkflowSpec, verbose bool) ([]*WorkflowSpec, error) {
expandedWorkflows := []*WorkflowSpec{}
for _, spec := range specs {
if spec.IsWildcard && isLocalWorkflowPath(spec.WorkflowPath) {
resolutionLog.Printf("Expanding local wildcard: %s", spec.WorkflowPath)
if verbose {
fmt.Fprintln(os.Stderr, console.FormatInfoMessage(fmt.Sprintf("Discovering local workflows matching %s...", spec.WorkflowPath)))
}
// Expand local wildcard (e.g., ./*.md or ./workflows/*.md)
discovered, err := expandLocalWildcard(spec)
if err != nil {
return nil, fmt.Errorf("failed to expand wildcard %s: %w", spec.WorkflowPath, err)
}
if len(discovered) == 0 {
fmt.Fprintln(os.Stderr, console.FormatWarningMessage("No workflows found matching "+spec.WorkflowPath))
} else {
if verbose {
fmt.Fprintln(os.Stderr, console.FormatSuccessMessage(fmt.Sprintf("Found %d workflow(s)", len(discovered))))
}
expandedWorkflows = append(expandedWorkflows, discovered...)
}
} else {
expandedWorkflows = append(expandedWorkflows, spec)
}
}
if len(expandedWorkflows) == 0 {
return nil, errors.New("no workflows to add after expansion")
}
return expandedWorkflows, nil
}
// checkWorkflowHasDispatchFromContent checks if workflow content has a workflow_dispatch trigger
func checkWorkflowHasDispatchFromContent(content string) bool {
result, err := parser.ExtractFrontmatterFromContent(content)
if err != nil {
return false
}
onSection, exists := result.Frontmatter["on"]
if !exists {
return false
}
switch on := onSection.(type) {
case map[string]any:
_, hasDispatch := on["workflow_dispatch"]
return hasDispatch
case string:
return strings.Contains(strings.ToLower(on), "workflow_dispatch")
case []any:
for _, item := range on {
if str, ok := item.(string); ok && strings.ToLower(str) == "workflow_dispatch" {
return true
}
}
return false
default:
return false
}
}
// expandLocalWildcard expands a local wildcard path (e.g., ./*.md) into individual workflow specs
func expandLocalWildcard(spec *WorkflowSpec) ([]*WorkflowSpec, error) {
pattern := spec.WorkflowPath
// Use filepath.Glob to expand the pattern
matches, err := filepath.Glob(pattern)
if err != nil {
return nil, fmt.Errorf("invalid wildcard pattern %s: %w", pattern, err)
}
if len(matches) == 0 {
return nil, nil
}
mdMatches := sliceutil.Filter(matches, func(m string) bool {
return strings.HasSuffix(m, ".md")
})
result := sliceutil.Map(mdMatches, func(match string) *WorkflowSpec {
return &WorkflowSpec{
RepoSpec: RepoSpec{
RepoSlug: spec.RepoSlug,
Version: spec.Version,
},
WorkflowPath: match,
WorkflowName: normalizeWorkflowID(match),
IsWildcard: false,
}
})
return result, nil
}