Class: GitProc::GitLib

Inherits:
Object
  • Object
show all
Defined in:
lib/git-process/git_lib.rb

Overview

Provides Git commands

noinspection RubyTooManyMethodsInspection

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(dir, opts) ⇒ GitLib

Returns a new instance of GitLib.

Parameters:

  • dir (Dir)


34
35
36
37
# File 'lib/git-process/git_lib.rb', line 34

def initialize(dir, opts)
  self.log_level = GitLib.log_level(opts)
  self.workdir = dir
end

Class Method Details

.find_workdir(dir) ⇒ Object



89
90
91
92
93
94
95
96
97
# File 'lib/git-process/git_lib.rb', line 89

def self.find_workdir(dir)
  if dir == File::SEPARATOR
    nil
  elsif File.directory?(File.join(dir, '.git'))
    dir
  else
    find_workdir(File.expand_path("#{dir}#{File::SEPARATOR}.."))
  end
end

.log_level(opts) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
# File 'lib/git-process/git_lib.rb', line 48

def self.log_level(opts)
  if opts[:log_level]
    opts[:log_level]
  elsif opts[:quiet]
    Logger::ERROR
  elsif opts[:verbose]
    Logger::DEBUG
  else
    Logger::INFO
  end
end

Instance Method Details

#add(file) ⇒ Object



198
199
200
201
# File 'lib/git-process/git_lib.rb', line 198

def add(file)
  logger.info { "Adding #{[*file].join(', ')}" }
  command(:add, ['--', file])
end

#branch(branch_name, opts = {}) ⇒ String

Does branch manipulation.

Parameters:

  • branch_name (String)

    the name of the branch

  • opts (Hash) (defaults to: {})

    a customizable set of options

Options Hash (opts):

  • :delete (Boolean)

    delete the remote branch

  • :force (Boolean)

    force the update

  • :all (Boolean)

    list all branches, local and remote

  • :no_color (Boolean)

    force not using any ANSI color codes

  • :rename (String)

    the new name for the branch

  • :upstream (String)

    the new branch to track

  • :base_branch (String)

    the branch to base the new branch off of; defaults to ‘master’

Returns:

  • (String)

    the output of running the git command



318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
# File 'lib/git-process/git_lib.rb', line 318

def branch(branch_name, opts = {})
  if opts[:delete]
    delete_branch(branch_name, opts[:force])
  elsif opts[:rename]
    rename_branch(branch_name, opts[:rename])
  elsif opts[:upstream]
    set_upstream_branch(branch_name, opts[:upstream])
  elsif branch_name
    if opts[:force]
      change_branch(branch_name, opts[:base_branch])
    else
      create_branch(branch_name, opts[:base_branch])
    end
  else
    #list_branches(opts)
    list_branches(opts[:all], opts[:remote], opts[:no_color])
  end
end

#branchesObject



293
294
295
# File 'lib/git-process/git_lib.rb', line 293

def branches
  GitProc::GitBranches.new(self)
end

#checkout(branch_name, opts = {}) ⇒ void

This method returns an undefined value.

Parameters:

  • branch_name (String)

    the name of the branch to checkout/create

  • opts (Hash) (defaults to: {})

    a customizable set of options

Options Hash (opts):

  • :no_track (Boolean)

    do not track the base branch

  • :new_branch (String)

    the name of the base branch



418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
# File 'lib/git-process/git_lib.rb', line 418

def checkout(branch_name, opts = {})
  args = []
  args << '--no-track' if opts[:no_track]
  args << '-b' if opts[:new_branch]
  args << branch_name
  args << opts[:new_branch] if opts[:new_branch]
  branches = branches()
  command(:checkout, args)

  branches << GitBranch.new(branch_name, opts[:new_branch] != nil, self)

  if block_given?
    yield
    command(:checkout, branches.current.name)
    branches.current
  else
    branches[branch_name]
  end
