class Raykit::Git::Repository

Functionality to manage a remote git repository

def self.backup(url, backup_dir)

def self.backup(url, backup_dir)
  if (Dir.exist?(backup_dir))
    Dir.chdir(backup_dir) do
      run("git pull")
    end
  else
    run("git clone #{url} \"#{backup_dir}\"")
  end
end # def self.backup

def self.get_relative_path(url)

def self.get_relative_path(url)
  uri = URI.parse(url)
  # Remove top-level domain (e.g., ".com")

  if (uri.host.nil?)
    puts "uri.host is nil for #{url}"
  end
  host = uri.host.split(".")[0]
  #host.pop # remove the last element which should be the top-level domain

  #host = host.join(".")

  # Remove scheme (e.g., "http" or "https")

  path = host + uri.path
  # Remove top-level domain (e.g., ".com")

  #path = path.split(".")

  #path.pop # remove the last element which should be the top-level domain

  #path = path.join(".")

  # Remove trailing ".git" if present

  path = path.chomp(".git")
  path
end

def self.make_url(url, commit_id, command)

def self.make_url(url, commit_id, command)
  repo = Raykit::Git::Repository.new(url)
  puts "  make #{url} #{commit_id} #{command}"
  make_dir = Raykit::Environment::normalize_path(repo.get_dev_dir("make") + "/" + commit_id)
  FileUtils.mkdir_p(repo.get_dev_dir("make")) if !Dir.exist?(repo.get_dev_dir("make"))
  if (Dir.exist?(make_dir))
    FileUtils.rm_rf(make_dir)
  end
  run("git clone #{url} #{make_dir}")
  cmd = 0
  Dir.chdir(make_dir) do
    run("git reset --hard #{commit_id}")
    FileUtils.rm_rf(".git")
    cmd = Raykit::Command.new(command)
    cmd = cmd.run().summary()
  end
  FileUtils.rm_rf(make_dir) if (cmd.exitstatus == 0)
  cmd
end

def self.parse(json)

def self.parse(json)
  hash = JSON.parse(json)
  Repository.new(hash["url"])
end

def self.work_integrate(url)

def self.work_integrate(url)
  repo = Raykit::Git::Repository.new(url)
  work_dir = repo.get_dev_dir("work")
  repo.clone(work_dir) if !Dir.exist?(work_dir)
  Dir.chdir(work_dir) do
    run("git pull")
    run("rake integrate")
  end
end

def self.work_pull(url)

def self.work_pull(url)
  repo = Raykit::Git::Repository.new(url)
  work_dir = repo.get_dev_dir("work")
  repo.clone(work_dir) if !Dir.exist?(work_dir)
  Dir.chdir(work_dir) do
    run("git pull")
  end
end

def self.work_url(url, cmd)

def self.work_url(url, cmd)
  repo = Raykit::Git::Repository.new(url)
  puts "  work #{url} #{cmd}"
  work_dir = repo.get_dev_dir("work")
  repo.clone(work_dir) if !Dir.exist?(work_dir)
  Dir.chdir(work_dir) do
    #run("git pull")

    cmd = Raykit::Command.new(cmd)
    cmd = cmd.run().summary().details()
    cmd
  end
end

def branches

The branches for the git repository
def branches
  results = []
  update_local_clone_directory
  if Dir.exist?(local_clone_directory)
    Dir.chdir(local_clone_directory) do
      `git branch`.split('\n').each do |line|
        branch = line.gsub("*", "").strip
        results.insert(-1, branch) if branch.length.positive?
      end
    end
  end
  results
end

def checkout_local_clone_directory_branch(branch)

def checkout_local_clone_directory_branch(branch)
_local_clone_directory
.exist?(local_clone_directory)
chdir(local_clone_directory) do
eck = `git branch`
= `git checkout #{branch}` unless check.include?("* #{branch}")
eck = `git branch`
turn check.include?("* #{branch}")

def clobber

def clobber
  ["work", "clone", "make"].each { |d|
    dir = get_dev_dir(d)
    if (Dir.exist?(dir))
      begin
        puts "  deleting #{dir}"
        FileUtils.rm_rf(dir)
        FileUtils.rm(dir) if (Dir.exist?(dir))
      rescue
        puts "  problem while deleting #{dir}"
      end
    end
  }
end

def clone(directory, depth = 0)

