You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@buildr.apache.org by as...@apache.org on 2008/10/17 03:02:10 UTC

svn commit: r705438 - in /incubator/buildr/trunk: CHANGELOG _buildr bin/buildr lib/buildr/core/application.rb lib/buildr/core/project.rb

Author: assaf
Date: Thu Oct 16 18:02:09 2008
New Revision: 705438

URL: http://svn.apache.org/viewvc?rev=705438&view=rev
Log:
Bringing Buildr::Application to better extend Rake::Application from Rake 0.8.3, along introduction of a few new options from Rake.

No longer using buildr:initialize task, calling Buildr.projects instead, so this would break Nailgun.

Modified:
    incubator/buildr/trunk/CHANGELOG
    incubator/buildr/trunk/_buildr
    incubator/buildr/trunk/bin/buildr
    incubator/buildr/trunk/lib/buildr/core/application.rb
    incubator/buildr/trunk/lib/buildr/core/project.rb

Modified: incubator/buildr/trunk/CHANGELOG
URL: http://svn.apache.org/viewvc/incubator/buildr/trunk/CHANGELOG?rev=705438&r1=705437&r2=705438&view=diff
==============================================================================
--- incubator/buildr/trunk/CHANGELOG (original)
+++ incubator/buildr/trunk/CHANGELOG Thu Oct 16 18:02:09 2008
@@ -1,5 +1,7 @@
 1.3.4 (Pending)
 * Change: Upgraded to use Rake 0.8.3, RSpec 1.1.8.
+* Change: Introduced new options from Rake 0.8.3: -I (libdir), -R (rakelib),
+          --rules, --no-search, --silent.
 * Fixed:  BUILDR-172 Scala compiler not loaded by default.
 * Fixed:  Removed double complete/fail messages showing up on console.
 

Modified: incubator/buildr/trunk/_buildr
URL: http://svn.apache.org/viewvc/incubator/buildr/trunk/_buildr?rev=705438&r1=705437&r2=705438&view=diff
==============================================================================
--- incubator/buildr/trunk/_buildr (original)
+++ incubator/buildr/trunk/_buildr Thu Oct 16 18:02:09 2008
@@ -19,7 +19,6 @@
 # For example to use jruby:
 #   export _BUILDR_RB=/path/to/jruby
 
-start = Time.now
 require 'rubygems'
 $LOAD_PATH << File.join(File.dirname(__FILE__), 'lib') << File.join(File.dirname(__FILE__), 'addon')
 spec = Gem::Specification.load(File.join(File.dirname(__FILE__), 'buildr.gemspec'))
@@ -28,11 +27,3 @@
 end
 require 'buildr'
 Buildr.application.run
-if verbose
-  elapsed = Time.now - start
-  real = []
-  real << ("%ih" % (elapsed / 3600)) if elapsed >= 3600
-  real << ("%im" % ((elapsed / 60) % 60)) if elapsed >= 60
-  real << ("%.3fs" % (elapsed % 60))
-  puts $terminal.color("Completed in #{real.join}", :green)
-end

Modified: incubator/buildr/trunk/bin/buildr
URL: http://svn.apache.org/viewvc/incubator/buildr/trunk/bin/buildr?rev=705438&r1=705437&r2=705438&view=diff
==============================================================================
--- incubator/buildr/trunk/bin/buildr (original)
+++ incubator/buildr/trunk/bin/buildr Thu Oct 16 18:02:09 2008
@@ -14,15 +14,6 @@
 # License for the specific language governing permissions and limitations under
 # the License.
 
-start = Time.now
 require 'rubygems'
 require 'buildr'
 Buildr.application.run
-if verbose
-  elapsed = Time.now - start
-  real = []
-  real << ("%ih" % (elapsed / 3600)) if elapsed >= 3600
-  real << ("%im" % ((elapsed / 60) % 60)) if elapsed >= 60
-  real << ("%.3fs" % (elapsed % 60))
-  puts $terminal.color("Completed in #{real.join}", :green)
-end

Modified: incubator/buildr/trunk/lib/buildr/core/application.rb
URL: http://svn.apache.org/viewvc/incubator/buildr/trunk/lib/buildr/core/application.rb?rev=705438&r1=705437&r2=705438&view=diff
==============================================================================
--- incubator/buildr/trunk/lib/buildr/core/application.rb (original)
+++ incubator/buildr/trunk/lib/buildr/core/application.rb Thu Oct 16 18:02:09 2008
@@ -13,6 +13,7 @@
 # License for the specific language governing permissions and limitations under
 # the License.
 
