Module: Strata::CLI::Utils::Git

Defined in:
lib/strata/cli/utils/git.rb

Class Method Summary collapse

Class Method Details

.changed_file_paths_since(commit_hash) ⇒ Object



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
# File 'lib/strata/cli/utils/git.rb', line 119

def changed_file_paths_since(commit_hash)
  return [] unless git_repo?
  return [] unless commit_hash

  unless validate_commit_hash(commit_hash)
    raise Strata::CommandError, "Invalid commit hash format: #{commit_hash.inspect}"
  end

  # Check if commit exists in repo
  _, _, status = Open3.capture3("git", "rev-parse", "--verify", "#{commit_hash}^{commit}")
  return [] unless status.success?

  # Get file paths that changed (for added and modified files only, exclude deleted)
  # --diff-filter=ACMR: Added, Copied, Modified, Renamed (excludes Deleted)
  diff_output = run_git_command("diff", "--name-status", "--diff-filter=ACMR", commit_hash, "HEAD")
  return [] unless diff_output

  paths = []
  diff_output.lines.each do |line|
    line = line.strip
    next if line.empty?

    parts = line.split(/\s+/)
    next if parts.length < 2

    status = parts[0]
    # For renames (R), parts[1] is old path, parts[2] is new path
    # For others, parts[1] is the path
    if status.start_with?("R")
      # Rename: use the new path
      paths << parts[2] if parts.length >= 3 && parts[2]
    elsif parts[1]
      # Added, Copied, Modified: use the path
      paths << parts[1]
    end
  end

  # Filter to only yml files and return unique paths
  paths.select { |path| path&.end_with?(".yml", ".yaml") }.uniq
end

.changed_files_since(commit_hash) ⇒ Object



99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/strata/cli/utils/git.rb', line 99

def changed_files_since(commit_hash)
  return [] unless git_repo?
  return [] unless commit_hash

  unless validate_commit_hash(commit_hash)
    raise Strata::CommandError, "Invalid commit hash format: #{commit_hash.inspect}"
  end

  # Check if commit exists in repo
  _, _, status = Open3.capture3("git", "rev-parse", "--verify", "#{commit_hash}^{commit}")
  return [] unless status.success?

  # Get all changed files since that commit (including added, modified, deleted, renamed)
  diff_output = run_git_command("diff", "--name-status", commit_hash, "HEAD")
  return [] unless diff_output

  modifications = parse_diff_output(diff_output)
  filter_yml_files(modifications)
end

.check_commit_status(branch_name) ⇒ Object



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
# File 'lib/strata/cli/utils/git.rb', line 283

def check_commit_status(branch_name)
  return {status: :ok, message: "Not a git repository"} unless git_repo?

  remote_branch = "origin/#{branch_name}"

  # Check if remote branch exists
  remote_sha, _, remote_status = Open3.capture3("git", "rev-parse", remote_branch)
  unless remote_status.success?
    return {status: :ok, message: "Remote branch not found, proceeding with local commit"}
  end

  remote_sha = remote_sha.strip
  local_sha = run_git_command("rev-parse", "HEAD")

  # If SHAs are the same, branches are in sync
  return {status: :same, message: "Local branch is in sync with remote"} if local_sha == remote_sha

  # Check if local is ahead, behind, or diverged
  # rev-list --left-right shows: > = commits in local not in remote (ahead), < = commits in remote not in local (behind)
  diff_output, = Open3.capture3("git", "rev-list", "--left-right", "#{remote_sha}...#{local_sha}")

  ahead_count = diff_output.lines.count { |line| line.start_with?(">") }
  behind_count = diff_output.lines.count { |line| line.start_with?("<") }

  if ahead_count.positive? && behind_count.zero?
    {status: :ahead, message: "Local branch is #{ahead_count} commit(s) ahead of remote"}
  elsif ahead_count.zero? && behind_count.positive?
    {status: :behind, message: "Local branch is #{behind_count} commit(s) behind remote"}
  else
    {status: :diverged,
     message: "Local branch has diverged from remote (#{ahead_count} ahead, #{behind_count} behind)"}
  end
end

.check_requirement_and_exit_if_unavailable(args) ⇒ Object



186
187
188
189
190
191
192
193
194
195
196
# File 'lib/strata/cli/utils/git.rb', line 186

def check_requirement_and_exit_if_unavailable(args)
  # Allow help and version commands to work without Git
  command = args.first
  return if args.empty? || %w[version help].include?(command)

  return if git_available?

  Thor::Shell::Color.new.say_error "ERROR: Git is required but not found. Please install Git to use strata-cli.",
    :red
  exit 1
end

.checkout_branch(branch_name) ⇒ Object



43
44
45
46
47
48
49
50
51
# File 'lib/strata/cli/utils/git.rb', line 43