Clone the repository to a specific directory
def clone(directory, depth = 0)
  if depth.zero?
    PROJECT.run("git clone #{@url} #{directory}")
  else
    PROJECT.run("git clone #{@url} #{directory} --depth #{depth}")
  end
end

def default_branch

default branch
def default_branch
  update_local_clone_directory
  if Dir.exist?(local_clone_directory)
    Dir.chdir(local_clone_directory) do
      # refs/remotes/origin/master

      default_branch = `git symbolic-ref refs/remotes/origin/HEAD`.split("/").last.strip
      return default_branch
    end
  end
  "main"
end

def filename

def filename
  Environment.get_dev_dir("data") + File::SEPARATOR + "repository" + File::SEPARATOR + Raykit::FileSystem::replace_invalid_chars(relative_path.gsub("/", ".").gsub("\\", ".")) + ".json"
end

def get_dev_dir(dir)

def get_dev_dir(dir)
  dev_dir = Environment.get_dev_dir(dir)
  Raykit::Environment::normalize_path("#{dev_dir}/#{relative_path}")
end

def get_make_command(commit_id, command)

def get_make_command(commit_id, command)
  make_id = "make_#{relative_path.gsub("/", "-")}_#{commit_id}"
  fcommand = Raykit::FileSystem::replace_invalid_chars(command)
  filename = "#{Raykit::Environment::log_dir}/#{make_id}_#{fcommand}.json"
  return Raykit::Command::parse(IO.read(filename)) if (File.exist?(filename))
  nil
end

def initialize(url)

def initialize(url)
  if (url.nil? || url.empty?)
    raise "Raykit::Git::Repository::initialize(url), url is nil or empty!"
  end
  @url = url
  @clone_directory = Raykit::Git::Directory.new(get_dev_dir("clone"))
  @work_directory = Raykit::Git::Directory.new(get_dev_dir("work"))
  load
end

def latest_commit(branch)

The latest commit id for a branch of the repostiory
def latest_commit(branch)
  if checkout_local_clone_directory_branch(branch)
    update_local_clone_directory
    Dir.chdir(local_clone_directory) do
      text = `git log -n 1`
      scan = text.scan(/commit (\w+)\s/)
      return scan[0][0].to_s
    end
  end
  ""
end

def latest_commit_date(branch)

def latest_commit_date(branch)
  if checkout_local_clone_directory_branch(branch)
    update_local_clone_directory
    Dir.chdir(local_clone_directory) do
      text = `git log -n 1`
      scan = text.scan(/Date:\s+(.*)/)
      return scan[0][0].to_s
    end # Dir.chdir

  end # if checkout_local_clone_directory_branch

  ""
end

def latest_tag(branch)

The latest tag for a branch of the repository
def latest_tag(branch)
  return `git describe --abbrev=0`.strip if checkout_local_clone_directory_branch(branch)
  ""
end

def load

def load
  if (File.exist?(filename))
    data = JSON.parse(File.read(filename))
    @latest_commit_id = data["latest_commit_id"]
    @latest_commit_exit_status = data["latest_commit_exit_status"]
  end
end

def local_clone_directory

def local_clone_directory
dir = Environment::normalize_path("#{Environment.get_dev_dir("clone")}/#{relative_path}")

def make(command, force = false)

def make(command, force = false)
  commit_id = "#{latest_commit(default_branch)}"
  make_id = "make_#{relative_path.gsub("/", "-")}_#{commit_id}"
  fcommand = Raykit::FileSystem::replace_invalid_chars(command)
  filename = "#{Raykit::Environment::log_dir}/#{make_id}_#{fcommand}.json"
  if (!force && File.exist?(filename))
    return Raykit::Command::parse(IO.read(filename))
  else
    make_cmd = Raykit::Git::Repository::make_url(url, commit_id, "rake default")
    make_cmd.save_as(filename)
    update
    return make_cmd
  end
end

def pull

def pull
  #repo = Raykit::Git::Repository.new(url)

  #work_dir = repo.get_dev_dir("work")

  #repo.clone(work_dir) if !Dir.exist?(work_dir)

  Raykit::Git::Repository::work_pull(url)
  update_local_clone_directory
end

def relative_path

The relative path is a valid local path name derived from the url
def relative_path
  Repository::get_relative_path(@url)
  #@url.gsub("https://", "").gsub(".git", "").gsub("http://", "")