+
 # Portion of this file derived from Rake.
 # Copyright (c) 2003, 2004 Jim Weirich
 #
@@ -35,15 +36,14 @@
 # SOFTWARE.
 
 
-require 'highline/import'
 require 'rake'
+require 'highline/import'
 require 'rubygems/source_info_cache'
-require 'buildr/core/application_cli'
 require 'buildr/core/util'
 
 
 # Gem::user_home is nice, but ENV['HOME'] lets you override from the environment.
-ENV["HOME"] ||= File.expand_path(Gem::user_home)
+ENV['HOME'] ||= File.expand_path(Gem::user_home)
 ENV['BUILDR_ENV'] ||= 'development'
 
 
@@ -107,28 +107,42 @@
 
   class Application < Rake::Application #:nodoc:
 
+    # Deprecated: rakefile/Rakefile, removed in 1.5
     DEFAULT_BUILDFILES = ['buildfile', 'Buildfile'] + DEFAULT_RAKEFILES
     
-    include CommandLineInterface
+    #include CommandLineInterface
 
     attr_reader :rakefiles, :requires
     private :rakefiles, :requires
 
     def initialize
       super
-      @rakefiles = DEFAULT_BUILDFILES
-      @name = 'Buildr'
-      @requires = []
+      @rakefiles = DEFAULT_BUILDFILES.dup
       @top_level_tasks = []
-      parse_options
-      collect_tasks
       @home_dir = File.expand_path('.buildr', ENV['HOME'])
       mkpath @home_dir, :verbose=>false unless File.exist?(@home_dir)
-      @environment = ENV['BUILDR_ENV'] ||= 'development'
       @on_completion = []
       @on_failure = []
     end
 
+    def run
+      standard_exception_handling do
+        init 'Buildr'
+        load_buildfile
+        top_level
+      end
+    end
+
+    # Not for external consumption.
+    def switch_to_namespace(names) #:nodoc:
+      current, @scope = @scope, names
+      begin
+        yield
+      ensure
+        @scope = current
+      end
+    end
+
     # Returns list of Gems associated with this buildfile, as listed in build.yaml.
     # Each entry is of type Gem::Specification.
     attr_reader :gems
@@ -151,28 +165,13 @@
     def buildfile
       @buildfile_task ||= BuildfileTask.define_task(File.expand_path(rakefile))
     end
-    
+
     # Files that complement the buildfile itself
     def build_files #:nodoc:
+      deprecated 'Please call buildfile.prerequisites instead' 
       buildfile.prerequisites
     end
 
-    def run
-      standard_exception_handling do
-        find_buildfile
-        load_gems
-        load_artifacts
-        load_tasks
-        load_requires
-        load_buildfile
-        load_imports
-        task('buildr:initialize').invoke
-        top_level
-      end
-      title, message = 'Your build has completed', "#{Dir.pwd}\nbuildr #{@top_level_tasks.join(' ')}"
-      @on_completion.each { |block| block.call(title, message) rescue nil }
-    end
-
     # Yields to block on successful completion. Primarily used for notifications.
     def on_completion(&block)
       @on_completion << block
@@ -183,16 +182,6 @@
       @on_failure << block
     end
 
-    # Not for external consumption.
-    def switch_to_namespace(names) #:nodoc:
-      current, @scope = @scope, names
-      begin
-        yield
-      ensure
-        @scope = current
-      end
-    end
-
     # :call-seq:
     #   deprecated(message)
     #
@@ -213,30 +202,172 @@
       end
     end
 
-  private
-
-    # Returns Gem::Specification for every listed and installed Gem, Gem::Dependency
-    # for listed and uninstalled Gem, which is the installed before loading the buildfile.
-    def listed_gems #:nodoc:
-      Array(settings.build['gems']).map do |dep|
-        name, trail = dep.scan(/^\s*(\S*)\s*(.*)\s*$/).first
-        versions = trail.scan(/[=><~!]{0,2}\s*[\d\.]+/)
-        versions = ['>= 0'] if versions.empty?
-        dep = Gem::Dependency.new(name, versions)
-        Gem::SourceIndex.from_installed_gems.search(dep).last || dep
+  protected
+    
+    def load_buildfile # replaces load_rakefile
+      standard_exception_handling do
+        find_buildfile
+        load_gems
+        load_artifact_ns
+        load_tasks
+        raw_load_buildfile
       end
     end
 
