~ubuntu-branches/ubuntu/trusty/ruby1.9/trusty

« back to all changes in this revision

Viewing changes to lib/rubygems/source_index.rb

  • Committer: Bazaar Package Importer
  • Author(s): Stephan Hermann
  • Date: 2008-01-24 11:42:29 UTC
  • mfrom: (1.1.9 upstream)
  • Revision ID: james.westby@ubuntu.com-20080124114229-jw2f87rdxlq6gp11
Tags: 1.9.0.0-2ubuntu1
* Merge from debian unstable, remaining changes:
  - Robustify check for target_os, fixing build failure on lpia.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#--
 
2
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
 
3
# All rights reserved.
 
4
# See LICENSE.txt for permissions.
 
5
#++
 
6
 
 
7
require 'rubygems'
 
8
require 'rubygems/user_interaction'
 
9
require 'rubygems/specification'
 
10
 
 
11
module Gem
 
12
 
 
13
  # The SourceIndex object indexes all the gems available from a
 
14
  # particular source (e.g. a list of gem directories, or a remote
 
15
  # source).  A SourceIndex maps a gem full name to a gem
 
16
  # specification.
 
17
  #
 
18
  # NOTE:: The class used to be named Cache, but that became
 
19
  #        confusing when cached source fetchers where introduced. The
 
20
  #        constant Gem::Cache is an alias for this class to allow old
 
21
  #        YAMLized source index objects to load properly.
 
22
  #
 
23
  class SourceIndex
 
24
 
 
25
    include Enumerable
 
26
 
 
27
    include Gem::UserInteraction
 
28
 
 
29
    # Class Methods. -------------------------------------------------
 
30
    class << self
 
31
      include Gem::UserInteraction
 
32
    
 
33
      # Factory method to construct a source index instance for a given
 
34
      # path.
 
35
      #
 
36
      # deprecated::
 
37
      #   If supplied, from_installed_gems will act just like
 
38
      #   +from_gems_in+.  This argument is deprecated and is provided
 
39
      #   just for backwards compatibility, and should not generally
 
40
      #   be used.
 
41
      # 
 
42
      # return::
 
43
      #   SourceIndex instance
 
44
      #
 
45
      def from_installed_gems(*deprecated)
 
46
        if deprecated.empty?
 
47
          from_gems_in(*installed_spec_directories)
 
48
        else
 
49
          from_gems_in(*deprecated)
 
50
        end
 
51
      end
 
52
      
 
53
      # Return a list of directories in the current gem path that
 
54
      # contain specifications.
 
55
      # 
 
56
      # return::
 
57
      #   List of directory paths (all ending in "../specifications").
 
58
      #
 
59
      def installed_spec_directories
 
60
        Gem.path.collect { |dir| File.join(dir, "specifications") }        
 
61
      end
 
62
 
 
63
      # Factory method to construct a source index instance for a
 
64
      #   given path.
 
65
      # 
 
66
      # spec_dirs::
 
67
      #   List of directories to search for specifications.  Each
 
68
      #   directory should have a "specifications" subdirectory
 
69
      #   containing the gem specifications.
 
70
      #
 
71
      # return::
 
72
      #   SourceIndex instance
 
73
      #
 
74
      def from_gems_in(*spec_dirs)
 
75
        self.new.load_gems_in(*spec_dirs)
 
76
      end
 
77
      
 
78
      # Load a specification from a file (eval'd Ruby code)
 
79
      # 
 
80
      # file_name:: [String] The .gemspec file
 
81
      # return:: Specification instance or nil if an error occurs
 
82
      #
 
83
      def load_specification(file_name)
 
84
        begin
 
85
          spec_code = File.read(file_name).untaint
 
86
          gemspec = eval spec_code, binding, file_name
 
87
          if gemspec.is_a?(Gem::Specification)
 
88
            gemspec.loaded_from = file_name
 
89
            return gemspec
 
90
          end
 
91
          alert_warning "File '#{file_name}' does not evaluate to a gem specification"
 
92
        rescue SyntaxError => e
 
93
          alert_warning e
 
94
          alert_warning spec_code
 
95
        rescue Exception => e
 
96
          alert_warning(e.inspect.to_s + "\n" + spec_code)
 
97
          alert_warning "Invalid .gemspec format in '#{file_name}'"
 
98
        end
 
99
        return nil
 
100
      end
 
