class GitRepo
  WORKING_DIR="#{Rails.root}/tmp/build-partition"

  class << self
    def inside_copy(cached_repo_name, ref = "master", submodules = false)
      # update local repo
      run! "cd #{WORKING_DIR}/#{cached_repo_name} && git fetch"

      Dir.mktmpdir(nil, WORKING_DIR) do |dir|
        Dir.chdir(dir) do
          # clone local repo (fast!)
          run! "git clone #{WORKING_DIR}/web-cache ."

          # checkout
          run! "git checkout #{ref}"
          run! "git submodule update --init" if submodules

          yield
        end
      end
    end

    def run!(cmd)
      unless system(cmd)
        raise "non-0 exit code #{$?} returned from [#{cmd}]"
      end
    end

    def create_working_dir
      FileUtils.mkdir_p(WORKING_DIR)
    end
  end
end

class GitRepo
  WORKING_DIR="#{Rails.root}/tmp/build-partition"

  class << self
    def inside_copy(cached_repo_name, ref = "master", submodules = false)
      cached_repo_path = File.join(WORKING_DIR, cached_repo_name)
      # update local repo
      run! "cd #{cached_repo_path} && git fetch && git submodule update --init"

      Dir.mktmpdir(nil, WORKING_DIR) do |dir|
        Dir.chdir(dir) do
          # clone local repo (fast!)
          run! "git clone #{cached_repo_path} ."

          run! "git checkout #{ref}"

          run! "git submodule init"
          # redirect the submodules to the cached_repo
          submodules = `git config --get-regexp "^submodule\\..*\\.url$"`
          submodules.each_line do |config_line|
            submodule_path = config_line.match(/submodule\.(.*?)\.url/)[1]
            `git config --replace-all submodule.#{submodule_path}.url "#{cached_repo_path}/#{submodule_path}"`
          end

          run! "git submodule update"

          yield
        end
      end
    end

    def run!(cmd)
      unless system(cmd)
        raise "non-0 exit code #{$?} returned from [#{cmd}]"
      end
    end

    def create_working_dir
      FileUtils.mkdir_p(WORKING_DIR)
    end
  end
end

Make the submodule support for inside_copy efficient
Make the submodule support for inside_copy efficient
