Skip to content
This repository
branch: master
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 1178 lines (890 sloc) 29.678 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 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
NAME
  main.rb

SYNOPSIS
  a class factory and dsl for generating command line programs real quick

URI
  http://codeforpeople.com/lib/ruby/
  http://rubyforge.org/projects/codeforpeople/
  http://github.com/ahoward/main

INSTALL
  gem install main

DESCRIPTION
  main.rb features the following:

    - unification of option, argument, keyword, and environment parameter
      parsing
    - auto generation of usage and help messages
    - support for mode/sub-commands
    - io redirection support
    - logging hooks using ruby's built-in logging mechanism
    - intelligent error handling and exit codes
    - use as dsl or library for building Main objects
    - parsing user defined ARGV and ENV
    - zero requirements for understanding the obtuse apis of *any* command
      line option parsers
    - leather pants

  in short main.rb aims to drastically lower the barrier to writing uniform
  command line applications.

  for instance, this program

    require 'main'

    Main {
      argument 'foo'
      option 'bar'

      def run
        p params['foo']
        p params['bar']
        exit_success!
      end
    }

  sets up a program which requires one argument, 'bar', and which may accept one
  command line switch, '--foo' in addition to the single option/mode which is always
  accepted and handled appropriately: 'help', '--help', '-h'. for the most
  part main.rb stays out of your command line namespace but insists that your
  application has at least a help mode/option.

  main.rb supports sub-commands in a very simple way

    require 'main'

    Main {
      mode 'install' do
        def run() puts 'installing...' end
      end

      mode 'uninstall' do
        def run() puts 'uninstalling...' end
      end
    }

  which allows a program, called 'a.rb', to be invoked as

    ruby a.rb install

  and

    ruby a.rb uninstall

  for simple programs main.rb is a real time saver but it's for more complex
  applications where main.rb's unification of parameter parsing, class
  configuration dsl, and auto-generation of usage messages can really streamline
  command line application development. for example the following 'a.rb'
  program:

    require 'main'

    Main {
      argument('foo'){
        cast :int
      }
      keyword('bar'){
        arity 2
        cast :float
        defaults 0.0, 1.0
      }
      option('foobar'){
        argument :optional
        description 'the foobar option is very handy'
      }
      environment('BARFOO'){
        cast :list_of_bool
        synopsis 'export barfoo=value'
      }

      def run
        p params['foo'].value
        p params['bar'].values
        p params['foobar'].value
        p params['BARFOO'].value
      end
    }

  when run with a command line of

    BARFOO=true,false,false ruby a.rb 42 bar=40 bar=2 --foobar=a

  will produce

    42
    [40.0, 2.0]
    "a"
    [true, false, false]

  while a command line of

    ruby a.rb --help

  will produce

    NAME
      a.rb

    SYNOPSIS
      a.rb foo [bar=bar] [options]+

    PARAMETERS
      * foo [ 1 -> int(foo) ]

      * bar=bar [ 2 ~> float(bar=0.0,1.0) ]

      * --foobar=[foobar] [ 1 ~> foobar ]
          the foobar option is very handy

      * --help, -h

      * export barfoo=value

  and this shows how all of argument, keyword, option, and environment parsing
  can be declartively dealt with in a unified fashion - the dsl for all
  parameter types is the same - and how auto synopsis and usage generation saves
  keystrokes. the parameter synopsis is compact and can be read as

      * foo [ 1 -> int(foo) ]

        'one argument will get processed via int(argument_name)'

          1 : one argument
          -> : will get processed (the argument is required)
          int(foo) : the cast is int, the arg name is foo

      * bar=bar [ 2 ~> float(bar=0.0,1.0) ]

        'two keyword arguments might be processed via float(bar=0.0,1.0)'

          2 : two arguments
          ~> : might be processed (the argument is optional)
          float(bar=0.0,1.0) : the cast will be float, the default values are
                               0.0 and 1.0

      * --foobar=[foobar] [ 1 ~> foobar ]

        'one option with optional argument may be given directly'

      * --help, -h

        no synopsis, simple switch takes no args and is not required

      * export barfoo=value

        a user defined synopsis

