Class: MendixBridge::GitWorkflow

Inherits:
Object
  • Object
show all
Defined in:
lib/mendix_bridge/git_workflow.rb

Constant Summary collapse

IN_PROGRESS_MARKERS =
%w[
  MERGE_HEAD CHERRY_PICK_HEAD REVERT_HEAD REBASE_HEAD
  rebase-merge rebase-apply BISECT_LOG
].freeze
TERMINAL_SUBCOMMANDS =
%w[
  status diff log show blame branch switch checkout add restore reset commit
  fetch pull push merge rebase cherry-pick revert stash tag remote worktree
  rev-parse reflog clean mv rm grep shortlog describe bisect
].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(project_file, inventory_dir: nil, mxcli: nil, mx: nil) ⇒ GitWorkflow

Returns a new instance of GitWorkflow.



18
19
20
21
22
23
24
25
26
27
# File 'lib/mendix_bridge/git_workflow.rb', line 18

def initialize(project_file, inventory_dir: nil, mxcli: nil, mx: nil)
  @project_file = File.expand_path(project_file)
  @project_dir = File.dirname(@project_file)
  @inventory_dir = inventory_dir && File.expand_path(inventory_dir)
  @root = git!("rev-parse", "--show-toplevel").strip
  @git_dir = git!("rev-parse", "--absolute-git-dir").strip
  @mxcli = mxcli
  @mx = mx || resolve_mx
  verify_project_tracking!
end

Instance Attribute Details

#rootObject (readonly)

Returns the value of attribute root.



29
30
31
# File 'lib/mendix_bridge/git_workflow.rb', line 29

def root
  @root
end

Instance Method Details

#add_remote(name, url) ⇒ Object

Raises:



404
405
406
407
408
409
410
411
412
413
# File 'lib/mendix_bridge/git_workflow.rb', line 404

def add_remote(name, url)
  name = name.to_s.strip
  url = url.to_s.strip
  raise GitWorkflowError, "remote name cannot be empty" if name.empty?
  raise GitWorkflowError, "remote URL cannot be empty" if url.empty?
  raise GitWorkflowError, "invalid remote name: #{name}" unless name.match?(/\A[A-Za-z0-9._-]+\z/)

  git!("remote", "add", name, url)
  { "ok" => true, "name" => name, "url" => url }
end

#branchesObject



43
44
45
46
# File 'lib/mendix_bridge/git_workflow.rb', line 43

def branches
  git!("for-each-ref", "--format=%(refname:short)", "refs/heads", "refs/remotes")
    .lines.map(&:strip).reject { |name| name.end_with?("/HEAD") }
end

#cherry_pick(sha, studio_closed:) ⇒ Object

Raises:



423
424
425
426
427
428
429
430
431
# File 'lib/mendix_bridge/git_workflow.rb', line 423

def cherry_pick(sha, studio_closed:)
  ensure_studio_closed!(studio_closed)
  ensure_no_operation!
  output, error, result = Open3.capture3("git", "-C", @root, "cherry-pick", sha)
  raise GitWorkflowError, "cherry-pick failed:\n#{error}#{output}" unless result.success?

  refresh_inventory! if @inventory_dir
  { "ok" => true, "output" => output.strip, **status }
end

#commit(message, studio_closed:) ⇒ Object

Stages the whole project directory then commits. Skips mx check so work-in-progress can be committed; branch switches still guard a dirty tree.

Raises:



280
281
282
283
284
285
286
287
288
289
290
291
292
293
# File 'lib/mendix_bridge/git_workflow.rb', line 280

def commit(message, studio_closed:)
  ensure_studio_closed!(studio_closed)
  ensure_no_operation!
  message = message.to_s.strip
  raise GitWorkflowError, "commit message cannot be empty" if message.empty?
  verify_project_tracking!

  git!("add", "--", project_pathspec)
  raise GitWorkflowError, "nothing to commit; the project has no staged changes" if
    git!("diff", "--cached", "--name-only").strip.empty?

  git!("commit", "-m", message)
  status
end

#commit_staged(message, studio_closed:) ⇒ Object

