Skip to content
Snippets Groups Projects
repository.rb 1.2 KiB
Newer Older
Arnaud Levy's avatar
Arnaud Levy committed
class Git::Repository
Arnaud Levy's avatar
Arnaud Levy committed
  attr_reader :website, :commit_message
Arnaud Levy's avatar
Arnaud Levy committed

Sébastien Gaya's avatar
Sébastien Gaya committed
  def initialize(website)
    @website = website
Arnaud Levy's avatar
Arnaud Levy committed
  end

Arnaud Levy's avatar
Arnaud Levy committed
  def add_git_file(git_file)
    if git_files.empty?
      action = git_file.should_destroy? ? "Destroy" : "Save"
      @commit_message = "[#{ git_file.about.class.name }] #{ action } #{ git_file.about }"
    end
Arnaud Levy's avatar
Arnaud Levy committed
    git_files << git_file
  end

  def sync!
    return if git_files.empty?
    sync_git_files
Arnaud Levy's avatar
Arnaud Levy committed
    mark_as_synced if provider.push(commit_message)
Arnaud Levy's avatar
Arnaud Levy committed
  end

Arnaud Levy's avatar
Arnaud Levy committed
  def git_sha(path)
    provider.git_sha path
  end

Arnaud Levy's avatar
Arnaud Levy committed
  protected

Arnaud Levy's avatar
Arnaud Levy committed
  # TODO add gitlab
Arnaud Levy's avatar
Arnaud Levy committed
  def provider
Arnaud Levy's avatar
Arnaud Levy committed
    @provider ||= Git::Providers::Github.new(website&.access_token, website&.repository)
Arnaud Levy's avatar
Arnaud Levy committed
  end

Arnaud Levy's avatar
Arnaud Levy committed
  def git_files
    @git_files ||= []
  end

  def sync_git_files
Arnaud Levy's avatar
Arnaud Levy committed
    git_files.each do |file|
      if file.should_create?
        provider.create_file file.path, file.to_s
      elsif file.should_update?
        provider.update_file file.path, file.previous_path, file.to_s
      elsif file.should_destroy?
Arnaud Levy's avatar
Arnaud Levy committed
        provider.destroy_file file.previous_path
Arnaud Levy's avatar
Arnaud Levy committed
      end
Arnaud Levy's avatar
Arnaud Levy committed
    end
  end

Arnaud Levy's avatar
Arnaud Levy committed
  def mark_as_synced
    git_files.each do |git_file|
      git_file.update_columns previous_path: git_file.path, previous_sha: git_file.sha
Sébastien Gaya's avatar
Sébastien Gaya committed
    end
  end
Arnaud Levy's avatar
Arnaud Levy committed
end