* io.c (rb_open_file): encoding in mode string was ignored if perm is
[ruby-svn.git] / lib / rubygems / specification.rb
blobf3f38e50333455c4fa2f714a22e7b9125ab45182
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.
63     #
64     # NOTE RubyGems < 1.2 cannot load specification versions > 2.
66     CURRENT_SPECIFICATION_VERSION = 2
68     ##
69     # An informal list of changes to the specification.  The highest-valued
70     # key should be equal to the CURRENT_SPECIFICATION_VERSION.
72     SPECIFICATION_VERSION_HISTORY = {
73       -1 => ['(RubyGems versions up to and including 0.7 did not have versioned specifications)'],
74       1  => [
75         'Deprecated "test_suite_file" in favor of the new, but equivalent, "test_files"',
76         '"test_file=x" is a shortcut for "test_files=[x]"'
77       ],
78       2  => [
79         'Added "required_rubygems_version"',
80         'Now forward-compatible with future versions',
81       ],
82     }
84     # :stopdoc:
85     MARSHAL_FIELDS = { -1 => 16, 1 => 16, 2 => 16 }
87     now = Time.at(Time.now.to_i)
88     TODAY = now - ((now.to_i + now.gmt_offset) % 86400)
89     # :startdoc:
91     # ------------------------- Class variables.
93     # List of Specification instances.
94     @@list = []
96     # Optional block used to gather newly defined instances.
97     @@gather = nil
99     # List of attribute names: [:name, :version, ...]
100     @@required_attributes = []
102     # List of _all_ attributes and default values: [[:name, nil], [:bindir, 'bin'], ...]
103     @@attributes = []
105     @@nil_attributes = []
106     @@non_nil_attributes = [:@original_platform]
108     # List of array attributes
109     @@array_attributes = []
111     # Map of attribute names to default values.
112     @@default_value = {}
114     # ------------------------- Convenience class methods.
116     def self.attribute_names
117       @@attributes.map { |name, default| name }
118     end
120     def self.attribute_defaults
121       @@attributes.dup
122     end
124     def self.default_value(name)
125       @@default_value[name]
126     end
128     def self.required_attributes
129       @@required_attributes.dup
130     end
132     def self.required_attribute?(name)
133       @@required_attributes.include? name.to_sym
134     end
136     def self.array_attributes
137       @@array_attributes.dup
138     end
140     # ------------------------- Infrastructure class methods.
142     # A list of Specification instances that have been defined in this Ruby instance.
143     def self.list
144       @@list
145     end
147     # Used to specify the name and default value of a specification
148     # attribute.  The side effects are:
149     # * the name and default value are added to the @@attributes list
150     #   and @@default_value map
151     # * a standard _writer_ method (<tt>attribute=</tt>) is created
152     # * a non-standard _reader method (<tt>attribute</tt>) is created
153     #
154     # The reader method behaves like this:
155     #   def attribute
156     #     @attribute ||= (copy of default value)
157     #   end
158     #
159     # This allows lazy initialization of attributes to their default
160     # values. 
161     #
162     def self.attribute(name, default=nil)
163       ivar_name = "@#{name}".intern
164       if default.nil? then
165         @@nil_attributes << ivar_name
166       else
167         @@non_nil_attributes << [ivar_name, default]
168       end
170       @@attributes << [name, default]
171       @@default_value[name] = default
172       attr_accessor(name)
173     end
175     # Same as :attribute, but ensures that values assigned to the
176     # attribute are array values by applying :to_a to the value.
177     def self.array_attribute(name)
178       @@non_nil_attributes << ["@#{name}".intern, []]
180       @@array_attributes << name
181       @@attributes << [name, []]
182       @@default_value[name] = []
183       code = %{
184         def #{name}
185           @#{name} ||= []
186         end
187         def #{name}=(value)
188           @#{name} = Array(value)
189         end
190       }
192       module_eval code, __FILE__, __LINE__ - 9
193     end
195     # Same as attribute above, but also records this attribute as mandatory.
196     def self.required_attribute(*args)
197       @@required_attributes << args.first
198       attribute(*args)
199     end
201     # Sometimes we don't want the world to use a setter method for a particular attribute.
202     # +read_only+ makes it private so we can still use it internally.
203     def self.read_only(*names)
204       names.each do |name|
205         private "#{name}="
206       end
207     end
209     # Shortcut for creating several attributes at once (each with a default value of
210     # +nil+).
211     def self.attributes(*args)
212       args.each do |arg|
213         attribute(arg, nil)
214       end
215     end
217     # Some attributes require special behaviour when they are accessed.  This allows for
218     # that.
219     def self.overwrite_accessor(name, &block)
220       remove_method name
221       define_method(name, &block)
222     end
224     # Defines a _singular_ version of an existing _plural_ attribute
225     # (i.e. one whose value is expected to be an array).  This means
226     # just creating a helper method that takes a single value and
227     # appends it to the array.  These are created for convenience, so
228     # that in a spec, one can write 
229     #
230     #   s.require_path = 'mylib'
231     #
232     # instead of
233     #
234     #   s.require_paths = ['mylib']
235     #
236     # That above convenience is available courtesy of
237     #
238     #   attribute_alias_singular :require_path, :require_paths 
239     #
240     def self.attribute_alias_singular(singular, plural)
241       define_method("#{singular}=") { |val|
242         send("#{plural}=", [val])
243       }
244       define_method("#{singular}") { 
245         val = send("#{plural}")
246         val.nil? ? nil : val.first
247       }
248     end
250     ##
251     # Dump only crucial instance variables.
252     #--
253     # MAINTAIN ORDER!
255     def _dump(limit)
256       Marshal.dump [
257         @rubygems_version,
258         @specification_version,
259         @name,
260         @version,
261         (Time === @date ? @date : (require 'time'; Time.parse(@date.to_s))),
262         @summary,
263         @required_ruby_version,
264         @required_rubygems_version,
265         @original_platform,
266         @dependencies,
267         @rubyforge_project,
268         @email,
269         @authors,
270         @description,
271         @homepage,
272         @has_rdoc,
273         @new_platform,
274       ]
275     end
277     ##
278     # Load custom marshal format, re-initializing defaults as needed
280     def self._load(str)
281       array = Marshal.load str
283       spec = Gem::Specification.new
284       spec.instance_variable_set :@specification_version, array[1]
286       current_version = CURRENT_SPECIFICATION_VERSION
288       field_count = if spec.specification_version > current_version then
289                       spec.instance_variable_set :@specification_version,
290                                                  current_version
291                       MARSHAL_FIELDS[current_version]
292                     else
293                       MARSHAL_FIELDS[spec.specification_version]
294                     end
296       if array.size < field_count then
297         raise TypeError, "invalid Gem::Specification format #{array.inspect}"
298       end
300       spec.instance_variable_set :@rubygems_version,          array[0]
301       # spec version
302       spec.instance_variable_set :@name,                      array[2]
303       spec.instance_variable_set :@version,                   array[3]
304       spec.instance_variable_set :@date,                      array[4]
305       spec.instance_variable_set :@summary,                   array[5]
306       spec.instance_variable_set :@required_ruby_version,     array[6]
307       spec.instance_variable_set :@required_rubygems_version, array[7]
308       spec.instance_variable_set :@original_platform,         array[8]
309       spec.instance_variable_set :@dependencies,              array[9]
310       spec.instance_variable_set :@rubyforge_project,         array[10]
311       spec.instance_variable_set :@email,                     array[11]
312       spec.instance_variable_set :@authors,                   array[12]
313       spec.instance_variable_set :@description,               array[13]
314       spec.instance_variable_set :@homepage,                  array[14]
315       spec.instance_variable_set :@has_rdoc,                  array[15]
316       spec.instance_variable_set :@new_platform,              array[16]
317       spec.instance_variable_set :@platform,                  array[16].to_s
318       spec.instance_variable_set :@loaded,                    false
320       spec
321     end
323     # REQUIRED gemspec attributes ------------------------------------
324     
325     required_attribute :rubygems_version, Gem::RubyGemsVersion
326     required_attribute :specification_version, CURRENT_SPECIFICATION_VERSION
327     required_attribute :name
328     required_attribute :version
329     required_attribute :date, TODAY
330     required_attribute :summary
331     required_attribute :require_paths, ['lib']
333     # OPTIONAL gemspec attributes ------------------------------------
334     
335     attributes :email, :homepage, :rubyforge_project, :description
336     attributes :autorequire, :default_executable
338     attribute :bindir,                     'bin'
339     attribute :has_rdoc,                   false
340     attribute :required_ruby_version,      Gem::Requirement.default
341     attribute :required_rubygems_version,  Gem::Requirement.default
342     attribute :platform,                   Gem::Platform::RUBY
344     attribute :signing_key,            nil
345     attribute :cert_chain,             []
346     attribute :post_install_message,   nil
348     array_attribute :authors
349     array_attribute :files
350     array_attribute :test_files
351     array_attribute :rdoc_options
352     array_attribute :extra_rdoc_files
353     array_attribute :executables
355     # Array of extensions to build.  See Gem::Installer#build_extensions for
356     # valid values.
358     array_attribute :extensions
359     array_attribute :requirements
360     array_attribute :dependencies
362     read_only :dependencies
364     def runtime_dependencies
365       dependencies.select { |d| d.type == :runtime || d.type == nil }
366     end
368     def development_dependencies
369       dependencies.select { |d| d.type == :development }
370     end
372     # ALIASED gemspec attributes -------------------------------------
373     
374     attribute_alias_singular :executable,   :executables
375     attribute_alias_singular :author,   :authors
376     attribute_alias_singular :require_path, :require_paths
377     attribute_alias_singular :test_file,    :test_files
379     # DEPRECATED gemspec attributes ----------------------------------
380     
381     def test_suite_file
382       warn 'test_suite_file deprecated, use test_files'
383       test_files.first
384     end
386     def test_suite_file=(val)
387       warn 'test_suite_file= deprecated, use test_files='
388       @test_files = [] unless defined? @test_files
389       @test_files << val
390     end
392     # true when this gemspec has been loaded from a specifications directory.
393     # This attribute is not persisted.
395     attr_writer :loaded
397     # Path this gemspec was loaded from.  This attribute is not persisted.
398     attr_accessor :loaded_from
400     # Special accessor behaviours (overwriting default) --------------
401     
402     overwrite_accessor :version= do |version|
403       @version = Version.create(version)
404     end
406     overwrite_accessor :platform do
407       @new_platform
408     end
410     overwrite_accessor :platform= do |platform|
411       if @original_platform.nil? or
412          @original_platform == Gem::Platform::RUBY then
413         @original_platform = platform
414       end
416       case platform
417       when Gem::Platform::CURRENT then
418         @new_platform = Gem::Platform.local
419         @original_platform = @new_platform.to_s
421       when Gem::Platform then
422         @new_platform = platform
424       # legacy constants
425       when nil, Gem::Platform::RUBY then
426         @new_platform = Gem::Platform::RUBY
427       when 'mswin32' then # was Gem::Platform::WIN32
428         @new_platform = Gem::Platform.new 'x86-mswin32'
429       when 'i586-linux' then # was Gem::Platform::LINUX_586
430         @new_platform = Gem::Platform.new 'x86-linux'
431       when 'powerpc-darwin' then # was Gem::Platform::DARWIN
432         @new_platform = Gem::Platform.new 'ppc-darwin'
433       else
434         @new_platform = Gem::Platform.new platform
435       end
437       @platform = @new_platform.to_s
439       @new_platform
440     end
442     overwrite_accessor :required_ruby_version= do |value|
443       @required_ruby_version = Gem::Requirement.create(value)
444     end
446     overwrite_accessor :required_rubygems_version= do |value|
447       @required_rubygems_version = Gem::Requirement.create(value)
448     end
450     overwrite_accessor :date= do |date|
451       # We want to end up with a Time object with one-day resolution.
452       # This is the cleanest, most-readable, faster-than-using-Date
453       # way to do it.
454       case date
455       when String then
456         @date = if /\A(\d{4})-(\d{2})-(\d{2})\Z/ =~ date then
457                   Time.local($1.to_i, $2.to_i, $3.to_i)
458                 else
459                   require 'time'
460                   Time.parse date
461                 end
462       when Time then
463         @date = Time.local(date.year, date.month, date.day)
464       when Date then
465         @date = Time.local(date.year, date.month, date.day)
466       else
467         @date = TODAY
468       end
469     end
471     overwrite_accessor :date do
472       self.date = nil if @date.nil?  # HACK Sets the default value for date
473       @date
474     end
476     overwrite_accessor :summary= do |str|
477       @summary = if str then
478                    str.strip.
479                    gsub(/(\w-)\n[ \t]*(\w)/, '\1\2').
480                    gsub(/\n[ \t]*/, " ")
481                  end
482     end
484     overwrite_accessor :description= do |str|
485       @description = if str then
486                        str.strip.
487                        gsub(/(\w-)\n[ \t]*(\w)/, '\1\2').
488                        gsub(/\n[ \t]*/, " ")
489                      end
490     end
492     overwrite_accessor :default_executable do
493       begin
494         if defined?(@default_executable) and @default_executable
495           result = @default_executable
496         elsif @executables and @executables.size == 1
497           result = Array(@executables).first
498         else
499           result = nil
500         end
501         result
502       rescue
503         nil
504       end
505     end
507     def add_bindir(executables)
508       return nil if executables.nil?
510       if @bindir then
511         Array(executables).map { |e| File.join(@bindir, e) }
512       else
513         executables
514       end
515     rescue
516       return nil
517     end
519     overwrite_accessor :files do
520       result = []
521       result.push(*@files) if defined?(@files)
522       result.push(*@test_files) if defined?(@test_files)
523       result.push(*(add_bindir(@executables)))
524       result.push(*@extra_rdoc_files) if defined?(@extra_rdoc_files)
525       result.push(*@extensions) if defined?(@extensions)
526       result.uniq.compact
527     end
529     # Files in the Gem under one of the require_paths
530     def lib_files
531       @files.select do |file|
532         require_paths.any? do |path|
533           file.index(path) == 0
534         end
535       end
536     end
538     overwrite_accessor :test_files do
539       # Handle the possibility that we have @test_suite_file but not
540       # @test_files.  This will happen when an old gem is loaded via
541       # YAML.
542       if defined? @test_suite_file then
543         @test_files = [@test_suite_file].flatten
544         @test_suite_file = nil
545       end
546       if defined?(@test_files) and @test_files then
547         @test_files
548       else
549         @test_files = []
550       end
551     end
553     # Predicates -----------------------------------------------------
554     
555     def loaded?; @loaded ? true : false ; end
556     def has_rdoc?; has_rdoc ? true : false ; end
557     def has_unit_tests?; not test_files.empty?; end
558     alias has_test_suite? has_unit_tests?               # (deprecated)
559     
560     # Constructors ---------------------------------------------------
561     
562     # Specification constructor.  Assigns the default values to the
563     # attributes, adds this spec to the list of loaded specs (see
564     # Specification.list), and yields itself for further initialization.
565     #
566     def initialize
567       @new_platform = nil
568       assign_defaults
569       @loaded = false
570       @loaded_from = nil
571       @@list << self
573       yield self if block_given?
575       @@gather.call(self) if @@gather
576     end
578     # Each attribute has a default value (possibly nil).  Here, we
579     # initialize all attributes to their default value.  This is
580     # done through the accessor methods, so special behaviours will
581     # be honored.  Furthermore, we take a _copy_ of the default so
582     # each specification instance has its own empty arrays, etc.
583     def assign_defaults
584       @@nil_attributes.each do |name|
585         instance_variable_set name, nil
586       end
588       @@non_nil_attributes.each do |name, default|
589         value = case default
590                 when Time, Numeric, Symbol, true, false, nil then default
591                 else default.dup
592                 end
594         instance_variable_set name, value
595       end
597       # HACK
598       instance_variable_set :@new_platform, Gem::Platform::RUBY
599     end
601     # Special loader for YAML files.  When a Specification object is
602     # loaded from a YAML file, it bypasses the normal Ruby object
603     # initialization routine (#initialize).  This method makes up for
604     # that and deals with gems of different ages.
605     #
606     # 'input' can be anything that YAML.load() accepts: String or IO. 
607     #
608     def self.from_yaml(input)
609       input = normalize_yaml_input input
610       spec = YAML.load input
612       if spec && spec.class == FalseClass then
613         raise Gem::EndOfYAMLException
614       end
616       unless Gem::Specification === spec then
617         raise Gem::Exception, "YAML data doesn't evaluate to gem specification"
618       end
620       unless (spec.instance_variables.include? '@specification_version' or
621               spec.instance_variables.include? :@specification_version) and
622              spec.instance_variable_get :@specification_version
623         spec.instance_variable_set :@specification_version, 
624                                    NONEXISTENT_SPECIFICATION_VERSION
625       end
627       spec
628     end 
630     def self.load(filename)
631       gemspec = nil
632       fail "NESTED Specification.load calls not allowed!" if @@gather
633       @@gather = proc { |gs| gemspec = gs }
634       data = File.read(filename)
635       eval(data)
636       gemspec
637     ensure
638       @@gather = nil
639     end
641     # Make sure the yaml specification is properly formatted with dashes.
642     def self.normalize_yaml_input(input)
643       result = input.respond_to?(:read) ? input.read : input
644       result = "--- " + result unless result =~ /^--- /
645       result
646     end
647     
648     # Instance methods -----------------------------------------------
649     
650     # Sets the rubygems_version to Gem::RubyGemsVersion.
651     #
652     def mark_version
653       @rubygems_version = RubyGemsVersion
654     end
656     # Ignore unknown attributes if the 
657     def method_missing(sym, *a, &b) # :nodoc:
658       if @specification_version > CURRENT_SPECIFICATION_VERSION and
659          sym.to_s =~ /=$/ then
660         warn "ignoring #{sym} loading #{full_name}" if $DEBUG
661       else
662         super
663       end
664     end
666     # Adds a development dependency to this Gem.  For example,
667     #
668     #   spec.add_development_dependency('jabber4r', '> 0.1', '<= 0.5')
669     #
670     # Development dependencies aren't installed by default, and
671     # aren't activated when a gem is required.
672     #
673     # gem:: [String or Gem::Dependency] The Gem name/dependency.
674     # requirements:: [default=">= 0"] The version requirements.
675     def add_development_dependency(gem, *requirements)
676       add_dependency_with_type(gem, :development, *requirements)
677     end
679     # Adds a runtime dependency to this Gem.  For example,
680     #
681     #   spec.add_runtime_dependency('jabber4r', '> 0.1', '<= 0.5')
682     #
683     # gem:: [String or Gem::Dependency] The Gem name/dependency.
684     # requirements:: [default=">= 0"] The version requirements.
685     def add_runtime_dependency(gem, *requirements)
686       add_dependency_with_type(gem, :runtime, *requirements)
687     end
689     alias add_dependency add_runtime_dependency
691     # Returns the full name (name-version) of this Gem.  Platform information
692     # is included (name-version-platform) if it is specified (and not the
693     # default Ruby platform).
694     #
695     def full_name
696       if platform == Gem::Platform::RUBY or platform.nil? then
697         "#{@name}-#{@version}"
698       else
699         "#{@name}-#{@version}-#{platform}"
700       end
701     end
703     # Returns the full name (name-version) of this gemspec using the original
704     # platform.
705     #
706     def original_name # :nodoc:
707       if platform == Gem::Platform::RUBY or platform.nil? then
708         "#{@name}-#{@version}"
709       else
710         "#{@name}-#{@version}-#{@original_platform}"
711       end
712     end
714     ##
715     # The full path to the gem (install path + full name).
717     def full_gem_path
718       path = File.join installation_path, 'gems', full_name
719       return path if File.directory? path
720       File.join installation_path, 'gems', original_name
721     end
723     ##
724     # The default (generated) file name of the gem.
726     def file_name
727       full_name + ".gem"
728     end
730     ##
731     # The directory that this gem was installed into.
733     def installation_path
734       path = File.dirname(@loaded_from).split(File::SEPARATOR)[0..-2]
735       path = path.join File::SEPARATOR
736       File.expand_path path
737     end
739     # Checks if this Specification meets the requirement of the supplied
740     # dependency.
741     # 
742     # dependency:: [Gem::Dependency] the dependency to check
743     # return:: [Boolean] true if dependency is met, otherwise false
744     #
745     def satisfies_requirement?(dependency)
746       return @name == dependency.name && 
747         dependency.version_requirements.satisfied_by?(@version)
748     end
750     # Comparison methods ---------------------------------------------
752     def sort_obj
753       [@name, @version.to_ints, @new_platform == Gem::Platform::RUBY ? -1 : 1]
754     end
756     def <=>(other) # :nodoc:
757       sort_obj <=> other.sort_obj
758     end
760     # Tests specs for equality (across all attributes).
761     def ==(other) # :nodoc:
762       self.class === other && same_attributes?(other)
763     end
765     alias eql? == # :nodoc:
767     def same_attributes?(other)
768       @@attributes.each do |name, default|
769         return false unless self.send(name) == other.send(name)
770       end
771       true
772     end
773     private :same_attributes?
775     def hash # :nodoc:
776       @@attributes.inject(0) { |hash_code, (name, default_value)|
777         n = self.send(name).hash
778         hash_code + n
779       }
780     end
782     # Export methods (YAML and Ruby code) ----------------------------
784     def to_yaml(opts = {}) # :nodoc:
785       mark_version
787       attributes = @@attributes.map { |name,| name.to_s }.sort
788       attributes = attributes - %w[name version platform]
790       yaml = YAML.quick_emit object_id, opts do |out|
791         out.map taguri, to_yaml_style do |map|
792           map.add 'name', @name
793           map.add 'version', @version
794           platform = case @original_platform
795                      when nil, '' then
796                        'ruby'
797                      when String then
798                        @original_platform
799                      else
800                        @original_platform.to_s
801                      end
802           map.add 'platform', platform
804           attributes.each do |name|
805             map.add name, instance_variable_get("@#{name}")
806           end
807         end
808       end
809     end
811     def yaml_initialize(tag, vals) # :nodoc:
812       vals.each do |ivar, val|
813         instance_variable_set "@#{ivar}", val
814       end
816       @original_platform = @platform # for backwards compatibility
817       self.platform = Gem::Platform.new @platform
818     end
820     ##
821     # Returns a Ruby code representation of this specification, such that it
822     # can be eval'ed and reconstruct the same specification later.  Attributes
823     # that still have their default values are omitted.
825     def to_ruby
826       mark_version
827       result = []
828       result << "Gem::Specification.new do |s|"
830       result << "  s.name = #{ruby_code name}"
831       result << "  s.version = #{ruby_code version}"
832       unless platform.nil? or platform == Gem::Platform::RUBY then
833         result << "  s.platform = #{ruby_code original_platform}"
834       end
835       result << ""
836       result << "  s.required_rubygems_version = #{ruby_code required_rubygems_version} if s.respond_to? :required_rubygems_version="
838       handled = [
839         :dependencies,
840         :name,
841         :platform,
842         :required_rubygems_version,
843         :specification_version,
844         :version,
845       ]
847       attributes = @@attributes.sort_by { |attr_name,| attr_name.to_s }
849       attributes.each do |attr_name, default|
850         next if handled.include? attr_name
851         current_value = self.send(attr_name)
852         if current_value != default or
853            self.class.required_attribute? attr_name then
854           result << "  s.#{attr_name} = #{ruby_code current_value}"
855         end
856       end
858       result << nil
859       result << "  if s.respond_to? :specification_version then"
860       result << "    current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION"
861       result << "    s.specification_version = #{specification_version}"
862       result << nil
864       result << "    if current_version >= 3 then"
866       unless dependencies.empty? then
867         dependencies.each do |dep|
868           version_reqs_param = dep.requirements_list.inspect
869           dep.instance_variable_set :@type, :runtime if dep.type.nil? # HACK
870           result << "      s.add_#{dep.type}_dependency(%q<#{dep.name}>, #{version_reqs_param})"
871         end
872       end
874       result << "    else"
876       unless dependencies.empty? then
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       end
883       result << '    end'
885       result << "  else"
886         dependencies.each do |dep|
887           version_reqs_param = dep.requirements_list.inspect
888           result << "    s.add_dependency(%q<#{dep.name}>, #{version_reqs_param})"
889         end
890       result << "  end"
892       result << "end"
893       result << nil
895       result.join "\n"
896     end
898     # Validation and normalization methods ---------------------------
900     # Checks that the specification contains all required fields, and
901     # does a very basic sanity check.
902     #
903     # Raises InvalidSpecificationException if the spec does not pass
904     # the checks..
905     def validate
906       extend Gem::UserInteraction
908       normalize
910       if rubygems_version != RubyGemsVersion then
911         raise Gem::InvalidSpecificationException,
912               "expected RubyGems version #{RubyGemsVersion}, was #{rubygems_version}"
913       end
915       @@required_attributes.each do |symbol|
916         unless self.send symbol then
917           raise Gem::InvalidSpecificationException,
918                 "missing value for attribute #{symbol}"
919         end
920       end 
922       if require_paths.empty? then
923         raise Gem::InvalidSpecificationException,
924               "specification must have at least one require_path"
925       end
927       case platform
928       when Gem::Platform, Platform::RUBY then # ok
929       else
930         raise Gem::InvalidSpecificationException,
931               "invalid platform #{platform.inspect}, see Gem::Platform"
932       end
934       unless Array === authors and
935              authors.all? { |author| String === author } then
936         raise Gem::InvalidSpecificationException,
937               'authors must be Array of Strings'
938       end
940       # Warnings
942       %w[author email homepage rubyforge_project summary].each do |attribute|
943         value = self.send attribute
944         alert_warning "no #{attribute} specified" if value.nil? or value.empty?
945       end
947       alert_warning "RDoc will not be generated (has_rdoc == false)" unless
948         has_rdoc
950       alert_warning "deprecated autorequire specified" if autorequire
952       executables.each do |executable|
953         executable_path = File.join bindir, executable
954         shebang = File.read(executable_path, 2) == '#!'
956         alert_warning "#{executable_path} is missing #! line" unless shebang
957       end
959       true
960     end
962     # Normalize the list of files so that:
963     # * All file lists have redundancies removed.
964     # * Files referenced in the extra_rdoc_files are included in the
965     #   package file list. 
966     #
967     # Also, the summary and description are converted to a normal
968     # format. 
969     def normalize
970       if defined?(@extra_rdoc_files) and @extra_rdoc_files then
971         @extra_rdoc_files.uniq!
972         @files ||= []
973         @files.concat(@extra_rdoc_files)
974       end
975       @files.uniq! if @files
976     end
978     # Dependency methods ---------------------------------------------
979     
980     # Return a list of all gems that have a dependency on this
981     # gemspec.  The list is structured with entries that conform to:
982     #
983     #   [depending_gem, dependency, [list_of_gems_that_satisfy_dependency]]
984     #
985     # return:: [Array] [[dependent_gem, dependency, [list_of_satisfiers]]]
986     #
987     def dependent_gems
988       out = []
989       Gem.source_index.each do |name,gem|
990         gem.dependencies.each do |dep|
991           if self.satisfies_requirement?(dep) then
992             sats = []
993             find_all_satisfiers(dep) do |sat|
994               sats << sat
995             end
996             out << [gem, dep, sats]
997           end
998         end
999       end
1000       out
1001     end
1003     def to_s
1004       "#<Gem::Specification name=#{@name} version=#{@version}>"
1005     end
1007     private
1009     def add_dependency_with_type(dependency, type, *requirements)
1010       requirements = if requirements.empty? then
1011                        Gem::Requirement.default
1012                      else
1013                        requirements.flatten
1014                      end
1016       unless dependency.respond_to?(:name) &&
1017         dependency.respond_to?(:version_requirements)
1019         dependency = Dependency.new(dependency, requirements, type)
1020       end
1022       dependencies << dependency
1023     end
1025     def find_all_satisfiers(dep)
1026       Gem.source_index.each do |name,gem|
1027         if(gem.satisfies_requirement?(dep)) then
1028           yield gem
1029         end
1030       end
1031     end
1033     # Return a string containing a Ruby code representation of the
1034     # given object.
1035     def ruby_code(obj)
1036       case obj
1037       when String            then '%q{' + obj + '}'
1038       when Array             then obj.inspect
1039       when Gem::Version      then obj.to_s.inspect
1040       when Date              then '%q{' + obj.strftime('%Y-%m-%d') + '}'
1041       when Time              then '%q{' + obj.strftime('%Y-%m-%d') + '}'
1042       when Numeric           then obj.inspect
1043       when true, false, nil  then obj.inspect
1044       when Gem::Platform     then "Gem::Platform.new(#{obj.to_a.inspect})"
1045       when Gem::Requirement  then "Gem::Requirement.new(#{obj.to_s.inspect})"
1046       else raise Exception, "ruby_code case not handled: #{obj.class}"
1047       end
1048     end
1050   end