lib/raykit/sourceImport.rb



# frozen_string_literal: true


module Raykit
  class SourceImport < Hash
    def initialize(url, source, glob, target, commit)
      self["remote"] = url
      self["source"] = source
      self["glob"] = glob
      self["target"] = target
      self["commit"] = commit
    end

    def remote
      self["remote"]
    end

    def source
      self["source"]
    end

    def target
      self["target"]
    end

    def glob
      self["glob"]
    end

    def update
      work = self["remote"].work_dir
      work_parent = File.dirname(work)
      FileUtils.mkdir_p(work_parent) unless Dir.exist?(work_parent)
      if Dir.exist?(work)
        Dir.chdir(work) do
          cmd = Command.new("git pull")
        end
      else
        PROJECT.run("git clone #{remote} #{work}")
      end

      Dir.chdir(work) do
        text = `git log -n 1`
        scan = text.scan(/commit (\w+)\s/)
        self["commit"] = scan[0][0].to_s
      end
    end

    def copy
      if target.length.zero?
        puts "target has not been specified"
      else
        FileUtils.remove_dir(target) if Dir.exist?(target)
        count = 0
        source_names = []
        work = self["remote"].work_dir
        Dir.chdir(work) do
          cmd = Command.new("rake clean") if File.exist?("rakefile.rb")
          Dir.chdir(source) do
            source_names = Dir.glob(self["glob"])
          end
        end
        source_names.each do |source_name|
          source_file = "#{work}/#{source}/#{source_name}"
          target_name = "#{target}/#{source_name}"
          target_parent = File.dirname(target_name)
          FileUtils.mkdir_p(target_parent) unless Dir.exist?(target_parent)
          FileUtils.copy(source_file, target_name)
          count += 1
        end
        puts "        copied #{count} files to #{target}"
      end
    end
  end
end