-    # Load artifact specs from the build.yaml file, making them available 
-    # by name ( ruby symbols ).
-    def load_artifacts #:nodoc:
-      hash = settings.build['artifacts']
-      return unless hash
-      raise "Expected 'artifacts' element to be a hash" unless Hash === hash
-      # Currently we only use one artifact namespace to rule them all. (the root NS)
-      Buildr::ArtifactNamespace.load(:root => hash)
+    def top_level # adds on_completion hook
+      standard_exception_handling do
+        if options.show_tasks
+          display_tasks_and_comments
+        elsif options.show_prereqs
+          display_prerequisites
+        elsif options.execute
+          eval options.execute
+        else
+          @start = Time.now
+          top_level_tasks.each { |task_name| invoke_task(task_name) }
+          title, message = "Your build has completed", "#{Dir.pwd}\nbuildr #{@top_level_tasks.join(' ')}"
+          @on_completion.each do |block|
+            block.call(title, message) rescue nil
+          end
+          if verbose
+            elapsed = Time.now - @start
+            real = []
+            real << ('%ih' % (elapsed / 3600)) if elapsed >= 3600
+            real << ('%im' % ((elapsed / 60) % 60)) if elapsed >= 60
+            real << ('%.3fs' % (elapsed % 60))
+            puts $terminal.color("Completed in #{real.join}", :green)
+          end
+        end
+      end
     end
+
+    def handle_options
+      options.rakelib = ['tasks']
+
+      opts = OptionParser.new
+      opts.banner = "buildr [-f rakefile] {options} targets..."
+      opts.separator ""
+      opts.separator "Options are ..."
+      
+      opts.on_tail("-h", "--help", "-H", "Display this help message.") do
+        puts opts
+        exit
+      end
       
+      standard_buildr_options.each { |args| opts.on(*args) }
+      parsed_argv = opts.parse(ARGV)
+      @environment = ENV['BUILDR_ENV'] ||= 'development'
+      parsed_argv
+    end
+
+    def standard_buildr_options # replaces standard_rake_options
+      [
+        ['--describe', '-D [PATTERN]', "Describe the tasks (matching optional PATTERN), then exit.",
+          lambda { |value|
+            options.show_tasks = true
+            options.full_description = true
+            options.show_task_pattern = Regexp.new(value || '')
+          }
+        ],
+        ['--execute',  '-E CODE',
+          "Execute some Ruby code after loading the buildfile",
+          lambda { |value| options.execute = value }            
+        ],
+        ['--environment',  '-e ENV',
+          "Environment name (e.g. development, test, production).",
+          lambda { |value| ENV['BUILDR_ENV'] = value }            
+        ],
+        ['--libdir', '-I LIBDIR', "Include LIBDIR in the search path for required modules.",
+          lambda { |value| $:.push(value) }
+        ],
+        ['--prereqs', '-P [PATTERN]', "Display the tasks and dependencies (matching optional PATTERN), then exit.",
+          lambda { |value|
+            options.show_prereqs = true
+            options.show_task_pattern = Regexp.new(value || '')
+          }
+        ],
+        ['--quiet', '-q', "Do not log messages to standard output.",
+          lambda { |value| verbose(false) }
+        ],
+        ['--buildfile', '-f FILE', "Use FILE as the buildfile.",
+          lambda { |value| 
+            @rakefiles.clear 
+            @rakefiles << value
+          }
+        ],
+        ['--rakelibdir', '--rakelib', '-R PATH',
+          "Auto-import any .rake files in PATH. (default is 'tasks')",
+          lambda { |value| options.rakelib = value.split(':') }
+        ],
+        ['--require', '-r MODULE', "Require MODULE before executing rakefile.",
+          lambda { |value|
+            begin
+              require value
+            rescue LoadError => ex
+              begin
+                rake_require value
+              rescue LoadError => ex2
+                raise ex
+              end
+            end
+          }
+        ],
+        ['--rules', "Trace the rules resolution.",
+          lambda { |value| options.trace_rules = true }
+        ],
+        ['--no-search', '--nosearch', '-N', "Do not search parent directories for the Rakefile.",
+          lambda { |value| options.nosearch = true }
+        ],
+        ['--silent', '-s', "Like --quiet, but also suppresses the 'in directory' announcement.",
+          lambda { |value|
+            verbose(false)
+            options.silent = true
+          }
+        ],
+        ['--tasks', '-T [PATTERN]', "Display the tasks (matching optional PATTERN) with descriptions, then exit.",
+          lambda { |value|
+            options.show_tasks = true
+            options.show_task_pattern = Regexp.new(value || '')
+            options.full_description = false
+          }
+        ],
+        ['--trace', '-t', "Turn on invoke/execute tracing, enable full backtrace.",
+          lambda { |value|
+            options.trace = true
+            verbose(true)
+          }
+        ],
+        ['--verbose', '-v', "Log message to standard output (default).",
+          lambda { |value| verbose(true) }
+        ],
+        ['--version', '-V', "Display the program version.",
+          lambda { |value|
+            puts "Buildr #{Buildr::VERSION} #{RUBY_PLATFORM[/java/] && '(JRuby '+JRUBY_VERSION+')'}"
+            exit
+          }
+        ]
+      ]
+    end
+
+    def find_buildfile
+      buildfile, location = find_rakefile_location
+      fail "No Buildfile found (looking for: #{@rakefiles.join(', ')})" if buildfile.nil?
+      @rakefile = buildfile
+      Dir.chdir(location)
+    end
+
+    def raw_load_buildfile # replaces raw_load_rakefile
+      puts "(in #{Dir.pwd}, #{environment})" unless options.silent
+      load File.expand_path(@rakefile) if @rakefile && @rakefile != ''
+      options.rakelib.each do |rlib|
+        glob("#{rlib}/*.rake") do |name|
+          add_import name
+        end
+      end
+      load_imports
+      Buildr.projects
+    end
+
     # Load/install all Gems specified in build.yaml file.
     def load_gems #:nodoc:
       missing_deps, installed = listed_gems.partition { |gem| gem.is_a?(Gem::Dependency) }