end

#command(cmd, opts = [], chdir = true, redirect = '', &block) ⇒ String

Returns:



496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
# File 'lib/git-process/git_lib.rb', line 496

def command(cmd, opts = [], chdir = true, redirect = '', &block)
  ENV['GIT_INDEX_FILE'] = File.join(workdir, '.git', 'index')
  ENV['GIT_DIR'] = File.join(workdir, '.git')
  ENV['GIT_WORK_TREE'] = workdir
  path = workdir

  git_cmd = create_git_command(cmd, opts, redirect)

  out = command_git_cmd(path, git_cmd, chdir, block)

  if logger
    logger.debug(git_cmd)
    logger.debug(out)
  end

  handle_exitstatus($?, git_cmd, out)
end

#commit(msg = nil) ⇒ Object



204
205
206
207
# File 'lib/git-process/git_lib.rb', line 204

def commit(msg = nil)
  logger.info 'Committing changes'
  command(:commit, msg.nil? ? nil : ['-m', msg])
end

#configObject



176
177
178
179
180
181
# File 'lib/git-process/git_lib.rb', line 176

def config
  if @config.nil?
    @config = GitConfig.new(self)
  end
  @config
end

#delete_sync_control_file!(branch_name) ⇒ Object



538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
# File 'lib/git-process/git_lib.rb', line 538

def delete_sync_control_file!(branch_name)
  filename = sync_control_filename(branch_name)
  logger.debug { "Deleting sync control file, #{filename}" }

  counter = 10
  while counter > 0
    begin
      File.delete(filename)
      counter = 0
    rescue
      counter = counter - 1
      sleep(0.25)
    end
  end
end

#fetch(name = remote.name) ⇒ Object



236
237
238
239
240
241
242
243
# File 'lib/git-process/git_lib.rb', line 236

def fetch(name = remote.name)
  logger.info 'Fetching the latest changes from the server'
  output = self.command(:fetch, ['-p', name])

  log_fetch_changes(fetch_changes(output))

  output
end

#fetch_changes(output) ⇒ Hash

Returns:

  • (Hash)


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
# File 'lib/git-process/git_lib.rb', line 259

def fetch_changes(output)
  changed = output.split("\n")

  changes = {:new_branch => [], :new_tag => [], :force_updated => [], :deleted => [], :updated => []}

  line = changed.shift

  until line.nil? do
    case line
      when /^\s\s\s/
        m = /^\s\s\s(\S+)\s+(\S+)\s/.match(line)
        changes[:updated] << "#{m[2]} (#{m[1]})"
      when /^\s\*\s\[new branch\]/
        m = /^\s\*\s\[new branch\]\s+(\S+)\s/.match(line)
        changes[:new_branch] << m[1]
      when /^\s\*\s\[new tag\]/
        m = /^\s\*\s\[new tag\]\s+(\S+)\s/.match(line)
        changes[:new_tag] << m[1]
      when /^\sx\s/
        m = /^\sx\s\[deleted\]\s+\(none\)\s+->\s+[^\/]+\/(\S+)/.match(line)
        changes[:deleted] << m[1]
      when /^\s\+\s/
        m = /^\s\+\s(\S+)\s+(\S+)\s/.match(line)
        changes[:force_updated] << "#{m[2]} (#{m[1]})"
      else
        # ignore the line
    end
    line = changed.shift
  end

  changes
end

#fetch_remote_changes(remote_name = nil) ⇒ Object



100
101
102
103
104
105
106
# File 'lib/git-process/git_lib.rb', line 100

def fetch_remote_changes(remote_name = nil)
  if remote.exists?
    fetch(remote_name || remote.name)
  else
    logger.debug 'Can not fetch latest changes because there is no remote defined'
  end
end

#has_a_remote?Boolean

Returns does this have a remote defined?.

Returns:

  • (Boolean)

    does this have a remote defined?



