Re-enable spec/library for full CI runs.
[rbx.git] / lib / rubygems / specification.rb
blob0642a4f3e01870024f9e8c593e88fa2d79cd60f6
1 #--
2 # Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
3 # All rights reserved.
4 # See LICENSE.txt for permissions.
5 #++
7 require 'rubygems'
8 require 'rubygems/version'
9 require 'rubygems/requirement'
10 require 'rubygems/platform'
12 # :stopdoc:
13 # Time::today has been deprecated in 0.9.5 and will be removed.
14 if RUBY_VERSION < '1.9' then
15   def Time.today
16     t = Time.now
17     t - ((t.to_f + t.gmt_offset) % 86400)
18   end unless defined? Time.today
19 end
21 class Date; end # for ruby_code if date.rb wasn't required
23 # :startdoc:
25 module Gem
27   # == Gem::Specification
28   #
29   # The Specification class contains the metadata for a Gem.  Typically
30   # defined in a .gemspec file or a Rakefile, and looks like this:
31   #
32   #   spec = Gem::Specification.new do |s|
33   #     s.name = 'rfoo'
34   #     s.version = '1.0'
35   #     s.summary = 'Example gem specification'
36   #     ...
37   #   end
38   #
39   # There are many <em>gemspec attributes</em>, and the best place to learn
40   # about them in the "Gemspec Reference" linked from the RubyGems wiki.
41   #
42   class Specification
44     ##
45     # Allows deinstallation of gems with legacy platforms.
47     attr_accessor :original_platform # :nodoc:
49     # ------------------------- Specification version constants.
51     ##
52     # The the version number of a specification that does not specify one
53     # (i.e. RubyGems 0.7 or earlier).
55     NONEXISTENT_SPECIFICATION_VERSION = -1
57     ##
58     # The specification version applied to any new Specification instances
59     # created.  This should be bumped whenever something in the spec format
60     # changes.
61     #--
62     # When updating this number, be sure to also update #to_ruby.
64     CURRENT_SPECIFICATION_VERSION = 3
66     ##
67     # An informal list of changes to the specification.  The highest-valued
68     # key should be equal to the CURRENT_SPECIFICATION_VERSION.
70     SPECIFICATION_VERSION_HISTORY = {
71       -1 => ['(RubyGems versions up to and including 0.7 did not have versioned specifications)'],
72       1  => [
73         'Deprecated "test_suite_file" in favor of the new, but equivalent, "test_files"',
74         '"test_file=x" is a shortcut for "test_files=[x]"'
75       ],
76       2  => [
77         'Added "required_rubygems_version"',
78         'Now forward-compatible with future versions',
79       ],
80       3  => [
81         'Added dependency types',
82       ],
83     }
85     # :stopdoc:
86     MARSHAL_FIELDS = { -1 => 16, 1 => 16, 2 => 16, 3 => 16 }
88     now = Time.at(Time.now.to_i)
89     TODAY = now - ((now.to_i + now.gmt_offset) % 86400)
90     # :startdoc:
92     # ------------------------- Class variables.
94     # List of Specification instances.
95     @@list = []
97     # Optional block used to gather newly defined instances.
98     @@gather = nil
100     # List of attribute names: [:name, :version, ...]
101     @@required_attributes = []
103     # List of _all_ attributes and default values: [[:name, nil], [:bindir, 'bin'], ...]
104     @@attributes = []
106     @@nil_attributes = []
107     @@non_nil_attributes = [:@original_platform]
109     # List of array attributes
110     @@array_attributes = []
112     # Map of attribute names to default values.
113     @@default_value = {}
115     # ------------------------- Convenience class methods.
117     def self.attribute_names
118       @@attributes.map { |name, default| name }
119     end
121     def self.attribute_defaults
122       @@attributes.dup
123     end
125     def self.default_value(name)
126       @@default_value[name]
127     end
129     def self.required_attributes
130       @@required_attributes.dup
131     end
133     def self.required_attribute?(name)
134       @@required_attributes.include? name.to_sym
135     end
137     def self.array_attributes
138       @@array_attributes.dup
139     end
141     # ------------------------- Infrastructure class methods.
143     # A list of Specification instances that have been defined in this Ruby instance.
144     def self.list
145       @@list
146     end
148     # Used to specify the name and default value of a specification
149     # attribute.  The side effects are:
150     # * the name and default value are added to the @@attributes list
151     #   and @@default_value map
152     # * a standard _writer_ method (<tt>attribute=</tt>) is created
153     # * a non-standard _reader method (<tt>attribute</tt>) is created
154     #
155     # The reader method behaves like this:
156     #   def attribute
157     #     @attribute ||= (copy of default value)
158     #   end
159     #
160     # This allows lazy initialization of attributes to their default
161     # values. 
162     #
163     def self.attribute(name, default=nil)
164       ivar_name = "@#{name}".intern
165       if default.nil? then
166         @@nil_attributes << ivar_name
167       else
168         @@non_nil_attributes << [ivar_name, default]
169       end
171       @@attributes << [name, default]
172       @@default_value[name] = default
173       attr_accessor(name)
174     end
176     # Same as :attribute, but ensures that values assigned to the
177     # attribute are array values by applying :to_a to the value.
178     def self.array_attribute(name)
179       @@non_nil_attributes << ["@#{name}".intern, []]
181       @@array_attributes << name
182       @@attributes << [name, []]
183       @@default_value[name] = []
184       code = %{
185         def #{name}
186           @#{name} ||= []
187         end
188         def #{name}=(value)
189           @#{name} = Array(value)
190         end
191       }
193       module_eval code, __FILE__, __LINE__ - 9
194     end
196     # Same as attribute above, but also records this attribute as mandatory.
197     def self.required_attribute(*args)
198       @@required_attributes << args.first
199       attribute(*args)
200     end
202     # Sometimes we don't want the world to use a setter method for a particular attribute.
203     # +read_only+ makes it private so we can still use it internally.
204     def self.read_only(*names)
205       names.each do |name|
206         private "#{name}="
207       end
208     end
210     # Shortcut for creating several attributes at once (each with a default value of
211     # +nil+).
212     def self.attributes(*args)
213       args.each do |arg|
214         attribute(arg, nil)
215       end
216     end
218     # Some attributes require special behaviour when they are accessed.  This allows for
219     # that.
220     def self.overwrite_accessor(name, &block)
221       remove_method name
222       define_method(name, &block)
223     end
225     # Defines a _singular_ version of an existing _plural_ attribute
226     # (i.e. one whose value is expected to be an array).  This means
227     # just creating a helper method that takes a single value and
228     # appends it to the array.  These are created for convenience, so
229     # that in a spec, one can write 
230     #
231     #   s.require_path = 'mylib'
232     #
233     # instead of
234     #
235     #   s.require_paths = ['mylib']
236     #
237     # That above convenience is available courtesy of
238     #
239     #   attribute_alias_singular :require_path, :require_paths 
240     #
241     def self.attribute_alias_singular(singular, plural)
242       define_method("#{singular}=") { |val|
243         send("#{plural}=", [val])
244       }
245       define_method("#{singular}") { 
246         val = send("#{plural}")
247         val.nil? ? nil : val.first
248       }
249     end
251     # Dump only crucial instance variables.
252     #
253     # MAINTAIN ORDER!
254     def _dump(limit) # :nodoc:
255       Marshal.dump [
256         @rubygems_version,
257         @specification_version,
258         @name,
259         @version,
260         (Time === @date ? @date : (require 'time'; Time.parse(@date.to_s))),
261         @summary,
262         @required_ruby_version,
263         @required_rubygems_version,
264         @original_platform,
265         @dependencies,
266         @rubyforge_project,
267         @email,
268         @authors,
269         @description,
270         @homepage,
271         @has_rdoc,
272         @new_platform,
273       ]
274     end
276     # Load custom marshal format, re-initializing defaults as needed
277     def self._load(str)
278       array = Marshal.load str
280       spec = Gem::Specification.new
281       spec.instance_variable_set :@specification_version, array[1]
283       current_version = CURRENT_SPECIFICATION_VERSION
285       field_count = MARSHAL_FIELDS[spec.specification_version]
287       if field_count.nil? or array.size < field_count then
288         raise TypeError, "invalid Gem::Specification format #{array.inspect}"
289       end
291       spec.instance_variable_set :@rubygems_version,          array[0]
292       # spec version
293       spec.instance_variable_set :@name,                      array[2]
294       spec.instance_variable_set :@version,                   array[3]
295       spec.instance_variable_set :@date,                      array[4]
296       spec.instance_variable_set :@summary,                   array[5]
297       spec.instance_variable_set :@required_ruby_version,     array[6]
298       spec.instance_variable_set :@required_rubygems_version, array[7]
299       spec.instance_variable_set :@original_platform,         array[8]
300       spec.instance_variable_set :@dependencies,              array[9]
301       spec.instance_variable_set :@rubyforge_project,         array[10]
302       spec.instance_variable_set :@email,                     array[11]
303       spec.instance_variable_set :@authors,                   array[12]
304       spec.instance_variable_set :@description,               array[13]
305       spec.instance_variable_set :@homepage,                  array[14]
306       spec.instance_variable_set :@has_rdoc,                  array[15]
307       spec.instance_variable_set :@new_platform,              array[16]
308       spec.instance_variable_set :@platform,                  array[16].to_s
309       spec.instance_variable_set :@loaded,                    false
311       spec
312     end
314     # REQUIRED gemspec attributes ------------------------------------
315     
316     required_attribute :rubygems_version, Gem::RubyGemsVersion
317     required_attribute :specification_version, CURRENT_SPECIFICATION_VERSION
318     required_attribute :name
319     required_attribute :version
320     required_attribute :date, TODAY
321     required_attribute :summary
322     required_attribute :require_paths, ['lib']
324     # OPTIONAL gemspec attributes ------------------------------------
325     
326     attributes :email, :homepage, :rubyforge_project, :description
327     attributes :autorequire, :default_executable
329     attribute :bindir,                     'bin'
330     attribute :has_rdoc,                   false
331     attribute :required_ruby_version,      Gem::Requirement.default
332     attribute :required_rubygems_version,  Gem::Requirement.default
333     attribute :platform,                   Gem::Platform::RUBY
335     attribute :signing_key,            nil
336     attribute :cert_chain,             []
337     attribute :post_install_message,   nil
339     array_attribute :authors
340     array_attribute :files
341     array_attribute :test_files
342     array_attribute :rdoc_options
343     array_attribute :extra_rdoc_files
344     array_attribute :executables
346     # Array of extensions to build.  See Gem::Installer#build_extensions for
347     # valid values.
349     array_attribute :extensions
350     array_attribute :requirements
351     array_attribute :dependencies
353     read_only :dependencies
355     def runtime_dependencies
356       dependencies.select { |d| d.type == :runtime || d.type == nil }
357     end
359     def development_dependencies
360       dependencies.select { |d| d.type == :development }
361     end
363     # ALIASED gemspec attributes -------------------------------------
364     
365     attribute_alias_singular :executable,   :executables
366     attribute_alias_singular :author,   :authors
367     attribute_alias_singular :require_path, :require_paths
368     attribute_alias_singular :test_file,    :test_files
370     # DEPRECATED gemspec attributes ----------------------------------
371     
372     def test_suite_file
373       warn 'test_suite_file deprecated, use test_files'
374       test_files.first
375     end
377     def test_suite_file=(val)
378       warn 'test_suite_file= deprecated, use test_files='
379       @test_files = [] unless defined? @test_files
380       @test_files << val
381     end
383     # true when this gemspec has been loaded from a specifications directory.
384     # This attribute is not persisted.
386     attr_writer :loaded
388     # Path this gemspec was loaded from.  This attribute is not persisted.
389     attr_accessor :loaded_from
391     # Special accessor behaviours (overwriting default) --------------
392     
393     overwrite_accessor :version= do |version|
394       @version = Version.create(version)
395     end
397     overwrite_accessor :platform do
398       @new_platform
399     end
401     overwrite_accessor :platform= do |platform|
402       if @original_platform.nil? or
403          @original_platform == Gem::Platform::RUBY then
404         @original_platform = platform
405       end
407       case platform
408       when Gem::Platform::CURRENT then
409         @new_platform = Gem::Platform.local
410         @original_platform = @new_platform.to_s
412       when Gem::Platform then
413         @new_platform = platform
415       # legacy constants
416       when nil, Gem::Platform::RUBY then
417         @new_platform = Gem::Platform::RUBY
418       when 'mswin32' then # was Gem::Platform::WIN32
419         @new_platform = Gem::Platform.new 'x86-mswin32'
420       when 'i586-linux' then # was Gem::Platform::LINUX_586
421         @new_platform = Gem::Platform.new 'x86-linux'
422       when 'powerpc-darwin' then # was Gem::Platform::DARWIN
423         @new_platform = Gem::Platform.new 'ppc-darwin'
424       else
425         @new_platform = Gem::Platform.new platform
426       end
428       @platform = @new_platform.to_s
430       @new_platform
431     end
433     overwrite_accessor :required_ruby_version= do |value|
434       @required_ruby_version = Gem::Requirement.create(value)
435     end
437     overwrite_accessor :required_rubygems_version= do |value|
438       @required_rubygems_version = Gem::Requirement.create(value)
439     end
441     overwrite_accessor :date= do |date|
442       # We want to end up with a Time object with one-day resolution.
443       # This is the cleanest, most-readable, faster-than-using-Date
444       # way to do it.
445       case date
446       when String then
447         @date = if /\A(\d{4})-(\d{2})-(\d{2})\Z/ =~ date then
448                   Time.local($1.to_i, $2.to_i, $3.to_i)
449                 else
450                   require 'time'
451                   Time.parse date
452                 end
453       when Time then
454         @date = Time.local(date.year, date.month, date.day)
455       when Date then
456         @date = Time.local(date.year, date.month, date.day)
457       else
458         @date = TODAY
459       end
460     end
462     overwrite_accessor :date do
463       self.date = nil if @date.nil?  # HACK Sets the default value for date
464       @date
465     end
467     overwrite_accessor :summary= do |str|
468       @summary = if str then
469                    str.strip.
470                    gsub(/(\w-)\n[ \t]*(\w)/, '\1\2').
471                    gsub(/\n[ \t]*/, " ")
472                  end
473     end
475     overwrite_accessor :description= do |str|
476       @description = if str then
477                        str.strip.
478                        gsub(/(\w-)\n[ \t]*(\w)/, '\1\2').
479                        gsub(/\n[ \t]*/, " ")
480                      end
481     end
483     overwrite_accessor :default_executable do
484       begin
485         if defined?(@default_executable) and @default_executable
486           result = @default_executable
487         elsif @executables and @executables.size == 1
488           result = Array(@executables).first
489         else
490           result = nil
491         end
492         result
493       rescue
494         nil
495       end
496     end
498     def add_bindir(executables)
499       return nil if executables.nil?
501       if @bindir then
502         Array(executables).map { |e| File.join(@bindir, e) }
503       else
504         executables
505       end
506     rescue
507       return nil
508     end
510     overwrite_accessor :files do
511       result = []
512       result.push(*@files) if defined?(@files)
513       result.push(*@test_files) if defined?(@test_files)
514       result.push(*(add_bindir(@executables)))
515       result.push(*@extra_rdoc_files) if defined?(@extra_rdoc_files)
516       result.push(*@extensions) if defined?(@extensions)
517       result.uniq.compact
518     end
520     # Files in the Gem under one of the require_paths
521     def lib_files
522       @files.select do |file|
523         require_paths.any? do |path|
524           file.index(path) == 0
525         end
526       end
527     end
529     overwrite_accessor :test_files do
530       # Handle the possibility that we have @test_suite_file but not
531       # @test_files.  This will happen when an old gem is loaded via
532       # YAML.
533       if defined? @test_suite_file then
534         @test_files = [@test_suite_file].flatten
535         @test_suite_file = nil
536       end
537       if defined?(@test_files) and @test_files then
538         @test_files
539       else
540         @test_files = []
541       end
542     end
544     # Predicates -----------------------------------------------------
545     
546     def loaded?; @loaded ? true : false ; end
547     def has_rdoc?; has_rdoc ? true : false ; end
548     def has_unit_tests?; not test_files.empty?; end
549     alias has_test_suite? has_unit_tests?               # (deprecated)
550     
551     # Constructors ---------------------------------------------------
552     
553     # Specification constructor.  Assigns the default values to the
554     # attributes, adds this spec to the list of loaded specs (see
555     # Specification.list), and yields itself for further initialization.
556     #
557     def initialize
558       @new_platform = nil
559       assign_defaults
560       @loaded = false
561       @loaded_from = nil
562       @@list << self
564       yield self if block_given?
566       @@gather.call(self) if @@gather
567     end
569     # Each attribute has a default value (possibly nil).  Here, we
570     # initialize all attributes to their default value.  This is
571     # done through the accessor methods, so special behaviours will
572     # be honored.  Furthermore, we take a _copy_ of the default so
573     # each specification instance has its own empty arrays, etc.
574     def assign_defaults
575       @@nil_attributes.each do |name|
576         instance_variable_set name, nil
577       end
579       @@non_nil_attributes.each do |name, default|
580         value = case default
581                 when Time, Numeric, Symbol, true, false, nil then default
582                 else default.dup
583                 end
585         instance_variable_set name, value
586       end
588       # HACK
589       instance_variable_set :@new_platform, Gem::Platform::RUBY
590     end
592     # Special loader for YAML files.  When a Specification object is
593     # loaded from a YAML file, it bypasses the normal Ruby object
594     # initialization routine (#initialize).  This method makes up for
595     # that and deals with gems of different ages.
596     #
597     # 'input' can be anything that YAML.load() accepts: String or IO. 
598     #
599     def self.from_yaml(input)
600       input = normalize_yaml_input input
601       spec = YAML.load input
603       if spec && spec.class == FalseClass then
604         raise Gem::EndOfYAMLException
605       end
607       unless Gem::Specification === spec then
608         raise Gem::Exception, "YAML data doesn't evaluate to gem specification"
609       end
611       unless (spec.instance_variables.include? '@specification_version' or
612               spec.instance_variables.include? :@specification_version) and
613              spec.instance_variable_get :@specification_version
614         spec.instance_variable_set :@specification_version, 
615                                    NONEXISTENT_SPECIFICATION_VERSION
616       end
618       spec
619     end 
621     def self.load(filename)
622       gemspec = nil
623       fail "NESTED Specification.load calls not allowed!" if @@gather
624       @@gather = proc { |gs| gemspec = gs }
625       data = File.read(filename)
626       eval(data)
627       gemspec
628     ensure
629       @@gather = nil
630     end
632     # Make sure the yaml specification is properly formatted with dashes.
633     def self.normalize_yaml_input(input)
634       result = input.respond_to?(:read) ? input.read : input
635       result = "--- " + result unless result =~ /^--- /
636       result
637     end
638     
639     # Instance methods -----------------------------------------------
640     
641     # Sets the rubygems_version to Gem::RubyGemsVersion.
642     #
643     def mark_version
644       @rubygems_version = RubyGemsVersion
645     end
647     # Ignore unknown attributes if the 
648     def method_missing(sym, *a, &b) # :nodoc:
649       if @specification_version > CURRENT_SPECIFICATION_VERSION and
650          sym.to_s =~ /=$/ then
651         warn "ignoring #{sym} loading #{full_name}" if $DEBUG
652       else
653         super
654       end
655     end
657     # Adds a development dependency to this Gem.  For example,
658     #
659     #   spec.add_development_dependency('jabber4r', '> 0.1', '<= 0.5')
660     #
661     # Development dependencies aren't installed by default, and
662     # aren't activated when a gem is required.
663     #
664     # gem:: [String or Gem::Dependency] The Gem name/dependency.
665     # requirements:: [default=">= 0"] The version requirements.
666     def add_development_dependency(gem, *requirements)
667       add_dependency_with_type(gem, :development, *requirements)
668     end
670     # Adds a runtime dependency to this Gem.  For example,
671     #
672     #   spec.add_runtime_dependency('jabber4r', '> 0.1', '<= 0.5')
673     #
674     # gem:: [String or Gem::Dependency] The Gem name/dependency.
675     # requirements:: [default=">= 0"] The version requirements.
676     def add_runtime_dependency(gem, *requirements)
677       add_dependency_with_type(gem, :runtime, *requirements)
678     end
680     alias add_dependency add_runtime_dependency
682     # Returns the full name (name-version) of this Gem.  Platform information
683     # is included (name-version-platform) if it is specified (and not the
684     # default Ruby platform).
685     #
686     def full_name
687       if platform == Gem::Platform::RUBY or platform.nil? then
688         "#{@name}-#{@version}"
689       else
690         "#{@name}-#{@version}-#{platform}"
691       end
692     end
694     # Returns the full name (name-version) of this gemspec using the original
695     # platform.
696     #
697     def original_name # :nodoc:
698       if platform == Gem::Platform::RUBY or platform.nil? then
699         "#{@name}-#{@version}"
700       else
701         "#{@name}-#{@version}-#{@original_platform}"
702       end
703     end
705     ##
706     # The full path to the gem (install path + full name).
708     def full_gem_path
709       path = File.join installation_path, 'gems', full_name
710       return path if File.directory? path
711       File.join installation_path, 'gems', original_name
712     end
714     ##
715     # The default (generated) file name of the gem.
717     def file_name
718       full_name + ".gem"
719     end
721     ##
722     # The directory that this gem was installed into.
724     def installation_path
725       path = File.dirname(@loaded_from).split(File::SEPARATOR)[0..-2]
726       path = path.join File::SEPARATOR
727       File.expand_path path
728     end
730     # Checks if this Specification meets the requirement of the supplied
731     # dependency.
732     # 
733     # dependency:: [Gem::Dependency] the dependency to check
734     # return:: [Boolean] true if dependency is met, otherwise false
735     #
736     def satisfies_requirement?(dependency)
737       return @name == dependency.name && 
738         dependency.version_requirements.satisfied_by?(@version)
739     end
741     # Comparison methods ---------------------------------------------
743     def sort_obj
744       [@name, @version.to_ints, @new_platform == Gem::Platform::RUBY ? -1 : 1]
745     end
747     def <=>(other) # :nodoc:
748       sort_obj <=> other.sort_obj
749     end
751     # Tests specs for equality (across all attributes).
752     def ==(other) # :nodoc:
753       self.class === other && same_attributes?(other)
754     end
756     alias eql? == # :nodoc:
758     def same_attributes?(other)
759       @@attributes.each do |name, default|
760         return false unless self.send(name) == other.send(name)
761       end
762       true
763     end
764     private :same_attributes?
766     def hash # :nodoc:
767       @@attributes.inject(0) { |hash_code, (name, default_value)|
768         n = self.send(name).hash
769         hash_code + n
770       }
771     end
773     # Export methods (YAML and Ruby code) ----------------------------
775     def to_yaml(opts = {}) # :nodoc:
776       mark_version
778       attributes = @@attributes.map { |name,| name.to_s }.sort
779       attributes = attributes - %w[name version platform]
781       yaml = YAML.quick_emit object_id, opts do |out|
782         out.map taguri, to_yaml_style do |map|
783           map.add 'name', @name
784           map.add 'version', @version
785           platform = case @original_platform
786                      when nil, '' then
787                        'ruby'
788                      when String then
789                        @original_platform
790                      else
791                        @original_platform.to_s
792                      end
793           map.add 'platform', platform
795           attributes.each do |name|
796             map.add name, instance_variable_get("@#{name}")
797           end
798         end
799       end
800     end
802     def yaml_initialize(tag, vals) # :nodoc:
803       vals.each do |ivar, val|
804         instance_variable_set "@#{ivar}", val
805       end
807       @original_platform = @platform # for backwards compatibility
808       self.platform = Gem::Platform.new @platform
809     end
811     ##
812     # Returns a Ruby code representation of this specification, such that it
813     # can be eval'ed and reconstruct the same specification later.  Attributes
814     # that still have their default values are omitted.
816     def to_ruby
817       mark_version
818       result = []
819       result << "Gem::Specification.new do |s|"
821       result << "  s.name = #{ruby_code name}"
822       result << "  s.version = #{ruby_code version}"
823       unless platform.nil? or platform == Gem::Platform::RUBY then
824         result << "  s.platform = #{ruby_code original_platform}"
825       end
826       result << ""
827       result << "  s.required_rubygems_version = #{ruby_code required_rubygems_version} if s.respond_to? :required_rubygems_version="
829       handled = [
830         :dependencies,
831         :name,
832         :platform,
833         :required_rubygems_version,
834         :specification_version,
835         :version,
836       ]
838       attributes = @@attributes.sort_by { |attr_name,| attr_name.to_s }
840       attributes.each do |attr_name, default|
841         next if handled.include? attr_name
842         current_value = self.send(attr_name)
843         if current_value != default or
844            self.class.required_attribute? attr_name then
845           result << "  s.#{attr_name} = #{ruby_code current_value}"
846         end
847       end
849       result << nil
850       result << "  if s.respond_to? :specification_version then"
851       result << "    current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION"
852       result << "    s.specification_version = #{specification_version}"
853       result << nil
855       result << "    if current_version >= 3 then"
857       unless dependencies.empty? then
858         dependencies.each do |dep|
859           version_reqs_param = dep.requirements_list.inspect
860           dep.instance_variable_set :@type, :runtime if dep.type.nil? # HACK
861           result << "      s.add_#{dep.type}_dependency(%q<#{dep.name}>, #{version_reqs_param})"
862         end
863       end
865       result << "    else"
867       unless dependencies.empty? then
868         dependencies.each do |dep|
869           version_reqs_param = dep.requirements_list.inspect
870           result << "      s.add_dependency(%q<#{dep.name}>, #{version_reqs_param})"
871         end
872       end
874       result << '    end'
876       result << "  else"
877         dependencies.each do |dep|
878           version_reqs_param = dep.requirements_list.inspect
879           result << "    s.add_dependency(%q<#{dep.name}>, #{version_reqs_param})"
880         end
881       result << "  end"
883       result << "end"
884       result << nil
886       result.join "\n"
887     end
889     # Validation and normalization methods ---------------------------
891     # Checks that the specification contains all required fields, and
892     # does a very basic sanity check.
893     #
894     # Raises InvalidSpecificationException if the spec does not pass
895     # the checks..
896     def validate
897       extend Gem::UserInteraction
899       normalize
901       if rubygems_version != RubyGemsVersion then
902         raise Gem::InvalidSpecificationException,
903               "expected RubyGems version #{RubyGemsVersion}, was #{rubygems_version}"
904       end
906       @@required_attributes.each do |symbol|
907         unless self.send symbol then
908           raise Gem::InvalidSpecificationException,
909                 "missing value for attribute #{symbol}"
910         end
911       end 
913       if require_paths.empty? then
914         raise Gem::InvalidSpecificationException,
915               "specification must have at least one require_path"
916       end
918       case platform
919       when Gem::Platform, Platform::RUBY then # ok
920       else
921         raise Gem::InvalidSpecificationException,
922               "invalid platform #{platform.inspect}, see Gem::Platform"
923       end
925       unless Array === authors and
926              authors.all? { |author| String === author } then
927         raise Gem::InvalidSpecificationException,
928               'authors must be Array of Strings'
929       end
931       # Warnings
933       %w[author email homepage rubyforge_project summary].each do |attribute|
934         value = self.send attribute
935         alert_warning "no #{attribute} specified" if value.nil? or value.empty?
936       end
938       alert_warning "RDoc will not be generated (has_rdoc == false)" unless
939         has_rdoc
941       alert_warning "deprecated autorequire specified" if autorequire
943       executables.each do |executable|
944         executable_path = File.join bindir, executable
945         shebang = File.read(executable_path, 2) == '#!'
947         alert_warning "#{executable_path} is missing #! line" unless shebang
948       end
950       true
951     end
953     # Normalize the list of files so that:
954     # * All file lists have redundancies removed.
955     # * Files referenced in the extra_rdoc_files are included in the
956     #   package file list. 
957     #
958     # Also, the summary and description are converted to a normal
959     # format. 
960     def normalize
961       if defined?(@extra_rdoc_files) and @extra_rdoc_files then
962         @extra_rdoc_files.uniq!
963         @files ||= []
964         @files.concat(@extra_rdoc_files)
965       end
966       @files.uniq! if @files
967     end
969     # Dependency methods ---------------------------------------------
970     
971     # Return a list of all gems that have a dependency on this
972     # gemspec.  The list is structured with entries that conform to:
973     #
974     #   [depending_gem, dependency, [list_of_gems_that_satisfy_dependency]]
975     #
976     # return:: [Array] [[dependent_gem, dependency, [list_of_satisfiers]]]
977     #
978     def dependent_gems
979       out = []
980       Gem.source_index.each do |name,gem|
981         gem.dependencies.each do |dep|
982           if self.satisfies_requirement?(dep) then
983             sats = []
984             find_all_satisfiers(dep) do |sat|
985               sats << sat
986             end
987             out << [gem, dep, sats]
988           end
989         end
990       end
991       out
992     end
994     def to_s
995       "#<Gem::Specification name=#{@name} version=#{@version}>"
996     end
998     private
1000     def add_dependency_with_type(dependency, type, *requirements)
1001       requirements = if requirements.empty? then
1002                        Gem::Requirement.default
1003                      else
1004                        requirements.flatten
1005                      end
1007       unless dependency.respond_to?(:name) &&
1008         dependency.respond_to?(:version_requirements)
1010         dependency = Dependency.new(dependency, requirements, type)
1011       end
1013       dependencies << dependency
1014     end
1016     def find_all_satisfiers(dep)
1017       Gem.source_index.each do |name,gem|
1018         if(gem.satisfies_requirement?(dep)) then
1019           yield gem
1020         end
1021       end
1022     end
1024     # Return a string containing a Ruby code representation of the
1025     # given object.
1026     def ruby_code(obj)
1027       case obj
1028       when String            then '%q{' + obj + '}'
1029       when Array             then obj.inspect
1030       when Gem::Version      then obj.to_s.inspect
1031       when Date              then '%q{' + obj.strftime('%Y-%m-%d') + '}'
1032       when Time              then '%q{' + obj.strftime('%Y-%m-%d') + '}'
1033       when Numeric           then obj.inspect
1034       when true, false, nil  then obj.inspect
1035       when Gem::Platform     then "Gem::Platform.new(#{obj.to_a.inspect})"
1036       when Gem::Requirement  then "Gem::Requirement.new(#{obj.to_s.inspect})"
1037       else raise Exception, "ruby_code case not handled: #{obj.class}"
1038       end
1039     end
1041   end