Sha256: 9af8c581a627476b7fa903627d4b514e03b92eeee78672aad30d31f2b686296f

Contents?: true

Size: 1.42 KB

Versions: 3

Compression:

Stored size: 1.42 KB

Contents

module Octodmin::Controllers::Syncs
  class Create
    include Octodmin::Action
    expose :message

    def call(params)
      self.format = :json

      site = Octodmin::Site.new
      git = Git.open(Octodmin::App.dir)

      # Add posts only to commit stage
      stage(site, git)

      # Compute staged paths
      staged = paths(site, git)

      # Pull changes
      git.pull

      # Commit and push changes if any
      if staged.any?
        @message  = "Octodmin sync for #{staged.count} file#{"s" if staged.count > 1}"
        @message += "\n\n#{staged.join("\n")}"

        git.commit(@message)
        git.push
      else
        @message = "Everything is up-to-date"
      end
    rescue Git::GitExecuteError => e
      halt 400, JSON.dump(errors: [e.message])
    ensure
      git.reset(".")
    end

    private

    def stage(site, git)
      deleted = site.status.deleted.keys.map { |path| File.join(Octodmin::App.dir, path) }

      site.posts.each do |post|
        path = File.join(site.source, post.path)
        git.add(path) unless deleted.include?(path)
      end
    end

    def paths(site, git)
      status = site.reset.status

      paths = (
        status.changed.keys +
        status.added.keys +
        status.deleted.keys
      ).map { |path| File.join(Octodmin::App.dir, path) }

      site.posts.select do |post|
        paths.any? { |path| path.end_with?(post.path) }
      end.map(&:path)
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
octodmin-0.2.1 app/controllers/syncs/create.rb
octodmin-0.2.0 app/controllers/syncs/create.rb
octodmin-0.1.0 app/controllers/syncs/create.rb