@@ -34,77 +34,64 @@ This command performs the following actions:
34345. Updates the Assignee ID in the local database if it differs from the one in Jira.
35356. Use --dry-run to preview changes without modifying the local database.` ,
3636 RunE : func (cmd * cobra.Command , args []string ) error {
37- // 1) Set default label if not provided
3837 if syncJiraSearchLabel == "" {
39- syncJiraSearchLabel = "flaky_test" // Default label
38+ syncJiraSearchLabel = "flaky_test"
4039 }
4140 log .Info ().Str ("label" , syncJiraSearchLabel ).Msg ("Using Jira search label" )
4241
43- // 2) Load local DB
44- // LoadDBWithPath now returns an empty DB if file not found, but returns error on decode failure etc.
4542 db , err := localdb .LoadDBWithPath (syncTestDBPath )
4643 if err != nil {
47- // If error is critical (not just file not found), log and return
4844 log .Error ().Err (err ).Str ("path" , syncTestDBPath ).Msg ("Failed to load or decode local DB" )
4945 return fmt .Errorf ("failed to load local DB from %s: %w" , syncTestDBPath , err )
50- // If we wanted to continue with an empty DB even on decode errors:
51- // log.Warn().Err(err).Msg("Failed to load local DB; continuing with empty DB.")
52- // db = localdb.NewDBWithPath(syncTestDBPath) // Ensure path is set correctly on new DB
5346 }
5447
55- // 3) Get Jira client
5648 client , err := jirautils .GetJiraClient ()
5749 if err != nil {
5850 log .Error ().Err (err ).Msg ("Failed to create Jira client" )
59- return err // Cannot proceed without Jira client
51+ return err
6052 }
6153 log .Info ().Msg ("Jira client created successfully." )
6254
63- // 4) Search for all flaky test tickets in Jira
6455 jql := fmt .Sprintf (`labels = "%s" ORDER BY created DESC` , syncJiraSearchLabel )
6556 var startAt int
6657 var allIssues []jira.Issue
67- totalTicketsInJira := 0 // Keep track even before appending
58+ totalTicketsInJira := 0
6859
6960 log .Info ().Msg ("Searching Jira for tickets..." )
7061 for {
71- // Fetch required fields: summary (for test name), assignee
7262 issues , resp , searchErr := client .Issue .SearchWithContext (context .Background (), jql , & jira.SearchOptions {
7363 StartAt : startAt ,
7464 MaxResults : 50 , // Fetch in batches
7565 Fields : []string {"summary" , "assignee" },
7666 })
7767 if searchErr != nil {
78- // Attempt to read response for more detailed error
7968 errMsg := jirautils .ReadJiraErrorResponse (resp )
8069 log .Error ().Err (searchErr ).Str ("jql" , jql ).Str ("response" , errMsg ).Msg ("Error searching Jira" )
8170 return fmt .Errorf ("error searching Jira: %w (response: %s)" , searchErr , errMsg )
8271 }
8372
8473 if resp != nil {
85- totalTicketsInJira = resp .Total // Get total count from the response
74+ totalTicketsInJira = resp .Total
8675 }
8776
8877 if len (issues ) == 0 {
89- break // No more issues found
78+ break
9079 }
9180 allIssues = append (allIssues , issues ... )
9281 startAt += len (issues )
9382 log .Debug ().Int ("fetched" , len (issues )).Int ("total_fetched" , startAt ).Int ("jira_total" , totalTicketsInJira ).Msg ("Fetched batch of issues from Jira" )
9483
95- // Safety break if StartAt exceeds total, although Jira should handle this.
9684 if totalTicketsInJira > 0 && startAt >= totalTicketsInJira {
9785 break
9886 }
9987 }
10088 log .Info ().Int ("count" , len (allIssues )).Msg ("Finished fetching all matching Jira tickets." )
10189
102- // 5) Process each issue
10390 var addedCount int
104- var updatedCount int // Counts tickets found in DB (assignee might or might not be updated)
91+ var updatedCount int
10592 var skippedCount int
10693 var assigneeUpdatedCount int
107- dbModified := false // Flag to track if save is needed
94+ dbModified := false
10895
10996 // Get all current DB entries for efficient lookup by Jira Key
11097 // Note: This map uses JiraKey as the map key, NOT the internal pkg::name key.
@@ -141,18 +128,16 @@ This command performs the following actions:
141128 // Check if this ticket (by Jira Key) is already in our local DB map
142129 if entry , exists := entryMapByJiraKey [issue .Key ]; exists {
143130 // Ticket exists in DB, check if assignee needs update
144- updatedCount ++ // Increment count of tickets found in DB
131+ updatedCount ++
145132 if entry .AssigneeID != assigneeID {
146133 log .Info ().Str ("key" , issue .Key ).Str ("old_assignee" , entry .AssigneeID ).Str ("new_assignee" , assigneeID ).Msg ("Assignee mismatch found." )
147134 if ! syncDryRun {
148- // Update the entry using UpsertEntry, preserving existing fields
149135 errUpsert := db .UpsertEntry (entry .TestPackage , entry .TestName , entry .JiraTicket , entry .SkippedAt , assigneeID ) // Pass new assigneeID
150136 if errUpsert != nil {
151137 log .Error ().Err (errUpsert ).Str ("key" , issue .Key ).Msg ("Failed to update assignee in local DB" )
152- // Continue processing other tickets? Yes.
153138 } else {
154- assigneeUpdatedCount ++ // Count successful updates
155- dbModified = true // Mark DB as modified
139+ assigneeUpdatedCount ++
140+ dbModified = true
156141 log .Info ().Str ("key" , issue .Key ).Str ("new_assignee" , assigneeID ).Msg ("Successfully updated assignee in local DB." )
157142 }
158143 } else {
@@ -161,37 +146,30 @@ This command performs the following actions:
161146 log .Info ().Str ("key" , issue .Key ).Str ("new_assignee" , assigneeID ).Msg ("[Dry Run] Would update assignee." )
162147 }
163148 } else {
164- // Assignee matches, nothing to do for this entry
165149 log .Debug ().Str ("key" , issue .Key ).Msg ("Existing ticket found in DB, assignee matches." )
166150 }
167151 } else {
168152 // Ticket NOT found in DB, add it
169153 log .Info ().Str ("key" , issue .Key ).Str ("test" , testName ).Str ("assignee" , assigneeID ).Msg ("New ticket found in Jira, adding to DB." )
170154 if ! syncDryRun {
171- // Add new entry using UpsertEntry
172- // TestPackage is unknown, SkippedAt is zero time for new entries
173155 errUpsert := db .UpsertEntry ("" , testName , issue .Key , time.Time {}, assigneeID )
174156 if errUpsert != nil {
175157 log .Error ().Err (errUpsert ).Str ("key" , issue .Key ).Msg ("Failed to add new ticket to local DB" )
176- // Continue processing other tickets? Yes.
177158 } else {
178- addedCount ++ // Count successful additions
179- dbModified = true // Mark DB as modified
159+ addedCount ++
160+ dbModified = true
180161 log .Info ().Str ("key" , issue .Key ).Msg ("Successfully added new ticket to local DB." )
181162 }
182163 } else {
183- // In dry run, just log the potential addition and increment counter
184164 addedCount ++
185165 log .Info ().Str ("key" , issue .Key ).Str ("test" , testName ).Str ("assignee" , assigneeID ).Msg ("[Dry Run] Would add new ticket." )
186166 }
187167 }
188- } // End of processing loop
168+ }
189169
190- // 6) Save DB if not in dry run mode and modifications occurred
191170 if ! syncDryRun && dbModified {
192171 if err := db .Save (); err != nil {
193172 log .Error ().Err (err ).Msg ("Failed to save updated local DB" )
194- // Return error here as saving failed
195173 return fmt .Errorf ("failed to save local DB changes: %w" , err )
196174 }
197175 log .Info ().Str ("path" , db .FilePath ()).Msg ("Local DB saved with updates." )
@@ -201,7 +179,6 @@ This command performs the following actions:
201179 log .Info ().Msg ("No changes detected requiring DB save." )
202180 }
203181
204- // 7) Print summary
205182 fmt .Printf ("\n --- Sync Summary ---\n " )
206183 fmt .Printf ("Total Jira tickets scanned (label: %s): %d\n " , syncJiraSearchLabel , len (allIssues ))
207184 fmt .Printf ("Tickets added to local DB: %d\n " , addedCount )
@@ -216,28 +193,23 @@ This command performs the following actions:
216193 fmt .Printf ("\n Local database is already up-to-date.\n " )
217194 }
218195
219- return nil // Success
196+ return nil
220197 },
221198}
222199
223200func init () {
224- // Use exported DefaultDBPath from localdb package for the default value
225201 SyncJiraCmd .Flags ().StringVar (& syncTestDBPath , "test-db-path" , localdb .DefaultDBPath (), "Path to the flaky test JSON database" )
226- SyncJiraCmd .Flags ().StringVar (& syncJiraSearchLabel , "jira-search-label" , "flaky_test" , "Jira label used to find flaky test tickets" ) // Default set here
202+ SyncJiraCmd .Flags ().StringVar (& syncJiraSearchLabel , "jira-search-label" , "flaky_test" , "Jira label used to find flaky test tickets" )
227203 SyncJiraCmd .Flags ().BoolVar (& syncDryRun , "dry-run" , false , "If true, only show what would be changed without saving" )
228204}
229205
230- // extractTestName attempts to extract the test name from a ticket summary.
231- // NOTE: This is fragile and depends on a consistent summary format.
232206func extractTestName (summary string ) string {
233207 // Expected format variations:
234208 // "Fix Flaky Test: TestName (X% flake rate)"
235- // "Fix Flaky Test: TestName"
236209 prefix := "Fix Flaky Test: "
237210 if ! strings .HasPrefix (summary , prefix ) {
238- // Maybe try other prefixes or patterns if needed?
239211 log .Debug ().Str ("summary" , summary ).Msg ("Summary does not match expected prefix." )
240- return "" // Doesn't match expected format
212+ return ""
241213 }
242214
243215 // Get the part after the prefix
@@ -247,13 +219,10 @@ func extractTestName(summary string) string {
247219 flakeRateIndex := strings .Index (testPart , " (" )
248220 testName := ""
249221 if flakeRateIndex != - 1 {
250- // Flake rate part exists, take the substring before it
251222 testName = testPart [:flakeRateIndex ]
252223 } else {
253- // No flake rate part found, assume the whole remaining part is the test name
254224 testName = testPart
255225 }
256226
257- // Final trim just in case
258227 return strings .TrimSpace (testName )
259228}
0 commit comments