Commits only what is already staged — no implicit git add. Enables fine-grained staging via the git panel before committing.

Raises:



297
298
299
300
301
302
303
304
305
306
307
# File 'lib/mendix_bridge/git_workflow.rb', line 297

def commit_staged(message, studio_closed:)
  ensure_studio_closed!(studio_closed)
  ensure_no_operation!
  message = message.to_s.strip
  raise GitWorkflowError, "commit message cannot be empty" if message.empty?
  raise GitWorkflowError, "nothing staged to commit" if
    git!("diff", "--cached", "--name-only").strip.empty?

  git!("commit", "-m", message)
  status
end

#create(branch, studio_closed:, start_point: nil, carry_changes: false) ⇒ Object



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
# File 'lib/mendix_bridge/git_workflow.rb', line 106

def create(branch, studio_closed:, start_point: nil, carry_changes: false)
  ensure_studio_closed!(studio_closed)
  ensure_no_operation!
  validate_branch_name!(branch)
  raise GitWorkflowError, "branch already exists: #{branch}" if local_branch?(branch) || remote_branch?(branch)

  previous = current_branch
  switched = false
  stashed = false
  if !clean? && !carry_changes
    git!("stash", "push", "--include-untracked", "-m", "Before creating #{branch}")
    stashed = true
  end
  arguments = ["switch", "-c", branch]
  arguments << start_point if start_point
  git!(*arguments)
  switched = true
  # Creating a ref does not change the project contents. Existing Mendix
  # consistency errors must not make Git undo an otherwise valid branch.
  { **status, "carried_changes" => !clean?, "stashed_changes" => stashed }
rescue StandardError => error
  begin
    git!("switch", previous) if switched && current_branch != previous
    git!("stash", "pop", "--index") if stashed
  rescue GitWorkflowError
    # Keep the original error; the named automatic stash remains recoverable.
  end
  raise error
end

#create_tag(name, sha: nil, message: nil) ⇒ Object



454
455
456
457
458
459
460
461
# File 'lib/mendix_bridge/git_workflow.rb', line 454

def create_tag(name, sha: nil, message: nil)
  args = ["tag"]
  args.concat(["-a", name, "-m", message]) if message
  args << name unless message
  args << sha if sha
  git!(*args)
  { "ok" => true }
end

#delete_branch(name, force: false) ⇒ Object

Raises:



468
469
470
471
472
473
# File 'lib/mendix_bridge/git_workflow.rb', line 468

def delete_branch(name, force: false)
  raise GitWorkflowError, "cannot delete the current branch" if name == current_branch

  git!("branch", force ? "-D" : "-d", name)
  { "ok" => true }
end

#delete_tag(name) ⇒ Object



463
464
465
466
# File 'lib/mendix_bridge/git_workflow.rb', line 463

def delete_tag(name)
  git!("tag", "-d", name)
  { "ok" => true }
end

#discard(path) ⇒ Object



383
384
385
386
387
388
389
390
391
392
393
394
395
396
# File 'lib/mendix_bridge/git_workflow.rb', line 383

def discard(path)
  target = File.expand_path(path, @root)
  unless target.start_with?("#{@root}/")
    raise GitWorkflowError, "path is outside the Git repository: #{path}"
  end

  raw = git!("status", "--porcelain", "--", path).strip
  if raw.start_with?("??")
    FileUtils.rm_rf(target)
  else
    git!("checkout", "--", path)
  end
  { "ok" => true }
end

#fetchObject



78
79
80
# File 'lib/mendix_bridge/git_workflow.rb', line 78

def fetch
  git!("fetch", "--prune", "origin")
end

#file_statusObject

Per-file working-tree and index status (porcelain v1, NUL-terminated).



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
# File 'lib/mendix_bridge/git_workflow.rb', line 338