@@ -259,37 +390,32 @@
       @gems = installed
     end
 
-    def find_buildfile #:nodoc:
-      here = original_dir
-      Dir.chdir(here) unless Dir.pwd == here
-      while !(@rakefile = have_rakefile)
-        Dir.chdir('..')
-        if Dir.pwd == here || options.nosearch
-          error = "No Buildfile found (looking for: #{@rakefiles.join(', ')})"
-          if STDIN.isatty
-            chdir(original_dir) { task('generate').invoke }
-            exit 1
-          else
-            raise error
-          end
-        end
-        here = Dir.pwd
+    # Returns Gem::Specification for every listed and installed Gem, Gem::Dependency
+    # for listed and uninstalled Gem, which is the installed before loading the buildfile.
+    def listed_gems #:nodoc:
+      Array(settings.build['gems']).map do |dep|
+        name, trail = dep.scan(/^\s*(\S*)\s*(.*)\s*$/).first
+        versions = trail.scan(/[=><~!]{0,2}\s*[\d\.]+/)
+        versions = ['>= 0'] if versions.empty?
+        dep = Gem::Dependency.new(name, versions)
+        Gem::SourceIndex.from_installed_gems.search(dep).last || dep
       end
     end
 
-    def load_buildfile #:nodoc:
-      info "(in #{Dir.pwd}, #{environment})"
-      load File.expand_path(@rakefile) if @rakefile != ''
-      buildfile.enhance @requires.select { |f| File.file?(f) }.map{ |f| File.expand_path(f) }
-    end
-
-    def load_requires #:nodoc:
-      @requires.each { |name| require name }
+    # Load artifact specs from the build.yaml file, making them available 
+    # by name ( ruby symbols ).
+    def load_artifact_ns #:nodoc:
+      hash = settings.build['artifacts']
+      return unless hash
+      raise "Expected 'artifacts' element to be a hash" unless Hash === hash
+      # Currently we only use one artifact namespace to rule them all. (the root NS)
+      Buildr::ArtifactNamespace.load(:root => hash)
     end
-
+    
     # Loads buildr.rb files from users home directory and project directory.
     # Loads custom tasks from .rake files in tasks directory.
     def load_tasks #:nodoc:
