2 # Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
4 # See LICENSE.txt for permissions.
8 require 'rubygems/version'
9 require 'rubygems/requirement'
10 require 'rubygems/platform'
13 # Time::today has been deprecated in 0.9.5 and will be removed.
14 if RUBY_VERSION < '1.9' then
17 t - ((t.to_f + t.gmt_offset) % 86400)
18 end unless defined? Time.today
21 class Date; end # for ruby_code if date.rb wasn't required
27 # == Gem::Specification
29 # The Specification class contains the metadata for a Gem. Typically
30 # defined in a .gemspec file or a Rakefile, and looks like this:
32 # spec = Gem::Specification.new do |s|
35 # s.summary = 'Example gem specification'
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.
45 # Allows deinstallation of gems with legacy platforms.
47 attr_accessor :original_platform # :nodoc:
49 # ------------------------- Specification version constants.
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
58 # The specification version applied to any new Specification instances
59 # created. This should be bumped whenever something in the spec format
62 # When updating this number, be sure to also update #to_ruby.
64 # NOTE RubyGems < 1.2 cannot load specification versions > 2.
66 CURRENT_SPECIFICATION_VERSION = 2
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)'],
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]"'
79 'Added "required_rubygems_version"',
80 'Now forward-compatible with future versions',
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)
91 # ------------------------- Class variables.
93 # List of Specification instances.
96 # Optional block used to gather newly defined instances.
99 # List of attribute names: [:name, :version, ...]
100 @@required_attributes = []
102 # List of _all_ attributes and default values: [[:name, nil], [:bindir, 'bin'], ...]
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.
114 # ------------------------- Convenience class methods.
116 def self.attribute_names
117 @@attributes.map { |name, default| name }
120 def self.attribute_defaults
124 def self.default_value(name)
125 @@default_value[name]
128 def self.required_attributes
129 @@required_attributes.dup
132 def self.required_attribute?(name)
133 @@required_attributes.include? name.to_sym
136 def self.array_attributes
137 @@array_attributes.dup
140 # ------------------------- Infrastructure class methods.
142 # A list of Specification instances that have been defined in this Ruby instance.
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
154 # The reader method behaves like this:
156 # @attribute ||= (copy of default value)
159 # This allows lazy initialization of attributes to their default
162 def self.attribute(name, default=nil)
163 ivar_name = "@#{name}".intern
165 @@nil_attributes << ivar_name
167 @@non_nil_attributes << [ivar_name, default]
170 @@attributes << [name, default]
171 @@default_value[name] = default
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] = []
188 @#{name} = Array(value)
192 module_eval code, __FILE__, __LINE__ - 9
195 # Same as attribute above, but also records this attribute as mandatory.
196 def self.required_attribute(*args)
197 @@required_attributes << args.first
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)
209 # Shortcut for creating several attributes at once (each with a default value of
211 def self.attributes(*args)
217 # Some attributes require special behaviour when they are accessed. This allows for
219 def self.overwrite_accessor(name, &block)
221 define_method(name, &block)
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
230 # s.require_path = 'mylib'
234 # s.require_paths = ['mylib']
236 # That above convenience is available courtesy of
238 # attribute_alias_singular :require_path, :require_paths
240 def self.attribute_alias_singular(singular, plural)
241 define_method("#{singular}=") { |val|
242 send("#{plural}=", [val])
244 define_method("#{singular}") {
245 val = send("#{plural}")
246 val.nil? ? nil : val.first
251 # Dump only crucial instance variables.
258 @specification_version,
261 (Time === @date ? @date : (require 'time'; Time.parse(@date.to_s))),
263 @required_ruby_version,
264 @required_rubygems_version,
278 # Load custom marshal format, re-initializing defaults as needed
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,
291 MARSHAL_FIELDS[current_version]
293 MARSHAL_FIELDS[spec.specification_version]
296 if array.size < field_count then
297 raise TypeError, "invalid Gem::Specification format #{array.inspect}"
300 spec.instance_variable_set :@rubygems_version, array[0]
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
323 # REQUIRED gemspec attributes ------------------------------------
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 ------------------------------------
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
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 }
368 def development_dependencies
369 dependencies.select { |d| d.type == :development }
372 # ALIASED gemspec attributes -------------------------------------
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 ----------------------------------
382 warn 'test_suite_file deprecated, use test_files'
386 def test_suite_file=(val)
387 warn 'test_suite_file= deprecated, use test_files='
388 @test_files = [] unless defined? @test_files
392 # true when this gemspec has been loaded from a specifications directory.
393 # This attribute is not persisted.
397 # Path this gemspec was loaded from. This attribute is not persisted.
398 attr_accessor :loaded_from
400 # Special accessor behaviours (overwriting default) --------------
402 overwrite_accessor :version= do |version|
403 @version = Version.create(version)
406 overwrite_accessor :platform do
410 overwrite_accessor :platform= do |platform|
411 if @original_platform.nil? or
412 @original_platform == Gem::Platform::RUBY then
413 @original_platform = 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
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'
434 @new_platform = Gem::Platform.new platform
437 @platform = @new_platform.to_s
442 overwrite_accessor :required_ruby_version= do |value|
443 @required_ruby_version = Gem::Requirement.create(value)
446 overwrite_accessor :required_rubygems_version= do |value|
447 @required_rubygems_version = Gem::Requirement.create(value)
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
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)
463 @date = Time.local(date.year, date.month, date.day)
465 @date = Time.local(date.year, date.month, date.day)
471 overwrite_accessor :date do
472 self.date = nil if @date.nil? # HACK Sets the default value for date
476 overwrite_accessor :summary= do |str|
477 @summary = if str then
479 gsub(/(\w-)\n[ \t]*(\w)/, '\1\2').
480 gsub(/\n[ \t]*/, " ")
484 overwrite_accessor :description= do |str|
485 @description = if str then
487 gsub(/(\w-)\n[ \t]*(\w)/, '\1\2').
488 gsub(/\n[ \t]*/, " ")
492 overwrite_accessor :default_executable do
494 if defined?(@default_executable) and @default_executable
495 result = @default_executable
496 elsif @executables and @executables.size == 1
497 result = Array(@executables).first
507 def add_bindir(executables)
508 return nil if executables.nil?
511 Array(executables).map { |e| File.join(@bindir, e) }
519 overwrite_accessor :files do
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)
529 # Files in the Gem under one of the require_paths
531 @files.select do |file|
532 require_paths.any? do |path|
533 file.index(path) == 0
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
542 if defined? @test_suite_file then
543 @test_files = [@test_suite_file].flatten
544 @test_suite_file = nil
546 if defined?(@test_files) and @test_files then
553 # Predicates -----------------------------------------------------
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)
560 # Constructors ---------------------------------------------------
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.
573 yield self if block_given?
575 @@gather.call(self) if @@gather
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.
584 @@nil_attributes.each do |name|
585 instance_variable_set name, nil
588 @@non_nil_attributes.each do |name, default|
590 when Time, Numeric, Symbol, true, false, nil then default
594 instance_variable_set name, value
598 instance_variable_set :@new_platform, Gem::Platform::RUBY
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.
606 # 'input' can be anything that YAML.load() accepts: String or IO.
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
616 unless Gem::Specification === spec then
617 raise Gem::Exception, "YAML data doesn't evaluate to gem specification"
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
630 def self.load(filename)
632 fail "NESTED Specification.load calls not allowed!" if @@gather
633 @@gather = proc { |gs| gemspec = gs }
634 data = File.read(filename)
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 =~ /^--- /
648 # Instance methods -----------------------------------------------
650 # Sets the rubygems_version to Gem::RubyGemsVersion.
653 @rubygems_version = RubyGemsVersion
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
666 # Adds a development dependency to this Gem. For example,
668 # spec.add_development_dependency('jabber4r', '> 0.1', '<= 0.5')
670 # Development dependencies aren't installed by default, and
671 # aren't activated when a gem is required.
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)
679 # Adds a runtime dependency to this Gem. For example,
681 # spec.add_runtime_dependency('jabber4r', '> 0.1', '<= 0.5')
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)
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).
696 if platform == Gem::Platform::RUBY or platform.nil? then
697 "#{@name}-#{@version}"
699 "#{@name}-#{@version}-#{platform}"
703 # Returns the full name (name-version) of this gemspec using the original
706 def original_name # :nodoc:
707 if platform == Gem::Platform::RUBY or platform.nil? then
708 "#{@name}-#{@version}"
710 "#{@name}-#{@version}-#{@original_platform}"
715 # The full path to the gem (install path + full name).
718 path = File.join installation_path, 'gems', full_name
719 return path if File.directory? path
720 File.join installation_path, 'gems', original_name
724 # The default (generated) file name of the gem.
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
739 # Checks if this Specification meets the requirement of the supplied
742 # dependency:: [Gem::Dependency] the dependency to check
743 # return:: [Boolean] true if dependency is met, otherwise false
745 def satisfies_requirement?(dependency)
746 return @name == dependency.name &&
747 dependency.version_requirements.satisfied_by?(@version)
750 # Comparison methods ---------------------------------------------
753 [@name, @version.to_ints, @new_platform == Gem::Platform::RUBY ? -1 : 1]
756 def <=>(other) # :nodoc:
757 sort_obj <=> other.sort_obj
760 # Tests specs for equality (across all attributes).
761 def ==(other) # :nodoc:
762 self.class === other && same_attributes?(other)
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)
773 private :same_attributes?
776 @@attributes.inject(0) { |hash_code, (name, default_value)|
777 n = self.send(name).hash
782 # Export methods (YAML and Ruby code) ----------------------------
784 def to_yaml(opts = {}) # :nodoc:
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
800 @original_platform.to_s
802 map.add 'platform', platform
804 attributes.each do |name|
805 map.add name, instance_variable_get("@#{name}")
811 def yaml_initialize(tag, vals) # :nodoc:
812 vals.each do |ivar, val|
813 instance_variable_set "@#{ivar}", val
816 @original_platform = @platform # for backwards compatibility
817 self.platform = Gem::Platform.new @platform
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.
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}"
836 result << " s.required_rubygems_version = #{ruby_code required_rubygems_version} if s.respond_to? :required_rubygems_version="
842 :required_rubygems_version,
843 :specification_version,
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}"
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}"
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})"
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})"
886 dependencies.each do |dep|
887 version_reqs_param = dep.requirements_list.inspect
888 result << " s.add_dependency(%q<#{dep.name}>, #{version_reqs_param})"
898 # Validation and normalization methods ---------------------------
900 # Checks that the specification contains all required fields, and
901 # does a very basic sanity check.
903 # Raises InvalidSpecificationException if the spec does not pass
906 extend Gem::UserInteraction
910 if rubygems_version != RubyGemsVersion then
911 raise Gem::InvalidSpecificationException,
912 "expected RubyGems version #{RubyGemsVersion}, was #{rubygems_version}"
915 @@required_attributes.each do |symbol|
916 unless self.send symbol then
917 raise Gem::InvalidSpecificationException,
918 "missing value for attribute #{symbol}"
922 if require_paths.empty? then
923 raise Gem::InvalidSpecificationException,
924 "specification must have at least one require_path"
928 when Gem::Platform, Platform::RUBY then # ok
930 raise Gem::InvalidSpecificationException,
931 "invalid platform #{platform.inspect}, see Gem::Platform"
934 unless Array === authors and
935 authors.all? { |author| String === author } then
936 raise Gem::InvalidSpecificationException,
937 'authors must be Array of Strings'
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?
947 alert_warning "RDoc will not be generated (has_rdoc == false)" unless
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
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
967 # Also, the summary and description are converted to a normal
970 if defined?(@extra_rdoc_files) and @extra_rdoc_files then
971 @extra_rdoc_files.uniq!
973 @files.concat(@extra_rdoc_files)
975 @files.uniq! if @files
978 # Dependency methods ---------------------------------------------
980 # Return a list of all gems that have a dependency on this
981 # gemspec. The list is structured with entries that conform to:
983 # [depending_gem, dependency, [list_of_gems_that_satisfy_dependency]]
985 # return:: [Array] [[dependent_gem, dependency, [list_of_satisfiers]]]
989 Gem.source_index.each do |name,gem|
990 gem.dependencies.each do |dep|
991 if self.satisfies_requirement?(dep) then
993 find_all_satisfiers(dep) do |sat|
996 out << [gem, dep, sats]
1004 "#<Gem::Specification name=#{@name} version=#{@version}>"
1009 def add_dependency_with_type(dependency, type, *requirements)
1010 requirements = if requirements.empty? then
1011 Gem::Requirement.default
1013 requirements.flatten
1016 unless dependency.respond_to?(:name) &&
1017 dependency.respond_to?(:version_requirements)
1019 dependency = Dependency.new(dependency, requirements, type)
1022 dependencies << dependency
1025 def find_all_satisfiers(dep)
1026 Gem.source_index.each do |name,gem|
1027 if(gem.satisfies_requirement?(dep)) then
1033 # Return a string containing a Ruby code representation of the
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}"