def file_status
  raw = git!("status", "--porcelain=v1", "-z")
  files = []
  entries = raw.split("\x00")
  i = 0
  while i < entries.length
    entry = entries[i]
    unless entry.length >= 4
      i += 1
      next
    end
    xy            = entry[0..1]
    path          = entry[3..]
    renamed_from  = nil
    if xy[0] == "R" || xy[0] == "C"
      renamed_from = entries[i + 1].to_s
      i += 1
    end
    files << {
      "path"            => path.to_s,
      "xy"              => xy,
      "index_status"    => xy[0].to_s,
      "worktree_status" => xy[1].to_s,
      "renamed_from"    => renamed_from
    }
    i += 1
  end
  files
end

#log(max: 200) ⇒ Object

Commit log across all branches in topo order (newest first). Returns an array of hashes with sha, short_sha, author, email, date, subject, refs (typed array), parents (SHA array).



312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
# File 'lib/mendix_bridge/git_workflow.rb', line 312

def log(max: 200)
  fmt = "%H%x1f%h%x1f%an%x1f%ae%x1f%ai%x1f%P%x1f%D%x1f%s"
  raw = git!("log", "--all", "--topo-order",
             "--pretty=format:#{fmt}",
             "--max-count=#{max.to_i}")
  raw.each_line.filter_map do |line|
    fields = line.chomp.split("\x1f", 8)
    next if fields.length < 8

    sha, short_sha, author, email, date, parents_str, refs_str, subject = fields
    next if sha.to_s.strip.empty?

    {
      "sha"       => sha.strip,
      "short_sha" => short_sha.strip,
      "author"    => author.strip,
      "email"     => email.strip,
      "date"      => date.strip,
      "subject"   => subject.to_s.strip,
      "refs"      => parse_refs(refs_str.to_s.strip),
      "parents"   => parents_str.to_s.strip.split.reject(&:empty?)
    }
  end
end

#merge(branch, studio_closed:) ⇒ Object



237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
# File 'lib/mendix_bridge/git_workflow.rb', line 237

def merge(branch, studio_closed:)
  ensure_switch_ready!(branch, studio_closed:)
  output, error, result = Open3.capture3(
    "git", "-C", @root, "merge", "--no-ff", "--no-commit", branch
  )
  unless result.success?
    raise GitWorkflowError,
      "merge has conflicts; resolve them or run git merge --abort:\n#{error}#{output}"
  end

  begin
    validate_project!
  rescue StandardError => validation_error
    raise GitWorkflowError,
      "#{validation_error.message}\nmerge was not committed; run git merge --abort"
  end

  git!("commit", "--no-edit")
  refresh_inventory! if @inventory_dir
  status
end

#pull(studio_closed:) ⇒ Object



415
416
417
418
419
420
421
# File 'lib/mendix_bridge/git_workflow.rb', line 415

def pull(studio_closed:)
  ensure_studio_closed!(studio_closed)
  ensure_no_operation!
  output = git!("pull", "--rebase")
  refresh_inventory! if @inventory_dir
  { "ok" => true, "output" => output.strip, **status }
end

#push(remote: "origin", branch: nil) ⇒ Object



398
399
400
401
402
# File 'lib/mendix_bridge/git_workflow.rb', line 398

def push(remote: "origin", branch: nil)
  branch ||= current_branch
  output = git!("push", "--set-upstream", remote, branch)
  { "ok" => true, "output" => output.strip }
end

#rebase(branch, studio_closed:) ⇒ Object



259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
# File 'lib/mendix_bridge/git_workflow.rb', line 259

def rebase(branch, studio_closed:)
  ensure_switch_ready!(branch, studio_closed:)
  validation = [
    Shellwords.escape(@mx),
    "check",
    Shellwords.escape(@project_file)
  ].join(" ")
  output, error, result = Open3.capture3(
    "git", "-C", @root, "rebase", "--exec", validation, branch
  )
  unless result.success?
    raise GitWorkflowError,
      "rebase stopped; resolve the issue and continue, or run git rebase --abort:\n#{error}#{output}"
  end

  refresh_inventory! if @inventory_dir
  status
end

#remote_namesObject



82
83
84
# File 'lib/mendix_bridge/git_workflow.rb', line 82

def remote_names
  git!("remote").lines.map(&:strip).reject(&:empty?)
end

#reset_to(sha, mode: "mixed", studio_closed:) ⇒ Object

Raises:



