summaryrefslogtreecommitdiff
path: root/lib/jive/repo.rb
blob: 8b3c78324132c9c7f99904d0f25843d77216abc7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# frozen_string_literal: true

module Jive
  class Repo
    SSH_REGEX = %r{\Agit@(?<host>.+):(?<account>.+)/(?<repo>.+)\z}.freeze

    def initialize(path)
      @repo = Rugged::Repository.new(path.to_s)
    end

    def uri
      @uri ||= URI.parse(canonical_url)
    end

    def canonical_url
      remote = @repo.remotes.find { |x| x.name == "origin" }
      return if remote.nil?

      ssh?(remote) ? url_for_ssh(remote) : url_for(remote)
    end

    def nwo
      segments = uri.path.split("/")
      "#{segments[1]}/#{segments[2].gsub(".git", "")}"
    end

    def branch
      uri.path[1..-1]
    end

    class << self
      def current
        @current ||= new(Pathname.pwd)
      end
    end

    private

    def ssh?(remote)
      remote.url.match?(SSH_REGEX)
    end

    def url_for_ssh(remote)
      match = remote.url.match(SSH_REGEX)
      [
        "https:/",
        match[:host],
        match[:account],
        match[:repo],
        @repo.head.name
      ].join("/")
    end

    def url_for(remote)
      uri = URI.parse(remote.url)
      [uri.host, uri.path, @repo.head.name].join("/")
    end
  end
end