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 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410
|
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<title>CommandLine (with OptionParser)</title>
<style type="text/css">
body,td {
font-size: small;
line-height: 130%;
}
a {
text-decoration: none;
}
a:link, a:visited {
color: #2050f0;
}
h1, h2, h3, h4, h5, h6 {
color: #900;
}
pre {
/*border-left: 7px solid #e8d8d8;*/
/*background-color: #ffeeff;*/
background-color: #eee;
/*
border-top: 2px solid #aaaaaa;
border-left: 2px solid #aaaaaa;
*/
}
.sidebar {
font-size: smaller;
color: #70b0b0;
}
.sidebar a:link {
color: #104020;
}
.sidebar a:visited {
color: #104020;
}
.sidebar a:hover {
color: #401020;
font-weight: bold;
}
.Sidebarwarning {
color: #902020;
padding-left: 1em;
}
.sidebarholder {
border-top: 2px solid #aaaaaa;
border-left: 2px solid #aaaaaa;
padding: 0px;
margin-bottom: 16px;
}
.sidebartitle {
background-color: #c0e0e0;
padding-left: 8px;
color: #0000cc;
}
.sidebarbody {
background-color: #f8ffff;
color: #a08080;
padding-left: 8px;
}
.sidebartext {
color: #80a0a0;
}
.sidebar table table, .sidebar table table td {
color: #a08080;
padding-right: 0.5em;
padding-left: 0em;
padding-top: 0em;
padding-bottom: 0em;
}
.sidebarsubhead {
color: #503030;
background-color: #f8d0d0;
}
.indent {
margin-left: 1.5em;
}
.catcount {
color: #807070;
}
.entry {
/*
border-top: 2px solid #aaaaaa;
border-left: 2px solid #aaaaaa;
*/
padding: 0px;
}
.entrytitlebar {
/*background-color: #e0c0e0;*/
background-color: #aaaaff;
}
.entrytitle {
font-family: Arial,Helvetica;
color: #111166;
padding-left: 12pt;
font-size: large;
font-variant: small-caps;
}
.entrytitledetail {
text-align: right;
font-size: x-small;
padding-right: 12pt;
}
.entrybody {
font-family: Arial;
background-color: #fff;
padding-left: 36pt;
padding-right: 12pt;
padding-bottom: 12pt;
line-height: 130%;
/*background-color: #f8f0f0;*/
background-color: #fff;
}
.entrybody h1,h2,h3,h4 {
background-color: #fff;
line-height: 100%;
}
.pagetitle {
font-size: xx-large;
font-family: Arial,Helvetica;
/*text-shadow: .18em .15em .2em #223366;*/
text-shadow: .18em .15em .2em #9999cc;
}
.titlemenu {
font-size: x-small;
font-family: Arial,Helvetica;
text-align: right;
}
.schedhead {
font-size: small;
font-family: Arial,Helvetica;
text-align: right;
font-weight: bold;
background-color: #403030;
color: #c0c0c0;
}
.schedentry {
font-size: small;
font-family: Arial,Helvetica;
text-align: center;
background-color: #d0c0c0;
}
.schedempty {
font-size: small;
background-color: #f0e0e0;
}
.sidebartable {
color: #a08080;
}
.c {
text-align: right;
padding-right: 0.5em;
padding-left: 0em;
padding-top: 0em;
padding-bottom: 0em;
}
.ctitle {
text-align: right;
padding-right: 0.5em;
padding-left: 0em;
padding-top: 0em;
padding-bottom: 0em;
border-bottom: 1px solid #d0d0d0;
}
.ctotal {
text-align: right;
padding-right: 0.5em;
padding-left: 0em;
padding-top: 0em;
padding-bottom: 0em;
border-top: 1px solid #d0d0d0;
border-bottom: 1px solid #d0d0d0;
}
.caltoday {
text-align: right;
background-color: #f8d0d0;
}
</style>
</head>
<body>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="bottom">
<td class="pagetitle">CommandLine</a></td>
</tr>
</table>
<hr />
<table>
<tr valign="top"><td>
<table class="entry" border="0" cellspacing="0" width="100%">
<tr class="entrybody"><td colspan="3" class="entrybody">
<h1>Welcome to CommandLine</h1>
<ul>
<li>Copyright © 2005 Jim Freeze
</li>
<li>Author: Jim Freeze
</li>
<li><a href="http://www.freeze.org/ruby/optionparser/license.txt">License</a>
</li>
</ul>
<tt>CommandLine</tt> is a library that greatly simplifies the repetitive
process of building a command line user interface for your applications.
It's 'ruby-like' usage style streamlines application development so that
even applications with numerous configuration options can be quickly put
together. CommandLine automatically builds friendly usage and help
screens that are nicely formatted for the user. No longer is starting
an application a pain where you have to copy boiler plate code (or a
previous application) and retype repetitive code to get an application started.
<p>
<tt>CommandLine</tt> smartly handles the arguments passed on the commandline.
For example, if your application accepts arguments, and none are given, it prints a usage
statement. But, if your application accepts no arguments, <tt>CommandLine</tt> will happily
run your application. <tt>CommandLine</tt> also handles a complex set of
options through the <tt>OptionParser</tt> library, which is described below.
In addition to these features, <tt>CommandLine</tt> also ships with the
<b>ability to run system tests</b> on your applications. (Note: It was
recently noticed that the system test infrastructure needs some work
to make it more robust. Anyone willing to help out with this, please
contact me.)
<p>
<tt>OptionParser</tt> is
designed to be a flexible command line parser with a Ruby look and feel to
it. <tt>OptionParser</tt> got
its birth from the need for a parser that is standards compliant, yet
flexible. <tt>OptionParser</tt>
supports the standard command line styles of <tt>Unix</tt>, <tt>Gnu</tt>
and <tt>X Toolkit</tt>, but also lets you break those rules.
<p>
<tt>OptionParser</tt> is
not a port of a traditional command line parser, but it is written to meet
the feature requirements of traditional command line parsers. When using it
as a library, you should notice that it is expressive, supports
Ruby’s blocks and lambda’s, and is sprinkled with a little bit
of magic.
</p>
<p>
While the library can be used by itself, it is also designed to work with
the <tt>CommandLine::Application</tt> class. These tools work together to
facilitate the generation of a sophisticated (batch oriented) application
user interface in a matter of minutes.
</p>
<p>
If you need a refresher on the traditional option parsing schemes, see
<a href="#traditional">"Traditional Option Parsing Schemes"</a> below.
</p>
<h1>CommandLine Usage</h1>
<p>
<h2>Getting Started</h2>
<h3>Installing</h3>
<p>
CommandLine is a gem and can be installed using the <tt>gem</tt> install command:
<pre>
gem install -r commandline
</pre>
<h3>Loading the library</h3>
When using the library, it is loaded as usual with:
<pre>
require 'rubygems'
require 'commandline'
</pre>
<h2>CommandLine::Application</h2>
The <tt>CommandLine::Application</tt> class is only the class the most
users will need to interact with. This class has many wrappers and convenience
methods that utilize the <tt>Option</tt> and <tt>OptionParser</tt>
classes.
<h3>Example 1: A very simple application</h3>
When you want to test a new library, you usually aren't interested
in handling a vast array of options. You usually want just enough
of a user interface to make some specific calls into your library
too see how it responds. So, the simplist application is one that does
not go out of its way to identify itself and does not take any command
line arguments.
<pre>
#!/usr/bin/env ruby
require 'rubygems'
require 'commandline'
class App < CommandLine::Application
def main
puts "call your library here"
end
end#class App
</pre>
To run this app, we just change the mode and launch it:
<pre>
% chmod 755 myapp
% ./myapp
"call your library here"
</pre>
Notice that <tt>CommandLine</tt> does not complain about missing arguments.
It assumes that the number of expected arguments is zero, unless told otherwise.
<h3>Standard Options</h3>
But an application like this will be useless in about 2 hours when
you have forgotten what it does or how to use it. Let's dress it up
a little by adding a <tt>help</tt> option. And, since we are probably
going to need to debug this app, let's provide the ability to get
a backtrace when we need it.
<pre>
#!/usr/bin/env ruby
require 'rubygems'
require 'commandline'
class App < CommandLine::Application
def initialize
options :help, :debug
end
def main
puts "call your library here"
end
end#class App
</pre>
Now, lets run the app with the help option.
<pre>
% ./myapp -h
NAME
myapp.rb
OPTIONS
--help,-h
Displays help page.
--debug,-d
Sets debug to true.
</pre>
<h3>Adding Expected Arguments</h3>
<p>
Ok, that's a little better. Now, let's tell our application that it needs
to accept a filename as an argument. We don't have to name the arguments,
but since there is only one, it is convenient to go ahead and give
it a name. We will call it <tt>@file</tt>.
We'll also add a synopsis so that we know how to call and use the application.
<pre>
#!/usr/bin/env ruby
require 'rubygems'
require 'commandline'
class App < CommandLine::Application
def initialize
synopsis "[-dh] file"
expected_args :file # will set instance variable @file to command line argument.
end
def main
puts "#{name} called with #{args.size} arguments: #{args.inspect}"
puts "@file = #{@file}"
end
end#class App
</pre>
And run it:
<pre>
% ruby myapp.rb
Usage: myapp.rb [-dh] file
% ruby myapp.rb fred_file
myapp.rb called with 1 arguments: ["fred_file"]
@file = fred_file
</pre>
You may notice that this application has a new method -- :initialize.
In this method, Since we've added some setup code to our application object, we created an
<tt>initialize</tt> method and put our code inside it.
<b>(BTW, don't mispell initialize. It can cause real confusion.)</b>
This is where all the
setup takes place for an application. Of course you are free to add other
methods to delegate complex tasks, but it is best if those methods
begin with an underscore '_', as we will see later.
<pre>
</pre>
<h3>Automatic Running</h3>
By the way, if you haven't picked up on it already, notice that
there <tt>myapp.rb</tt> does not contain any code that explicitly
launches <tt>App</tt>. This is handled automatically with an
<tt>at_exit {...}</tt> statement.
If you need to add <tt>at_exit</tt> handlers in your app, they will
be added during the execution of the built-in <tt>at_exit</tt> handler.
If this doesn't work for you, then you can always create an application
without the <em>auto run</em> feature.
<pre>
class App < CommandLine::Application_wo_AutoRun
...
end
</pre>
(If you have an idea for a better name, please share it with me.)
<h3>Adding Options</h3>
Most applications take options. These options usually come in two forms:
<b>Flags</b> or <b>Argument Identifiers</b>.
<h4>Flags</h4>
Option flags simply have a <tt>true</tt> or <tt>false</tt> value, depending if they
are present on the command line. You can define your own flags
explicitly:
<pre>
option :names => %w(--my-flag -m),
opt_description => "Sets my-flag to true"
opt_found => true,
opt_not_found => false
</pre>
Or, using the <tt>:flag</tt> shorthand provided by <tt>Application</tt>
<pre>
option :flag, :names => %w(--my-flag -m)
</pre>
Both methods produce the same results.
<pre>
OPTIONS
--my-flag,-m
Sets --my-flag to true.
</pre>
<h4>Argument Identifiers</h4>
More complex options take arguments, and <tt>CommandLine</tt> does not
place limitations on the argument list like most other option parsers do.
Consider the situtation where you need to indicate a file as a parameter
on the command line. This common case can be done simply with the notation:
<pre>
option :names => "--file",
opt_found => get_args
</pre>
And we retrieve the value with:
<pre>
opt.file # or opt["--file"]
</pre>
or, more fully
<pre>
@option_data.file # or @option_data["--file"]
</pre>
Let's fill this app out a little more completely and look at it in more detail.
<pre>
#!/usr/bin/env ruby
require 'rubygems'
require 'commandline'
class App < CommandLine::Application
def initialize
author "Author Name"
copyright "Author Name, 2005"
synopsis "[-dh] [--in-file <in_file>] file"
short_description "Example application with one arg"
long_description "put your long description here!"
options :help, :debug
option :names => "--in-file", opt_found => get_args,
:opt_description => "Input file for sample app.",
:arg_description => "input_file"
expected_args :file
end
def main
puts "args: #{args}
puts "--in-file: #{opt["--in-file"]}"
end
end#class App
</pre>
Running this application without any arguments, we get the <em>usage</em>
since it is expecting an argument.
<pre>
% ./myapp.rb
Usage: myapp.rb [-dh] [--in-file <in_file>] file
</pre>
But, this may not be clear enough, so let's ask for the help page.
<pre>
</pre>
<pre>
% ./myapp.rb --help
NAME
app_file.rb - Example application with one arg
SYNOPSIS
app_file.rb [-dh] [--in-file <in_file>] file
DESCRIPTION
put your long description here!
OPTIONS
--help,-h
Displays help page.
--debug,-d
Sets debug to true.
--in-file input_file
Input file for sample app.
AUTHOR: Author Name
COPYRIGHT (c) Author Name, 2005
</pre>
Pretty nice for just a small amount of source code.
Now that we know how to use the application, let's call
it with some arguments and options.
<pre>
% ./myapp.rb file --in-file fred
args: file
--in-file: fred
</pre>
That's all there is to it.
<h2>Replay</h2>
<p>
If ever there was a nifty little feature for applications that
have large command lines, it is replay.
</p>
<p>
Replay is not my original idea, but I got it from a company
that I worked for. We had applications that would create
working directories and launch sub applications in those
working directories.
</p>
<p>
Some of these applications had hundreds
of options. The replay file was useful for those times that these
sub applications had to be launched manually. The <tt>.replay</tt>
file could be modified if needed, and the app re-launched with
a simple '<tt>app -r</tt>' from the commandline.
</p>
<h3>Activating Replay</h3>
<p>
Replay is activated by by calling <tt>use_replay</tt> in your
<em>initialization</em> method.
</p>
<p>
Replay stores the command line in a <tt>.replay</tt> file
in the working directory from which the app was launched.
Relaunching the app with -r uses the arguments from the
.replay file, saving typing and mistakes.
Without the -r flag, any existing replay file is overwritten
with the arguments sent to the application. If no arguments
are sent, the .replay file is left untouched.
If the -r flag is provided with other arguments, they are
ignored if <tt>@replay</tt> is set to true.
</p>
<pre>
#!/usr/bin/env ruby
require 'rubygems'
require 'commandline'
class App < CommandLine::Application
# If use_replay is given, and '-r' is supplied,
# it checks for the existance of a .replay file. If such a file
# exists, the app will use those arguments when run.
# Also, every time the app is run with arguments, the replay file
# is updated.
def initialize
use_replay
expected_args :input, :output
end
def main
p @arg_names
puts "#{name} called with #{@args.size} arguments: #{@args.inspect}"
puts "input: #{@input}"
puts "output: #{@output}"
end
end#class App
</pre>
Now we run the app:
<pre>
% ls
myapp.rb
% ./myapp.rb aa bb
[:input, :output]
myapp.rb called with 2 arguments: ["aa", "bb"]
input: aa
output: bb
% ls -A
.replay myapp.rb
% cat .replay
aa bb
</pre>
And, run it using replay:
<pre>
% ./myapp.rb -r
[:input, :output]
app_replay.rb called with 2 arguments: ["aa", "bb"]
input: aa
output: bb
</pre>
To customize your application and options, you can read the next section
for more low level details.
<h1>OptionParser Usage</h1>
<p>
The OptionParser
library consists of three classes, <tt>Option</tt>, <tt>OptionParser</tt> and
<tt>OptionData</tt>. For each option an <tt>Option</tt> object is created.
When you are ready to prepare for command line parsing, these options are
collected into an array and fed to <tt>OptionParser</tt>.
This <tt>OptionParser</tt>
object controls the type of option scheme that is implemented. When it
comes time to parse a command line, call the method <tt>Option#parse</tt>.
This will parse any array, but parses ARGV by default. The result is an
<tt>OptionData</tt> object. This object can be used from which to extract
values or it can be passed to another class as a fully encapsulated data
object.
</p>
<h3>Using Option Parser</h3>
<p>
An option is created with the following syntax:
</p>
<pre>
opt = Option.new([options], <properties>)
</pre>
<p>
The options can be <tt>:flag</tt> or <tt>:posix</tt>. <tt>:flag</tt> means
that the option is a mode flag and does not take any arguments.
<tt>:posix</tt> means that <tt>Option</tt> will validate the properties to
ensure they are posix compliant.
</p>
<p>
An option object has six properties. Four of these properties define
attributes of the object. The last two define <em>actions</em> that are
taken when a command line is parsed.
</p>
<ol>
<li>:names
</li>
<li>:arity
</li>
<li>:opt_description
</li>
<li>:arg_description
</li>
<li>:opt_found
</li>
<li>:opt_not_found
</li>
</ol>
<p>
It is not necessary to set values for all of these properties. Some are set
automatically, as we’ll see below.
</p>
<h3>Posix</h3>
<p>
The default <tt>Option</tt> object is non-posix.
</p>
<pre>
op1 = OptionParser.new(:posix, opts)
op2 = OptionParser.new(opts)
op1.posix #=> true
op2.posix #=> false
</pre>
<h3>Mode-Flag</h3>
<p>
To create a mode flag, that is, an option that is either true or false
depending if it is seen on the command line or not, we could write:
</p>
<pre>
opt_debug = Option.new(
:names => %w(--debug -d), # the flag has two names
:arity => [0,0], # this says take no arugments
:opt_description => "Sets debug to true",
:arg_description => "",
:opt_found => true, # true if seen on command line
:opt_not_found => false # false if not seen on command line
)
</pre>
<p>
Now, this is a lot of work just for a common mode-flag. However, there is a
shorter way:
</p>
<pre>
opt = Option.new(:flag, :names => %w(--debug -d))
</pre>
<p>
When <tt>Option</tt> sees the :flag option, it makes some assignments
behind the scenes and what you are left with is:
</p>
<pre>
:names => ["--debug", "-d"]
:arity => [0, 0]
:opt_description => "Sets debug to true." # debug is taken from the first name
:arg_description => ""
:opt_found => true
:opt_not_found => false
</pre>
<p>
For a common option like a mode-flag, <tt>Option</tt> will use the first
option ‘word’ it finds in the :names list and use that in the
automatic option text. Of course, if you don’t want any text, just
set the option description to an empty string:
</p>
<pre>
:opt_description => "".
</pre>
<h3>Option Arguments</h3>
<p>
If an option is not a mode flag, then it takes arguments. Most option
parsers only permit a single argument per option flag. If your application
needs multiple arguments, the standard method is just to repeat the option
multiple times, once for each required argument. For example, if I need to
pass two files to an application I would need something like:
</p>
<pre>
myapp -f file1 -f file2
</pre>
<p>
But, it would be cleaner if the command line could be expressed as:
</p>
<pre>
myapp -f file1 file2
</pre>
<p>
Well, no longer do you have to suffer with thirty-year old option parser
technology. <tt>OptionParser</tt>
permits multiple arguments per option flag and the number of arguments can
be defined to be variable.
</p>
<p>
To define an option that takes 1 or more arguments, the following can be
done:
</p>
<pre>
opt = Option.new(:names => "--file", :arity => [1,-1])
</pre>
<p>
Let’s say the option required at least two arguments, but not more
than five. This is defined with:
</p>
<pre>
opt = Option.new(:names => "--file", :arity => [2,5])
OptionParser.new(opt).parse
% myapp --file file1 # exception raised
% myapp --file file1 file2 # ok
% myapp --file file1 file2 file3 # ok
% myapp --file f1 f2 f3 f4 f5 f6 # f6 remains on the command line
</pre>
<p>
This ability is handy on occassions where an option argument is
‘optional’.
</p>
<pre>
myapp --custom # no args, uses $HOME/.myapprc
myapp --custom my_custom_file # uses my_custom_file
</pre>
<p>
This type of option is defined by:
</p>
<pre>
opt = Option.new(:names => "--custom", :arity => [0,1])
</pre>
<p>
If the <tt>:arity</tt> is not satisfied, an exception is raised.
</p>
<h3>Actions</h3>
<p>
The option properties <tt>:opt_found</tt> and <tt>:opt_not_found</tt> are
the source of the value returned for an option when it is parsed. These
properties can be either an object or a proc/lambda. If they are an object,
then the stored object is simply returned. If they are lambdas, then the
stored value is the return value of the proc/lambda. So, the following will
have the same result:
</p>
<pre>
opt_debug = Option.new(:flag
:names => %w(--debug -d),
:opt_found => true,
:opt_not_found => false
)
opt_debug = Option.new(:flag
:names => %w(--debug -d),
:opt_found => lambda { true },
:opt_not_found => lambda { false }
)
</pre>
<p>
Notice that there is no need to set an instance variable to a default
value. Normally one does:
</p>
<pre>
@debug = false
# option setup
... parse the commandline
@debug = true if parse_results["--debug"]
</pre>
<p>
But with <tt>OptionParser</tt>, one
has the capability of doing the following:
</p>
<pre>
opt_debug = Option.new(:flag, :names => %w(--debug -d))
... parse the commandline
@debug = option_data[:debug] # value is set without need for default
# or
opt_debug = Option.new(:flag
:names => %w(--debug -d),
:opt_found => lambda { @debug = true },
:opt_not_found => lambda { @debug = false }
)
# do nothing, variable already set.
</pre>
<p>
I find this much easier to manage than having to worry about setting
default behaviour. Now that we know how to create options, let’s move
on to the commandline parser.
</p>
<h2>OptionParser</h2>
<p>
Once the options are defined, we load them into an <tt>OptionParser</tt> and
parse the command line. The syntax for creating an <tt>OptionParser</tt>
object is:
</p>
<pre>
OptionParser.new(prop_flags, option)
OptionParser.new(prop_flags, [options])
OptionParser.new(option)
OptionParser.new([options])
</pre>
<p>
where the possible property flags are:
</p>
<pre>
:posix
:unknown_options_action => :collect | :ignore | :raise
</pre>
<p>
If you want to parse posix, you must specify so. <tt>OptionParser</tt> will
not assume posix mode just because all of the options are posix options.
This allows you to use posix only options but not require the strict
parsing rules.
</p>
<p>
Below are a few examples of creating an <tt>OptionParser</tt>
object:
</p>
<pre>
opt = Option.new(:flag, :names => %w(-h))
op1 = OptionParser.new(:posix, opt)
op2 = OptionParser.new(opt)
</pre>
<p>
or
</p>
<pre>
opts = []
opts << Option.new(:flag, :names => %w(--help h))
opts << Option.new(:flag, :names => %w(--debug d))
</pre>
<p>
Options may be added to an <tt>OptionParser</tt> by
three different methods:
</p>
<pre>
# Options added as arguments during OptionParser construction
op = OptionParser.new(opt1, opt2)
op = OptionParser.new([opt1, opt2])
</pre>
<p>
or
</p>
<pre>
# Options added in a block constructor
op = OptionParser.new { |o| o << opts }
</pre>
<p>
or
</p>
<pre>
# Options added to an existing OptionParser object
op = OptionParser.new
op << opts
</pre>
<h3>Parsing the Command Line</h3>
<p>
Parsing the command line is as simple as calling <tt>#parse</tt>:
</p>
<pre>
option_data = op.parse
</pre>
<h3>Printing an Option Summary</h3>
<p>
A <tt>OptionParser</tt> with
a complete set of options added to it defines the human interface that your
application presents to a user. Therefore, the parser should be able to
provide a nicely formatted summary for the user.
</p>
<p>
An example is shown below with its corresponding output:
</p>
<pre>
require 'rubygems'
require 'commandline/optionparser'
include CommandLine
puts OptionParser.new { |o|
o << Option.new(:flag, :names => %w[--debug -d])
o << Option.new(:flag, :names => %w[--help -h],
:opt_description => "Prints this page.")
o << Option.new(:names => %w[--ouput -o],
:opt_description => "Defines the output file.",
:arg_description => "output_file")
o << Option.new(:names => %w[--a-long-opt --with-many-names -a -A],
:arity => [2,-1],
:opt_description => "Your really long description here.",
:arg_description => "file1 file2 [file3 ...]")
}.to_s
</pre>
<p>
Generates the output:
</p>
<pre>
OPTIONS
--debug,-d
Sets debug to true.
--help,-h
Prints this page.
--ouput,-o output_file
Defines the output file.
--a-long-opt,--with-many-names,-a,-A file1 file2 [file3 ...]
Your really long description here.
</pre>
<h2>Option Data</h2>
<p>
The <tt>OptionData</tt> is the return value of <tt>OptionParser#parse</tt>.
The parsing results for each option are accessed with the bracket notation
#[].
</p>
<pre>
opt = Option.new(:posix,
:names => %w(-r),
:opt_found => OptionParser::GET_ARGS)
od = OptionParser.new(:posix, opt).parse(["-rubygems"])
od["-r"] #=> "ubygems"
od = OptionParser.new(:posix, opt).parse(["-r", "ubygems"])
od["-r"] #=> "ubygems"
</pre>
<p>
<tt>OptionData</tt> behaves similar to a hash object in that the parsed
option data is accessed with #[] where the key is the first item in the
:names array of each option. An option cannot access its parsed values
using just any of its names.
</p>
<pre>
od = OptionParser.new { |o|
o << Option.new(:flag, :names => %w(--valid --notvalid))
o << Option.new(:flag, :names => %w(--first --second))
}.parse(%w(--notvalid --second))
od["--valid"] #=> true
od["--first"] #=> true
od["--notvalid"] #=> CommandLine::OptionData::UnknownOptionError
od["--second"] #=> CommandLine::OptionData::UnknownOptionError
</pre>
<h3>Built-in Data Handlers</h3>
<p>
OptionParser has
built-in data handlers for handling common scenarios. These lambdas can
save a lot of typing.
</p>
<h3>GET_ARG_ARRAY</h3>
<p>
This is useful for options that take a variable number of arguments. It
returns all the arguments in an array.
</p>
<pre>
# GET_ARG_ARRAY returns all arguments in an array, even if no
# arguments are present. This is not to be confused with the option
# occuring multiple times on the command line.
opt = Option.new(:names => %w(--file),
:argument_arity => [0,-1],
:opt_found => OptionParser::GET_ARG_ARRAY)
#:opt_found => :collect) # would this be better?
od = OptionParser.new(opt).parse(%w(--file))
od["--file"] #=> []
od = OptionParser.new(opt).parse(%w(--file=file))
od["--file"] #=> ["file"]
od = OptionParser.new(opt).parse(%w(--file=file1 --file file2))
od["--file"] #=> ["file2"]
od = OptionParser.new(opt).parse(%w(--file=file1 file2))
od["--file"] #=> ["file1", "file2"]
od = OptionParser.new(opt).parse(%w(--file file1 file2))
od["--file"] #=> ["file1", "file2"]
</pre>
<h3>GET_ARGS</h3>
<p>
This is a ‘smart’ option getter. If no arguments are found, it
returns true. If a single argument is found, it returns that argument. If
more than one argument is found, it returns an array of those arguments.
</p>
<pre>
opt = Option.new(:names => %w(--file),
:argument_arity => [0,-1],
:opt_found => OptionParser::GET_ARGS)
#:opt_found => :smart_collect) # would this be better?
od = OptionParser.new(opt).parse(%w(--file))
od["--file"] #=> true
od = OptionParser.new(opt).parse(%w(--file=file))
od["--file"] #=> "file"
od = OptionParser.new(opt).parse(%w(--file=file1 --file file2))
od["--file"] #=> "file2"
od = OptionParser.new(opt).parse(%w(--file=file1 file2))
od["--file"] #=> ["file1", "file2"]
od = OptionParser.new(opt).parse(%w(--file file1 file2))
od["--file"] #=> ["file1", "file2"]
</pre>
<p>
And, for those oxymoronic non-optional options:
</p>
<pre>
opt = Option.new(:names => %w(--not-really-an-option),
:opt_not_found => OptionParser::OPT_NOT_FOUND_BUT_REQUIRED
)
OptionParser.new(opt).parse([]) #=> OptionParser::MissingRequiredOptionError
</pre>
<h3><tt>OptionData</tt></h3>
<p>
We have just shown that after parsing a command line, the result of each
option is found from OptionData. The values that remain on the command line
are assigned to <tt>args</tt>. Other attributes of <tt>OptionData</tt> are:
</p>
<pre>
od.argv # the original command line
od.unknown_options # If OptionParser was told to :collect unknown options
od.args # arguments not claimed by any option
od.not_parsed # arguments following a '--' on the command line
od.cmd # not yet implemented - but a cvs like command
</pre>
<a name="traditional"/>
<hr size="2"></hr><h1>Traditional Option Parsing Schemes</h1>
<p>
This section is a brief overview of traditional command line parsing.
</p>
<p>
Command line options traditionally occur in three flavors:
</p>
<ul>
<li><em>Unix</em> (or POSIX.2)
</li>
<li><em>Gnu</em>
</li>
<li><em>X Toolkit</em>
</li>
</ul>
<p>
Below is a summary of these schemes. <em>(Note: I did not invent these
traditional parsing conventions. Most of the information contained below
was pulled from internet resources and I have quoted these resources where
possible.)</em>
</p>
<h2>Unix Style (POSIX)</h2>
<p>
The Unix style command line options are a single character preceded by a
single dash (hyphen character). In general, lowercase options are preferred
with their uppercase counterparts being the special case variant.
</p>
<h3>Mode Flag</h3>
<p>
If an option does not take an argument, then it is a mode-flag.
</p>
<h3>Optional Separation Between the Option Flag and Its Argument</h3>
<p>
If the option takes an argument, the argument follows it with optional
white space separating the two. For example, the following forms are both
valid:
</p>
<pre>
sort -k 5
sort -k5
</pre>
<h3>Grouping</h3>
<p>
A mode-flag can be grouped together with other mode-flags behind a single
dash. For example:
</p>
<pre>
tar -c -v -f
</pre>
<p>
is equivalent to:
</p>
<pre>
tar -cvf
</pre>
<p>
If grouping is done, the last option in a group can be an option that takes
an argument. For example
</p>
<pre>
sort -r -n -k 5
</pre>
<p>
can be written as
</p>
<pre>
sort -rnk 5
</pre>
<p>
but not
</p>
<pre>
sort -rkn 5
</pre>
<p>
because the ‘5’ argument belongs to the ‘k’ option
flag.
</p>
<h3>Option Parsing Termination</h3>
<p>
It is convention that a double hyphen is a signal to stop option
interpretation and to read the remaining statements on the command line
literally. So, a command such as:
</p>
<pre>
app -- -x -y -z
</pre>
<p>
will not ‘see’ the three mode-flags. Instead, they will be
treated as arguments to the application:
</p>
<pre>
#args = ["-x", "-y", "-z"]
</pre>
<h3>POSIX Summary</h3>
<ol>
<li>An option is a hyphen followed by a single alphanumeric character.
</li>
<li>An option may require an argument which must follow the option with an
optional space in between.
<pre>
-r ubygems
-rubygems
-r=ubygems # not ok. '=' is Gnu style
</pre>
</li>
<li>Options that do not require arguments can be grouped after a hyphen.
</li>
<li>Options can appear in any order.
</li>
<li>Options can appear multiple times.
</li>
<li>Options precede other nonoption arguments. TODO: Test for this
</li>
<li>The — argument terminates options.
</li>
<li>The - option is used to represent the standard input stream.
</li>
</ol>
<h3>References</h3>
<p>
<a
href="http://www.mkssoftware.com/docs/man1/getopts.1.asp">www.mkssoftware.com/docs/man1/getopts.1.asp</a>
</p>
<h2>Gnu Style</h2>
<p>
The Gnu style command line options provide support for option words (or
keywords), yet still maintain compatibility with the Unix style options.
The options in this style are sometimes referred to as
<em>long_options</em> and the Unix style options as <em>short_options</em>.
The compatibility is maintained by preceding the <em>long_options</em> with
two dashes. The option word must be two or more characters.
</p>
<h3>Separation Between the Option Flag and Its Argument</h3>
<p>
Gnu style options cannot be grouped. For options that have an argument, the
argument follows the option with either whitespace or an ’=’.
For example, the following are equivalent:
</p>
<pre>
app --with-optimizer yes
app --with-optimizer=yes
</pre>
<h3>Option Parsing Termination</h3>
<p>
Similar to the <em>Unix</em> style double-hyphen ’- -’, the
<em>Gnu</em> style has a triple-hyphen ’- - -’ to signal that
option parsing be halted and to treat the remaining text as arguments (that
is, read literally from the command line)
</p>
<pre>
app --- -x -y -z
args = ["-x", "-y", "-z"]
</pre>
<h3>Mixing <em>Gnu</em> and <em>Unix</em> Styles</h3>
<p>
The <em>Gnu</em> and the <em>Unix</em> option types can be mixed on the
same commandline. The following are equivalent:
</p>
<pre>
app -a -b --with-c
app -ab --with-c
app -ba --with-c
app --with-c -ab
</pre>
<h2>X Toolkit Style</h2>
<p>
The X Toolkit style uses the single hyphen followed by a keyword option.
This style is not compatible with the <em>Unix</em> or the <em>Gnu</em>
option types. In most situations this is OK since these options will be
filtered from the command line before passing them to an application.
</p>
<h3>’-’ and STDIN</h3>
<p>
It is convention that a bare hypen indicates to read from stdin.
</p>
<h2>The OptionParser Style</h2>
<p>
The CommandLine::OptionParser does not
care what style you use. It is designed for maximum flexiblity so it may be
used within any organiziation to meet their standards.
</p>
<h3>Multiple Option Names</h3>
<p> OptionParser does
not place restrictions on the number of options. The only restriction is
that an option name begin with a hyphen ’-’. A definitely
conjured example of this freedom is:
</p>
<pre>
:names => %w(
--file --File --f --F -file -File -f -F
)
</pre>
<h3>Prefix Matching</h3>
<p>
Although not encouraged, some prefer the ability to truncate option words
to their first unique match. For example, an application that support this
style and accepts the following two option words:
</p>
<pre>
["--foos", "--fbars"]
</pre>
<p>
will accept any of the following as valid options
</p>
<pre>
app --fo
app --foo
app --foos
</pre>
<p>
for the "—foos" option flag since it can be determined that
"—fo" will only match "—foos" and not
"—fbars".
</p>
<h3>Repeated Arguments</h3>
<p>
A common question is how an option parser should respond when an option is
specified on the command line multiple times. This is true for mode flags,
but especially true for options that require an argument, For example, what
should happen when the following is given:
</p>
<pre>
app -f file1 -f file2
</pre>
<p>
Should the parser flag this as an error or should it accept both arguments.
</p>
<p> OptionParser gives
you the choice of whether it raises an exception when an option is seen
more than once, or it just passes the data onto the user.
</p>
<p>
How the data is handled is up to the user, but it typically boils down to
either Append, Replace or Raise. This is described in more detail in the
usage section.
</p>
<h2>CVS Mode</h2>
<p>
CVS is a common application with a unique command line structure. The cvs
application commandline can be given options, but requires a command. This
command can also be given options. This means that there are two sets of
options, one set for the cvs application and one set for the cvs-command.
Some example formats are:
</p>
<pre>
cvs [cvs-options]
cvs [cvs-options] command [command-options-and-arguments]
cvs -r update
cvs -r update .
cvs edit -p file
</pre>
<p>
To handle this, the first unclaimed argument is treated as a command and
the options and option-arguments that follow belong to that command. More
on how this is handled in the usage section.
</p>
<h2>Option Grouping</h2>
<p>
A conflict can occur where a grouping of single letter Unix options has the
value as a word option preceded by a single dash. For this reason, it is
customary to use the double-dash notation for word options. Unless
double-dashes are enforced for word options, OptionParser will
check for possible name conflicts and raise an exception if it finds one.
</p>
</td></tr>
</table>
</table>
</body>
</html>
|