Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 93d3fe22ef
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 852 lines (724 sloc) 19.252 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851

class Levitate
  def initialize(gem_name)
    @gem_name = gem_name

    $LOAD_PATH.unshift File.expand_path(File.dirname(__FILE__) + '/../lib')

    yield self

    self.class.instance_methods(false).sort.each do |name|
      if name.to_s =~ %r!\Adefine_!
        send(name)
      end
    end
  end

  attr_reader :gem_name

  def self.attribute(name, &block)
    var = :"@#{name}"
    define_method name do
      if instance_variable_defined?(var)
        instance_variable_get(var)
      else
        instance_variable_set(var, instance_eval(&block))
      end
    end
    attr_writer name
  end

  attribute :version_constant_name do
    "VERSION"
  end

  attribute :camel_name do
    to_camel_case(gem_name)
  end

  attribute :version do
    catch :bail do
      if File.file?(version_file = "./lib/#{gem_name}/version.rb")
        require version_file
      elsif File.file?("./lib/#{gem_name}.rb")
        require gem_name
      else
        throw :bail
      end
      mod = Kernel.const_get(camel_name)
      constants = mod.constants.map { |t| t.to_sym }
      unless constants.include?(version_constant_name.to_sym)
        throw :bail
      end
      mod.const_get(version_constant_name)
    end or "0.0.0"
  end

  attribute :required_ruby_version do
    ">= 0"
  end
  
  attribute :readme_file do
    "README.rdoc"
  end
  
  attribute :history_file do
    "CHANGES.rdoc"
  end
  
  attribute :doc_dir do
    "doc"
  end
  
  attribute :spec_files do
    Dir["./spec/*_{spec,example}.rb"]
  end
  
  attribute :test_files do
    (Dir["./test/test_*.rb"] + Dir["./test/*_test.rb"]).uniq
  end
  
  attribute :cov_dir do
    "coverage"
  end
  
  attribute :spec_output_dir do
    "rspec_output"
  end

  attribute :spec_output_file do
    "spec.html"
  end

  attribute :spec_output do
    "#{spec_output_dir}/#{spec_output_file}"
  end

  attribute :rcov_options do
    # workaround for the default rspec task
    Dir["*"].select { |f| File.directory? f }.inject(Array.new) { |acc, dir|
      if dir == "lib"
        acc
      else
        acc + ["--exclude", dir + "/"]
      end
    } + ["--text-report"]
  end

  attribute :generated_files do
    []
  end

  attribute :extra_gemspec do
    lambda { |spec| }
  end

  attribute :files do
    if source_control?
      IO.popen("git ls-files") { |pipe| pipe.read.split "\n" }
    end.to_a + generated_files
  end

  attribute :rdoc_files do
    files_in_require_paths
  end
    
  attribute :rdoc_title do
    "#{gem_name}: #{summary}".sub(/\.\Z/, "")
  end

  attribute :require_paths do
    ["lib"]
  end

  attribute :rdoc_options do
    if File.file?(readme_file)
      ["--main", readme_file]
    else
      []
    end + [
     "--title", rdoc_title,
    ] + (files_in_require_paths - rdoc_files).inject(Array.new) {
      |acc, file|
      acc + ["--exclude", file]
    }
  end

  attribute :extra_rdoc_files do
    [readme_file, history_file].select { |file| File.file?(file) }
  end

  attribute :browser do
    require 'rbconfig'
    if RbConfig::CONFIG["host"] =~ %r!darwin!
      "open"
    else
      "firefox"
    end
  end

  attribute :gemspec do
    Gem::Specification.new do |g|
      %w[
summary
version
description
files
rdoc_options
extra_rdoc_files
require_paths
required_ruby_version
].each do |param|
        t = send(param) and g.send("#{param}=", t)
      end
      g.name = gem_name
      g.homepage = url if url
      dependencies.each { |dep|
        g.add_dependency(*dep)
      }
      development_dependencies.each { |dep|
        g.add_development_dependency(*dep)
      }
      g.authors = developers.map { |d| d[0] }
      g.email = developers.map { |d| d[1] }
      extra_gemspec.call(g)
    end
  end

  attribute :readme_contents do
    File.read(readme_file) rescue "FIXME: readme_file"
  end
  
  attribute :sections do
    begin
      data = readme_contents.split(%r!^==\s*(.*?)\s*$!)
      pairs = data[1..-1].each_slice(2).map { |section, contents|
        [section.downcase, contents.strip]
      }
      Hash[*pairs.flatten]
    rescue
      nil
    end
  end

  attribute :description_section do
    "description"
  end

  attribute :summary_section do
    "summary"
  end

  attribute :description_sentences do
    1
  end

  attribute :summary_sentences do
    1
  end
  
  [:summary, :description].each { |section|
    attribute section do
      begin
        sections[send("#{section}_section")].
        gsub("\n", " ").
        split(%r!\.\s+!m).
        first(send("#{section}_sentences")).
        join(". ").
        concat(".").
        sub(%r!\.+\Z!, ".")
      rescue
        "FIXME: #{section}"
      end
    end
  }

  attribute :url do
    "http://#{username}.github.com/#{gem_name}"
  end

  attribute :username do
    raise "username not set"
  end

  attribute :rubyforge_info do
    nil
  end

  attribute :dependencies do
    []
  end

  attribute :development_dependencies do
    []
  end

  attribute :developers do
    []
  end

  attribute :remote_levitate do
    url = ENV["LEVITATE"] ||
      "https://github.com/quix/levitate/raw/master/levitate.rb"
    IO.popen("curl -s #{url}") { |f| f.read }
  end

  attribute :local_levitate do
    File.open(__FILE__, "rb") { |f| f.read }
  end

  #### tasks

  def define_clean
    require 'rake/clean'
    task :clean do
      Rake::Task[:clobber].invoke
    end
  end

  def define_package
    if source_control?
      require 'rubygems/package_task'

      task :package => :clean
      Gem::PackageTask.new(gemspec).define
    end
  end

  def define_spec
    unless spec_files.empty?
      no_warnings {
        require 'spec/rake/spectask'
      }
      
      desc "run specs"
      Spec::Rake::SpecTask.new('spec') do |t|
        t.spec_files = spec_files
      end
    
      desc "run specs with text output"
      Spec::Rake::SpecTask.new('text_spec') do |t|
        t.spec_files = spec_files
        t.spec_opts = ['-fs']
      end
  
      desc "run specs with html output"
      Spec::Rake::SpecTask.new('full_spec') do |t|
        t.spec_files = spec_files
        t.rcov = true
        t.rcov_opts = rcov_options
        t.spec_opts = ["-fh:#{spec_output}"]
      end
      
      suppress_task_warnings :spec, :full_spec, :text_spec

      desc "run full_spec then open browser"
      task :show_spec => :full_spec do
        open_browser(spec_output, cov_dir + "/index.html")
      end

      desc "run specs individually"
      task :spec_deps do
        run_each_file(*spec_files)
      end

      task :prerelease => [:spec, :spec_deps]
      task :default => :spec

      CLEAN.add spec_output_dir
    end
  end

  def define_test
    unless test_files.empty?
      desc "run tests"
      task :test do
        test_files.each { |file| require file }

        # if we use at_exit hook instead, it won't run before :release
        MiniTest::Unit.new.run ARGV
      end
      
      desc "run tests with coverage"
      if ruby_18?
        task :full_test do
          verbose(false) {
            sh("rcov", "-o", cov_dir, "--text-report",
               *(test_files + rcov_options)
            )
          }
        end
      else
        task :full_test do
          rm_rf cov_dir
          require 'simplecov'
          SimpleCov.start do
            add_filter "test/"
            add_filter "devel/"
          end
          Rake::Task[:test].invoke
        end
      end
      
      desc "run full_test then open browser"
      task :show_test => :full_test do
        show = lambda { open_browser(cov_dir + "/index.html") }
        if ruby_18?
          show.call
        else
          SimpleCov.at_exit do
            SimpleCov.result.format!
            show.call
          end
        end
      end
      
      desc "run tests individually"
      task :test_deps do
        run_each_file(*test_files)
      end
      
      task :prerelease => [:test, :test_deps]
      task :default => :test
      
      CLEAN.add cov_dir
    end
  end

  def define_doc
    desc "run rdoc"
    task :doc => :clean_doc do
      gem 'rdoc' rescue nil
      require 'rdoc/rdoc'
      args = (
        gemspec.rdoc_options +
        gemspec.require_paths.clone +
        gemspec.extra_rdoc_files +
        ["-o", doc_dir]
      ).flatten.map { |t| t.to_s }
      RDoc::RDoc.new.document args
    end
    
    task :clean_doc do
      # normally rm_rf, but mimic rake/clean output
      rm_r(doc_dir) rescue nil
    end

    desc "run rdoc then open browser"
    task :show_doc => :doc do
      open_browser(doc_dir + "/index.html")
    end

    task :rdoc => :doc
    task :clean => :clean_doc
  end

  def define_publish
    if source_control?
      desc "publish docs"
      task :publish => [:clean, :check_directory, :doc] do
        current_branch = `git branch`[/^\* (\S+)$/, 1] or raise "??? branch"
        if rubyforge_info
          user, project = rubyforge_info
          Dir.chdir(doc_dir) do
            sh "scp", "-r",
               ".",
               "#{user}@rubyforge.org:/var/www/gforge-projects/#{project}"
          end
        end
        git "branch", "-D", "gh-pages"
        git "checkout", "--orphan", "gh-pages"
        FileUtils.rm ".git/index"
        git "clean", "-fdx", "-e", "doc"
        Dir["doc/*"].each { |path|
          FileUtils.mv path, "."
        }
        FileUtils.rmdir "doc"
        git "add", "."
        git "commit", "-m", "generated by rdoc"
        git "checkout", current_branch
        git "push", "-f", "origin", "gh-pages"
      end
    end
  end

  def define_install
    desc "direct install (no gem)"
    task :install do
      Installer.new.install
    end

    desc "direct uninstall (no gem)"
    task :uninstall do
      Installer.new.uninstall
    end
  end
  
  def define_check_directory
    task :check_directory do
      unless `git status` =~ %r!nothing to commit \(working directory clean\)!
        raise "directory not clean"
      end
    end
  end

  def define_ping
    task :ping do
      require 'rbconfig'
      [
       "github.com",
       ("rubyforge.org" if rubyforge_info),
      ].compact.each do |server|
        cmd = "ping " + (
          if RbConfig::CONFIG["host"] =~ %r!darwin!
            "-c2 #{server}"
          else
            "#{server} 2 2"
          end
        )
        unless `#{cmd}` =~ %r!0% packet loss!
          raise "No ping for #{server}"
        end
      end
    end
  end

  def define_check_levitate
    task :check_levitate do
      unless local_levitate == remote_levitate
        raise "levitate is out of date"
      end
    end
  end

  def define_update_levitate
    task :update_levitate do
      if local_levitate == remote_levitate
        puts "Already up-to-date."
      else
        File.open(__FILE__, "w") { |f| f.print(remote_levitate) }
        git "commit", __FILE__, "-m", "update levitate"
        puts "Updated levitate."
      end
    end
  end

  def define_changes
    task :changes do
      if File.read(history_file).index version
        raise "version not updated"
      end

      header = "\n\n== Version #{version}\n\n"

      bullets = `git log --format=%s #{last_release}..HEAD`.lines.map { |line|
        "* #{line}"
      }.join.chomp

      write_file(history_file) do
        File.read(history_file).sub(/(?<=#{gem_name} Changes)/) {
          header + bullets
        }
      end
    end
  end

  def define_release
    task :prerelease => [
      :clean,
      :check_directory,
      :check_levitate,
      :ping,
      history_file
    ]

    task :finish_release do
      git "tag", "#{gem_name}-" + version.to_s
      git "push", "--tags", "origin", "master"
      sh "gem", "push", "pkg/#{gem_name}-#{version}.gem"
    end

    task :release => [:prerelease, :package, :finish_release, :publish]
  end

  def define_debug_gem
    task :debug_gem do
      puts gemspec.to_ruby
    end
  end

  #### helpers

  def files_in_require_paths
    require_paths.inject([]) { |acc, dir|
      acc + Dir.glob("#{dir}/**/*.rb")
    }
  end

  def last_release
    `git tag`.lines.select { |t| t.index(gem_name) == 0 }.last.chomp
  end

  def git(*args)
    sh "git", *args
  end

  def open_browser(*files)
    sh(*([browser].flatten + files))
  end

  def suppress_task_warnings(*task_names)
    task_names.each { |task_name|
      Rake::Task[task_name].actions.map! { |action|
        lambda { |*args|
          no_warnings {
            action.call(*args)
          }
        }
      }
    }
  end

  def ruby_18?
    RUBY_VERSION =~ %r!\A1\.8!
  end

  def source_control?
    File.directory? ".git"
  end

  #### utility for instance and class

  module Util
    def ruby_bin
      require 'rbconfig'

      name = File.join(
        RbConfig::CONFIG["bindir"],
        RbConfig::CONFIG["RUBY_INSTALL_NAME"]
      )

      if RbConfig::CONFIG["host"] =~ %r!(mswin|cygwin|mingw)! and
          File.basename(name) !~ %r!\.(exe|com|bat|cmd)\Z!i
        name + RbConfig::CONFIG["EXEEXT"]
      else
        name
      end
    end

    def ruby_command
      [ruby_bin] + Levitate.ruby_opts.to_a
    end

    def ruby_command_string
      ruby_command.join(" ")
    end

    def run(*args)
      cmd = ruby_command + args
      unless system(*cmd)
        cmd_str = cmd.map { |t| "'#{t}'" }.join(", ")
        raise "system(#{cmd_str}) failed with status #{$?.exitstatus}"
      end
    end

    def run_each_file(*files)
      files.each { |file|
        run("-w", file)
      }
    end

    def run_code_and_capture(code)
      IO.popen(ruby_command_string, "r+") { |pipe|
        pipe.print(code)
        pipe.flush
        pipe.close_write
        pipe.read
      }
    end

    def run_file_and_capture(file)
      unless File.file? file
        raise "file does not exist: `#{file}'"
      end
      IO.popen(ruby_command_string + " " + file, "r") { |pipe|
        pipe.read
      }
    end
      
    def with_warnings(value = true)
      previous = $VERBOSE
      $VERBOSE = value
      begin
        yield
      ensure
        $VERBOSE = previous
      end
    end
      
    def no_warnings(&block)
      with_warnings(nil, &block)
    end

    def to_camel_case(str)
      str.split('_').map { |t| t.capitalize }.join
    end

    def write_file(file)
      contents = yield
      File.open(file, "wb") { |out|
        out.print(contents)
      }
      contents
    end

    def instance_exec2(obj, *args, &block)
      method_name = ["_", obj.object_id, "_", Thread.current.object_id].join
      (class << obj ; self ; end).class_eval do
        define_method method_name, &block
        begin
          obj.send(method_name, *args)
        ensure
          remove_method method_name
        end
      end
    end
  end
  extend Util
  include Util

  #### public helpers for testing

  class << self
    # From 'minitest' by Ryan Davis.
    def capture_io
      require 'stringio'

      orig_stdout, orig_stderr = $stdout, $stderr
      captured_stdout, captured_stderr = StringIO.new, StringIO.new
      $stdout, $stderr = captured_stdout, captured_stderr

      yield

      return captured_stdout.string, captured_stderr.string
    ensure
      $stdout = orig_stdout
      $stderr = orig_stderr
    end

    def run_doc_code(code, expected, index, instance, &block)
      lib = File.expand_path(File.dirname(__FILE__) + "/../lib")
      header = %{
$LOAD_PATH.unshift "#{lib}"
begin
}
      footer = %{
rescue Exception => __levitate_exception
puts "raises \#{__levitate_exception.class}"
end
}
      final_code = header + code + footer

      # Sometimes code is required to be inside a file.
      actual = nil
      require 'tempfile'
      Tempfile.open("run-rdoc-code") { |temp_file|
        temp_file.print(final_code)
        temp_file.close
        actual = run_file_and_capture(temp_file.path).chomp
      }

      instance_exec2(instance, expected, actual, index, &block)
    end

    def run_doc_section(file, section, instance, &block)
      contents = File.read(file)
      re = %r!^=+[ \t]#{Regexp.quote(section)}.*?\n(.*?)^=!m
      if section_contents = contents[re, 1]
        index = 0
        section_contents.scan(%r!^( \S.*?)(?=(^\S|\Z))!m) { |indented, unused|
          code_sections = indented.split(%r!^ \#\#\#\# output:\s*$!)
          code, expected = (
            case code_sections.size
            when 1
              [indented, indented.scan(%r!\# => (.*?)\n!).flatten.join("\n")]
            when 2
              code_sections
            else
              raise "parse error"
            end
          )
          code.gsub!(/^\s*%.*$/, "") # ignore shell command examples
          run_doc_code(code, expected, index, instance, &block)
          index += 1
        }
      else
        raise "couldn't find section `#{section}' of `#{file}'"
      end
    end

    def doc_to_spec(file, *sections, &block)
      levitate = self
      describe file do
        sections.each { |section|
          describe "section `#{section}'" do
            it "should run as claimed" do
              if block
                levitate.run_doc_section(file, section, self, &block)
              else
                levitate.run_doc_section(file, section, self) {
                  |expected, actual, index|
                  actual.should == expected
                }
              end
            end
          end
        }
      end
    end

    def doc_to_test(file, *sections, &block)
      levitate = self
      klass = Class.new MiniTest::Unit::TestCase do
        sections.each { |section|
          define_method "test_#{file}_#{section}" do
            if block
              levitate.run_doc_section(file, section, self, &block)
            else
              levitate.run_doc_section(file, section, self) {
                |expected, actual, index|
                assert_equal expected, actual
              }
            end
          end
        }
      end
      Object.const_set("Test#{file}".gsub(".", ""), klass)
    end

    def ruby_opts
      @ruby_opts ||= []
    end
    attr_writer :ruby_opts
  end

  #### raw install, bypass gems

  class Installer
    def initialize
      require 'fileutils'
      require 'rbconfig'
      require 'find'

      @fu = FileUtils::Verbose
      @spec = []

      rb_root = RbConfig::CONFIG["sitelibdir"]

      Find.find "lib" do |source|
        next if source == "lib"
        next unless File.directory?(source) || File.extname(source) == ".rb"
        dest = File.join(rb_root, source.sub(%r!\Alib/!, ""))
        @spec << [source, dest]
      end
    end

    def install
      @spec.each do |source, dest|
        if File.directory?(source)
          @fu.mkdir(dest) unless File.directory?(dest)
        else
          @fu.install(source, dest)
        end
      end
    end
  
    def uninstall
      @spec.reverse.each do |source, dest|
        if File.directory?(source)
          @fu.rmdir(dest) if File.directory?(dest)
        else
          @fu.rm(dest) if File.file?(dest)
        end
      end
    end
  end
end

lambda do
  config = File.join(File.dirname(__FILE__), "levitate_config.rb")
  require config if File.file? config
end.call
Something went wrong with that request. Please try again.