193
194
195
# File 'lib/git-process/git_lib.rb', line 193

def has_a_remote?
  remote.exists?
end

#is_parked?Boolean

Returns:

  • (Boolean)


153
154
155
156
# File 'lib/git-process/git_lib.rb', line 153

def is_parked?
  mybranches = self.branches()
  mybranches.parking == mybranches.current
end

#log_countObject



439
440
441
# File 'lib/git-process/git_lib.rb', line 439

def log_count
  command(:log, '--oneline').split(/\n/).length
end

#log_fetch_changes(changes) ⇒ void

This method returns an undefined value.

Parameters:

  • changes (Hash)

    a hash of the changes that were made



249
250
251
252
253
254
255
# File 'lib/git-process/git_lib.rb', line 249

def log_fetch_changes(changes)
  changes.each do |key, v|
    unless v.empty?
      logger.info { "  #{key.to_s.sub(/_/, ' ')}: #{v.join(', ')}" }
    end
  end
end

#log_levelObject



61
62
63
# File 'lib/git-process/git_lib.rb', line 61

def log_level
  @log_level || Logger::WARN
end

#log_level=(lvl) ⇒ Object



66
67
68
# File 'lib/git-process/git_lib.rb', line 66

def log_level=(lvl)
  @log_level = lvl
end

#loggerObject



40
41
42
43
44
45
# File 'lib/git-process/git_lib.rb', line 40

def logger
  if @logger.nil?
    @logger = GitLogger.new(log_level)
  end
  @logger
end

#merge(base, opts = {}) ⇒ Object



227
228
229
230
231
232
233
# File 'lib/git-process/git_lib.rb', line 227

def merge(base, opts= {})
  logger.info { "Merging #{branches.current.name} with #{base}" }
  args = []
  args << '-s' << opts[:merge_strategy] if opts[:merge_strategy]
  args << base
  command(:merge, args)
end

#porcelain_statusString

Returns the raw porcelain status string.

Returns:

  • (String)

    the raw porcelain status string



462
463
464
# File 'lib/git-process/git_lib.rb', line 462

def porcelain_status
  command(:status, '--porcelain')
end

#previous_remote_sha(current_branch, remote_branch) ⇒ String

Returns the previous remote sha ONLY IF it is not the same as the new remote sha; otherwise nil.

Returns:

  • (String)

    the previous remote sha ONLY IF it is not the same as the new remote sha; otherwise nil



128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/git-process/git_lib.rb', line 128

def previous_remote_sha(current_branch, remote_branch)
  return nil unless has_a_remote?
  return nil unless remote_branches.include?(remote_branch)

  control_file_sha = read_sync_control_file(current_branch)
  old_sha = control_file_sha || remote_branch_sha(remote_branch)
  fetch_remote_changes
  new_sha = remote_branch_sha(remote_branch)

  if old_sha != new_sha
    logger.info('The remote branch has changed since the last time')
    old_sha
  else
    logger.debug 'The remote branch has not changed since the last time'
    nil
  end
end

#proc_merge(base, opts = {}) ⇒ Object



118
119
120
121
122
123
124
# File 'lib/git-process/git_lib.rb', line 118

def proc_merge(base, opts = {})
  begin
    merge(base, opts)
  rescue GitExecuteError => merge_error
    raise MergeError.new(merge_error.message, self)
  end
end

#proc_rebase(base, opts = {}) ⇒ Object



109
110
111
112
113
114
115
# File 'lib/git-process/git_lib.rb', line 109

def proc_rebase(base, opts = {})
  begin
    rebase(base, opts)
  rescue GitExecuteError => rebase_error
    raise RebaseError.new(rebase_error.message, self)
  end
end

#push(remote_name, local_branch, remote_branch, opts = {}) ⇒ void

This method returns an undefined value.

Pushes the given branch to the server.