443
444
445
446
447
448
449
450
451
452
# File 'lib/mendix_bridge/git_workflow.rb', line 443

def reset_to(sha, mode: "mixed", studio_closed:)
  ensure_studio_closed!(studio_closed)
  ensure_no_operation!
  raise GitWorkflowError, "invalid reset mode: #{mode}" unless
    %w[soft mixed hard].include?(mode.to_s)

  git!("reset", "--#{mode}", sha)
  refresh_inventory! if @inventory_dir && mode == "hard"
  { "ok" => true, **status }
end

#revert_commit(sha, studio_closed:) ⇒ Object

Raises:



433
434
435
436
437
438
439
440
441
# File 'lib/mendix_bridge/git_workflow.rb', line 433

def revert_commit(sha, studio_closed:)
  ensure_studio_closed!(studio_closed)
  ensure_no_operation!
  output, error, result = Open3.capture3("git", "-C", @root, "revert", "--no-edit", sha)
  raise GitWorkflowError, "revert failed:\n#{error}#{output}" unless result.success?

  refresh_inventory! if @inventory_dir
  { "ok" => true, "output" => output.strip, **status }
end

#stage(path) ⇒ Object



368
369
370
371
# File 'lib/mendix_bridge/git_workflow.rb', line 368

def stage(path)
  git!("add", "--", path)
  { "ok" => true }
end

#stash_apply(reference = "stash@{0}", studio_closed:, drop: false) ⇒ Object



211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
# File 'lib/mendix_bridge/git_workflow.rb', line 211

def stash_apply(reference = "stash@{0}", studio_closed:, drop: false)
  ensure_switch_ready!(current_branch, studio_closed:)
  output, error, result = Open3.capture3(
    "git", "-C", @root, "stash", "apply", "--index", reference
  )
  unless result.success?
    raise GitWorkflowError,
      "stash apply has conflicts; the stash was preserved:\n#{error}#{output}"
  end

  begin
    validate_project!
    refresh_inventory! if @inventory_dir
  rescue StandardError => validation_error
    raise GitWorkflowError,
      "#{validation_error.message}\nthe stash was preserved and its changes remain in the working tree"
  end

  git!("stash", "drop", reference) if drop
  status
end

#stash_drop(reference = "stash@{0}") ⇒ Object



233
234
235
# File 'lib/mendix_bridge/git_workflow.rb', line 233

def stash_drop(reference = "stash@{0}")
  git!("stash", "drop", reference).strip
end

#stash_listObject



203
204
205
# File 'lib/mendix_bridge/git_workflow.rb', line 203

def stash_list
  git!("stash", "list")
end

#stash_push(studio_closed:, message: nil, include_untracked: false) ⇒ Object



192
193
194
195
196
197
198
199
200
201
# File 'lib/mendix_bridge/git_workflow.rb', line 192

def stash_push(studio_closed:, message: nil, include_untracked: false)
  ensure_studio_closed!(studio_closed)
  ensure_no_operation!

  arguments = ["stash", "push"]
  arguments << "--include-untracked" if include_untracked
  arguments.concat(["-m", message]) if message
  output = git!(*arguments)
  { "output" => output.strip, **status }
end

#stash_show(reference = "stash@{0}") ⇒ Object



207
208
209
# File 'lib/mendix_bridge/git_workflow.rb', line 207

def stash_show(reference = "stash@{0}")
  git!("stash", "show", "--stat", reference)
end

#statusObject



31
32
33
34
35
36
37
38
39
40
41
# File 'lib/mendix_bridge/git_workflow.rb', line 31

def status
  {
    "branch"               => current_branch,
    "clean"                => clean?,
    "operation_in_progress" => operation_in_progress,
    "project"              => @project_file,
    "project_tracked"      => tracked?(@project_file),
    "mprcontents_tracked"  => mprcontents_tracked?,
    "ready_to_switch"      => clean? && operation_in_progress.nil?
  }
end

#switch(branch, studio_closed:) ⇒ Object



86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/mendix_bridge/git_workflow.rb', line 86