SAMPLES

  <========< samples/a.rb >========>

  ~ > cat samples/a.rb

    require 'main'
    
    ARGV.replace %w( 42 ) if ARGV.empty?
    
    Main {
      argument('foo'){
        required # this is the default
        cast :int # value cast to Fixnum
        validate{|foo| foo == 42} # raises error in failure case
        description 'the foo param' # shown in --help
      }
    
      def run
        p params['foo'].given?
        p params['foo'].value
      end
    }

  ~ > ruby samples/a.rb

    true
    42


  <========< samples/b.rb >========>

  ~ > cat samples/b.rb

    require 'main'
    
    ARGV.replace %w( 40 1 1 ) if ARGV.empty?
    
    Main {
      argument('foo'){
        arity 3 # foo will given three times
        cast :int # value cast to Fixnum
        validate{|foo| [40,1].include? foo} # raises error in failure case
        description 'the foo param' # shown in --help
      }
    
      def run
        p params['foo'].given?
        p params['foo'].values
      end
    }

  ~ > ruby samples/b.rb

    true
    [40, 1, 1]


  <========< samples/c.rb >========>

  ~ > cat samples/c.rb

    require 'main'
    
    ARGV.replace %w( foo=40 foo=2 bar=false ) if ARGV.empty?
    
    Main {
      keyword('foo'){
        required # by default keywords are not required
        arity 2
        cast :float
      }
      keyword('bar'){
        cast :bool
      }
    
      def run
        p params['foo'].given?
        p params['foo'].values
        p params['bar'].given?
        p params['bar'].value
      end
    }

  ~ > ruby samples/c.rb

    true
    [40.0, 2.0]
    true
    false


  <========< samples/d.rb >========>

  ~ > cat samples/d.rb

    require 'main'
    
    ARGV.replace %w( --foo=40 -f2 ) if ARGV.empty?
    
    Main {
      option('foo', 'f'){
        required # by default options are not required, we could use 'foo=foo'
                  # above as a shortcut
        argument_required
        arity 2
        cast :float
      }
    
      option('bar=[bar]', 'b'){ # note shortcut syntax for optional args
        # argument_optional # we could also use this method
        cast :bool
        default false
      }
    
      def run
        p params['foo'].given?
        p params['foo'].values
        p params['bar'].given?
        p params['bar'].value
      end
    }

  ~ > ruby samples/d.rb

    true
    [40.0, 2.0]
    nil
    false


  <========< samples/e.rb >========>

  ~ > cat samples/e.rb

    require 'main'
    
    ARGV.replace %w( x y argument )
    
    Main {
      argument 'argument'
      option 'option'
    
      def run() puts 'run' end
    
      mode 'a' do
        option 'a-option'
        def run() puts 'a-run' end
      end
    
      mode 'x' do
        option 'x-option'
    
        def run() puts 'x-run' end
    
          mode 'y' do
            option 'y-option'
    
            def run() puts 'y-run' end
          end
      end
    }

  ~ > ruby samples/e.rb

    y-run


  <========< samples/f.rb >========>

  ~ > cat samples/f.rb

    require 'main'
    
    ARGV.replace %W( compress /data )
    
    Main {
      argument('directory'){ description 'the directory to operate on' }
    
      option('force'){ description 'use a bigger hammer' }
    
      def run
        puts 'this is how we run when no mode is specified'
      end
    
      mode 'compress' do
        option('bzip'){ description 'use bzip compression' }
    
        def run
          puts 'this is how we run in compress mode'
        end
      end
    
      mode 'uncompress' do
        option('delete-after'){ description 'delete orginal file after uncompressing' }
    
        def run
          puts 'this is how we run in un-compress mode'
        end
      end
    }

  ~ > ruby samples/f.rb

    this is how we run in compress mode


  <========< samples/g.rb >========>

  ~ > cat samples/g.rb

    require 'main'
    
    ARGV.replace %w( 42 ) if ARGV.empty?
    
    Main {
      argument( 'foo' )
      option( 'bar' )
    
      run { puts "This is what to_options produces: #{params.to_options.inspect}" }
    }

  ~ > ruby samples/g.rb

    This is what to_options produces: {"help"=>nil, "foo"=>"42", "bar"=>nil}


  <========< samples/h.rb >========>

  ~ > cat samples/h.rb

    require 'main'
    
    # block-defaults are instance_eval'd in the main instance and be combined with
    # mixins
    #
    # ./h.rb #=> forty-two
    # ./h.rb a #=> 42
    # ./h.rb b #=> 42.0
    #
    
    Main {
      fattr :default_for_foobar => 'forty-two'
    
      option(:foobar) do
        default{ default_for_foobar }
      end
    
      mixin :foo do
        fattr :default_for_foobar => 42
      end
    
      mixin :bar do
        fattr :default_for_foobar => 42.0
      end
    
    
      run{ p params[:foobar].value }
    
      mode :a do
        mixin :foo
      end
    
      mode :b do
        mixin :bar
      end
    }

  ~ > ruby samples/h.rb

    "forty-two"


  <========< samples/j.rb >========>

  ~ > cat samples/j.rb

    #!/usr/bin/env ruby
    
    require 'open-uri'
    
    require 'main'
    require 'digest/sha2'
    
    # you have access to a sequel/amalgalite/sqlite db for free
    #
    
    Main {
      name :i_can_haz_db
    
      db {
        create_table(:mp3s) do
          primary_key :id
          String :url
          String :sha
        end unless table_exists?(:mp3s)
      }
    
      def run
        url = 'http://s3.amazonaws.com/drawohara.com.mp3/ween-voodoo_lady.mp3'
        mp3 = open(url){|fd| fd.read}
        sha = Digest::SHA2.hexdigest(mp3)
    
        db[:mp3s].insert(:url => url, :sha => sha)
        p db[:mp3s].all
        p db
      end
    }

  ~ > ruby samples/j.rb

    [{:url=>"http://s3.amazonaws.com/drawohara.com.mp3/ween-voodoo_lady.mp3", :sha=>"54c99ac7588dcfce1e70540b734805e9c69ff98dcca001e6f2bdec140fb0f9dc", :id=>1}, {:url=>"http://s3.amazonaws.com/drawohara.com.mp3/ween-voodoo_lady.mp3", :sha=>"54c99ac7588dcfce1e70540b734805e9c69ff98dcca001e6f2bdec140fb0f9dc", :id=>2}]
    #<Sequel::Amalgalite::Database: "amalgalite://Users/ahoward/.i_can_haz_db/db.sqlite">



