Class: Kettle::Dev::GhaShaPinsCLI

Inherits:
Object
  • Object
show all
Defined in:
lib/kettle/dev/gha_sha_pins_cli.rb

Overview

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

Defined Under Namespace

Classes: GitHubClient, PersistentActionCache

Constant Summary collapse

API_BASE =
"https://api.github.com"
RELEASE_PATH =
"releases/latest"
SHA_RE =
/\A[0-9a-f]{40}\z/i
WEAK_SHA_RE =
/\A[0-9a-f]{7,39}\z/i
NON_SHA_REASON =
"convert_to_sha"
STALE_SHA_REASON =
"upgrade_to_latest_release_sha"
UPGRADE_REASON =
"upgrade_to_allowed_release"
COMMENT_REASON =
"update_version_comment"
DEFAULT_UPGRADE_LEVEL =
"patch"
DEFAULT_CACHE_TTL_SECONDS =
24 * 60 * 60
VALID_UPGRADE_LEVELS =
%w[major minor patch].freeze

Instance Method Summary collapse

Constructor Details

#initialize(argv, err: $stderr) ⇒ GhaShaPinsCLI

Returns a new instance of GhaShaPinsCLI.



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/kettle/dev/gha_sha_pins_cli.rb', line 37

def initialize(argv, err: $stderr)
  @argv = argv
  @err = err
  @options = {
    root: Dir.pwd,
    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-sha-pins",
    upgrade: DEFAULT_UPGRADE_LEVEL,
    cache_path: ENV["KETTLE_GHA_SHA_PINS_CACHE"] || PersistentActionCache.default_path,
    refresh_cache: false,
    reject_patterns: Set.new,
    progress: nil
  }
end

Instance Method Details

#run!Object



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
# File 'lib/kettle/dev/gha_sha_pins_cli.rb', line 58

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: [],
    outdated_pins: []
  }

  progress_message("Discovering workflow files under #{Kettle::Dev.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 = progress_bar(title: "Actions", total: action_count)
  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]
        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

        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
        }
      ensure
        action_progress&.increment
      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

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

  0
end