aboutsummaryrefslogtreecommitdiffstats
path: root/lib/bundler/lockfile_parser.rb
blob: 572791d8bb6517f0fdd322ae81b1ce3337929943 (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
77
78
79
require "strscan"

module Bundler
  class LockfileParser
    attr_reader :sources, :dependencies, :specs

    # Do stuff
    def initialize(lockfile)
      @sources = []
      @dependencies = []
      @specs = []

      lockfile.split(/\n+/).each do |line|
        case line
        when "sources:"
          @state = :source
        when "dependencies:"
          @state = :dependencies
        when "specs:"
          @state = :specs
        else
          send("parse_#{@state}", line)
        end
      end
    end

  private

    TYPES = {
      "git"  => Bundler::Source::Git,
      "gem"  => Bundler::Source::Rubygems,
      "path" => Bundler::Source::Path
    }

    def parse_source(line)
      @sources << parse_source_line(line)
    end

    def parse_source_line(line)
      type, source, option_line = line.match(/^\s+(\w+): ([^\s]*?)(?: (.*))?$/).captures
      options = extract_options(option_line)
      TYPES[type].from_lock(source, options)
    end

    NAME_VERSION = '(?! )(.*?)(?: \((.*)\))?:?'

    def parse_dependencies(line)
      if line =~ %r{^ {2}#{NAME_VERSION}$}
        name, version = $1, $2

        @current = Bundler::Dependency.new(name, version)
        @dependencies << @current
      else
        @current.source = parse_source_line(line)
      end
    end

    def parse_specs(line)
      if line =~ %r{^ {2}#{NAME_VERSION}$}
        @current = LazySpecification.new($1, $2)
        @specs << @current
      else
        line =~ %r{^ {4}#{NAME_VERSION}$}
        @current.dependencies << Gem::Dependency.new($1, $2)
      end
    end

    def extract_options(line)
      options = {}
      return options unless line

      line.scan(/(\w+):"((?:|.*?[^\\])(?:\\\\)*)" ?/) do |k,v|
        options[k] = v
      end

      options
    end
  end
end