101
      
 
102
    end
 
103
 
 
104
    # Instance Methods -----------------------------------------------
 
105
 
 
106
    # Constructs a source index instance from the provided
 
107
    # specifications
 
108
    #
 
109
    # specifications::
 
110
    #   [Hash] hash of [Gem name, Gem::Specification] pairs
 
111
    #
 
112
    def initialize(specifications={})
 
113
      @gems = specifications
 
114
    end
 
115
    
 
116
    # Reconstruct the source index from the list of source
 
117
    # directories.
 
118
    def load_gems_in(*spec_dirs)
 
119
      @gems.clear
 
120
      specs = Dir.glob File.join("{#{spec_dirs.join(',')}}", "*.gemspec")
 
121
      specs.each do |file_name|
 
122
        gemspec = self.class.load_specification(file_name.untaint)
 
123
        add_spec(gemspec) if gemspec
 
124
      end
 
125
      self
 
126
    end
 
127
 
 
128
    # Returns a Hash of name => Specification of the latest versions of each
 
129
    # gem in this index.
 
130
    def latest_specs
 
131
      result, latest = Hash.new { |h,k| h[k] = [] }, {}
 
132
 
 
133
      self.each do |_, spec| # SourceIndex is not a hash, so we're stuck with each
 
134
        name = spec.name
 
135
        curr_ver = spec.version
 
136
        prev_ver = latest[name]
 
137
 
 
138
        next unless prev_ver.nil? or curr_ver >= prev_ver
 
139
 
 
140
        if prev_ver.nil? or curr_ver > prev_ver then
 
141
          result[name].clear
 
142
          latest[name] = curr_ver
 
143
        end
 
144
 
 
145
        result[name] << spec
 
146
      end
 
147
 
 
148
      result.values.flatten
 
149
    end
 
150
 
 
151
    # Add a gem specification to the source index.
 
152
    def add_spec(gem_spec)
 
153
      @gems[gem_spec.full_name] = gem_spec
 
154
    end
 
155
 
 
156
    # Remove a gem specification named +full_name+.
 
157
    def remove_spec(full_name)
 
158
      @gems.delete(full_name)
 
159
    end
 
160
 
 
161
    # Iterate over the specifications in the source index.
 
162
    def each(&block) # :yields: gem.full_name, gem
 
163
      @gems.each(&block)
 
164
    end
 
165
 
 
166
    # The gem specification given a full gem spec name.
 
167
    def specification(full_name)
 
168
      @gems[full_name]
 
169
    end
 
170
 
 
171
    # The signature for the source index.  Changes in the signature
 
172
    # indicate a change in the index.
 
173
    def index_signature
 
174
      require 'rubygems/digest/sha2'
 
175
 
 
176
      Gem::SHA256.new.hexdigest(@gems.keys.sort.join(',')).to_s
 
177
    end
 
178
 
 
179
    # The signature for the given gem specification.
 
180
    def gem_signature(gem_full_name)
 
181
      require 'rubygems/digest/sha2'
 
182
 
 
183
      Gem::SHA256.new.hexdigest(@gems[gem_full_name].to_yaml).to_s
 
184
    end
 
185
 
 
186
    def size
 
187
      @gems.size
 
188
    end
 
189
    alias length size
 
190
 
 
191
    # Find a gem by an exact match on the short name.
 
192
    def find_name(gem_name, version_requirement = Gem::Requirement.default)
 
