# frozen_string_literal: true require_relative 'asset_type' require 'singleton' module KCommercial module Resources class GitSourceManager include Singleton # The shared manager # @return [CocoaDepot::Resources::GitSourceManager] def self.shared GitSourceManager.instance end attr_reader :repos_dir def home_dir @home_dir ||= Pathname.new(ENV['CP_HOME_DIR'] || '~/.cocoadepot-resources').expand_path @home_dir.mkpath unless @home_dir.exist? @home_dir end def repos_dir @repos_dir ||= home_dir.join('repos') @repos_dir.mkpath unless @repos_dir.exist? @repos_dir end def sources @sources ||= {} end # Get the git source with name or url # @param [String] url # @return [GitSource] def source_with_url(url) name = name_for_url(url) sources[name] ||= begin path = repos_dir.join(name) GitSource.new(url, path) end sources[name] end # Returns a suitable repository name for `url`. # # @example A GitHub.com URL # # name_for_url('https://github.com/Artsy/Specs.git') # # "artsy" # name_for_url('https://github.com/Artsy/Specs.git') # # "artsy-1" # # @example A non-Github.com URL # # name_for_url('https://sourceforge.org/Artsy/Specs.git') # # sourceforge-artsy-specs # # @example A file URL # # name_for_url('file:///Artsy/Specs.git') # # artsy-specs # # @param [#to_s] url # The URL of the source. # # @return [String] A suitable repository name for `url`. # def name_for_url(url) base_from_host_and_path = lambda do |host, path| if host && !host.empty? base = host.split('.')[-2] || host base += '-' else base = '' end base + path.gsub(/.git$/, '').gsub(%r{^/}, '').split('/').join('-') end case url.to_s.downcase when %r{github.com[:/]+(.+)/(.+)} base = Regexp.last_match[1] when %r{^\S+@(\S+)[:/]+(.+)$} host, path = Regexp.last_match.captures base = base_from_host_and_path[host, path] when URI.regexp url = URI(url.downcase) base = base_from_host_and_path[url.host, url.path] else base = url.to_s.downcase end name = base # infinity = 1.0 / 0 # (1..infinity).each do |i| # break unless source_dir(name).exist? # name = "#{base}-#{i}" # end name end # @return [Pathname] The path of the source with the given name. # # @param [String] name # The name of the source. # def source_dir(name) repos_dir + name end end end end