Parameters:

  • remote_name (String)

    the repository name; nil -> ‘origin’

  • local_branch (String)

    the local branch to push; nil -> the current branch

  • remote_branch (String)

    the name of the branch to push to; nil -> same as local_branch

  • opts (Hash) (defaults to: {})

    a customizable set of options

Options Hash (opts):

  • :delete (Boolean, String)

    delete the remote branch

  • :force (Boolean)

    force the update, even if not a fast-forward

Raises:

  • (ArgumentError)

    if :delete is true, but no branch name is given



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
# File 'lib/git-process/git_lib.rb', line 351

def push(remote_name, local_branch, remote_branch, opts = {})
  remote_name ||= 'origin'

  args = [remote_name]

  if opts[:delete]
    if remote_branch
      rb = remote_branch
    elsif local_branch
      rb = local_branch
    elsif !(opts[:delete].is_a? TrueClass)
      rb = opts[:delete]
    else
      raise ArgumentError.new('Need a branch name to delete.')
    end

    int_branch = config.master_branch
    if rb == int_branch
      raise GitProc::GitProcessError.new("Can not delete the integration branch '#{int_branch}'")
    end

    logger.info { "Deleting remote branch '#{rb}' on '#{remote_name}'." }
    args << '--delete' << rb
  else
    local_branch ||= branches.current
    remote_branch ||= local_branch
    args << '-f' if opts[:force]

    logger.info do
      if local_branch == remote_branch
        "Pushing to '#{remote_branch}' on '#{remote_name}'."
      else
        "Pushing #{local_branch} to '#{remote_branch}' on '#{remote_name}'."
      end
    end

    args << "#{local_branch}:#{remote_branch}"
  end
  command(:push, args)
end

#push_to_server(local_branch, remote_branch, opts = {}) ⇒ Object



159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/git-process/git_lib.rb', line 159

def push_to_server(local_branch, remote_branch, opts = {})
  if opts[:local]
    logger.debug('Not pushing to the server because the user selected local-only.')
  elsif not has_a_remote?
    logger.debug('Not pushing to the server because there is no remote.')
  elsif local_branch == config.master_branch
    logger.warn('Not pushing to the server because the current branch is the mainline branch.')
  else
    opts[:prepush].call if opts[:prepush]

    push(remote.name, local_branch, remote_branch, :force => opts[:force])

    opts[:postpush].call if opts[:postpush]
  end
end

#read_sync_control_file(branch_name) ⇒ Object



523
524
525
526
527
528
529
530
531
532
533
534
535
# File 'lib/git-process/git_lib.rb', line 523

def read_sync_control_file(branch_name)
  filename = sync_control_filename(branch_name)
  if File.exists?(filename)
    sha = File.open(filename) do |file|
      file.readline.chop
    end
    logger.debug "Read sync control file, #{filename}: #{sha}"
    sha
  else
    logger.debug "Sync control file, #{filename}, was not found"
    nil
  end
end

#rebase(upstream, opts = {}) ⇒ Object



210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
# File 'lib/git-process/git_lib.rb', line 210

def rebase(upstream, opts = {})
  args = []
  if opts[:interactive]
    logger.info { "Interactively rebasing #{branches.current.name} against #{upstream}" }
    args << '-i'
    args << upstream
  elsif opts[:oldbase]
    logger.info { "Doing rebase from #{opts[:oldbase]} against #{upstream} on #{branches.current.name}" }
    args << '--onto' << upstream << opts[:oldbase] << branches.current.name
  else
    logger.info { "Rebasing #{branches.current.name} against #{upstream}" }
    args << upstream
  end
  command('rebase', args)
end

#rebase_continueObject



393
394
395
# File 'lib/git-process/git_lib.rb', line 393

def rebase_continue
  command(:rebase, '--continue')
end

#remoteObject



184
185
186
187
188
189
# File 'lib/git-process/git_lib.rb', line 184