end

def save

def save
  # Create the config directory if it doesn't exist.

  dir = File.dirname(filename)
  FileUtils.mkdir_p(dir) unless Dir.exist?(dir)
  File.write(filename, {
    latest_commit_id: @latest_commit_id,
    latest_commit_exit_status: @latest_commit_exit_status,
  }.to_json)
end

def short_name()

def short_name()
  @url.split("/").last.gsub(".git", "")
end

def to_json(*_args)

def to_json(*_args)
  JSON.generate({ "url" => @url })
end

def to_s

def to_s
  #short_name

  latest_commit_id = @latest_commit_id.nil? ? "" : @latest_commit_id # latest_commit(default_branch)

  latest_commit_exit_status = @latest_commit_exit_status.nil? ? nil : @latest_commit_exit_status # latest_commit(default_branch)

  symbol = Raykit::Symbols::warning
  symbol = Raykit::Symbols::success if (!latest_commit_exit_status.nil? && latest_commit_exit_status == 0)
  symbol = Raykit::Symbols::success if (!latest_commit_exit_status.nil? && latest_commit_exit_status != 0)
  #latest_make_cmd = get_make_command(latest_commit_id, "rake default")

  #commit = Rainbow(latest_commit(default_branch)[0..8]).cyan

  #if (latest_make_cmd.nil?)

  #  symbol = Raykit::Symbols::warning

  #else

  #  symbol = latest_make_cmd.exitstatus == 0 ? Raykit::Symbols::success : Raykit::Symbols::error

  #end

  commit = latest_commit_id[0..8]
  "#{symbol} #{commit} #{short_name}"
end # def to_s

def to_table

def to_table
  #max_name_width = 10

  #max_value_width = 10

  #header = "  =".ljust(max_name_width + max_value_width + 5, "=")

  header = "==Repository=="
  table = header
  table += "\n" + to_table_row("Name", short_name)
  table += "\n" + to_table_row("Url", @url)
  table += "\n" + to_table_row("Default Branch", default_branch)
  table += "\n" + to_table_row("Latest Commit", latest_commit(default_branch))
  table += "\n" + to_table_row("Latest Commit Date", latest_commit_date(default_branch))
  table += "\n" + to_table_row("Latest Commit Make", make("rake default").summary(false))
  table += "\n" + to_table_row("Clone Directory", local_clone_directory)
  table += "\n" + to_table_row("Work Directory", get_dev_dir("work"))
  table += "\n" + to_table_row("Latest Tag", latest_tag(default_branch))
  table
end # def to_table

def to_table_row(name, value)

def to_table_row(name, value)
  max_name_width = 20
  max_value_width = 30
  Rainbow(name.rjust(max_name_width, " ")).cyan + " | " + Rainbow(value).white.bold
end

def update

def update
  @latest_commit_id = latest_commit(default_branch)
  if (@latest_commit_id.nil? || @latest_commit_id.empty?)
    cmd = get_make_command(@latest_commit_id, "rake default")
    if (!cmd.nil?)
      @latest_commit_exit_status = cmd.exitstatus
    end
  end
  save
end

def update_local_clone_directory

def update_local_clone_directory
r.exist?(local_clone_directory)
.chdir(local_clone_directory) do
ull = Raykit::Command.new("git pull")
ull.run
ull
 t = `git pull`


JECT.run("git clone #{@url} #{local_clone_directory}")

def work(command, force = false)

def work(command, force = false)
  pull if (!Dir.exist?(get_dev_dir("work")))
  fcommand = Raykit::FileSystem::replace_invalid_chars(command)
  filename = "#{Raykit::Environment::log_dir}/work_#{fcommand}_#{relative_path.gsub("/", "-")}.json"
  if (Raykit::Git::Directory.new(get_dev_dir("work")).outstanding_commit? || force)
    puts "  outstanding commit in #{get_dev_dir("work")}"
    work_cmd = Raykit::Git::Repository::work_url(url, command)
    work_cmd.save_as(filename)
    return work_cmd
  else
    if (File.exist?(filename))
      return Raykit::Command::parse(IO.read(filename))
    else
      work_cmd = Raykit::Git::Repository::work_url(url, command)
      work_cmd.save_as(filename)
      update
    end
    #

  end
end