def switch(branch, studio_closed:)
  ensure_switch_ready!(branch, studio_closed:)
  previous = current_branch
  switched = false

  if local_branch?(branch)
    git!("switch", branch)
  elsif remote_branch?(branch)
    git!("switch", "--track", "-c", branch, "origin/#{branch}")
  else
    raise GitWorkflowError, "branch does not exist locally or at origin: #{branch}"
  end
  switched = true
  validate_and_refresh!
  status
rescue StandardError => error
  git!("switch", previous) if switched && current_branch != previous
  raise error
end

#tagsObject



48
49
50
# File 'lib/mendix_bridge/git_workflow.rb', line 48

def tags
  git!("tag", "--list", "--sort=-creatordate").lines.map(&:strip).reject(&:empty?)
end

#terminal_command(command, studio_closed:) ⇒ Object

Non-interactive Git CLI used by the embedded terminal. It deliberately accepts Git commands only: a browser must never become an arbitrary shell on the machine hosting the bridge.



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
# File 'lib/mendix_bridge/git_workflow.rb', line 145

def terminal_command(command, studio_closed:)
  arguments = Shellwords.split(command.to_s.strip)
  arguments.shift if arguments.first == "git"
  raise GitWorkflowError, "enter a git command" if arguments.empty?
  raise GitWorkflowError, "git global options are not allowed in the embedded terminal" if
    arguments.first.start_with?("-")

  subcommand = arguments.first
  unless TERMINAL_SUBCOMMANDS.include?(subcommand)
    raise GitWorkflowError, "unsupported git command: #{subcommand}"
  end

  read_only = %w[status diff log show blame rev-parse reflog grep shortlog describe].include?(subcommand)
  read_only ||= subcommand == "remote" &&
    (arguments.length == 1 || arguments[1] == "-v" || arguments[1] == "show")
  mutating = !read_only
  ensure_studio_closed!(studio_closed) if mutating
  ensure_no_operation! if mutating && !%w[rebase merge cherry-pick revert bisect].include?(subcommand)

  output = error = nil
  result = nil
  Timeout.timeout(120) do
    output, error, result = Open3.capture3(
      {
        "GIT_TERMINAL_PROMPT" => "0",
        "GIT_EDITOR" => "true",
        "GIT_SEQUENCE_EDITOR" => "true"
      },
      "git", "-C", @root, *arguments
    )
  end
  combined = [output, error].compact.reject(&:empty?).join
  raise GitWorkflowError, combined.strip.empty? ? "git command failed" : combined.strip unless result.success?

  {
    "ok" => true,
    "command" => "git #{Shellwords.join(arguments)}",
    "output" => combined.strip,
    "exit_code" => result.exitstatus,
    **status
  }
rescue ArgumentError => error
  raise GitWorkflowError, "invalid command line: #{error.message}"
rescue Timeout::Error
  raise GitWorkflowError, "git command timed out after 120 seconds"
end

#unstage(path) ⇒ Object



373
374
375
376
377
378
379
380
381
# File 'lib/mendix_bridge/git_workflow.rb', line 373

def unstage(path)
  begin
    git!("reset", "HEAD", "--", path)
  rescue GitWorkflowError
    # HEAD doesn't exist yet (empty repo) — use rm --cached instead
    git!("rm", "--cached", "--", path)
  end
  { "ok" => true }
end

#worktreesObject



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
# File 'lib/mendix_bridge/git_workflow.rb', line 52

def worktrees
  records = []
  current = {}
  git!("worktree", "list", "--porcelain").each_line do |line|
    line = line.chomp
    if line.empty?
      records << current unless current.empty?
      current = {}
    elsif line.start_with?("worktree ")
      current["path"] = line.delete_prefix("worktree ")
    elsif line.start_with?("HEAD ")
      current["sha"] = line.delete_prefix("HEAD ")
    elsif line.start_with?("branch ")
      current["branch"] = line.delete_prefix("branch refs/heads/")
    elsif line == "detached"
      current["detached"] = true
    elsif line == "prunable"
      current["prunable"] = true
    elsif line.start_with?("locked")
      current["locked"] = true
    end
  end
  records << current unless current.empty?
  records
end