Sha256: 163c4c1c9ee7a5163b379eae96fce1e16c63c96e721c74c15ae98450d518c560

Contents?: true

Size: 1.92 KB

Versions: 1

Compression:

Stored size: 1.92 KB

Contents

require 'shellwords'
require 'pathname'

class InvocaGems::GitRepo
  # Encapsulates running git commands in a given directory

  include InvocaGems::ShellCommand
  attr_accessor :presenter

  def initialize(presenter, repo_root = nil)
    @presenter = presenter
    @repo_root = Pathname.new(repo_root ||  Dir.pwd)
  end

  def branch
    git_cmd('rev-parse --abbrev-ref HEAD')
  end

  def sha
    git_cmd("rev-parse --verify HEAD")
  end

  def uri
    git_cmd("config --get remote.origin.url")
  end

  def fetch
    git_cmd("fetch")
  end

  def commit(message)
    git_cmd("add -A")
    git_cmd("commit -m #{Shellwords.escape(message)}")
  end

  def is_ancestor_commit?(earlier_sha, current_sha)
    git_cmd("merge-base --is-ancestor #{earlier_sha} #{current_sha}", raise_errors: false)
  end


  def branch_exists?(branch_name)
    branch_name_escaped = Regexp.escape(branch_name)
    if result = git_cmd("branch -a")
      result.split("\n").any? do |branch_line|
        branch_line =~ / #{branch_name_escaped}\z/ || branch_line =~ / remotes\/origin\/#{branch_name_escaped}\z/
      end
    end
  end

  def checkout_branch(branch_name)
    git_cmd("checkout #{branch_name}")
  end


  def self.clone(root_directory, uri, directory_name, presenter:)
    git_cmd(root_directory, "clone #{uri} #{directory_name}", presenter: presenter)
  end

  def unsaved_changes?
    !git_cmd("diff --quiet", raise_errors: false) || !git_cmd("diff --quiet --cached", raise_errors: false)
  end

  def create_branch_at(branch_name, sha)
    git_cmd("branch #{branch_name} #{sha}")
  end

  def push
    git_cmd("push -u origin #{branch}")
  end


  def self.git_cmd(path, str, raise_errors: true, presenter: )
    shell_command(command: "/usr/bin/git #{str}", path: path, raise_errors: raise_errors, presenter: presenter)
  end

  def git_cmd(str, raise_errors: true)
    self.class.git_cmd(@repo_root, str, raise_errors: raise_errors, presenter: presenter)
  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
invoca_gems-0.1.0 lib/invoca_gems/git_repo.rb