Module: JayAPI::Git::Gerrit::GitilesHelper

Defined in:
lib/jay_api/git/gerrit/gitiles_helper.rb

Overview

Offers a set of utility methods to work with Gerrit’s Gitiles URLs.

Constant Summary collapse

GITILES_PATH =
'/plugins/gitiles/'
GITILES_REFSPEC =
'/+/%<refspec>s'

Instance Method Summary collapse

Instance Method Details

#gitiles_url(repository:, refspec:, path: nil, line_number: nil) ⇒ String

Returns a Gitiles URL for the given parameters

Parameters:

  • repository (String)

    The URL of the git repository.

  • refspec (String)

    The name of a branch or the SHA1 of a particular commit.

  • path (String, nil) (defaults to: nil)

    The path to the source file. If nil is given a link to the refspec itself is will be created.

  • line_number (Integer, String, nil) (defaults to: nil)

    The line number. Ignored when path is nil.

Returns:

  • (String)

    The corresponding Gitiles URL.



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/jay_api/git/gerrit/gitiles_helper.rb', line 22

def gitiles_url(repository:, refspec:, path: nil, line_number: nil)
  # NOTE: Here File.join is being used because it takes care of cases in
  # which both strings have slash (/) at their tips and removes the double
  # slash, for example:
  #
  #   ['https://example.com/', '/path/to/file'].join('/') => https://example.com///path/to/file
  #   File.join('https://example.com/', '/path/to/file') => https://example.com/path/to/file
  #
  # Do not use URL.join because it interprets a slash at the beginning
  # of the second string as a reference to the URL's root:
  #
  #   URI.join('https://www.example.com/hello/world', '/again') => https://www.example.com/again

  fragments = [
    gerrit_urls_cache[repository] ||= translate_gerrit_url(repository),
    format(GITILES_REFSPEC, refspec: refspec)
  ]

  # If there is no line number the # will not appear in the URL
  fragments << [path, line_number].compact.join('#') if path

  File.join(*fragments)
end

#translate_gerrit_url(url) ⇒ String

Translates a Gerrit repository URL into a Gerrit Gitiles URL for that repository, for example:

ssh://[email protected]:29418/tools/elite becomes

https://gerrit.local/plugins/gitiles/tools/elite

Parameters:

  • url (String)

    Gerrit’s repository URL

Returns:

  • (String)

    The corresponding Gitiles URL



53
54
55
56
57
# File 'lib/jay_api/git/gerrit/gitiles_helper.rb', line 53

def translate_gerrit_url(url)
  uri = URI.parse(url)
  path = uri.path.sub(%r{^/a/}, '/') # Removes the /a/ at the beginning of HTTP/S repository URLs
  URI::HTTPS.build(host: uri.host, path: File.join(GITILES_PATH, path)).to_s
end