module Spoom::Git

def self.checkout(*arg, path: ".")

def self.checkout(*arg, path: ".")
  exec("git checkout -q #{arg.join(' ')}", path: path)
end

def self.commit_time(sha, path: ".")

def self.commit_time(sha, path: ".")
  timestamp = commit_timestamp(sha, path: path)
  return nil unless timestamp
  epoch_to_time(timestamp.to_s)
end

def self.commit_timestamp(sha, path: ".")

def self.commit_timestamp(sha, path: ".")
  out, _, status = show("--no-notes --no-patch --pretty=%at #{sha}", path: path)
  return nil unless status
  out.strip.to_i
end

def self.diff(*arg, path: ".")

def self.diff(*arg, path: ".")
  exec("git diff #{arg.join(' ')}", path: path)
end

def self.epoch_to_time(timestamp)

def self.epoch_to_time(timestamp)
  Time.strptime(timestamp, "%s")
end

def self.exec(command, *arg, path: '.')

def self.exec(command, *arg, path: '.')
  return "", "Error: `#{path}` is not a directory.", false unless File.directory?(path)
  opts = {}
  opts[:chdir] = path
  _, o, e, s = Open3.popen3(*T.unsafe([command, *T.unsafe(arg), opts]))
  out = o.read.to_s
  o.close
  err = e.read.to_s
  e.close
  [out, err, T.cast(s.value, Process::Status).success?]
end

def self.last_commit(path: ".")

def self.last_commit(path: ".")
  out, _, status = rev_parse("HEAD", path: path)
  return nil unless status
  out.strip
end

def self.log(*arg, path: ".")

def self.log(*arg, path: ".")
  exec("git log #{arg.join(' ')}", path: path)
end

def self.rev_parse(*arg, path: ".")

def self.rev_parse(*arg, path: ".")
  exec("git rev-parse --short #{arg.join(' ')}", path: path)
end

def self.show(*arg, path: ".")

def self.show(*arg, path: ".")
  exec("git show #{arg.join(' ')}", path: path)
end

def self.sorbet_intro_commit(path: ".")

def self.sorbet_intro_commit(path: ".")
  res, _, status = Spoom::Git.log("--diff-filter=A --format='%h' -1 -- sorbet/config", path: path)
  return nil unless status
  res.strip
end

def self.workdir_clean?(path: ".")

def self.workdir_clean?(path: ".")
  diff("HEAD", path: path).first.empty?
end