-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
629 lines (540 loc) · 18.1 KB
/
main.go
File metadata and controls
629 lines (540 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
package main
import (
"context"
"flag"
"fmt"
"os"
"os/signal"
"path/filepath"
"reflect"
"strconv"
"strings"
"syscall"
"github.com/andygrunwald/go-jira"
"github.com/kitproj/jira-cli/internal/config"
flagpkg "github.com/kitproj/jira-cli/internal/flag"
"golang.org/x/term"
)
var (
host string
token string
issueKey string
client *jira.Client
)
func main() {
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer cancel()
flag.Usage = func() {
w := flag.CommandLine.Output()
fmt.Fprintf(w, "Usage:")
fmt.Fprintln(w)
fmt.Fprintln(w, " jira configure <host> - Configure JIRA host and token (reads token from stdin)")
fmt.Fprintln(w, " jira create-issue <project> <issue-type> <title> <description> [assignee] - Create a new JIRA issue")
fmt.Fprintln(w, " jira get-issue <issue-key> - Get details of the specified JIRA issue")
fmt.Fprintln(w, " jira list-issues [-a=user] [-t=type] [-p=key] - List issues with optional filters")
fmt.Fprintln(w, " jira update-issue-status <issue-key> <status> [-f field=value]... - Update the status of the specified JIRA issue")
fmt.Fprintln(w, " jira get-comments <issue-key> - Get comments of the specified JIRA issue")
fmt.Fprintln(w, " jira add-comment <issue-key> <comment> - Add a comment to the specified JIRA issue")
fmt.Fprintln(w, " jira attach-file <issue-key> <file-path> - Attach a file to the specified JIRA issue")
fmt.Fprintln(w, " jira assign-issue <issue-key> <assignee> - Assign an issue to a user")
fmt.Fprintln(w, " jira add-issue-to-sprint <issue-key> - Add an issue to the current sprint")
fmt.Fprintln(w, " jira mcp-server - Start MCP server (stdio transport)")
fmt.Fprintln(w)
fmt.Fprintln(w, "Options:")
flag.PrintDefaults()
}
flag.Parse()
if err := run(ctx, flag.Args()); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
flag.Usage()
os.Exit(1)
}
}
func run(ctx context.Context, args []string) error {
if len(args) < 1 {
return fmt.Errorf("usage: jira <command> [args...]")
}
// First argument is the command
command := args[0]
switch command {
case "configure":
if len(args) < 2 {
return fmt.Errorf("usage: jira configure <host>")
}
return configure(args[1])
case "create-issue":
if len(args) < 5 {
return fmt.Errorf("usage: jira create-issue <project> <issue-type> <title> <description> [assignee]")
}
project := args[1]
issueType := args[2]
title := args[3]
description := args[4]
var assignee string
if len(args) >= 6 {
assignee = args[5]
}
return executeCommand(ctx, func(ctx context.Context) error {
return createIssue(ctx, project, issueType, title, description, assignee)
})
case "get-issue":
if len(args) < 2 {
return fmt.Errorf("usage: jira <command> <issue-key> [args...]")
}
issueKey = args[1]
return executeCommand(ctx, getIssue)
case "update-issue-status":
if len(args) < 3 {
return fmt.Errorf("usage: jira update-issue-status <issue-key> <status> [-f field=value]")
}
issueKey = args[1]
statusName := args[2]
// Create a new flag set for this command
fs := flag.NewFlagSet("update-issue-status", flag.ContinueOnError)
fields := make(flagpkg.FieldFlag)
fs.Var(fields, "f", "field=value pair to include in transition (can be specified multiple times)")
// Parse flags from remaining args
if err := fs.Parse(args[3:]); err != nil {
return fmt.Errorf("failed to parse flags: %w", err)
}
return executeCommand(ctx, func(ctx context.Context) error {
return updateIssueStatus(ctx, statusName, map[string]string(fields))
})
case "add-comment":
if len(args) < 3 {
return fmt.Errorf("usage: jira add-comment <issue-key> <comment>")
}
issueKey = args[1]
message := args[2]
return executeCommand(ctx, func(ctx context.Context) error {
return addComment(ctx, message)
})
case "get-comments":
if len(args) < 2 {
return fmt.Errorf("usage: jira <command> <issue-key> [args...]")
}
issueKey = args[1]
return executeCommand(ctx, getComments)
case "list-issues":
// Create a new flag set for this command
fs := flag.NewFlagSet("list-issues", flag.ContinueOnError)
assignee := fs.String("a", "me", "filter by assignee (default: current user, use 'me' for current user)")
issueType := fs.String("t", "", "filter by issue type (e.g., Story, Bug, Task)")
project := fs.String("p", "", "filter by project key")
// Parse flags from args
if err := fs.Parse(args[1:]); err != nil {
return fmt.Errorf("failed to parse flags: %w", err)
}
return executeCommand(ctx, func(ctx context.Context) error {
return listIssues(ctx, *assignee, *issueType, *project)
})
case "attach-file":
if len(args) < 3 {
return fmt.Errorf("usage: jira attach-file <issue-key> <file-path>")
}
issueKey = args[1]
filePath := args[2]
return executeCommand(ctx, func(ctx context.Context) error {
return attachFile(ctx, filePath)
})
case "assign-issue":
if len(args) < 3 {
return fmt.Errorf("usage: jira assign-issue <issue-key> <assignee>")
}
issueKey = args[1]
assignee := args[2]
return executeCommand(ctx, func(ctx context.Context) error {
return assignIssue(ctx, assignee)
})
case "add-issue-to-sprint":
if len(args) < 2 {
return fmt.Errorf("usage: jira add-issue-to-sprint <issue-key>")
}
issueKey = args[1]
return executeCommand(ctx, addIssueToSprint)
case "mcp-server":
return runMCPServer(ctx)
default:
return fmt.Errorf("unknown sub-command: %s", command)
}
}
func executeCommand(ctx context.Context, fn func(context.Context) error) error {
// Load host from config file, or fall back to env var
if host == "" {
var err error
host, err = config.LoadConfig()
if err != nil {
// Fall back to environment variable
host = os.Getenv("JIRA_HOST")
}
}
// Load token from keyring, or fall back to env var
if token == "" {
token = os.Getenv("JIRA_TOKEN")
}
if token == "" {
var err error
token, err = config.LoadToken(host)
if err != nil {
return err
}
}
if host == "" {
return fmt.Errorf("host is required")
}
if token == "" {
return fmt.Errorf("token is required")
}
tp := jira.BearerAuthTransport{Token: token}
var err error
client, err = jira.NewClient(tp.Client(), "https://"+host)
if err != nil {
return fmt.Errorf("failed to create JIRA client: %w", err)
}
return fn(ctx)
}
func getIssue(ctx context.Context) error {
issue, _, err := client.Issue.GetWithContext(ctx, issueKey, nil)
if err != nil {
return fmt.Errorf("failed to get issue: %w", err)
}
printField("Key", issue.Key)
printField("Type", issue.Fields.Type.Name)
printField("Status", issue.Fields.Status.Name)
printField("Summary", issue.Fields.Summary)
printField("Reporter", fmt.Sprintf("%s (%s)", issue.Fields.Reporter.DisplayName, issue.Fields.Reporter.Name))
printField("Description", issue.Fields.Description)
// we need to only display fields the user can set, which are the editable fields
editMetaInfo, _, err := client.Issue.GetEditMetaWithContext(ctx, issue)
if err != nil {
return fmt.Errorf("failed to get edit meta: %w", err)
}
for key, value := range issue.Fields.Unknowns {
if _, ok := editMetaInfo.Fields[key]; ok && strings.HasPrefix(key, "customfield_") && isPrimitive(value) {
name := editMetaInfo.Fields[key].(map[string]any)["name"].(string)
printField(name, value)
}
}
return nil
}
func isPrimitive(v any) bool {
kind := reflect.ValueOf(v).Kind()
switch kind {
case reflect.Bool,
reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr,
reflect.Float32, reflect.Float64,
reflect.Complex64, reflect.Complex128,
reflect.String:
return true
default:
return false
}
}
func printField(key string, value any) {
valueStr := fmt.Sprint(value)
multiLine := strings.Contains(valueStr, "\n")
fmt.Printf("%-32s", key+":")
if !multiLine {
fmt.Printf(" %s\n", valueStr)
} else {
fmt.Println()
for line := range strings.SplitSeq(valueStr, "\n") {
fmt.Printf("%-32s %s\n", "", line)
}
}
}
// updateIssueStatus updates the status of a Jira issue using transitions
func updateIssueStatus(ctx context.Context, statusName string, extra map[string]string) error {
// First, get the issue to check current status
issue, _, err := client.Issue.GetWithContext(ctx, issueKey, nil)
if err != nil {
return fmt.Errorf("failed to get issue: %w", err)
}
// Check if already in the desired status
if issue.Fields.Status.Name == statusName {
fmt.Printf("Issue %s is already in status: %s\n", issueKey, statusName)
return nil
}
// Get available transitions for this issue
transitions, _, err := client.Issue.GetTransitionsWithContext(ctx, issueKey)
if err != nil {
return fmt.Errorf("failed to get transitions: %w", err)
}
// Find the transition that leads to the desired status
var targetTransition *jira.Transition
for _, transition := range transitions {
if transition.To.Name == statusName {
targetTransition = &transition
break
}
}
if targetTransition == nil {
// List available statuses for better error message
var availableStatuses []string
for _, transition := range transitions {
availableStatuses = append(availableStatuses, fmt.Sprintf("%q", transition.To.Name))
}
return fmt.Errorf("no transition found to status '%s'. Available statuses: %v", statusName, strings.Join(availableStatuses, ", "))
}
// Get edit metadata to map field names to field IDs
editMetaInfo, _, err := client.Issue.GetEditMetaWithContext(ctx, issue)
if err != nil {
return fmt.Errorf("failed to get field metadata: %w", err)
}
fieldNameByID := make(map[string]string)
for fieldID, value := range editMetaInfo.Fields {
valueMap, ok := value.(map[string]any)
if !ok {
continue
}
name, ok := valueMap["name"].(string)
if !ok {
continue
}
fieldNameByID[fieldID] = name
}
fields := make(map[string]any)
fmt.Println("Fields to update:")
for fieldID := range targetTransition.Fields {
fieldName := fieldNameByID[fieldID]
fieldValue := extra[fieldName]
printField(fmt.Sprintf("%s (%s)", fieldName, fieldID), fieldValue)
i, err := strconv.Atoi(fieldValue)
if err != nil {
fields[fieldID] = fieldValue
} else {
fields[fieldID] = i
}
}
// Build transition payload
payload := map[string]any{
"transition": map[string]any{
"id": targetTransition.ID,
},
"fields": fields,
}
// Perform the transition
_, err = client.Issue.DoTransitionWithPayloadWithContext(ctx, issueKey, payload)
if err != nil {
return fmt.Errorf("failed to update issue status: %w", err)
}
fmt.Printf("Successfully updated issue %s to status: %s (https://%s/browse/%s)\n", issueKey, statusName, host, issueKey)
return nil
}
func addComment(ctx context.Context, message string) error {
comment := &jira.Comment{
Body: message,
}
_, _, err := client.Issue.AddCommentWithContext(ctx, issueKey, comment)
if err != nil {
return fmt.Errorf("failed to add comment: %w", err)
}
return nil
}
func getComments(ctx context.Context) error {
options := &jira.GetQueryOptions{
Expand: "comments",
}
issue, _, err := client.Issue.GetWithContext(ctx, issueKey, options)
if err != nil {
return fmt.Errorf("failed to get issue with comments: %w", err)
}
if issue.Fields.Comments == nil {
fmt.Println("No comments found")
return nil
}
for _, comment := range issue.Fields.Comments.Comments {
fmt.Printf("%s (%s):\n", comment.Author.DisplayName, comment.Author.Name)
fmt.Println(comment.Body)
fmt.Println("---")
}
return nil
}
// createIssue creates a new JIRA issue with the specified project, issue type, title, description, and optional assignee
func createIssue(ctx context.Context, projectKey, issueType, title, description, assignee string) error {
// Create a new issue with the specified issue type
issue := &jira.Issue{
Fields: &jira.IssueFields{
Project: jira.Project{
Key: projectKey,
},
Summary: title,
Description: description,
Type: jira.IssueType{
Name: issueType,
},
},
}
// Add assignee if provided
if assignee != "" {
issue.Fields.Assignee = &jira.User{
Name: assignee,
}
}
// Create the issue
createdIssue, _, err := client.Issue.CreateWithContext(ctx, issue)
if err != nil {
return fmt.Errorf("failed to create issue: %w", err)
}
fmt.Printf("Successfully created issue: %s (https://%s/browse/%s)\n", createdIssue.Key, host, createdIssue.Key)
return nil
}
// configure reads the token from stdin and saves it to the keyring
func configure(host string) error {
if host == "" {
return fmt.Errorf("host is required")
}
fmt.Fprintf(os.Stderr, "To create a personal access token, visit: https://%s/secure/ViewProfile.jspa?selectedTab=com.atlassian.pats.pats-plugin:jira-user-personal-access-tokens\n", host)
fmt.Fprintf(os.Stderr, "The token will be stored securely in your system's keyring.\n")
fmt.Fprintf(os.Stderr, "\nEnter JIRA API token: ")
// Read password with hidden input
tokenBytes, err := term.ReadPassword(int(syscall.Stdin))
fmt.Fprintln(os.Stderr) // Print newline after hidden input
if err != nil {
return fmt.Errorf("failed to read token: %w", err)
}
token := string(tokenBytes)
if token == "" {
return fmt.Errorf("token cannot be empty")
}
// Save host to config file
if err := config.SaveConfig(host); err != nil {
return err
}
// Save token to keyring
if err := config.SaveToken(host, token); err != nil {
return err
}
fmt.Fprintf(os.Stderr, "Configuration saved successfully for host: %s\n", host)
return nil
}
// listIssues lists issues with optional filters
func listIssues(ctx context.Context, assigneeFilter, issueTypeFilter, projectFilter string) error {
// Build JQL query dynamically based on filters
var conditions []string
// Assignee filter (default to currentUser() if not specified)
if assigneeFilter == "me" {
conditions = append(conditions, "assignee = currentUser()")
} else if assigneeFilter != "" {
conditions = append(conditions, fmt.Sprintf("assignee = %q", assigneeFilter))
}
// Project filter
if projectFilter != "" {
conditions = append(conditions, fmt.Sprintf("project = %q", projectFilter))
}
// Issue type filter
if issueTypeFilter != "" {
conditions = append(conditions, fmt.Sprintf("issuetype = %q", issueTypeFilter))
}
// Default: exclude resolved issues
conditions = append(conditions, "resolution = Unresolved")
// Default: updated in last 14 days if no specific filters
if projectFilter == "" && issueTypeFilter == "" {
conditions = append(conditions, "updated >= -14d")
}
// Build JQL query
jql := strings.Join(conditions, " AND ") + " ORDER BY updated DESC"
// Search for issues using JQL
issues, _, err := client.Issue.SearchWithContext(ctx, jql, &jira.SearchOptions{
MaxResults: 50,
Fields: []string{"key", "issuetype", "summary", "status", "assignee", "project"},
})
if err != nil {
return fmt.Errorf("failed to search issues: %w", err)
}
if len(issues) == 0 {
fmt.Println("No issues found matching the specified criteria")
return nil
}
fmt.Printf("Found %d issue(s)", len(issues))
if len(issues) >= 50 {
fmt.Printf(" (showing first 50 only)")
}
fmt.Printf(":\n\n")
for _, issue := range issues {
assigneeName := "-"
if issue.Fields.Assignee != nil {
assigneeName = issue.Fields.Assignee.DisplayName
}
fmt.Printf("%-10s %-10s %-16s %-20s %s\n", issue.Key, issue.Fields.Type.Name, issue.Fields.Status.Name, assigneeName, issue.Fields.Summary)
}
return nil
}
// attachFile attaches a file to a Jira issue
func attachFile(ctx context.Context, filePath string) error {
// Open the file
file, err := os.Open(filePath)
if err != nil {
return fmt.Errorf("failed to open file: %w", err)
}
defer file.Close()
// Get the file name from the path using filepath.Base for cross-platform compatibility
fileName := filepath.Base(filePath)
// Post the attachment
attachments, _, err := client.Issue.PostAttachmentWithContext(ctx, issueKey, file, fileName)
if err != nil {
return fmt.Errorf("failed to attach file: %w", err)
}
if attachments != nil && len(*attachments) > 0 {
attachment := (*attachments)[0]
fmt.Printf("Successfully attached file '%s' to issue %s (ID: %s)\n", attachment.Filename, issueKey, attachment.ID)
} else {
fmt.Printf("Successfully attached file to issue %s\n", issueKey)
}
return nil
}
// assignIssue assigns an issue to a user
func assignIssue(ctx context.Context, assignee string) error {
// Create a User object with the assignee name
user := &jira.User{
Name: assignee,
}
// Update the assignee
_, err := client.Issue.UpdateAssigneeWithContext(ctx, issueKey, user)
if err != nil {
return fmt.Errorf("failed to assign issue: %w", err)
}
fmt.Printf("Successfully assigned issue %s to %s\n", issueKey, assignee)
return nil
}
// addIssueToSprint adds an issue to the current sprint
func addIssueToSprint(ctx context.Context) error {
// First, get the issue to find its project/board
issue, _, err := client.Issue.GetWithContext(ctx, issueKey, nil)
if err != nil {
return fmt.Errorf("failed to get issue: %w", err)
}
// Get all boards to find the one that contains this issue's project
boards, _, err := client.Board.GetAllBoardsWithContext(ctx, &jira.BoardListOptions{
ProjectKeyOrID: issue.Fields.Project.Key,
BoardType: "scrum",
})
if err != nil {
return fmt.Errorf("failed to get boards: %w", err)
}
if len(boards.Values) == 0 {
return fmt.Errorf("no boards found for project %s", issue.Fields.Project.Key)
}
// Use the first board (typically the main board for the project)
boardID := boards.Values[0].ID
// Get all sprints for this board
sprints, _, err := client.Board.GetAllSprintsWithOptionsWithContext(ctx, boardID, &jira.GetAllSprintsOptions{
State: "active",
})
if err != nil {
return fmt.Errorf("failed to get sprints: %w", err)
}
if len(sprints.Values) == 0 {
return fmt.Errorf("no active sprint found for board %d", boardID)
}
// Use the first active sprint
sprintID := sprints.Values[0].ID
// Move the issue to the sprint
_, err = client.Sprint.MoveIssuesToSprintWithContext(ctx, sprintID, []string{issueKey})
if err != nil {
return fmt.Errorf("failed to add issue to sprint: %w", err)
}
fmt.Printf("Successfully added issue %s to sprint %q\n", issueKey, sprints.Values[0].Name)
return nil
}