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 CURRENT_SPECIFICATION_VERSION = 3
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)'],
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]"'
77 'Added "required_rubygems_version"',
78 'Now forward-compatible with future versions',
81 'Added dependency types',
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)
92 # ------------------------- Class variables.
94 # List of Specification instances.
97 # Optional block used to gather newly defined instances.
100 # List of attribute names: [:name, :version, ...]
101 @@required_attributes = []
103 # List of _all_ attributes and default values: [[:name, nil], [:bindir, 'bin'], ...]
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.
115 # ------------------------- Convenience class methods.
117 def self.attribute_names
118 @@attributes.map { |name, default| name }
121 def self.attribute_defaults
125 def self.default_value(name)
126 @@default_value[name]
129 def self.required_attributes
130 @@required_attributes.dup
133 def self.required_attribute?(name)
134 @@required_attributes.include? name.to_sym
137 def self.array_attributes
138 @@array_attributes.dup
141 # ------------------------- Infrastructure class methods.
143 # A list of Specification instances that have been defined in this Ruby instance.
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
155 # The reader method behaves like this:
157 # @attribute ||= (copy of default value)
160 # This allows lazy initialization of attributes to their default
163 def self.attribute(name, default=nil)
164 ivar_name = "@#{name}".intern
166 @@nil_attributes << ivar_name
168 @@non_nil_attributes << [ivar_name, default]
171 @@attributes << [name, default]
172 @@default_value[name] = default
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] = []
189 @#{name} = Array(value)
193 module_eval code, __FILE__, __LINE__ - 9
196 # Same as attribute above, but also records this attribute as mandatory.
197 def self.required_attribute(*args)
198 @@required_attributes << args.first
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)
210 # Shortcut for creating several attributes at once (each with a default value of
212 def self.attributes(*args)
218 # Some attributes require special behaviour when they are accessed. This allows for
220 def self.overwrite_accessor(name, &block)
222 define_method(name, &block)
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
231 # s.require_path = 'mylib'
235 # s.require_paths = ['mylib']
237 # That above convenience is available courtesy of
239 # attribute_alias_singular :require_path, :require_paths
241 def self.attribute_alias_singular(singular, plural)
242 define_method("#{singular}=") { |val|
243 send("#{plural}=", [val])
245 define_method("#{singular}") {
246 val = send("#{plural}")
247 val.nil? ? nil : val.first
251 # Dump only crucial instance variables.
254 def _dump(limit) # :nodoc:
257 @specification_version,
260 (Time === @date ? @date : (require 'time'; Time.parse(@date.to_s))),
262 @required_ruby_version,
263 @required_rubygems_version,
276 # Load custom marshal format, re-initializing defaults as needed
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}"
291 spec.instance_variable_set :@rubygems_version, array[0]
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
314 # REQUIRED gemspec attributes ------------------------------------
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 ------------------------------------
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
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 }
359 def development_dependencies
360 dependencies.select { |d| d.type == :development }
363 # ALIASED gemspec attributes -------------------------------------
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 ----------------------------------
373 warn 'test_suite_file deprecated, use test_files'
377 def test_suite_file=(val)
378 warn 'test_suite_file= deprecated, use test_files='
379 @test_files = [] unless defined? @test_files
383 # true when this gemspec has been loaded from a specifications directory.
384 # This attribute is not persisted.
388 # Path this gemspec was loaded from. This attribute is not persisted.
389 attr_accessor :loaded_from
391 # Special accessor behaviours (overwriting default) --------------
393 overwrite_accessor :version= do |version|
394 @version = Version.create(version)
397 overwrite_accessor :platform do
401 overwrite_accessor :platform= do |platform|
402 if @original_platform.nil? or
403 @original_platform == Gem::Platform::RUBY then
404 @original_platform = 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
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'
425 @new_platform = Gem::Platform.new platform
428 @platform = @new_platform.to_s
433 overwrite_accessor :required_ruby_version= do |value|
434 @required_ruby_version = Gem::Requirement.create(value)
437 overwrite_accessor :required_rubygems_version= do |value|
438 @required_rubygems_version = Gem::Requirement.create(value)
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
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)
454 @date = Time.local(date.year, date.month, date.day)
456 @date = Time.local(date.year, date.month, date.day)
462 overwrite_accessor :date do
463 self.date = nil if @date.nil? # HACK Sets the default value for date
467 overwrite_accessor :summary= do |str|
468 @summary = if str then
470 gsub(/(\w-)\n[ \t]*(\w)/, '\1\2').
471 gsub(/\n[ \t]*/, " ")
475 overwrite_accessor :description= do |str|
476 @description = if str then
478 gsub(/(\w-)\n[ \t]*(\w)/, '\1\2').
479 gsub(/\n[ \t]*/, " ")
483 overwrite_accessor :default_executable do
485 if defined?(@default_executable) and @default_executable
486 result = @default_executable
487 elsif @executables and @executables.size == 1
488 result = Array(@executables).first
498 def add_bindir(executables)
499 return nil if executables.nil?
502 Array(executables).map { |e| File.join(@bindir, e) }
510 overwrite_accessor :files do
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)
520 # Files in the Gem under one of the require_paths
522 @files.select do |file|
523 require_paths.any? do |path|
524 file.index(path) == 0
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
533 if defined? @test_suite_file then
534 @test_files = [@test_suite_file].flatten
535 @test_suite_file = nil
537 if defined?(@test_files) and @test_files then
544 # Predicates -----------------------------------------------------
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)
551 # Constructors ---------------------------------------------------
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.
564 yield self if block_given?
566 @@gather.call(self) if @@gather
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.
575 @@nil_attributes.each do |name|
576 instance_variable_set name, nil
579 @@non_nil_attributes.each do |name, default|
581 when Time, Numeric, Symbol, true, false, nil then default
585 instance_variable_set name, value
589 instance_variable_set :@new_platform, Gem::Platform::RUBY
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.
597 # 'input' can be anything that YAML.load() accepts: String or IO.
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
607 unless Gem::Specification === spec then
608 raise Gem::Exception, "YAML data doesn't evaluate to gem specification"
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
621 def self.load(filename)
623 fail "NESTED Specification.load calls not allowed!" if @@gather
624 @@gather = proc { |gs| gemspec = gs }
625 data = File.read(filename)
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 =~ /^--- /
639 # Instance methods -----------------------------------------------
641 # Sets the rubygems_version to Gem::RubyGemsVersion.
644 @rubygems_version = RubyGemsVersion
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
657 # Adds a development dependency to this Gem. For example,
659 # spec.add_development_dependency('jabber4r', '> 0.1', '<= 0.5')
661 # Development dependencies aren't installed by default, and
662 # aren't activated when a gem is required.
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)
670 # Adds a runtime dependency to this Gem. For example,
672 # spec.add_runtime_dependency('jabber4r', '> 0.1', '<= 0.5')
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)
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).
687 if platform == Gem::Platform::RUBY or platform.nil? then
688 "#{@name}-#{@version}"
690 "#{@name}-#{@version}-#{platform}"
694 # Returns the full name (name-version) of this gemspec using the original
697 def original_name # :nodoc:
698 if platform == Gem::Platform::RUBY or platform.nil? then
699 "#{@name}-#{@version}"
701 "#{@name}-#{@version}-#{@original_platform}"
706 # The full path to the gem (install path + full name).
709 path = File.join installation_path, 'gems', full_name
710 return path if File.directory? path
711 File.join installation_path, 'gems', original_name
715 # The default (generated) file name of the gem.
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
730 # Checks if this Specification meets the requirement of the supplied
733 # dependency:: [Gem::Dependency] the dependency to check
734 # return:: [Boolean] true if dependency is met, otherwise false
736 def satisfies_requirement?(dependency)
737 return @name == dependency.name &&
738 dependency.version_requirements.satisfied_by?(@version)
741 # Comparison methods ---------------------------------------------
744 [@name, @version.to_ints, @new_platform == Gem::Platform::RUBY ? -1 : 1]
747 def <=>(other) # :nodoc:
748 sort_obj <=> other.sort_obj
751 # Tests specs for equality (across all attributes).
752 def ==(other) # :nodoc:
753 self.class === other && same_attributes?(other)
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)
764 private :same_attributes?
767 @@attributes.inject(0) { |hash_code, (name, default_value)|
768 n = self.send(name).hash
773 # Export methods (YAML and Ruby code) ----------------------------
775 def to_yaml(opts = {}) # :nodoc:
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
791 @original_platform.to_s
793 map.add 'platform', platform
795 attributes.each do |name|
796 map.add name, instance_variable_get("@#{name}")
802 def yaml_initialize(tag, vals) # :nodoc:
803 vals.each do |ivar, val|
804 instance_variable_set "@#{ivar}", val
807 @original_platform = @platform # for backwards compatibility
808 self.platform = Gem::Platform.new @platform
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.
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}"
827 result << " s.required_rubygems_version = #{ruby_code required_rubygems_version} if s.respond_to? :required_rubygems_version="
833 :required_rubygems_version,
834 :specification_version,
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}"
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}"
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})"
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})"
877 dependencies.each do |dep|
878 version_reqs_param = dep.requirements_list.inspect
879 result << " s.add_dependency(%q<#{dep.name}>, #{version_reqs_param})"
889 # Validation and normalization methods ---------------------------
891 # Checks that the specification contains all required fields, and
892 # does a very basic sanity check.
894 # Raises InvalidSpecificationException if the spec does not pass
897 extend Gem::UserInteraction
901 if rubygems_version != RubyGemsVersion then
902 raise Gem::InvalidSpecificationException,
903 "expected RubyGems version #{RubyGemsVersion}, was #{rubygems_version}"
906 @@required_attributes.each do |symbol|
907 unless self.send symbol then
908 raise Gem::InvalidSpecificationException,
909 "missing value for attribute #{symbol}"
913 if require_paths.empty? then
914 raise Gem::InvalidSpecificationException,
915 "specification must have at least one require_path"
919 when Gem::Platform, Platform::RUBY then # ok
921 raise Gem::InvalidSpecificationException,
922 "invalid platform #{platform.inspect}, see Gem::Platform"
925 unless Array === authors and
926 authors.all? { |author| String === author } then
927 raise Gem::InvalidSpecificationException,
928 'authors must be Array of Strings'
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?
938 alert_warning "RDoc will not be generated (has_rdoc == false)" unless
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
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
958 # Also, the summary and description are converted to a normal
961 if defined?(@extra_rdoc_files) and @extra_rdoc_files then
962 @extra_rdoc_files.uniq!
964 @files.concat(@extra_rdoc_files)
966 @files.uniq! if @files
969 # Dependency methods ---------------------------------------------
971 # Return a list of all gems that have a dependency on this
972 # gemspec. The list is structured with entries that conform to:
974 # [depending_gem, dependency, [list_of_gems_that_satisfy_dependency]]
976 # return:: [Array] [[dependent_gem, dependency, [list_of_satisfiers]]]
980 Gem.source_index.each do |name,gem|
981 gem.dependencies.each do |dep|
982 if self.satisfies_requirement?(dep) then
984 find_all_satisfiers(dep) do |sat|
987 out << [gem, dep, sats]
995 "#<Gem::Specification name=#{@name} version=#{@version}>"
1000 def add_dependency_with_type(dependency, type, *requirements)
1001 requirements = if requirements.empty? then
1002 Gem::Requirement.default
1004 requirements.flatten
1007 unless dependency.respond_to?(:name) &&
1008 dependency.respond_to?(:version_requirements)
1010 dependency = Dependency.new(dependency, requirements, type)
1013 dependencies << dependency
1016 def find_all_satisfiers(dep)
1017 Gem.source_index.each do |name,gem|
1018 if(gem.satisfies_requirement?(dep)) then
1024 # Return a string containing a Ruby code representation of the
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}"