def remote
  if @remote.nil?
    @remote = GitProc::GitRemote.new(config)
  end
  @remote
end

#remote_branch_sha(remote_branch) ⇒ Object



147
148
149
150
# File 'lib/git-process/git_lib.rb', line 147

def remote_branch_sha(remote_branch)
  logger.debug {"getting sha for remotes/#{remote_branch}"}
  rev_parse("remotes/#{remote_branch}") rescue ''
end

#remote_branchesObject



298
299
300
# File 'lib/git-process/git_lib.rb', line 298

def remote_branches
  GitProc::GitBranches.new(self, :remote => true)
end

#remove(files, opts = {}) ⇒ Object



444
445
446
447
448
449
# File 'lib/git-process/git_lib.rb', line 444

def remove(files, opts = {})
  args = []
  args << '-f' if opts[:force]
  args << [*files]
  command(:rm, args)
end

#reset(rev_name, opts = {}) ⇒ Object



467
468
469
470
471
472
473
474
475
# File 'lib/git-process/git_lib.rb', line 467

def reset(rev_name, opts = {})
  args = []
  args << '--hard' if opts[:hard]
  args << rev_name

  logger.info { "Resetting #{opts[:hard] ? '(hard)' : ''} to #{rev_name}" }

  command(:reset, args)
end

#rev_list(start_revision, end_revision, opts = {}) ⇒ Object



478
479
480
481
482
483
484
# File 'lib/git-process/git_lib.rb', line 478

def rev_list(start_revision, end_revision, opts ={})
  args = []
  args << "-#{opts[:num_revs]}" if opts[:num_revs]
  args << '--oneline' if opts[:oneline]
  args << "#{start_revision}..#{end_revision}"
  command('rev-list', args)
end

#rev_parse(name) ⇒ Object Also known as: sha



487
488
489
# File 'lib/git-process/git_lib.rb', line 487

def rev_parse(name)
  command('rev-parse', name)
end

#show(refspec) ⇒ Object



408
409
410
# File 'lib/git-process/git_lib.rb', line 408

def show(refspec)
  command(:show, refspec)
end

#stash_popObject



403
404
405
# File 'lib/git-process/git_lib.rb', line 403

def stash_pop
  command(:stash, %w(pop))
end

#stash_saveObject



398
399
400
# File 'lib/git-process/git_lib.rb', line 398

def stash_save
  command(:stash, %w(save))
end

#statusStatus

Returns the status of the git repository.

Returns:

  • (Status)


456
457
458
# File 'lib/git-process/git_lib.rb', line 456

def status
  GitStatus.new(self)
end

#sync_control_file_exists?(branch_name) ⇒ Boolean

Returns:

  • (Boolean)


555
556
557
558
# File 'lib/git-process/git_lib.rb', line 555

def sync_control_file_exists?(branch_name)
  filename = sync_control_filename(branch_name)
  File.exist?(filename)
end

#workdirObject



71
72
73
# File 'lib/git-process/git_lib.rb', line 71

def workdir
  @workdir
end

#workdir=(dir) ⇒ Object



76
77
78
79
80
81
82
83
84
85
86
# File 'lib/git-process/git_lib.rb', line 76

def workdir=(dir)
  workdir = GitLib.find_workdir(dir)
  if workdir.nil?
    @workdir = dir
    logger.info { "Initializing new repository at #{dir}" }
    command(:init)
  else
    @workdir = workdir
    logger.debug { "Opening existing repository at #{dir}" }
  end
end

#write_sync_control_file(branch_name) ⇒ Object



515
516
517
518
519
520
# File 'lib/git-process/git_lib.rb', line 515

def write_sync_control_file(branch_name)
  latest_sha = rev_parse(branch_name)
  filename = sync_control_filename(branch_name)
  logger.debug { "Writing sync control file, #{filename}, with #{latest_sha}" }
  File.open(filename, 'w') { |f| f.puts latest_sha }
end