aboutsummaryrefslogtreecommitdiffstats
path: root/Library/Homebrew/cmd/versions.rb
blob: 5283d9cb3aba4bf0c2d501c80808fbc45fe5986a (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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
require 'formula'

module Homebrew extend self

  module Versions
    # yields version, sha for all versions in the git history
    def self.old_versions f
      yielded = []
      f.rev_list.each do |sha|
        version = f.version_for_sha sha
        unless yielded.include? version or version.nil?
          yield version, sha
          yielded << version
        end
      end
    end
  end

  def versions
    raise "Please `brew install git` first" unless system "/usr/bin/which -s git"

    ARGV.formulae.all? do |f|
      old_versions = Versions.old_versions f do |version, sha|
        print Tty.white
        print "#{version.ljust(8)} "
        print Tty.reset
        puts "git checkout #{sha} #{f.pretty_relative_path}"
      end
    end
  end

end


class Formula
  def rev_list
    Dir.chdir HOMEBREW_REPOSITORY do
      `git rev-list --abbrev-commit HEAD Library/Formula/#{name}.rb`.split
    end
  end

  def sha_for_version version
    revlist.find{ |sha| version == version_for(sha) }
  end

  def version_for_sha sha
    # TODO really we should open a new ruby instance and parse the formula
    # class and then get the version but this would be too slow (?)

    code = Dir.chdir(HOMEBREW_REPOSITORY) do
      `git show #{sha}:Library/Formula/#{name}.rb`
    end

    version = code.match(/class #{Formula.class_s name} < ?Formula.*?(?:version\s|@version\s*=)\s*(?:'|")(.+?)(?:'|").*?end\s/m)
    return version[1] unless version.nil?

    url = code.match(/class #{Formula.class_s name} < ?Formula.*?(?:url\s|@url\s*=)\s*(?:'|")(.+?)(?:'|").*?end\s/m)
    unless url.nil?
      version = Pathname.new(url[1]).version
      return version unless version.to_s.empty?
    end

    head = code.match(/class #{Formula.class_s name} < ?Formula.*?head\s'(.*?)'.*?end\s\s/m)
    return 'HEAD' unless head.nil?

    opoo "Version of #{name} could not be determined for #{sha}."
  end

  def pretty_relative_path
    if Pathname.pwd == HOMEBREW_REPOSITORY
      "Library/Formula/#{name}.rb"
    else
      "#{HOMEBREW_REPOSITORY}/Library/Formula/#{name}.rb"
    end
  end
end