DOCS
  test/main.rb
  vim -p lib/main.rb lib/main/*rb
  API section below

HISTORY
  5.1.0
    - support for STATE_DIRNAME and STATE_BASENAME environment variables
  5.0.0
    ?
  4.4.0
    - support for automatic sequel/sqlite/amalgalite dbs for persistent state
      across invocations

        Main {
          db {
            create_table :foo do
              String key
              String val
            end unless table_exists? :foo
          }

          def run
            db[:foo].create(:key => 'using', :val => 'amalgalite')
          end
        }

      - support for automatic config files with auto populated template data

          Main {
            config :email => 'your.addy@gmail.com', :password => 'pa$$word'

            def run
              email = config[:email]
            end
          }

      - new paramter types :pathname, :path, :slug, :input, and :output

      - input/output parameters. can be filenames or '-' to supply
        stdin/stdout respectively

          Main {
            input :i
            output :o

            def run
              i = params[:i].value
              o = params[:o].value

              line = i.gets
              o.puts line
            end
          }

       - clean up warnings running with 'ruby -w'

       - fix a failing test

       - ability to ignore parameters in sub modes

          Main {
            argument :foo
            argument :bar

            def run
              p param[:bar].value
            end

            mode :ignoring do
              params[:foo].ignore!
            end
          }
  4.0.0
    - avoid duping ios. new methods Main.push_ios! and Main.pop_ios! are
    utilized for testing. this was done to make it simple to wrap
    daemon/servolux programs around main, althought not strictly required.
    not the version bump - there is not reason to expect existing main
    programs to break, but it *is* and interface change which requires a major
    version bump.

  3.0.0
    - major refactor to support modes via module/extend vs. subclassing.
    MIGHT NOT be backward compatible, though no known issues thus far.

  2.9.0
    - support ruby 1.9

  2.8.3
    - support for block defaults


  2.8.2
    - fixes and tests for negative arity/attr arguments, options, eg

        argument(:foo){
          arity -1
        }

        def run # ARGV == %w( a b c )
          p foo #=> %w( a b c )
        end

      thanks nathan

  2.8.1
    - move from attributes.rb to fattr.rb

  2.8.0
    - added 'to_options' method for Parameter::Table. this allows you to convert
      all the parameters to a simple hash.
      for example

        Main {
          option 'foo'
          argument 'baz'

          run { puts params.to_options.inspect }

        }

  2.7.0
    - removed bundled arrayfields and attributes. these are now dependancies
      mananged by rubygems. a.k.a. you must have rubygems installed for main
      to work.

  2.6.0
    - added 'mixin' feaature for storing, and later evaluating a block of
      code. the purpose of this is for use with modes where you want to keep
      your code dry, but may not want to define something in the base class
      for all to inherit. 'mixin' allows you to define the code to inherit
      once and the selectively drop it in child classes (modes) on demand.
      for example

        Main {
          mixin :foobar do
            option 'foo'
            option 'bar'
          end

          mode :install do
            mixin :foobar
          end

          mode :uninstall do
            mixin :foobar
          end

          mode :clean do
          end
        }

    - mode definitions are now deferred to the end of the Main block, so you
      can do this

        Main {
          mode 'a' do
            mixin :foo
          end

          mode 'b' do
            mixin :foo
          end

          def inherited_method
            42
          end

          mixin 'foo' do
            def another_inherited_method
              'forty-two'
            end
          end
        }

    - added sanity check at end of paramter contruction

    - improved auto usage generation when arity is used with arguments

    - removed 'p' shortcut in paramerter dsl because it collided with
      Kernel.p. it's now called 'param'. this method is availble *inside* a
      parameter definition

        option('foo', 'f'){
          synopsis "arity = #{ param.arity }"
        }
      
    - fixed bug where '--' did not signal the end of parameter parsing in a
      getoptlong compliant way

    - added (before/after)_parse_parameters, (before/after)_initialize, and
      (before/after)_run hooks

    - fixed bug where adding to usage via

        usage['my_section'] = 'custom message'

      totally horked the default auto generated usage message

    - updated dependancies in gemspec.rb for attributes (~> 5.0.0) and
      arrayfields (~> 4.3.0)

    - check that client code defined run, iff not wrap_run! is called. this is
      so mains with a mode, but no run defined, still function correctly when
      passed a mode

    - added new shortcut for creating accessors for parameters. for example

        option('foo'){
          argument :required
          cast :int
          attr
        }

        def run
          p foo ### this attr will return the parameter's *value*
        end

      a block can be passed to specify how to extract the value from the
      parameter

        argument('foo'){
          optional
          default 21
          cast :int
          attr{|param| param.value * 2}
        }

        def run
          p foo #=> 42
        end

    - fixed bug where 'abort("message")' would print "message" twice on exit
      if running under a nested mode (yes again - the fix in 2.4.0 wasn't
      complete)

    - added a time cast, which uses Time.parse

        argument('login_time'){ cast :time }

    - added a date cast, which uses Date.parse

        argument('login_date'){ cast :date }
    

  2.5.0
    - added 'examples', 'samples', and 'api' kewords to main dsl. each
      keyword takes a list of strings which will be included in the help
      message
        
        Main {
          examples "foobar example", "barfoo example"

          samples <<-txt
            do this

            don't do that
          txt

          api %(
            foobar string, hash

            barfoo hash, string
          )
        }

      results in a usage message with sections like

      ...

      EXAMPLES
        foobar example
        barfoo example

      SAMPLES
        do this

        don't do that

      API
        foobar string, hash

        barfoo hash, string

      ...

  2.4.0
    - fixed bug where 'abort("message")' would print "message" twice on exit
      if running under a nested mode.

    - allowed parameters to be overridden completely in subclasses (modes)

  2.3.0
    - re-worked Main.new such that client code may define an #initialize
      methods and the class will continue to work. that is to say it's fine
      to do this

        Main {
          def initialize
            @a = 42
          end

          def run
            p @a
          end

          mode 'foo' do
            def run
              p @a
            end
          end
        }

      the client #initialize will be called *after* main has done it's normal
      initialization so things like @argv, @env, and @stdin will all be there
      in initialize. of course you could have done this before but you'd have
      to both call super and call it with the correct arguments - now you can
      simply ignore it.

  2.2.0
    - added ability for parameter dsl error handlers to accept an argument,
      this will be passed the current error. for example

        argument(:x) do
          arity 42
        
          error do |e|
            case e
              when Parameter::Arity
            ...
          end
        end

    - refined the mode parsing a bit: modes can now be abbreviated to uniqness
      and, when the mode is ambiuous, a nice error message is printed, for
      example:

        ambiguous mode: in = (inflate or install)?

  2.1.0
    - added custom error handling dsl for parameters, this includes the ability
      to prepend, append, or replace the standard error handlers:

        require 'main'

        Main {
          argument 'x' do
            error :before do
              puts 'this fires *before* normal error handling using #instance_eval...'
            end

            error do
              puts 'this fires *instead of* normal error handling using #instance_eval...'
            end

            error :after do
              puts 'this fires *after* normal error handling using #instance_eval...'
            end
          end
          
          run(){ p param['x'].given? }
        }

    - added ability to exit at any time bypassing *all* error handling using
      'throw :exit, 42' where 42 is the desired exit status. throw without a
      status simply exits with 0.

    - added 'help!' method which simply dumps out usage and exits

  2.0.0
    - removed need for proxy.rb via Main::Base.wrap_run!
    - added error handling hooks for parameter parsing
    - bundled arrayfields, attributes, and pervasives although gems are tried
      first
    - softened error messages for parameter parsing errors: certain classes of
      errors are now 'softspoken' and print only the message, not the entire
      stacktrace, to stderr. much nicer for users. this is configurable.
    - added subcommand/mode support
    - added support for user defined exception handling on top level
      exceptions/exits
    - added support for negative arity. this users ruby's own arity
      semantics, for example:
      
        lambda{|*a|}.arity == -1
        lambda{|a,*b|}.arity == -2
        lambda{|a,b,*c|}.arity == -3
        ...

      in otherwords parameters now support 'zero or more', 'one or more' ...
      'n or more' argument semantics

  1.0.0
    - some improved usage messages from jeremy hinegardner

  0.0.2
    - removed dependancy on attributes/arrayfields. main now has zero gem
      dependancies.

    - added support for io redirection. redirection of stdin, stdout, and
      stderr can be done to any io like object or object that can be
      inerpreted as a pathname (object.to_s)

    - main objects can now easily be created and run on demand, which makes
      testing a breeze

        def test_unit_goodness!
          main =
            Main.new{
              stdout StringIO.new
              stderr '/dev/null'

              def run
                puts 42
              end
            }

          main.run
          main.stdout.rewind

          assert main.stdout.read == "42\n"
        end

    - added API section to readme and called it 'docs'

    - wrote a bunch more tests. there are now 42 of them.

  0.0.1

    initial version. this version extracts much of the functionality of alib's
    (gen install alib) Alib.script main program generator and also some of jim's
    freeze's excellent CommandLine::Aplication into what i hope is a simpler and
    more unified interface

API

  Main {

  ###########################################################################
  # CLASS LEVEL API #
  ###########################################################################
  #
  # the name of the program, auto-set and used in usage
  #
    program 'foo.rb'
  #
  # a short description of program functionality, auto-set and used in usage
  #
    synopsis "foo.rb arg [options]+"
  #
  # long description of program functionality, used in usage iff set
  #
    description <<-hdoc
      this text will automatically be indented to the right level.

      it should describe how the program works in detail
    hdoc
  #
  # used in usage iff set
  #
    author 'ara.t.howard@gmail.com'
  #
  # used in usage
  #
    version '0.0.42'
  #
  # stdin/out/err can be anthing which responds to read/write or a string
  # which will be opened as in the appropriate mode
  #
    stdin '/dev/null'
    stdout '/dev/null'
    stderr open('/dev/null', 'w')
  #
  # the logger should be a Logger object, something 'write'-able, or a string
  # which will be used to open the logger. the logger_level specifies the
  # initalize verbosity setting, the default is Logger::INFO
  #
    logger(( program + '.log' ))
    logger_level Logger::DEBUG
  #
  # you can configure exit codes. the defaults are shown
  #
    exit_success # 0
    exit_failure # 1
    exit_warn # 42
  #
  # the usage object is rather complex. by default it's an object which can
  # be built up in sections using the
  #
  # usage["BUGS"] = "something about bugs'
  #
  # syntax to append sections onto the already pre-built usage message which
  # contains program, synopsis, parameter descriptions and the like
  #
  # however, you always replace the usage object wholesale with one of your
  # chosing like so
  #
    usage <<-txt
      my own usage message
    txt

  ###########################################################################
  # MODE API #
  ###########################################################################
  #
  # modes are class factories that inherit from their parent class. they can
  # be nested *arbitrarily* deep. usage messages are tailored for each mode.
  # modes are, for the most part, independant classes but parameters are
  # always a superset of the parent class - a mode accepts all of it's parents
  # paramters *plus* and additional ones
  #
    option 'inherited-option'
    argument 'inherited-argument'

    mode 'install' do
      option 'force' do
        description 'clobber existing installation'
      end

      def run
        inherited_method()
        puts 'installing...'
      end

      mode 'docs' do
        description 'installs the docs'

        def run
          puts 'installing docs...'
        end
      end
    end

    mode 'un-install' do
      option 'force' do
        description 'remove even if dependancies exist'
      end

      def run
        inherited_method()
        puts 'un-installing...'
      end
    end

    def run
      puts 'no mode yo?'
    end

    def inherited_method
      puts 'superclass_method...'
    end


  ###########################################################################
  # PARAMETER API #
  ###########################################################################
  #
  # all the parameter types of argument|keyword|option|environment share this
  # api. you must specify the type when the parameter method is used.
  # alternatively used one of the shortcut methods
  # argument|keyword|option|environment. in otherwords
  #
  # parameter('foo'){ type :option }
  #
  # is synonymous with
  #
  # option('foo'){ }
  #
    option 'foo' {
    #
    # required - whether this paramter must by supplied on the command line.
    # note that you can create 'required' options with this keyword
    #
      required # or required true
    #
    # argument_required - applies only to options.
    #
      argument_required # argument :required
    #
    # argument_optional - applies only to options.
    #
      argument_optional # argument :optional
    #
    # cast - should be either a lambda taking one argument, or a symbol
    # designation one of the built in casts defined in Main::Cast. supported
    # types are :boolean|:integer|:float|:numeric|:string|:uri. built-in
    # casts can be abbreviated
    #
      cast :int
    #
    # validate - should be a lambda taking one argument and returning
    # true|false
    #
      validate{|int| int == 42}
    #
    # synopsis - should be a concise characterization of the paramter. a
    # default synopsis is built automatically from the parameter. this
    # information is displayed in the usage message
    #
      synopsis '--foo'
    #
    # description - a longer description of the paramter. it appears in the
    # usage also.
    #
      description 'a long description of foo'
    #
    # arity - indicates how many times the parameter should appear on the
    # command line. the default is one. negative arities are supported and
    # follow the same rules as ruby methods/procs.
    #
      arity 2
    #
    # default - you can provide a default value in case none is given. the
    # alias 'defaults' reads a bit nicer when you are giving a list of
    # defaults for paramters of > 1 arity
    #
      defaults 40, 2
    #
    # you can add custom per-parameter error handlers using the following
    #
      error :before do
        puts 'this fires *before* normal error handling using #instance_eval...'
      end

      error do
        puts 'this fires *instead of* normal error handling using #instance_eval...'
      end

      error :after do
        puts 'this fires *after* normal error handling using #instance_eval...'
      end
    }

  ###########################################################################
  # INSTANCE LEVEL API #
  ###########################################################################
  #
  # you must define a run method. it is the only method you must define.
  #
    def run
      #
      # all parameters are available in the 'params' hash and via the alias
      # 'param'. it can be indexed via string or symbol. the values are all
      # Main::Parameter objects
      #
        foo = params['foo']
      #
      # the given? method indicates whether or not the parameter was given on
      # the commandline/environment, etc. in particular this will not be true
      # when a default value was specified but no parameter was given
      #
        foo.given?
      #
      # the list of all values can be retrieved via 'values'. note that this
      # is always an array.
      #
        p foo.values
      #
      # the __first__ value can be retrieved via 'value'. note that this
      # never an array.
      #
        p foo.value
      #
      # the methods debug|info|warn|error|fatal are delegated to the logger
      # object
      #
        info{ "this goes to the log" }
      #
      # you can set the exit_status at anytime. this status is used when
      # exiting the program. exceptions cause this to be ext_failure if, and
      # only if, the current value was exit_success. in otherwords an
      # un-caught exception always results in a failing exit_status
      #
        exit_status exit_failure
      #
      # a few shortcuts both set the exit_status and exit the program.
      #
        exit_success!
        exit_failure!
        exit_warn!
    end

  }
Something went wrong with that request. Please try again.