193
      search(/^#{gem_name}$/, version_requirement)
 
194
    end
 
195
 
 
196
    # Search for a gem by Gem::Dependency +gem_pattern+.  If +only_platform+
 
197
    # is true, only gems matching Gem::Platform.local will be returned.  An
 
198
    # Array of matching Gem::Specification objects is returned.
 
199
    #
 
200
    # For backwards compatibility, a String or Regexp pattern may be passed as
 
201
    # +gem_pattern+, and a Gem::Requirement for +platform_only+.  This
 
202
    # behavior is deprecated and will be removed.
 
203
    def search(gem_pattern, platform_only = false)
 
204
      version_requirement = nil
 
205
      only_platform = false
 
206
 
 
207
      case gem_pattern # TODO warn after 2008/03, remove three months after
 
208
      when Regexp then
 
209
        version_requirement = platform_only || Gem::Requirement.default
 
210
      when Gem::Dependency then
 
211
        only_platform = platform_only
 
212
        version_requirement = gem_pattern.version_requirements
 
213
        gem_pattern = if gem_pattern.name.empty? then
 
214
                        //
 
215
                      else
 
216
                        /^#{Regexp.escape gem_pattern.name}$/
 
217
                      end
 
218
      else
 
219
        version_requirement = platform_only || Gem::Requirement.default
 
220
        gem_pattern = /#{gem_pattern}/i
 
221
      end
 
222
 
 
223
      unless Gem::Requirement === version_requirement then
 
224
        version_requirement = Gem::Requirement.create version_requirement
 
225
      end
 
226
 
 
227
      specs = @gems.values.select do |spec|
 
228
        spec.name =~ gem_pattern and
 
229
          version_requirement.satisfied_by? spec.version
 
230
      end
 
231
 
 
232
      if only_platform then
 
233
        specs = specs.select do |spec|
 
234
          Gem::Platform.match spec.platform
 
235
        end
 
236
      end
 
237
 
 
238
      specs.sort_by { |s| s.sort_obj }
 
239
    end
 
240
 
 
241
    # Refresh the source index from the local file system.
 
242
    #
 
243
    # return:: Returns a pointer to itself.
 
244
    #
 
245
    def refresh!
 
246
      load_gems_in(self.class.installed_spec_directories)
 
247
    end
 
248
 
 
249
    # Returns an Array of Gem::Specifications that are not up to date.
 
250
    #
 
251
    def outdated
 
252
      dep = Gem::Dependency.new '', Gem::Requirement.default
 
253
 
 
254
      remotes = Gem::SourceInfoCache.search dep, true
 
255
 
 
256
      outdateds = []
 
257
 
 
258
      latest_specs.each do |local|
 
259
        name = local.name
 
260
        remote = remotes.select  { |spec| spec.name == name }.
 
261
                         sort_by { |spec| spec.version.to_ints }.
 
262
                         last
 
263
        outdateds << name if remote and local.version < remote.version
 
264
      end
 
265
 
 
266
      outdateds
 
267
    end
 
268
 
 
269
    def update(source_uri)
 
270
      use_incremental = false
 
271
 
 
272
      begin
 
273
        gem_names = fetch_quick_index source_uri
 
274
        remove_extra gem_names
 
275
        missing_gems = find_missing gem_names
 
276
 
 
277
        return false if missing_gems.size.zero?
 
278
 
 
279
        say "missing #{missing_gems.size} gems" if
 
280
          missing_gems.size > 0 and Gem.configuration.really_verbose
 
281
 
 
282
        use_incremental = missing_gems.size <= Gem.configuration.bulk_threshold
 
283
      rescue Gem::OperationNotSupportedError => ex
 
284
        alert_error "Falling back to bulk fetch: #{ex.message}" if
 
285
          Gem.configuration.really_verbose
 
286
        use_incremental = false
 
287
      end
 
288
 
 
289
      if use_incremental then
 
290
        update_with_missing(source_uri, missing_gems)
 
291
      else
 
292
        new_index = fetch_bulk_index(source_uri)
 
293
        @gems.replace(new_index.gems)
 
294
      end
 
295
 
 
296
      true
 
297
    end
 
298
 
 
299
    def ==(other) # :nodoc:
 
300
      self.class === other and @gems == other.gems 
 
301
    end
 
302
 
 
303
    def dump
 
304
      Marshal.dump(self)
 
305
    end
 
306
 
 
307
    protected
 
308
 
 
309
    attr_reader :gems
 
310
 
 
311
    private
 
312
 
 
313
    def fetcher
 
314
      require 'rubygems/remote_fetcher'
 
315
 
 
316
      Gem::RemoteFetcher.fetcher
 
317
    end
 
318
 
 
319
    def fetch_index_from(source_uri)
 
320
      @fetch_error = nil
 
321
 
 
322
      indexes = %W[
 
323
        Marshal.#{Gem.marshal_version}.Z
 
324
        Marshal.#{Gem.marshal_version}
 
325
        yaml.Z
 
326
        yaml
 
327
      ]
 
328
 
 
329
      indexes.each do |name|
 
330
        spec_data = nil
 
331
        begin
 
332
          spec_data = fetcher.fetch_path("#{source_uri}/#{name}")
 
333
          spec_data = unzip(spec_data) if name =~ /\.Z$/
 
334
          if name =~ /Marshal/ then
 
335
            return Marshal.load(spec_data)
 
336
          else
 
337
            return YAML.load(spec_data)
 
338
          end
 
339
        rescue => e
 
340
          if Gem.configuration.really_verbose then
 
341
            alert_error "Unable to fetch #{name}: #{e.message}"
 
342
          end
 
343
          @fetch_error = e
 
344
        end
 
345
      end
 
346
      nil
 
347
    end
 
348
 
 
349
    def fetch_bulk_index(source_uri)
 
350
      say "Bulk updating Gem source index for: #{source_uri}"
 
351
 
 
352
      index = fetch_index_from(source_uri)
 
353
      if index.nil? then
 
354
        raise Gem::RemoteSourceException,
 
355
              "Error fetching remote gem cache: #{@fetch_error}"
 
356
      end
 
357
      @fetch_error = nil
 
358
      index
 
359
    end
 
360
 
 
361
    # Get the quick index needed for incremental updates.
 
362
    def fetch_quick_index(source_uri)
 
363
      zipped_index = fetcher.fetch_path source_uri + '/quick/index.rz'
 
364
      unzip(zipped_index).split("\n")
 
365
    rescue ::Exception => ex
 
366
      raise Gem::OperationNotSupportedError,
 
367
            "No quick index found: " + ex.message
 
368
    end
 
369
 
 
370
    # Make a list of full names for all the missing gemspecs.
 
371
    def find_missing(spec_names)
 
372
      spec_names.find_all { |full_name|
 
373
        specification(full_name).nil?
 
374
      }
 
375
    end
 
376
 
 
377
    def remove_extra(spec_names)
 
378
      dictionary = spec_names.inject({}) { |h, k| h[k] = true; h }
 
379
      each do |name, spec|
 
380
        remove_spec name unless dictionary.include? name
 
381
      end
 
382
    end
 
383
 
 
384
    # Unzip the given string.
 
385
    def unzip(string)
 
386
      require 'zlib'
 
387
      Zlib::Inflate.inflate(string)
 
388
    end
 
389
 
 
390
    # Tries to fetch Marshal representation first, then YAML
 
391
    def fetch_single_spec(source_uri, spec_name)
 
392
      @fetch_error = nil
 
393
      begin
 
394
        marshal_uri = source_uri + "/quick/Marshal.#{Gem.marshal_version}/#{spec_name}.gemspec.rz"
 
395
        zipped = fetcher.fetch_path marshal_uri
 
396
        return Marshal.load(unzip(zipped))
 
397
      rescue => ex
 
398
        @fetch_error = ex
 
399
        if Gem.configuration.really_verbose then
 
400
          say "unable to fetch marshal gemspec #{marshal_uri}: #{ex.class} - #{ex}"
 
401
        end
 
402
      end
 
403
 
 
404
      begin
 
405
        yaml_uri = source_uri + "/quick/#{spec_name}.gemspec.rz"
 
406
        zipped = fetcher.fetch_path yaml_uri
 
407
        return YAML.load(unzip(zipped))
 
408
      rescue => ex
 
409
        @fetch_error = ex
 
410
        if Gem.configuration.really_verbose then
 
411
          say "unable to fetch YAML gemspec #{yaml_uri}: #{ex.class} - #{ex}"
 
412
        end
 
413
      end
 
414
      nil
 
415
    end
 
416
 
 
417
    # Update the cached source index with the missing names.
 
418
    def update_with_missing(source_uri, missing_names)
 
419
      progress = ui.progress_reporter(missing_names.size,
 
420
        "Updating metadata for #{missing_names.size} gems from #{source_uri}")
 
421
      missing_names.each do |spec_name|
 
422
        gemspec = fetch_single_spec(source_uri, spec_name)
 
423
        if gemspec.nil? then
 
424
          ui.say "Failed to download spec #{spec_name} from #{source_uri}:\n" \
 
425
                 "\t#{@fetch_error.message}"
 
426
        else
 
427
          add_spec gemspec
 
428
          progress.updated spec_name
 
429
        end
 
430
        @fetch_error = nil
 
431
      end
 
432
      progress.done
 
433
      progress.count
 
434
    end
 
435
 
 
436
  end
 
437
 
 
438
  # Cache is an alias for SourceIndex to allow older YAMLized source
 
439
  # index objects to load properly.
 
440
  Cache = SourceIndex
 
441
 
 
442
end
 
443