+      # TODO: this might need to be split up, look for deprecated features, better method name.
       files = [ File.expand_path('buildr.rb', ENV['HOME']), 'buildr.rb' ].select { |file| File.exist?(file) }
       files += [ File.expand_path('buildr.rake', ENV['HOME']), File.expand_path('buildr.rake') ].
         select { |file| File.exist?(file) }.each { |file| warn "Please use '#{file.ext('rb')}' instead of '#{file}'" }
@@ -305,42 +431,61 @@
       true
     end
 
-    def display_prerequisites
-      invoke_task('buildr:initialize')
-      tasks.each do |task|
-        if task.name =~ options.show_task_pattern
-          puts "buildr #{task.name}"
-          task.prerequisites.each { |prereq| puts "    #{prereq}" }
+    def display_tasks_and_comments
+      displayable_tasks = tasks.select { |t| t.comment && t.name =~ options.show_task_pattern }
+      if options.full_description
+        displayable_tasks.each do |t|
+          puts "buildr #{t.name_with_args}"
+          t.full_comment.split("\n").each do |line|
+            puts "    #{line}"
+          end
+          puts
+        end
+      else
+        width = displayable_tasks.collect { |t| t.name_with_args.length }.max || 10
+        max_column = truncate_output? ? terminal_width - name.size - width - 7 : nil
+        displayable_tasks.each do |t|
+          printf "#{name} %-#{width}s  # %s\n",
+            t.name_with_args, max_column ? truncate(t.comment, max_column) : t.comment
         end
       end
     end
-    
-    # Provide standard execption handling for the given block.
-    def standard_exception_handling
+
+    def display_prerequisites
+      displayable_tasks = tasks.select { |t| t.name =~ options.show_task_pattern }
+      displayable_tasks.each do |t|
+        puts "buildr #{t.name}"
+        t.prerequisites.each { |pre| puts "    #{pre}" }
+      end
+    end
+
+    def standard_exception_handling # adds on_failure hook
       begin
         yield
       rescue SystemExit => ex
         # Exit silently with current status
         exit(ex.status)
-      rescue SystemExit, GetoptLong::InvalidOption => ex
-        # Exit silently
+      rescue OptionParser::ParseError => ex
+        $stderr.puts $terminal.color(ex.message, :red)
         exit(1)
       rescue Exception => ex
-        title, message = 'Your build failed with an error', "#{Dir.pwd}:\n#{ex.message}"
-        @on_failure.each { |block| block.call(title, message, ex) rescue nil }
+        title, message = "Your build failed with an error", "#{Dir.pwd}:\n#{ex.message}"
+        @on_failure.each do |block|
+          block.call(title, message, ex) rescue nil
+        end
         # Exit with error message
-        $stderr.puts "buildr aborted!"
+        $stderr.puts "Buildr aborted!"
         $stderr.puts $terminal.color(ex.message, :red)
         if options.trace
           $stderr.puts ex.backtrace.join("\n")
         else
-          $stderr.puts ex.backtrace.select { |str| str =~ /#{buildfile}/ }.map { |line| $terminal.color(line, :red) }.join("\n")
+          $stderr.puts ex.backtrace.select { |str| str =~ /#{rakefile}/ }.map { |line| $terminal.color(line, :red) }.join("\n")
           $stderr.puts "(See full trace by running task with --trace)"
         end
         exit(1)
       end
     end
-    
+
   end
   
   
@@ -357,10 +502,6 @@
 
   class << self
 
-    task 'buildr:initialize' do
-      Buildr.load_tasks_and_local_files
-    end
-
     # Returns the Buildr::Application object.
     def application
       Rake.application

Modified: incubator/buildr/trunk/lib/buildr/core/project.rb
URL: http://svn.apache.org/viewvc/incubator/buildr/trunk/lib/buildr/core/project.rb?rev=705438&r1=705437&r2=705438&view=diff
==============================================================================
--- incubator/buildr/trunk/lib/buildr/core/project.rb (original)
+++ incubator/buildr/trunk/lib/buildr/core/project.rb Thu Oct 16 18:02:09 2008
@@ -864,9 +864,6 @@
   # Forces all the projects to be evaluated before executing any other task.
   # If we don't do that, we don't get to have tasks available when running Rake.
   namespace 'buildr' do
-    task 'initialize' do
-      projects
-    end
 
     desc "Freeze the Buildfile so it always uses Buildr version #{Buildr::VERSION}"
     task 'freeze' do