-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpt2linear.rb
executable file
·1598 lines (1366 loc) · 46.4 KB
/
pt2linear.rb
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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env ruby
# frozen_string_literal: true
require 'dotenv/load'
require 'json'
require 'logger'
require 'mimemagic'
require 'optparse'
require 'progress_bar'
require 'tempfile'
require 'time'
require 'typhoeus'
require 'tzinfo'
$logger = Logger.new($stdout)
$logger.level = Logger::INFO
class PivotalTrackerClient
BASE_URL = 'https://www.pivotaltracker.com/services/v5'
def initialize
@api_token = ENV['PIVOTAL_API_TOKEN'] or raise 'PIVOTAL_API_TOKEN not set'
@project_id = ENV['PIVOTAL_PROJECT_ID'] or raise 'PIVOTAL_PROJECT_ID not set'
@headers = {
'X-TrackerToken' => @api_token,
'Content-Type' => 'application/json'
}
end
def fetch_all_epics
get("/projects/#{@project_id}/epics")
end
def fetch_all_stories
fetch_paginated("/projects/#{@project_id}/stories", 'Fetching stories')
end
def fetch_epic_details(epic_id)
get("/projects/#{@project_id}/epics/#{epic_id}")
end
def fetch_story_details(story_id)
response = get("/projects/#{@project_id}/stories/#{story_id}?fields=:default,pull_requests,branches")
# The `get` method already parses the JSON, so we don't need to do it again
story = response
# Ensure pull_requests and branches are always arrays
story['pull_requests'] ||= []
story['branches'] ||= []
story
end
def fetch_epic_stories(epic_id)
get("/projects/#{@project_id}/search?query=epic%3A#{epic_id}")
end
def fetch_epic_comments(epic_id)
get("/projects/#{@project_id}/epics/#{epic_id}/comments?fields=:default,file_attachments,text")
end
def fetch_story_comments(story_id)
get("/projects/#{@project_id}/stories/#{story_id}/comments?fields=:default,file_attachments")
end
def fetch_story_tasks(story_id)
get("/projects/#{@project_id}/stories/#{story_id}/tasks")
end
def fetch_attachments(story_id)
story = fetch_story_details(story_id)
story['attachments'] || []
end
def fetch_all_project_members
get("/projects/#{@project_id}/memberships")
end
def fetch_person(person_id)
memberships = get("/projects/#{@project_id}/memberships?fields=person")
memberships.find { |m| m['person']['id'] == person_id }
end
def fetch_story_pr_and_branch(story_id)
story = fetch_story_details(story_id)
{
pull_requests: story['pull_requests'] || [],
branches: story['branches'] || []
}
end
def download_attachment(url, filename)
$logger.debug "Downloading attachment: #{filename} from #{url}"
full_url = "https://www.pivotaltracker.com#{url}"
response = Typhoeus.get(full_url, headers: @headers, followlocation: true)
if response.success?
temp_file = Tempfile.new(filename)
temp_file.binmode
temp_file.write(response.body)
temp_file.close
$logger.debug "Successfully downloaded: #{filename}"
temp_file.path
else
$logger.error "Failed to download: #{filename}. Status: #{response.code}"
$logger.error "Response body: #{response.body}"
nil
end
rescue StandardError => e
$logger.error "Exception downloading #{filename}: #{e.message}"
$logger.debug e.backtrace.join("\n")
nil
end
private
def get(path)
url = "#{BASE_URL}#{path}"
$logger.debug "GET Request to: #{url}"
response = Typhoeus.get(url, headers: @headers)
log_response(response, "GET #{path}")
if response.code != 200
$logger.error "API request failed: #{response.code}"
$logger.error "Response Body: #{response.body}"
raise "API request failed: #{response.code}, Body: #{response.body}"
end
JSON.parse(response.body)
end
def fetch_paginated(path, progress_message, options = {})
items = []
offset = 0
limit = options[:limit] || 100
use_pagination = options[:use_pagination].nil? ? true : options[:use_pagination]
total_count = nil
bar = nil
loop do
full_path = use_pagination ? "#{path}?limit=#{limit}&offset=#{offset}" : path
$logger.debug "Fetching: #{full_path}"
response = Typhoeus.get("#{BASE_URL}#{full_path}", headers: @headers)
log_response(response, "GET #{full_path}")
if response.code != 200
$logger.error "API request failed: #{response.code}"
$logger.error "Response Body: #{response.body}"
raise "API request failed: #{response.code}, Body: #{response.body}"
end
parsed_response = JSON.parse(response.body)
if total_count.nil?
total_count = response.headers['X-Tracker-Pagination-Total']&.to_i || parsed_response.size
bar = ProgressBar.new(total_count, :bar, :percentage, :eta)
puts progress_message
end
items.concat(parsed_response)
bar.increment!(parsed_response.size)
break unless use_pagination
break if parsed_response.size < limit
offset += limit
end
items
end
def log_response(response, context)
$logger.debug "#{context}: Status #{response.code}"
$logger.debug 'Response Headers:'
response.headers.each do |name, value|
$logger.debug " #{name}: #{value}"
end
$logger.debug "Response Body: #{response.body}"
end
end
class LinearClient
BASE_URL = 'https://api.linear.app/graphql'
MAX_RETRIES = 3
INITIAL_BACKOFF = 1
LINEAR_WORKFLOW = {
'backlog' => [
{ name: 'Icebox', color: '#8DE8B5' },
{ name: 'Backlog', color: '#E2E2E2' }
],
'unstarted' => [{ name: 'Todo', color: '#F2C94C' }],
'started' => [{ name: 'In Progress', color: '#5E6AD2' }],
'finished' => [{ name: 'In Review', color: '#9B51E0' }],
'delivered' => [{ name: 'Ready to Merge', color: '#5E6AD2' }],
'completed' => [{ name: 'Done', color: '#0BB97A' }],
'canceled' => [
{ name: 'Canceled', color: '#95A2B3' },
{ name: 'Could not reproduce', color: '#95A2B3' },
{ name: "Won't Fix", color: '#95A2B3' },
{ name: 'Duplicate', color: '#95A2B3' }
]
}.freeze
def initialize
@api_token = ENV['LINEAR_API_TOKEN'] or raise 'LINEAR_API_TOKEN not set'
@headers = {
'Content-Type' => 'application/json',
'Authorization' => @api_token
}
@request_count = 0
@complexity_count = 0
@request_limit = 1500 # Ensure default integer value
@complexity_limit = 250_000 # Ensure default integer value
@request_remaining = 1500 # Default to the maximum limit
@complexity_remaining = 250_000 # Default to the maximum limit
@reset_time = nil
@last_reset_time = Time.now.to_i
@team_id = find_team_id(ENV['LINEAR_TEAM_NAME'])
@already_migrated_epics = find_all_pt_epics_from_linear
end
def find_team_id(team_name)
query = <<-GRAPHQL
query {
teams {
nodes {
id
name
}
}
}
GRAPHQL
response = post(query)
data = JSON.parse(response.body)
team = data['data']['teams']['nodes'].find { |t| t['name'] == team_name }
if team
puts "[DEBUG] Found team '#{team_name}' with ID: #{team['id']}"
else
puts "[ERROR] Team '#{team_name}' not found!"
end
team['id']
end
def fetch_team_state_id
query = <<-GRAPHQL
query {
workflowStates(filter: { team: { id: { eq: "#{@team_id}" } } }) {
nodes {
id
name
}
}
}
GRAPHQL
response = post(query)
log_response(response, 'Fetch Workflow States')
data = JSON.parse(response.body)
state = data['data']['workflowStates']['nodes'].find { |s| s['name'] == 'Todo' }
if state
puts "[DEBUG] Found workflow state 'Todo' with ID: #{state['id']}"
state['id']
else
puts "[ERROR] Failed to find workflow state 'Todo'"
raise 'State not found'
end
end
def find_all_pt_epics_from_linear
query = <<-GRAPHQL
query {
projects(first: 250) {
nodes {
id
name
description
content
}
}
}
GRAPHQL
response = post(query) # Assuming 'post' method is defined to send the query to Linear's GraphQL API
data = JSON.parse(response.body)
projects = data.dig('data', 'projects', 'nodes')
if projects && !projects.empty?
epic_to_project_map = projects.each_with_object({}) do |project, memo|
# Regex to extract Pivotal Tracker epic ID from content, assuming format: https://www.pivotaltracker.com/epic/show/ID
match = project['content'].to_s.match(%r{https://www\.pivotaltracker\.com/epic/show/(\d+)})
if match
epic_id = match[1].to_i
memo[epic_id] = project['id'] # Map Epic ID to Project ID
end
end
if epic_to_project_map.any?
puts "Found Pivotal Tracker epic IDs mapped to Linear project IDs: #{epic_to_project_map}"
epic_to_project_map
else
puts 'No Pivotal Tracker epics found in project contents'
{}
end
else
puts 'No projects found in Linear'
{}
end
end
def project_for_epic(epic_id)
@already_migrated_epics[epic_id]
end
def create_linear_project(name, content)
mutation = <<~GRAPHQL
mutation CreateProject($input: ProjectCreateInput!) {
projectCreate(input: $input) {
success
project {
id
name
documentContent {
content
}
}
}
}
GRAPHQL
variables = {
input: {
name:,
teamIds: [@team_id],
content:
}
}
response = post(mutation, variables)
data = JSON.parse(response.body)
if data['data'] && data['data']['projectCreate'] && data['data']['projectCreate']['project']
data['data']['projectCreate']['project']
else
puts 'Failed to create project. Full API response:'
puts JSON.pretty_generate(data)
nil
end
end
def setup_workflow_states
existing_states = fetch_existing_states
LINEAR_WORKFLOW.each do |type, states|
states.each do |state|
unless existing_states.any? { |s| s['name'] == state[:name] }
create_workflow_state(state[:name], type, state[:color])
end
end
end
@workflow_states = fetch_existing_states
end
def fetch_existing_states
query = <<-GRAPHQL
query($teamId: String!) {
team(id: $teamId) {
states {
nodes {
id
name
type
color
}
}
}
}
GRAPHQL
variables = { teamId: @team_id }
response = post(query, variables)
data = JSON.parse(response.body)
data.dig('data', 'team', 'states', 'nodes') || []
end
def create_workflow_state(name, type, color)
mutation = <<-GRAPHQL
mutation($input: WorkflowStateCreateInput!) {
workflowStateCreate(input: $input) {
workflowState {
id
name
type
color
}
}
}
GRAPHQL
variables = {
input: {
name:,
type:,
color:,
teamId: @team_id
}
}
response = post(mutation, variables)
data = JSON.parse(response.body)
data.dig('data', 'workflowStateCreate', 'workflowState')
end
def get_state_id(name)
state = @workflow_states.find { |s| s['name'] == name }
state ? state['id'] : nil
end
def find_issue_by_pt_link(pt_link)
query = <<-GRAPHQL
query {
issues(filter: { description: { contains: "#{pt_link}" } }) {
nodes {
id
title
}
}
}
GRAPHQL
response = post(query)
data = JSON.parse(response.body)
issues = data.dig('data', 'issues', 'nodes')
issues.first if issues.any?
end
def create_issue(title, description, label_names)
label_ids = label_names.map { |name| fetch_or_create_label(name) }.compact
input = {
title:,
description:,
teamId: @team_id,
labelIds: label_ids
}
mutation = <<-GRAPHQL
mutation CreateIssue($input: IssueCreateInput!) {
issueCreate(input: $input) {
success
issue {
id
title
}
}
}
GRAPHQL
variables = { input: }
response = post(mutation, variables)
log_response(response, 'Create Issue')
data = JSON.parse(response.body)
data.dig('data', 'issueCreate', 'issue')
end
def update_issue(issue_id, input)
mutation = <<-GRAPHQL
mutation UpdateIssue($id: String!, $input: IssueUpdateInput!) {
issueUpdate(id: $id, input: $input) {
success
issue {
id
}
}
}
GRAPHQL
# Ensure sortOrder is a float if it exists
input[:sortOrder] = input[:sortOrder].to_f if input[:sortOrder]
variables = { id: issue_id.to_s, input: }
response = post(mutation, variables)
data = JSON.parse(response.body)
data.dig('data', 'issueUpdate', 'success')
end
def create_comment_with_attachments(issue_id, body, attachments)
puts "[DEBUG] Creating comment with #{attachments.size} attachments for issue #{issue_id}"
attachment_markdown = attachments.map do |attachment|
puts "[DEBUG] Processing attachment: #{attachment[:filename]} (type: #{attachment[:type]})"
if attachment[:type].start_with?('image/')
"![#{attachment[:filename]}](#{attachment[:url]})"
else
"[#{attachment[:filename]}](#{attachment[:url]})"
end
end.join("\n\n")
full_body = "#{body}\n\n#{attachment_markdown}"
puts '[DEBUG] Full comment body:'
puts full_body
mutation = <<-GRAPHQL
mutation($input: CommentCreateInput!) {
commentCreate(input: $input) {
success
comment {
id
body
}
}
}
GRAPHQL
variables = {
input: {
issueId: issue_id,
body: full_body
}
}
response = post(mutation, variables)
log_response(response, 'Create Comment with Attachments')
data = JSON.parse(response.body)
comment = data.dig('data', 'commentCreate', 'comment')
if comment
puts "[DEBUG] Successfully created comment: ID #{comment['id']}"
puts '[DEBUG] Comment body:'
puts comment['body']
comment
else
puts "[ERROR] Failed to create comment for issue #{issue_id}"
puts "[ERROR] Response data: #{data.inspect}"
nil
end
end
def upload_file(file_path, filename)
puts "[DEBUG] Uploading file: #{filename} from path: #{file_path}"
puts "[DEBUG] File exists before read: #{File.exist?(file_path)}"
file_content = File.binread(file_path)
file_size = file_content.bytesize
puts "[DEBUG] File size after read: #{file_size} bytes"
content_type = detect_mime_type(file_path, filename)
puts "[DEBUG] Detected content type: #{content_type}"
upload_payload = file_upload(content_type, filename, file_size)
unless upload_payload && upload_payload['success'] && upload_payload['uploadFile']
puts "[ERROR] Failed to request upload URL for #{filename}"
return nil
end
upload_url = upload_payload['uploadFile']['uploadUrl']
asset_url = upload_payload['uploadFile']['assetUrl']
puts "[DEBUG] Received upload URL: #{upload_url}"
puts "[DEBUG] Received asset URL: #{asset_url}"
headers = {
'Content-Type' => content_type,
'Cache-Control' => 'public, max-age=31536000'
}
upload_payload['uploadFile']['headers'].each do |header|
headers[header['key']] = header['value']
puts "[DEBUG] Adding header: #{header['key']} = #{header['value']}"
end
response = Typhoeus.put(upload_url, headers:, body: file_content)
if response.success?
puts "[DEBUG] Successfully uploaded file to Linear: #{filename}"
{ url: asset_url, type: content_type, filename: }
else
puts "[ERROR] Failed to upload file to Linear: #{filename}. Status: #{response.code}"
puts "[ERROR] Response body: #{response.body}"
nil
end
rescue StandardError => e
puts "[ERROR] Exception uploading file: #{e.message}"
puts e.backtrace.join("\n")
nil
end
def create_comment(issue_id, body)
mutation = <<-GRAPHQL
mutation {
commentCreate(input: {
issueId: "#{issue_id}",
body: #{body.to_json}
}) {
success
comment {
id
}
}
}
GRAPHQL
response = post(mutation)
log_response(response, 'Create Comment')
data = JSON.parse(response.body)
data.dig('data', 'commentCreate', 'comment')
end
def create_attachment(issue_id, asset_url, filename, content_type, comment_id = nil)
puts "[DEBUG] Creating attachment: #{filename}"
input = {
issueId: issue_id,
url: asset_url,
title: filename,
subtitle: 'Uploaded from Pivotal Tracker',
contentType: content_type
}
input[:commentBody] = "Attachment for comment #{comment_id}" if comment_id
mutation = <<~GRAPHQL
mutation CreateAttachment($input: AttachmentCreateInput!) {
attachmentCreate(input: $input) {
success
attachment {
id
url
contentType
}
}
}
GRAPHQL
variables = { input: }
response = post(mutation, variables)
if response.success?
data = JSON.parse(response.body)
if data.dig('data', 'attachmentCreate', 'success')
puts '[DEBUG] Successfully created attachment in Linear'
data.dig('data', 'attachmentCreate', 'attachment')
else
puts "[ERROR] Failed to create attachment in Linear. Response: #{data}"
nil
end
else
puts "[ERROR] Failed to create attachment in Linear. Status: #{response.code}"
puts "[ERROR] Response body: #{response.body}"
nil
end
rescue StandardError => e
puts "[ERROR] Exception creating attachment: #{e.message}"
puts e.backtrace.join("\n")
nil
end
def link_issue_to_project(issue_id, project_id)
mutation = <<-GRAPHQL
mutation {
issueUpdate(id: "#{issue_id}", input: { projectId: "#{project_id}" }) {
success
issue {
id
project {
id
}
}
}
}
GRAPHQL
response = post(mutation)
data = JSON.parse(response.body)
data.dig('data', 'issueUpdate', 'success')
end
def fetch_labels
query = <<-GRAPHQL
query {
issueLabels(first: 250) {
nodes {
id
name
}
}
}
GRAPHQL
response = post(query)
log_response(response, 'Fetch Labels')
data = JSON.parse(response.body)
labels = data.dig('data', 'issueLabels', 'nodes')
if labels
puts "[DEBUG] Fetched #{labels.size} labels from Linear"
labels
else
puts '[ERROR] Failed to fetch labels from Linear'
[]
end
end
def fetch_team_members
query = <<-GRAPHQL
query($teamId: String!) {
team(id: $teamId) {
members {
nodes {
id
name
email
}
}
}
}
GRAPHQL
variables = { teamId: @team_id }
response = post(query, variables)
log_response(response, 'Fetch Team Members')
data = JSON.parse(response.body)
members = data.dig('data', 'team', 'members', 'nodes')
if members
puts "[DEBUG] Fetched #{members.size} team members from Linear"
members
else
puts '[ERROR] Failed to fetch team members from Linear'
[]
end
end
def assign_issue(issue_id, user_id)
mutation = <<-GRAPHQL
mutation AssignIssue($issueId: String!, $assigneeId: String!) {
issueUpdate(id: $issueId, input: { assigneeId: $assigneeId }) {
success
issue {
id
assignee {
id
name
}
}
}
}
GRAPHQL
variables = { issueId: issue_id.to_s, assigneeId: user_id.to_s }
response = post(mutation, variables)
data = JSON.parse(response.body)
data.dig('data', 'issueUpdate', 'success')
end
def fetch_workflow_states
query = <<-GRAPHQL
query {
workflowStates {
nodes {
id
name
type
}
}
}
GRAPHQL
response = post(query)
data = JSON.parse(response.body)
data['data']['workflowStates']['nodes']
end
def get_issue(issue_id)
query = <<-GRAPHQL
query($id: String!) {
issue(id: $id) {
id
sortOrder
}
}
GRAPHQL
variables = { id: issue_id.to_s }
response = post(query, variables)
data = JSON.parse(response.body)
data.dig('data', 'issue')
end
def create_label(name)
mutation = <<-GRAPHQL
mutation($input: IssueLabelCreateInput!) {
issueLabelCreate(input: $input) {
success
issueLabel {
id
name
}
}
}
GRAPHQL
variables = {
input: {
name:,
teamId: @team_id
}
}
response = post(mutation, variables)
data = JSON.parse(response.body)
data.dig('data', 'issueLabelCreate', 'issueLabel', 'id')
end
private
def post(query, variables = nil)
body = { query: }
body[:variables] = variables if variables
loop do
wait_for_rate_limit_reset if rate_limit_exceeded?
response = Typhoeus.post(BASE_URL, headers: @headers, body: body.to_json)
update_rate_limits(response)
if response.success?
return response
elsif response.code == 429 || (response.code >= 400 && response.code < 500 && response.body.include?('RATELIMITED'))
puts '[WARN] Rate limit exceeded. Waiting for reset.'
next
else
puts "[ERROR] API request failed: #{response.code}"
puts "[ERROR] Response Body: #{response.body}"
raise "API request failed: #{response.code}, Body: #{response.body}"
end
end
end
def check_rate_limits
current_time = Time.now.to_i
@last_reset_time ||= current_time
@request_limit ||= 1500 # Set default if nil
@complexity_limit ||= 250_000 # Set default if nil
@request_count ||= 0
@complexity_count ||= 0
if current_time - @last_reset_time >= 3600
@request_count = 0
@complexity_count = 0
@last_reset_time = current_time
end
raise RateLimitedError, 'Request limit exceeded' if @request_count >= @request_limit
raise RateLimitedError, 'Complexity limit exceeded' if @complexity_count >= @complexity_limit
end
def update_rate_limits(response)
@request_limit = response.headers['X-RateLimit-Requests-Limit'].to_i
@request_remaining = response.headers['X-RateLimit-Requests-Remaining'].to_i
@complexity_limit = response.headers['X-RateLimit-Complexity-Limit'].to_i
@complexity_remaining = response.headers['X-RateLimit-Complexity-Remaining'].to_i
@reset_time = adjusted_time(response.headers['X-RateLimit-Requests-Reset'].to_i)
@last_reset_time = Time.now.to_i
# Ensure we have valid values
@request_remaining = [@request_remaining, 0].max
@complexity_remaining = [@complexity_remaining, 0].max
end
def rate_limit_exceeded?
current_time = Time.now.to_i
if current_time - @last_reset_time >= 3600
@request_remaining = @request_limit
@complexity_remaining = @complexity_limit
@last_reset_time = current_time
end
(@request_remaining.to_i <= 0) || (@complexity_remaining.to_i <= 0)
end
SLEEP_FRACTION = 10
def wait_for_rate_limit_reset
now = Time.now
return unless @reset_time && @reset_time > now
sleep_duration = (@reset_time - now).ceil / SLEEP_FRACTION
puts "[INFO] Rate limit reached. Sleeping for #{sleep_duration} seconds. Full reset at #{@reset_time}"
sleep(sleep_duration)
end
def adjusted_time(epoch_ms)
time = Time.at(epoch_ms / 1000.0)
timezone_name = ENV['LINEAR_TIMEZONE'] || 'UTC'
begin
tz = TZInfo::Timezone.get(timezone_name)
tz.utc_to_local(time.utc)
rescue TZInfo::InvalidTimezoneIdentifier
$logger.warn "Invalid timezone: #{timezone_name}. Falling back to UTC."
time.utc
end
end
def log_response(response, context)
puts "[DEBUG] #{context}: Status #{response.code}"
puts '[DEBUG] Response Headers:'
response.headers.each do |name, value|
puts " #{name}: #{value}"
end
puts '[DEBUG] Response Body:'
puts response.body
end
def detect_mime_type(file_path, filename = nil)
puts "[DEBUG] Entering detect_mime_type for file: #{file_path}"
puts "[DEBUG] File exists: #{File.exist?(file_path)}"
begin
# Attempt to detect MIME type by reading the file content.
file_content = File.binread(file_path)
mime = MimeMagic.by_magic(file_content)
# If successful, return the detected type.
if mime
puts "[DEBUG] Detected content type by magic: #{mime.type}"
return mime.type
end
rescue StandardError => e
# Handle binread errors gracefully.
puts "[ERROR] Failed to read file content: #{e.message}"
puts "[ERROR] Backtrace: #{e.backtrace.join("\n")}"
end
# Fall back to filename-based MIME detection if reading content fails or yields no result.
if filename
mime = MimeMagic.by_path(filename)
if mime
puts "[DEBUG] Fallback MIME type by filename: #{mime.type}"
return mime.type
end
end
# Default to 'application/octet-stream' if all detection attempts fail.
puts '[WARN] Using default MIME type: application/octet-stream'
'application/octet-stream'
end
def file_upload(content_type, filename, size)
mutation = <<~GRAPHQL
mutation FileUpload($contentType: String!, $filename: String!, $size: Int!) {
fileUpload(contentType: $contentType, filename: $filename, size: $size) {
success
uploadFile {
uploadUrl
assetUrl
headers {
key
value
}
}
}
}
GRAPHQL
variables = {
contentType: content_type,
filename:,
size:
}
response = post(mutation, variables)
if response.success?
data = JSON.parse(response.body)
data['data']['fileUpload']
else
puts "[ERROR] Failed to get upload URL from Linear. Status: #{response.code}"
puts "[ERROR] Response body: #{response.body}"
nil
end
end
def fetch_or_create_label(name)
query = <<-GRAPHQL
query($teamId: String!) {
team(id: $teamId) {
labels {
nodes {
id
name
}
}
}
}
GRAPHQL