Class: Kettle::Gha::Pins::CLI

Inherits:
Object
  • Object
show all
Defined in:
lib/kettle/gha/pins/cli.rb

Overview

CLI to scan GitHub Action workflow files and pin mutable references in uses: to commit SHAs.

Constant Summary collapse

API_BASE =
Kettle::Gha::Pins::API_BASE
RELEASE_PATH =
Kettle::Gha::Pins::RELEASE_PATH
SHA_RE =
Kettle::Gha::Pins::SHA_RE
WEAK_SHA_RE =
Kettle::Gha::Pins::WEAK_SHA_RE
NON_SHA_REASON =
Kettle::Gha::Pins::NON_SHA_REASON
STALE_SHA_REASON =
Kettle::Gha::Pins::STALE_SHA_REASON
UPGRADE_REASON =
Kettle::Gha::Pins::UPGRADE_REASON
COMMENT_REASON =
"update_version_comment"
DEFAULT_UPGRADE_LEVEL =
Kettle::Gha::Pins::DEFAULT_UPGRADE_LEVEL
DEFAULT_CACHE_TTL_SECONDS =
Kettle::Gha::Pins::DEFAULT_CACHE_TTL_SECONDS
DEFAULT_HTTP_OPEN_TIMEOUT_SECONDS =
Kettle::Gha::Pins::DEFAULT_HTTP_OPEN_TIMEOUT_SECONDS
DEFAULT_HTTP_READ_TIMEOUT_SECONDS =
Kettle::Gha::Pins::DEFAULT_HTTP_READ_TIMEOUT_SECONDS
DEFAULT_HTTP_REFRESH_TIMEOUT_SECONDS =
Kettle::Gha::Pins::DEFAULT_HTTP_REFRESH_TIMEOUT_SECONDS
VALID_UPGRADE_LEVELS =
Kettle::Gha::Pins::VALID_UPGRADE_LEVELS
PersistentActionCache =
Kettle::Gha::Pins::PersistentActionCache
GitHubClient =
Kettle::Gha::Pins::GitHubClient
VERSION_COMMENT_SUFFIX_RE =
/\A\s+#\s*v?(?<version>\d+(?:\.\d+\.\d+(?:[-.]?[0-9A-Za-z.-]+)?)?)/
VERSION_COMMENT_REPLACEMENT_RE =
/\A(?<prefix>\s+#\s*)v?\d+(?:\.\d+\.\d+(?:[-.]?[0-9A-Za-z.-]+)?)?/

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(argv, err: $stderr, clock: -> { Time.now }) ⇒ CLI

Returns a new instance of CLI.



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
# File 'lib/kettle/gha/pins/cli.rb', line 48

def initialize(argv, err: $stderr, clock: -> { Time.now })
  cooldown_days = begin
    Integer(ENV.fetch("KETTLE_GHA_PINS_COOLDOWN_DAYS", "0"))
  rescue ArgumentError, TypeError
    0
  end
  cooldown_days = 0 if cooldown_days.negative?
  @argv = argv
  @err = err
  @options = {
    root: File.join(Dir.pwd, ".github", "workflows"),
    dry_run: true,
    token: ENV["GITHUB_TOKEN"] || ENV["GH_TOKEN"],
    json: false,
    validate: true,
    write: false,
    check: false,
    api_base: API_BASE,
    user_agent: "kettle-gha-pins",
    upgrade: DEFAULT_UPGRADE_LEVEL,
    cache_path: ENV["KETTLE_GHA_SHA_PINS_CACHE"] || PersistentActionCache.default_path,
    cooldown_days: cooldown_days,
    clock: clock,
    refresh_cache: false,
    reject_patterns: Set.new,
    progress: nil
  }
end

Class Method Details

.release_version_sort_key(entry) ⇒ Object



40
41
42
# File 'lib/kettle/gha/pins/cli.rb', line 40

def self.release_version_sort_key(entry)
  Kettle::Gha::Pins::VersionRubric.sort_key(entry)
end

.release_version_specificity(entry) ⇒ Object



44
45
46
# File 'lib/kettle/gha/pins/cli.rb', line 44

def self.release_version_specificity(entry)
  Kettle::Gha::Pins::VersionRubric.specificity(entry)
end

Instance Method Details

#run!Object



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
# File 'lib/kettle/gha/pins/cli.rb', line 77

def run!
  parse!

  @options[:token] ||= gh_auth_token if @options[:api_base] == API_BASE
  persistent_cache = if @options[:cache_path].to_s.empty?
    nil
  else
    PersistentActionCache.new(path: @options[:cache_path])
  end
  client = GitHubClient.new(
    token: @options[:token],
    api_base: @options[:api_base],
    user_agent: @options[:user_agent],
    persistent_cache: persistent_cache,
    refresh_cache: @options[:refresh_cache]
  )

  state = {
    files_scanned: 0,
    files_with_changes: 0,
    updates: 0,
    failures: 0,
    errors: [],
    changed_files: [],
    planned_changes: [],
    cooldown_changes: [],
    outdated_pins: []
  }

  progress_message("Discovering workflow files under #{display_path(@options[:root])}...")
  workflow_files = discover_workflow_files(@options[:root], @options[:reject_patterns])
  progress_message("Discovered #{workflow_files.length} workflow file(s).")

  workflows = load_workflows(workflow_files, state)
  action_count = workflows.sum { |workflow| workflow[:uses_nodes].count { |node| classify_action_ref(node[:value].to_s) } }
  progress_message("Resolving #{action_count} GitHub action reference(s)...") if action_count.positive?
  action_progress = CacheProgress.new(
    total: action_count,
    cached_title: "Actions cached",
    live_title: "Actions live",
    output: @err,
    enabled: progress_enabled?
  )
  action_plan_cache = {}

  workflows.each do |workflow|
    path = workflow.fetch(:path)
    text = workflow.fetch(:text)
    uses_nodes = workflow.fetch(:uses_nodes)

    edits = []
    uses_nodes.each do |node|
      value = node[:value].to_s
      parsed_ref = classify_action_ref(value)
      next unless parsed_ref

      begin
        action = parsed_ref[:action]
        repo_ref = "#{action[:owner]}/#{action[:repo]}"
        old_ref = action[:ref]
        upgrade_plan = resolve_action_plan(
          cache: action_plan_cache,
          client: client,
          progress: action_progress,
          repo_ref: repo_ref,
          old_ref: old_ref
        )

        updates = nil
        if upgrade_plan[:updates]
          updates = compute_updates(old_ref, upgrade_plan[:updates][:sha], upgrade_plan[:updates][:reason], repo_ref)
          updates[:new_version] = upgrade_plan[:updates][:version]
          updates[:old_version] = upgrade_plan[:current_version]
          updates[:released_at] = upgrade_plan[:updates][:released_at]
        end
        if updates.nil? && upgrade_plan[:current_version]
          comment_version = version_comment_from_line(text, node[:line], node[:col], parsed_ref[:value])
          if comment_version && comment_version != upgrade_plan[:current_version]
            updates = {
              new_ref: old_ref,
              new_version: upgrade_plan[:current_version],
              old_version: comment_version,
              reason: COMMENT_REASON,
              action: repo_ref
            }
          end
        end

        if upgrade_plan[:is_outdated]
          state[:outdated_pins] << {
            path: path,
            line: node[:line] + 1,
            action: repo_ref,
            old_ref: old_ref,
            old_version: upgrade_plan[:current_version],
            new_ref: upgrade_plan[:latest_outdated] ? upgrade_plan[:latest_outdated][:sha] : nil,
            new_version: upgrade_plan[:latest_outdated] ? upgrade_plan[:latest_outdated][:version] : nil,
            upgrade_level: @options[:upgrade],
            reason: upgrade_plan[:reason]
          }
        end

        next unless updates

        if (cooldown = cooldown_details(updates))
          state[:cooldown_changes] << {
            path: path,
            line: node[:line] + 1,
            old_ref: old_ref,
            old_version: updates[:old_version],
            new_ref: updates[:new_ref],
            new_version: updates[:new_version],
            reason: updates[:reason],
            released_at: cooldown[:released_at],
            cooldown_until: cooldown[:cooldown_until],
            action: repo_ref
          }
          next
        end

        replacement = build_replacement_from_line(text, node[:line], node[:col], parsed_ref[:value], updates[:new_ref], updates[:new_version])
        unless replacement
          record_failure(
            state,
            path: path,
            line: node[:line] + 1,
            error: "token_parse_failed",
            value: value
          )
          next
        end

        edits << {
          path: path,
          line: node[:line],
          col: node[:col],
          old_ref: old_ref,
          old_version: updates[:old_version],
          new_ref: updates[:new_ref],
          new_version: updates[:new_version],
          reason: updates[:reason],
          start: replacement[:start],
          end: replacement[:end],
          old_value: value,
          new_value: replacement[:new_scalar],
          new_scalar: replacement[:new_scalar],
          action: repo_ref
        }
      end
    end

    if edits.any?
      edited = apply_edits(text, edits)
      if edited[:changed]
        state[:changed_files] << path
        state[:files_with_changes] += 1
        state[:updates] += edits.length
        state[:planned_changes].concat(edited[:edits].map do |entry|
          {
            path: entry[:path],
            line: entry[:line] + 1,
            old_ref: entry[:old_ref],
            old_version: entry[:old_version],
            new_ref: entry[:new_ref],
            new_version: entry[:new_version],
            reason: entry[:reason],
            old_value: entry[:old_value],
            new_value: entry[:new_value],
            action: entry[:action]
          }
        end)

        if @options[:write]
          File.write(path, edited[:text])
          validate_yaml!(path) if @options[:validate]
        end
      end
    end
  end
  action_progress.stop
  progress_message("Action resolution checks: #{action_progress.cached_count} cached, #{action_progress.live_count} live.") if action_count.positive?

  print_report(state)
  return 2 unless state[:failures].zero?
  return 3 if @options[:check] && state[:updates].positive?

  0
end