def checkout_branch(branch_name)
  ensure_git_repo!
  branch_name = validate_branch_name!(branch_name)

  _, stderr, status = Open3.capture3("git", "switch", branch_name)
  raise Strata::CommandError, "Failed to checkout branch '#{branch_name}': #{stderr.strip}" unless status.success?

  branch_name
end

.commit_file(file_path, commit_message, project_path = Dir.pwd) ⇒ Object



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
# File 'lib/strata/cli/utils/git.rb', line 317

def commit_file(file_path, commit_message, project_path = Dir.pwd)
  return false unless git_repo?

  # Change to project directory for git operations
  Dir.chdir(project_path) do
    # Check if file exists
    return false unless File.exist?(file_path)

    # Check if file has changes (modified, added, or untracked)
    stdout, _, status = Open3.capture3("git", "status", "--porcelain", file_path)
    return false unless status.success?

    # If no changes, nothing to commit
    return false if stdout.strip.empty?

    # Stage the file (handles both modified and untracked files)
    _, _, add_status = Open3.capture3("git", "add", file_path)
    return false unless add_status.success?

    # Check if there are actually staged changes to commit
    # git diff --cached --quiet returns 0 if no changes, 1 if changes exist
    _, _, diff_status = Open3.capture3("git", "diff", "--cached", "--quiet", file_path)
    # If success? is true (exitstatus == 0), there are no changes staged
    return false if diff_status.success?

    # Commit the file
    _, _, commit_status = Open3.capture3("git", "commit", "-m", commit_message)
    commit_status.success?
  end
rescue
  false
end

.commit_infoObject



71
72
73
74
75
76
77
78
79
# File 'lib/strata/cli/utils/git.rb', line 71

def commit_info
  sha = run_git_command("rev-parse", "HEAD")
  message = run_git_command("log", "-1", "--pretty=%B")

  {
    sha: sha,
    message: message || "Manual deployment"
  }
end

.committer_infoObject



81
82
83
84
85
86
87
88
89
# File 'lib/strata/cli/utils/git.rb', line 81

def committer_info
  name = run_git_command("config", "user.name")
  email = run_git_command("config", "user.email")

  {
    name: name || "Unknown",
    email: email || "unknown@example.com"
  }
end

.create_and_checkout_branch(branch_name) ⇒ Object



33
34
35
36
37
38
39
40
41
# File 'lib/strata/cli/utils/git.rb', line 33

def create_and_checkout_branch(branch_name)
  ensure_git_repo!
  branch_name = validate_branch_name!(branch_name)

  _, stderr, status = Open3.capture3("git", "switch", "-c", branch_name)
  raise Strata::CommandError, "Failed to create branch '#{branch_name}': #{stderr.strip}" unless status.success?

  branch_name
end

.current_branchObject



18
19
20
21
22
# File 'lib/strata/cli/utils/git.rb', line 18

def current_branch
  return "main" unless git_repo?

  run_git_command("rev-parse", "--abbrev-ref", "HEAD")
end

.delete_local_branch(branch_name, fallback_branches: %w[main master])) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/strata/cli/utils/git.rb', line 53

def delete_local_branch(branch_name, fallback_branches: %w[main master])
  return :not_git_repo unless git_repo?

  branch_name = branch_name.to_s.strip
  raise Strata::CommandError, "Branch name is required." if branch_name.empty?

  return :not_found unless local_branch_exists?(branch_name)

  if current_branch == branch_name
    switch_to_fallback_branch(branch_name, fallback_branches)
  end

  _, stderr, status = Open3.capture3("git", "branch", "-D", branch_name)
  raise Strata::CommandError, "Failed to delete local branch '#{branch_name}': #{stderr.strip}" unless status.success?

  :deleted
end

.ensure_git_repo!Object



214
215
216
# File 'lib/strata/cli/utils/git.rb', line 214

def ensure_git_repo!
  raise Strata::CommandError, "Not a git repository." unless git_repo?
end

.fetch_branch(branch_name) ⇒ Object



277
278
279
280
281
# File 'lib/strata/cli/utils/git.rb', line 277

def fetch_branch(branch_name)
  return unless git_repo?

  run_git_command("fetch", "origin", branch_name)
end

.file_modificationsObject



91
92
93
94
95
96
97
# File 'lib/strata/cli/utils/git.rb', line 91

def file_modifications
  diff_output = run_git_command("diff", "--name-status", "HEAD~1")
  return [] unless diff_output

  modifications = parse_diff_output(diff_output)
  filter_yml_files(modifications)
end

.filter_yml_files(modifications) ⇒ Object



263
264
265
266
267
268
# File 'lib/strata/cli/utils/git.rb', line 263

def filter_yml_files(modifications)
  modifications.select do |mod|
    path = mod.is_a?(Array) ? (mod[1] || "") : ""
    path.end_with?(".yml", ".yaml")
  end
end

.format_file_modification(status, path) ⇒ Object



248
249
250
251
252
253
254
255
256
257
258
259
260
261
# File 'lib/strata/cli/utils/git.rb', line 248

def format_file_modification(status, path)
  case status
  when /^R(\d+)$/
    similarity = Regexp.last_match(1)
    old_path, new_path = path.split(/\s+/, 2)
    ["R#{similarity}", old_path, new_path]
  when "A"
    ["A", path]
  when "M"
    ["M", path]
  when "D"
    ["D", path]
  end
end

.git_available?Boolean

Returns:

  • (Boolean)


164
165
166
167
168
169
# File 'lib/strata/cli/utils/git.rb', line 164

def git_available?
  _, _, status = Open3.capture3("git", "--version")
  status.success?
rescue
  false
end

.git_remote_url(remote_name = "origin") ⇒ Object



198
199
200
201
202
203
204
205
206
207
# File 'lib/strata/cli/utils/git.rb', line 198

def git_remote_url(remote_name = "origin")
  return nil unless git_repo?

  url = run_git_command("remote", "get-url", remote_name)
  return nil if url.nil? || url.strip.empty?

  url.strip
rescue
  nil
end

.git_repo?Boolean

Returns:

  • (Boolean)


160
161
162
# File 'lib/strata/cli/utils/git.rb', line 160

def git_repo?
  File.directory?(".git")
end

.local_branch_exists?(branch_name) ⇒ Boolean

Returns:

  • (Boolean)


171
172
173
174
# File 'lib/strata/cli/utils/git.rb', line 171

def local_branch_exists?(branch_name)
  _, _, status = Open3.capture3("git", "show-ref", "--verify", "--quiet", "refs/heads/#{branch_name}")
  status.success?
end

.local_branchesObject



24
25
26
27
28
29
30
31
# File 'lib/strata/cli/utils/git.rb', line 24

def local_branches
  return [] unless git_repo?

  output = run_git_command("branch", "--format", "%(refname:short)")
  return [] unless output

  output.lines.map(&:strip).reject(&:empty?)
end

.parse_diff_output(output) ⇒ Object



230
231
232
233
234
# File 'lib/strata/cli/utils/git.rb', line 230

def parse_diff_output(output)
  output.lines.map do |line|
    parse_diff_status(line.strip)
  end.compact
end

.parse_diff_status(line) ⇒ Object



236
237
238
239
240
241
242
243
244
245
246
# File 'lib/strata/cli/utils/git.rb', line 236

def parse_diff_status(line)
  return nil if line.empty?

  parts = line.split(/\s+/, 2)
  return nil if parts.length < 2

  status = parts[0]
  path = parts[1]

  format_file_modification(status, path)
end

.run_git_command(*args) ⇒ Object



209
210
211
212
# File 'lib/strata/cli/utils/git.rb', line 209

def run_git_command(*args)
  stdout, = Open3.capture3("git", *args)
  stdout&.strip
end

.switch_to_fallback_branch(branch_name, fallback_branches) ⇒ Object



218
219
220
221
222
223
224
225
226
227
228
# File 'lib/strata/cli/utils/git.rb', line 218

def switch_to_fallback_branch(branch_name, fallback_branches)
  fallback_branch = fallback_branches.find { |candidate| candidate != branch_name && local_branch_exists?(candidate) }

  unless fallback_branch
    raise Strata::CommandError,
      "Cannot delete the currently checked out branch '#{branch_name}'. Check out another branch and try again."
  end

  _, stderr, status = Open3.capture3("git", "switch", fallback_branch)
  raise Strata::CommandError, "Failed to switch to '#{fallback_branch}': #{stderr.strip}" unless status.success?
end

.uncommitted_changes?Boolean

Returns:

  • (Boolean)


270
271
272
273
274
275
# File 'lib/strata/cli/utils/git.rb', line 270

def uncommitted_changes?
  return false unless git_repo?

  stdout, = Open3.capture3("git", "status", "--porcelain")
  !stdout.strip.empty?
end

.validate_branch_name!(branch_name) ⇒ Object



176
177
178
179
180
181
182
183
184
# File 'lib/strata/cli/utils/git.rb', line 176

def validate_branch_name!(branch_name)
  branch_name = branch_name.to_s.strip
  raise Strata::CommandError, "Branch name is required." if branch_name.empty?

  _, stderr, status = Open3.capture3("git", "check-ref-format", "--branch", branch_name)
  raise Strata::CommandError, "Invalid branch name '#{branch_name}': #{stderr.strip}" unless status.success?

  branch_name
end

.validate_commit_hash(commit_hash) ⇒ Object



11
12
13
14
15
16
# File 'lib/strata/cli/utils/git.rb', line 11

def validate_commit_hash(commit_hash)
  return false unless commit_hash.is_a?(String)
  return false unless commit_hash.match?(/\A[a-f0-9]{7,40}\z/i)

  true
end