cmdparse-2.0.6/0000755000004100000410000000000012335652375013360 5ustar www-datawww-datacmdparse-2.0.6/Rakefile0000644000004100000410000001107112335652375015025 0ustar www-datawww-data# -*- ruby -*- # #-- # cmdparse: advanced command line parser supporting commands # Copyright (C) 2004-2014 Thomas Leitner # # This file is part of cmdparse. # # cmdparse is free software: you can redistribute it and/or modify it under the terms of the GNU # Lesser General Public License as published by the Free Software Foundation, either version 3 of # the License, or (at your option) any later version. # # cmdparse is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even # the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser # General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with cmdparse. If # not, see . # #++ begin require 'rubygems' require 'rubygems/package_task' rescue Exception nil end begin require 'webgen/page' rescue LoadError end require 'rake/clean' require 'rake/packagetask' require 'rake/testtask' require 'rdoc/task' # General actions ############################################################## $:.unshift 'lib' require 'cmdparse' PKG_NAME = "cmdparse" PKG_VERSION = CmdParse::VERSION.join('.') PKG_FULLNAME = PKG_NAME + "-" + PKG_VERSION # End user tasks ################################################################ # The default task is run if rake is given no explicit arguments. desc "Default Task (does testing)" task :default => :test desc "Installs the package #{PKG_NAME} using setup.rb" task :install do ruby "setup.rb config" ruby "setup.rb setup" ruby "setup.rb install" end task :clean do ruby "setup.rb clean" end Rake::TestTask.new do |test| test.test_files = FileList['test/tc_*.rb'] end if defined?(Webgen) CLOBBER << "htmldoc" CLOBBER << "webgen-tmp" desc "Builds the documentation" task :htmldoc do sh "webgen" end end if defined? RDoc::Task RDoc::Task.new do |rdoc| rdoc.rdoc_dir = 'htmldoc/rdoc' rdoc.title = PKG_NAME rdoc.main = 'CmdParse::CommandParser' rdoc.options << '--line-numbers' rdoc.rdoc_files.include('lib') end end if defined?(Webgen) && defined?(RDoc::Task) desc "Build the whole user documentation" task :doc => [:rdoc, :htmldoc] end # Developer tasks ############################################################## namespace :dev do PKG_FILES = FileList.new( [ 'setup.rb', 'COPYING', 'COPYING.LESSER', 'README.md', 'Rakefile', 'net.rb', 'VERSION', 'lib/**/*.rb', 'doc/**/*', 'test/*' ]) CLOBBER << "VERSION" file 'VERSION' do puts "Generating VERSION file" File.open('VERSION', 'w+') {|file| file.write(PKG_VERSION + "\n")} end Rake::PackageTask.new('cmdparse', PKG_VERSION) do |pkg| pkg.need_tar = true pkg.need_zip = true pkg.package_files = PKG_FILES end if defined? Gem spec = Gem::Specification.new do |s| #### Basic information s.name = PKG_NAME s.version = PKG_VERSION s.summary = "Advanced command line parser supporting commands" s.description = <<-EOF cmdparse provides classes for parsing commands on the command line; command line options are parsed using optparse or any other option parser implementation. Programs that use such command line interfaces are, for example, subversion's 'svn' or Rubygem's 'gem' program. EOF s.license = 'LGPLv3' #### Dependencies, requirements and files s.files = PKG_FILES.to_a s.require_path = 'lib' s.autorequire = 'cmdparse' #### Documentation s.has_rdoc = true s.rdoc_options = ['--line-numbers', '--main', 'CmdParse::CommandParser'] #### Author and project details s.author = "Thomas Leitner" s.email = "t_leitner@gmx.at" s.homepage = "http://cmdparse.gettalong.org" end Gem::PackageTask.new(spec) do |pkg| pkg.need_zip = true pkg.need_tar = true end end if defined?(Gem) desc "Upload the release to Rubygems" task :publish_files => [:package] do sh "gem push pkg/cmdparse-#{PKG_VERSION}.gem" puts 'done' end end if defined?(Webgen) && defined?(Gem) && defined?(Rake::RDocTask) desc "Release cmdparse version " + PKG_VERSION task :release => [:clobber, :package, :publish_files] end end task :clobber => ['dev:clobber'] cmdparse-2.0.6/doc/0000755000004100000410000000000012335652375014125 5ustar www-datawww-datacmdparse-2.0.6/doc/logo.png0000644000004100000410000003025012335652375015573 0ustar www-datawww-dataPNG  IHDR<qsBIT|dtEXtSoftwarewww.inkscape.org< IDATxwx\g?LE3uɖ-$N '^ػ}] , e/K ]K pT׸KV5H{=1Xekd[<ǞsWm ,Zf(r帪#D)-~oH帴 .,b ܀ʱ/hdm,AځGe XjvYO,$ "?&{}ٔ-,A2/`~#S(BAhٙh ŕO[*UمT9BPS)~<#y&(Ͼ.Ĺ)Pl?qToЦr2oɶWĹ|n)b k[{^_sy.s v` ]mMQA.[ L^;VoRA9ÝSVYg8~|h!94miH?>3V ^T*º ;Cɥr eO,a ۪l};vg`wwRU+,@ {#wo䟝VYa7۾t[=xGH}%R/|VoYšXnj>tMƿ>BTX|qg~~(792_֔=Mykc_3+\E+ ) 3X ,nsឧ?0 yfՙxF:<{#,2rq';[̳|)aeYoW}I)//#,e9:]'N6w~1|ˏov}HX" NņuQ[T''{j>֫ewLNMQK]Zv]snś =?neя]S'M"wg~ϓxEV*3ĩueqmk]fs2>mLUzgoQ&c~9b@I!JIq1Q`mÇGj+;hks(IrX:FG#ZT;A tqgρKox0V\PÇGʹoX4%UC.H̚*qOɬSR\>/wZ=#/*$5mm.h* x,Cw 7BMZA 2p:8j wo(o6h]$p8 ,_:;~JJvH(n jY[jx8TٲT*Nwv_&+ge]\ҵɹʑIrX,yH&Ȳ)Q&`rGk(̋kEuRoKDi2<>֭X OcD2^f"ȑQ ih%nFuS4rꔟۚX`EǾ}CFGn3P(I$aj%D&ˇc!KLfq8 xQoox__&b144 I2]'|8F"."V9 <8̲eV˖9wZAsܺ FRHPnh1v\RJcFNtS0E3X: 7ֱ^<*Mߝ& Z#RL&B c0ck}3w4IfFS,[`t4Bg8ccQ&'^W80PBEQ$IF1:f|,J._Сa^xM`1ϑ0ޱ2_08`l,T9B,V|P(E(DdFyMN өطoW_CdD#i Fƣ Ex } +Vpf1zfM 1GB;8 y1 e`|!"jSi ^/}j^$I ȲL>/qamobjg+fw =lTlx`p0e\er\y7+06^V03rˑ䙜S_oof9N6aI$㙳:BbFK53x~Gvl_WIt] A0: ƂdA@Rm{SL溱$۹Duxsj,Q/rwjU%Q͌7mn Ѩ)[Tֿ~s|xDOe%Q\D&.@ԢP+/@mqFFbi  &'/+J/8~# d2s=lXR%28F"`0ɁC@g8{#AbqݎJY lPPZŢskkPD< EaTX8^y#\&*BDҩPYK _@0 }  fftGpVeNJ)sꤟ.Vol6=}~ ٴL&ϣv wY\9 Q,kq q0: }}mmd:,'{'V+ s+z#9qbH8F3^KcW_Qe1/ZU= 14h4J,-xvs/&WTXmmſ6P0A0K?7\*& (P\&R[k%PoCvCiqKM˄#H0۶7Muث u4vxLVɦHFDUQ+qLZNpLcFSM.DiΟz˖;p("6R٬Ym$+Drq+*,A(x.9f$2V0@T'Q(D8ZA4idt$L6'IPСa4Z%`2Hsǎzٶ؎{6m祗NcG3HQGeN FZ \XA^6@ V1|c+Tp*GJbQ_oD8XI( LLƩpꔟ*Rn&g|<-*yEg XVVf~N##aFG#LNƩ=zU=:9ժLJ,DUKP*#$Ӻ}C9_ۄ(x}NUr t I&McI#!ǣ440:U^&q긟U(%ÇG#i z5hUe_}šXj,җ}6u 0[(b8w8 =71⛋,]'|D:υr.C?@\˲\p\\M=_ۥ~s꒨#+VEV>_Qz{'LHtj?mW]M,zvI&rRPm/M;-.ˊp̜:9w?~TԆAxjĂ*,.jjcHBDWӫDv}鍤T  +] d跼9&(jhf].Si~z r"UECNOxc+r k$ZQJCONIV&ePklPV_|$vjk-T r Eq=K|R,  47WZ<0رQ_0n'ƹ7xW  &Y2c|,JAoNضq::JyL9~K"G_P(ɁCD")QFFTn1Y^/Nbb"Ƅ/ɬeAjk ${Ft 2<##a֬]0FoPsO2nӓIqFGDcivl@VtxVkQXZ;@V24⦛W8u_s|<ʘ7B? h4Ţ+E@*ÇG %O R[kᙧG"=xMx.n}K`"-~`F;J2mǪA\eђ n}RcfU2ȣDZXtMک'菉Fo$T,K2Hɚ|xX(Vh j^z$ va"0d GMϧ:JJP_o13 V+ 򅒠ODg峘\Cz=碳c*yh(a@_X,}VU5oW>VtmڣLr~a6iX j5SEHe˝)z5~7ºuH=[ܳݨ .. vǣX:\._맶JooG;ذ^gjVǼٶ{\gr`+eyJ>Lm(H&0 ͦ N5k<@{ JA[:+xV(EcuwШ\C &&|q\n\H$ޠd\Url7dGRGT,2 w#JbJcH}靈5>OųF$P&I,O:y.Wy45t&ql6=ҜcQū3E5ͦ?`kâ J2CS!LP(ȲXq_Zɚ5,VR`:7 Rh1 AXD!/RvgkJU$%T,ժXp̘T ,E%V\{PsVS#Uv9 K*RXLϢ7q4%?˖9LY5^ӫkdY&Η|VxaS.IDAT]XFݻXt jz(& mxS>_X,StkHRScA>Ε2Y7aJ|Nb2dr'##!֢gɉ8︫WH$3$˖9'(D/FS\^b%4sc lP-d9|1`Z2N R*JkXeYL_e*L&-u&+JX\ l~{4cc2<M-[9|hAH&xaL&MEXȢ ++񘨩bE52觬6\^odSe kݺ3k<>ENoS[7>˲|z΢ Ni_妧gdm. K}h%jPij"Nsh*):9zt*(Oq|nuNJ’e"#a*1   I2&}^45WX,:"4jlo<[˨@]Xk֐JJU0~C]*[Vw-ūXD"w̽PMWڝ~: WE։q>_B$]%Cv7|x+V( 5JLFMё#RujXz#j^z$mm]Xݴ-yǢ d֐LP*EDA 7aL0(h$R5m-Re M2|iu}>/0TL$YrQYtamg R)rO$F57JH 300kW5azW YC<%:eWrYƱ2<>xEK_F;uØ7 i4*Lmfd6#27;$D2˶mMtu Jx`aijy|dsy@SSAMssUɺAoP(x,}ji_Ph![9Q svq#4\4lk]Zgyg8󅞻\i_4d. BEX*, aUX*ª(TUaQ¢PVE" BEX*, aUX*ª(TUaQ¢PVE" BEX*, aUX*š>xr.VZS&Q)^ juG+ykFh z1'Z&ƍw\vmss[&s53x+Nұr``M HJ>s*ܦwo8zg8zNیC;|^M~{/nKS]S7Zx{/|oZJv/NF腱5檄ޖ;`8  z>ӏ֟~WiL1qjRԷk{P<8yTt]?wOٳٵzy>6.i][_o?bk}u/|w|k5P*~??Kf N"u[~핟R- ?Wx,wsaeQ O$IKboT4>'u8RزaSN@Q(E_{g˜'7޵ H߾埫g3k5_}=߸kw˶P˶gAM` 85WiQ)+Q!R"ط}h˾uo[=XDɷ'qbW7t+L*#hH 1dI&Oj%]-{!utmHu޹QNtfm\5kөHZ [h Ls4Wgco̶[VNdYcD"~WW(9Yv{426{E(,w5nYj|&'.,&rN)Q`n_3by/7ZK&Mk򙼨(jl }t4Fu*0ԛ @"ԫ T8U׋ 1ot7|x~LG%G(?߽K*H/gɷ{.A _x/Yƻ|{+2*rB&bWg\MfL"8j߂o7&*w:Fxgh:\&/>'n[_{BEYVCD0|տwp{#ڧt[!Wvވ߅gi,aɲ!㿾ǮxҠZ9Co,L?YsI ` 2onN%]W8Z|&/?|c^ ՜)`,3O),A)# pm۾sgSO=/7ɯ9<Q`,szNapM>EĆw}iQֱ':-~ ;3u>Ĺ)o?> @{\`i\&~ʈ{eu2g-s2eDX"+q{p(dC3&.~eY| œ(:6P)$`PE>Bgc*!(ȩYW * e-Mail: cmdparse-2.0.6/doc/default.template0000644000004100000410000000233312335652375017307 0ustar www-datawww-data cmdparse: {title:}
Navbar: {breadcrumb_trail: }
cmdparse-2.0.6/doc/tutorial.page0000644000004100000410000001437112335652375016634 0ustar www-datawww-data--- title: Tutorial in_menu: true sort_info: 6 --- ## Quickstart Here are some short code fragments which show how to use cmdparse. A complete example app can be found later in the [tutorial section](#tutorial). Defining commands using classes: ~~~ ruby class TestCmd < CmdParse::Command def initialize super('test', true) self.add_command(TestSubCmd.new) end end class TestSubCmd < CmdParse::Command def initialize super('sub',false) end def execute (args) puts "Hallo #{args}" end end cmd = CmdParse::CommandParser.new( true ) cmd.add_command(TestCmd.new) ~~~ Defining command using the basic `CmdParse::Command` class: ~~~ ruby cmd = CmdParse::CommandParser.new( true ) testcmd = CmdParse::Command.new( 'test', true ) testcmd.short_desc = "Short desc" cmd.add_command( testcmd ) sub = CmdParse::Command.new( 'sub', false ) sub.short_desc = "Add an IP address" sub.set_execution_block do |args| puts "Hallo #{args}" end testcmd.add_command( sub ) ~~~ ## Tutorial The complete code for this example can be found in the file `net.rb` of the `cmdparse` package! This tutorial produces a small `net` application which can add, delete and list IP adresses and show 'network statistics'. The shown code fragments do not include the whole program. So, instead of writing all the code yourself, just look at the code fragments first and then use the include `net.rb` file for running the program. ### Require statements Create a new new file and write the necessary `require` statements. ~~~ ruby {extract: {lines: !ruby/range 5..5}} ~~~ ### The `CommandParser` class Next we will define our basic `CommandParser` by defining the name of the program, its version and the global options. The first boolean argument to the constructor of the `CommandParser` class defines whether exceptions should be handled gracefully, i.e. by showing an appropriate error message and the help screen. The second boolean argument defines whether the top level commands should use partial command matching instead of full command matching. If partial command matching is used, then the shortest unambiguous part of a command name can be used instead of always specifing the full command name. ~~~ ruby {extract: {lines: !ruby/range 30..36}} ~~~ The options are defined using an option parser wrapper. Currently, the only option parser library supported is `optparse` from the Ruby Standard Library. If you want to use another option parser library, you need to write a wrapper for it so that `cmdparse` can use it. Now we only have to tell the program to use our newly defined class to process the command line arguments. ~~~ ruby {extract: {lines: !ruby/range 86..86}} ~~~ The `parse` method of our `CommandParser` instance parses the given array of options (or `ARGV` if no argument is specified). All the command line options are parsed and the given command executed. The program can be executed now but won't be useful as we did not specify any commands. ### Defining commands So, as we have defined our `CommandParser` object, we need to add some commands to it. First, we will add two predefined commands, namely the `help` and the `version` command. ~~~ ruby {extract: {lines: !ruby/range 37..38}} ~~~ That was easy! Now you can execute the program and specify the commands `help` or `version`. However, we want the program to do something "useful". Therefore we define a new command. ~~~ ruby {extract: {lines: !ruby/range 41..44}} ~~~ This command is defined by using the default `Command` class. First an instance is created assigning a name to the command and defining whether this command takes subcommands and uses partial command matching. Next we add a short description so that the `help` command can produce something useful. And at last, we add this command to our `CommandParser` instance. We specified that our `ipaddr` command takes subcommands. So we have to define them, too: ~~~ ruby {extract: {lines: !ruby/range 46..78}} ~~~ We add three subcommands to the `ipaddr` command: `add`, `del` and `list`. * The `add` command is similar to the `ipaddr` command. However, as the `add` command does not take other commands, we have to define an execution block. * The `del` command is similar to the `add` command. As we want to be able to delete all IP addresses by issuing only one command, we add an option for this. * By providing `true` as second argument when we add the `list` command to the `ipaddr` command, we specifiy that this command should be the default command which gets invoked when no command name is specified on the command line. Only one command can be specified as default command! Till now we only used the basic `Command` class to specify commands. However, new commands can also be created by subclassing the `Command` class, as shown with this last command: ~~~ ruby {extract: {lines: !ruby/range 9..28}} {extract: {lines: !ruby/range 39..39}} ~~~ ### Running the program That's all! You can run the program now and have a look at the output which differs depending on which arguments you choose. So, a typical invocation of this program looks like this: $ ruby net.rb --verbose ipaddr add 192.168.0.1 193.150.0.1 * `--verbose` is a global option * `ipaddr` is the first command name (which has no options) * `add` is the second command name (which also has no options) * `192.168.0.1 193.150.0.1` are additional arguments You should notice that if you type $ ruby net.rb you get an error because you did not specify any command. However, when you type $ ruby net.rb ipaddr you do not get an error! Why? As the `ipaddr` command takes subcommands there should be an additional command name (e.g. `list`) on the command line. However, as the `list` command is the default command for `ipaddr` you do not need to type it. *By the way:* You get the same output if you type $ ruby net.rb ip Why? As partial command matching is used for the top level commands, the shortest unambiguous name for a command can be used. As there is no other command starting with `ip` (or even with the letter `i`), it is sufficient to write the above to select the `ipaddr` command. *Notice:* The options of a command which does not take subcommands do not need to be at the front; they can be anywhere, like this $ ruby test.rb --verbose mycommand file1 file2 --recursive file3 cmdparse-2.0.6/doc/download.page0000644000004100000410000000125412335652375016574 0ustar www-datawww-data--- title: Download & Installation in_menu: true sort_info: 4 --- ## Download The newest version of cmdparse can be downloaded from [Rubygems] or the [cmdparse Github page][github]! [Rubygems]: http://rubygems.org/gems/cmdparse [github]: http://github.com/gettalong/cmdparse ## Dependencies This library has *no* dependencies. ## Installation The preferred way of installing cmdparse is via RubyGems: $ gem install cmdparse If you do not have RubyGems installed, but Rake, you can use the following command: $ rake install If you have neither RubyGems nor Rake, use these commands: $ ruby setup.rb config $ ruby setup.rb setup $ ruby setup.rb install cmdparse-2.0.6/doc/default.css0000644000004100000410000000442112335652375016264 0ustar www-datawww-data/* #5CB85C -> background #408040 -> headings #CFE6CF -> code #30BF30 -> other */ body { margin: 0px 2em; font-size: 12px; font-family: Verdana, Arial, Helvetica; border: 1px solid black; color: black; } h1, h2, h3, h4, h5 { color: #408040} a:visited { color: #408040; } a { color: #5CB85C; } .bar a { color: white } .bar a:visited { color: white } #all { background-color: #CFE6CF; } #header { border-bottom: 1px solid black; padding: 1ex; background-color: #5CB85C; } #header img { padding-right: 5em; } #header h1 { margin: 0ex; font-size: 300%; font-style: italic; font-weight: normal; color: white; } , #headerbar { border-bottom: 1px solid black; } #footer { border-top: 1px solid black; } #body { margin-left: 250px; margin-right: 20px; padding: 10px; } #menu { float: left; width: 230px; padding: 20px 0px 0px 2px; } .bar { clear: both; padding: 3px; text-align: center; font-size: 90%; background-color: #30BF30; } .left, .right { padding: 0px 1em; } .left { float: left; text-align: left; } .right { float: right; text-align: right; } /* styling the menu */ #menu a { text-decoration: none; font-weight: bold; font-size: 130%; } #menu a:hover { text-decoration: underline; } #menu .webgen-menuitem-selected { border-left: 3px solid #408040; } #menu ul { list-style-type: none; padding: 0px; margin-left: 10px; } #menu li > ul { font-size: 95%; } #menu li { margin: 0.0em 0px; padding: 2px 0px; padding-left: 5px; border-left: 3px solid #CCCCCC; } /* styling the content */ h2 { padding: 0px; letter-spacing: 0.2em; font-size: 150%; font-weight: bold; border-bottom: 1px solid #408040; } .webgen-file { padding-left: 10px; margin: 0px 10px; border-left: 3px solid #5CB85C; } .webgen-picture { text-align: center; } .webgen-picture img { border: 1px solid black; } .webgen-gallery { text-align: center; } .webgen-gallery table { width: 100%; } .webgen-gallery table td{ text-align: center; border: 1px solid black; } table.cmdparse-example td, pre { border: 1px solid #408040; background-color: white; padding: 5px; } cmdparse-2.0.6/doc/index.page0000644000004100000410000000530612335652375016076 0ustar www-datawww-data--- title: Homepage in_menu: true routed_title: cmdparse sort_info: 1 --- ## Welcome ... to the homepage of ***cmdparse***, an advanced command line parser supporting commands. ## Feature List * Commands can have subcommands * Default commands for showing help and the version of the program * Option parsing library of choice can be used (after writing wrapper), default is `optparse` * Easy to use ## News **2014-04-05 cmdparse 2.0.6 released!!!** There were no codewise changes but the used infrastructure and tools have been updated to newer versions. Also the license information has been added to the gem specification and the tests are now included in the distribution. **2012-06-09 cmdparse 2.0.5 released!!!** Changes: * Fixed backwards incompatible change **2012-06-07 cmdparse 2.0.4 released!!!** Changes: * Only some minor changes regarding the help output for commands which is nicer now. **2006-06-17 cmdparse 2.0.2 released!!!** Changes: * Included two patches from Assaph Mehr: * partial command matching can now be used (see the [tutorial page](tutorial.html)) * now a banner for the help and version commands can be specified **2006-04-05 cmdparse 2.0.1 released!!!** Changes: * Just a bug fix release for those using cmdparse with Rubygems. By issuing the command `require_gem 'cmdparse'` the cmdparse library gets automagically loaded. * Minor documentation updates **2005-08-16 cmdparse 2.0.0 released!!!** This version is not compatible to previous versions of cmdparse as there have been major changes in the API. However, updating your code to use the new API is very easy! Changes: * Commands can now have subcommands which can have subcommands which can have subcommands... * No need to implement a whole new class for simple commands anymore * Default option parser library is `optparse`, however, any option parser library can be used after writing a small wrapper **2005-07-05 cmdparse 1.0.5 released!!!** Changes: * added possibility to parse global options, command and local options separately **2005-06-16 cmdparse 1.0.4 released!!!** Changes: * fix for older ruby versions * fixed bug where exception was not caught **2005-06-09 cmdparse 1.0.3 released!!!** Changes: * added optional graceful exception handling **2005-04-21 cmdparse 1.0.2 released!!!** Changes: * splitted parsing of the arguments and executing the command into two methods **2005-04-13 cmdparse 1.0.1 released!!!** Changes: * Improved HelpCommand: the global options -h and --help take an optional command name now * Possibility to define a default command which is used when no command was specified * A `NoCommandGivenError` is thrown when no command on the CLI and no default command was specified cmdparse-2.0.6/doc/virtual0000644000004100000410000000013512335652375015535 0ustar www-datawww-dataapi.html: dest_path: rdoc/index.html title: API Reference sort_info: 7 in_menu: true cmdparse-2.0.6/COPYING.LESSER0000644000004100000410000001674312335652375015422 0ustar www-datawww-data GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. cmdparse-2.0.6/lib/0000755000004100000410000000000012335652375014126 5ustar www-datawww-datacmdparse-2.0.6/lib/cmdparse/0000755000004100000410000000000012335652375015724 5ustar www-datawww-datacmdparse-2.0.6/lib/cmdparse/wrappers/0000755000004100000410000000000012335652375017567 5ustar www-datawww-datacmdparse-2.0.6/lib/cmdparse/wrappers/optparse.rb0000644000004100000410000000313612335652375021754 0ustar www-datawww-data# #-- # cmdparse: advanced command line parser supporting commands # Copyright (C) 2004-2014 Thomas Leitner # # This file is part of cmdparse. # # cmdparse is free software: you can redistribute it and/or modify it under the terms of the GNU # Lesser General Public License as published by the Free Software Foundation, either version 3 of # the License, or (at your option) any later version. # # cmdparse is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even # the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser # General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with cmdparse. If # not, see . # #++ # require 'optparse' # Some extension to the standard option parser class class OptionParser if const_defined?('Officious') Officious.delete('version') Officious.delete('help') else DefaultList.long.delete('version') DefaultList.long.delete('help') end end module CmdParse # Parser wrapper for OptionParser (included in Ruby Standard Library). class OptionParserWrapper < ParserWrapper # Initializes the wrapper with a default OptionParser instance or the +parser+ parameter and # yields this instance. def initialize(parser = OptionParser.new, &block) @instance = parser self.instance(&block) end def order(args) @instance.order(args) end def permute(args) @instance.permute(args) end def summarize @instance.summarize end end end cmdparse-2.0.6/lib/cmdparse.rb0000644000004100000410000003420412335652375016254 0ustar www-datawww-data# #-- # cmdparse: advanced command line parser supporting commands # Copyright (C) 2004-2014 Thomas Leitner # # This file is part of cmdparse. # # cmdparse is free software: you can redistribute it and/or modify it under the terms of the GNU # Lesser General Public License as published by the Free Software Foundation, either version 3 of # the License, or (at your option) any later version. # # cmdparse is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even # the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser # General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with cmdparse. If # not, see . # #++ # # Namespace module for cmdparse. module CmdParse # The version of this cmdparse implemention VERSION = [2, 0, 6] # Base class for all cmdparse errors. class ParseError < RuntimeError # Set the reason for a subclass. def self.reason(reason, has_arguments = true) (@@reason ||= {})[self] = [reason, has_arguments] end # Return the reason plus the message. def message data = @@reason[self.class] || ['Unknown error', true] data[0] + (data[1] ? ": " + super : '') end end # This error is thrown when an invalid command is encountered. class InvalidCommandError < ParseError reason 'Invalid command' end # This error is thrown when an invalid argument is encountered. class InvalidArgumentError < ParseError reason 'Invalid argument' end # This error is thrown when an invalid option is encountered. class InvalidOptionError < ParseError reason 'Invalid option' end # This error is thrown when no command was given and no default command was specified. class NoCommandGivenError < ParseError reason 'No command given', false end # This error is thrown when a command is added to another command which does not support commands. class TakesNoCommandError < ParseError reason 'This command takes no other commands', false end # Base class for all parser wrappers. class ParserWrapper # Return the parser instance for the object and, if a block is a given, yield the instance. def instance yield @instance if block_given? @instance end # Parse the arguments in order, i.e. stops at the first non-option argument, and returns all # remaining arguments. def order(args) raise InvalidOptionError.new(args[0]) if args[0] =~ /^-/ args end # Permute the arguments so that all options anywhere on the command line are parsed and the # remaining non-options are returned. def permute(args) raise InvalidOptionError.new(args[0]) if args.any? {|a| a =~ /^-/} args end # Return a summary string of the options. def summarize "" end end # Require default option parser wrapper require 'cmdparse/wrappers/optparse' # Command Hash - will return partial key matches as well if there is a single # non-ambigous matching key class CommandHash < Hash def [](cmd_name) super or begin possible = keys.select {|key| key[0, cmd_name.length] == cmd_name } fetch(possible[0]) if possible.size == 1 end end end # Base class for the commands. This class implements all needed methods so that it can be used by # the +CommandParser+ class. class Command # The name of the command attr_reader :name # A short description of the command. Should ideally be smaller than 60 characters. attr_accessor :short_desc # A detailed description of the command. Maybe a single string or an array of strings for # multiline description. Each string should ideally be smaller than 76 characters. attr_accessor :description # The wrapper for parsing the command line options. attr_accessor :options # Returns the name of the default command. attr_reader :default_command # Sets or returns the super command of this command. The super command is either a +Command+ # instance for normal commands or a +CommandParser+ instance for the root command. attr_accessor :super_command # Returns the list of commands for this command. attr_reader :commands # Initialize the command called +name+. # # Parameters: # # [has_commands] # Specifies if this command takes other commands as argument. # [partial_commands (optional)] # Specifies whether partial command matching should be used. # [has_args (optional)] # Specifies whether this command takes arguments def initialize(name, has_commands, partial_commands = false, has_args = true) @name = name @options = ParserWrapper.new @has_commands = has_commands @has_args = has_args @commands = Hash.new @default_command = nil use_partial_commands(partial_commands) end # Define whether partial command matching should be used. def use_partial_commands(use_partial) temp = (use_partial ? CommandHash.new : Hash.new) temp.update(@commands) @commands = temp end # Return +true+ if this command supports sub commands. def has_commands? @has_commands end # Return +true+ if this command uses arguments. def has_args? @has_args end # Add a command to the command list if this command takes other commands as argument. # # If the optional parameter +default+ is true, then this command is used when no command is # specified on the command line. def add_command(command, default = false) raise TakesNoCommandError.new(@name) if !has_commands? @commands[command.name] = command @default_command = command.name if default command.super_command = self command.init end # For sorting commands by name. def <=>(other) @name <=> other.name end # Return the +CommandParser+ instance for this command or +nil+ if this command was not assigned # to a +CommandParser+ instance. def commandparser cmd = super_command cmd = cmd.super_command while !cmd.nil? && !cmd.kind_of?(CommandParser) cmd end # Return a list of super commands, ie.: # [command, super_command, super_super_command, ...] def super_commands cmds = [] cmd = self while !cmd.nil? && !cmd.super_command.kind_of?(CommandParser) cmds << cmd cmd = cmd.super_command end cmds end # This method is called when the command is added to a +Command+ instance. def init; end # Set the given +block+ as execution block. See also: +execute+. def set_execution_block(&block) @exec_block = block end # Invoke the block set by +set_execution_block+. # # This method is called by the +CommandParser+ instance if this command was specified on the # command line. def execute(args) @exec_block.call(args) end # Define the usage line for the command. def usage tmp = "Usage: #{commandparser.program_name}" tmp << " [global options]" if !commandparser.options.instance_of?(ParserWrapper) tmp << super_commands.reverse.collect do |c| t = " #{c.name}" t << " [options]" if !c.options.instance_of?(ParserWrapper) t end.join('') tmp << " COMMAND [options]" if has_commands? tmp << " [ARGS]" if has_args? tmp end # Default method for showing the help for the command. def show_help puts commandparser.banner + "\n" if commandparser.banner puts usage puts if short_desc && !short_desc.empty? puts short_desc puts end if description && !description.empty? puts " " + [description].flatten.join("\n ") puts end if has_commands? list_commands puts end if !(summary = options.summarize).empty? puts summary puts end if self != commandparser.main_command && !(summary = commandparser.main_command.options.summarize).empty? puts summary puts end end ####### private ####### def list_commands(command = self) puts "Available commands:" puts " " + collect_commands_info(command).join("\n ") end def collect_commands_info(command, level = 1) command.commands.sort.collect do |name, cmd| str = " "*level + name str = str.ljust(18) + cmd.short_desc.to_s str += " (default command)" if name == command.default_command [str] + (cmd.has_commands? ? collect_commands_info(cmd, level + 1) : []) end.flatten end end # The default help command. It adds the options "-h" and "--help" to the global options of the # associated +CommandParser+. When the command is specified on the command line, it can show the # main help or individual command help. class HelpCommand < Command def initialize super('help', false) self.short_desc = 'Provide help for individual commands' self.description = ['This command prints the program help if no arguments are given. If one or', 'more command names are given as arguments, these arguments are interpreted', 'as a hierachy of commands and the help for the right most command is show.'] end def init case commandparser.main_command.options when OptionParserWrapper commandparser.main_command.options.instance do |opt| opt.on_tail("-h", "--help", "Show help") do execute([]) end end end end def usage "Usage: #{commandparser.program_name} help [COMMAND SUBCOMMAND ...]" end def execute(args) if args.length > 0 cmd = commandparser.main_command arg = args.shift while !arg.nil? && cmd.commands[arg] cmd = cmd.commands[arg] arg = args.shift end if arg.nil? cmd.show_help else raise InvalidArgumentError, args.unshift(arg).join(' ') end else commandparser.main_command.show_help end exit end end # The default version command. It adds the options "-v" and "--version" to the global options of # the associated +CommandParser+. When specified on the command line, it shows the version of the # program. class VersionCommand < Command def initialize super('version', false, false, false) self.short_desc = "Show the version of the program" end def init case commandparser.main_command.options when OptionParserWrapper commandparser.main_command.options.instance do |opt| opt.on_tail("--version", "-v", "Show the version of the program") do execute([]) end end end end def usage "Usage: #{commandparser.program_name} version" end def execute(args) version = commandparser.program_version version = version.join('.') if version.instance_of?(Array) puts commandparser.banner + "\n" if commandparser.banner puts "#{commandparser.program_name} #{version}" exit end end # The main class for creating a command based CLI program. class CommandParser # A standard banner for help & version screens attr_accessor :banner # The top level command representing the program itself. attr_reader :main_command # The name of the program. attr_accessor :program_name # The version of the program. attr_accessor :program_version # Should exceptions be handled gracefully? I.e. by printing error message and the help screen? attr_reader :handle_exceptions # Create a new CommandParser object. # # [handleExceptions (optional)] # Specifies if the object should handle exceptions gracefully. # [partial_commands (optional)] # Specifies if you want partial command matching for the top level commands. # [has_args (optional)] # Specifies whether the command parser takes arguments (only used when no sub commands are # defined). def initialize(handleExceptions = false, partial_commands = false, has_args = true) @main_command = Command.new('mainCommand', true, partial_commands, has_args) @main_command.super_command = self @program_name = $0 @program_version = "0.0.0" @handle_exceptions = handleExceptions end # Return the wrapper for parsing the global options. def options @main_command.options end # Set the wrapper for parsing the global options. def options=(wrapper) @main_command.options = wrapper end # Add a top level command. def add_command(*args) @main_command.add_command(*args) end # Parse the command line arguments. # # If a block is specified, the current hierarchy level and the name of the current command is # yielded after the option parsing is done but before a command is executed. def parse(argv = ARGV) # :yields: level, commandName level = 0 command = @main_command while !command.nil? argv = if command.has_commands? || ENV.include?('POSIXLY_CORRECT') command.options.order(argv) else command.options.permute(argv) end yield(level, command.name) if block_given? if command.has_commands? cmdName, argv = argv[0], argv[1..-1] || [] if cmdName.nil? if command.default_command.nil? raise NoCommandGivenError else cmdName = command.default_command end else raise InvalidCommandError.new(cmdName) unless command.commands[ cmdName ] end command = command.commands[cmdName] level += 1 else command.execute(argv) command = nil end end rescue ParseError, OptionParser::ParseError => e raise if !@handle_exceptions puts "Error while parsing command line:\n " + e.message puts @main_command.commands['help'].execute(command.super_commands.reverse.collect {|c| c.name}) if @main_command.commands['help'] exit end end end cmdparse-2.0.6/metadata.yml0000644000004100000410000000304012335652375015660 0ustar www-datawww-data--- !ruby/object:Gem::Specification name: cmdparse version: !ruby/object:Gem::Version version: 2.0.6 platform: ruby authors: - Thomas Leitner autorequire: cmdparse bindir: bin cert_chain: [] date: 2014-04-05 00:00:00.000000000 Z dependencies: [] description: |2 cmdparse provides classes for parsing commands on the command line; command line options are parsed using optparse or any other option parser implementation. Programs that use such command line interfaces are, for example, subversion's 'svn' or Rubygem's 'gem' program. email: t_leitner@gmx.at executables: [] extensions: [] extra_rdoc_files: [] files: - setup.rb - COPYING - COPYING.LESSER - README.md - Rakefile - net.rb - VERSION - lib/cmdparse.rb - lib/cmdparse/wrappers/optparse.rb - doc/about.page - doc/default.css - doc/default.template - doc/download.page - doc/index.page - doc/logo.png - doc/tutorial.page - doc/virtual - test/tc_commandhash.rb homepage: http://cmdparse.gettalong.org licenses: - LGPLv3 metadata: {} post_install_message: rdoc_options: - --line-numbers - --main - CmdParse::CommandParser require_paths: - lib required_ruby_version: !ruby/object:Gem::Requirement requirements: - - '>=' - !ruby/object:Gem::Version version: '0' required_rubygems_version: !ruby/object:Gem::Requirement requirements: - - '>=' - !ruby/object:Gem::Version version: '0' requirements: [] rubyforge_project: rubygems_version: 2.0.3 signing_key: specification_version: 4 summary: Advanced command line parser supporting commands test_files: [] cmdparse-2.0.6/test/0000755000004100000410000000000012335652375014337 5ustar www-datawww-datacmdparse-2.0.6/test/tc_commandhash.rb0000644000004100000410000000624012335652375017636 0ustar www-datawww-datarequire 'minitest/autorun' require 'cmdparse' class CommandHashTest < Minitest::Test def setup @cmd = CmdParse::CommandHash.new end def test_basic assert_equal 0, @cmd.size assert_nil @cmd['import'] @cmd['import'] = 1 assert_equal 1, @cmd['import'] assert_equal 1, @cmd['i'] assert_equal 1, @cmd['im'] assert_equal 1, @cmd['imp'] assert_equal 1, @cmd['impo'] assert_equal 1, @cmd['impor'] assert_nil @cmd['importer'] @cmd['implode'] = 2 assert_equal 2, @cmd.size assert_equal 1, @cmd['import'] assert_equal 2, @cmd['implode'] assert_nil @cmd['impart'] assert_nil @cmd['i'] assert_nil @cmd['im'] assert_nil @cmd['imp'] assert_equal 1, @cmd['impo'] assert_equal 1, @cmd['impor'] assert_equal 1, @cmd['import'] assert_equal 2, @cmd['implo'] assert_equal 2, @cmd['implod'] assert_equal 2, @cmd['implode'] end def test_edge_cases @cmd['import'] = 1 @cmd['important'] = 2 assert_equal 1, @cmd['import'] assert_equal 2, @cmd['important'] assert_nil @cmd['i'] assert_nil @cmd['im'] assert_nil @cmd['imp'] assert_nil @cmd['impo'] assert_nil @cmd['impor'] assert_equal 2, @cmd['importa'] assert_equal 2, @cmd['importan'] assert_nil @cmd['impart'] end def test_integration # define and setup the commands cmd = CmdParse::CommandParser.new(handle_exceptions = false) cmd.main_command.use_partial_commands( true ) Object.const_set(:ImportCommand, Class.new(CmdParse::Command) do def initialize() super('import', false) end def execute(args) raise 'import' end def show_help() raise 'import' end end) Object.const_set(:ImpolodeCommand, Class.new(CmdParse::Command) do def initialize() super('implode', false) end def execute(args) raise 'implode' end def show_help() raise 'implode' end end) cmd.add_command( ImportCommand.new ) cmd.add_command( ImpolodeCommand.new ) # simulate running the program assert_raises(RuntimeError, 'import') {cmd.parse(['import'])} assert_raises(RuntimeError, 'implode') {cmd.parse(['implode'])} assert_raises(CmdParse::InvalidCommandError) {cmd.parse(['impart'])} assert_raises(CmdParse::InvalidCommandError) {cmd.parse(['i'])} assert_raises(CmdParse::InvalidCommandError) {cmd.parse(['im'])} assert_raises(CmdParse::InvalidCommandError) {cmd.parse(['imp'])} assert_raises(RuntimeError, 'import') {cmd.parse(['impo'])} assert_raises(RuntimeError, 'import') {cmd.parse(['impor'])} assert_raises(RuntimeError, 'implode') {cmd.parse(['impl'])} assert_raises(RuntimeError, 'implode') {cmd.parse(['implo'])} assert_raises(RuntimeError, 'implode') {cmd.parse(['implod'])} # simulate the help command cmd.add_command( CmdParse::HelpCommand.new ) assert_raises(RuntimeError, 'import') {cmd.parse(['help', 'import'])} assert_raises(RuntimeError, 'implode') {cmd.parse(['help', 'implode'])} cmd.main_command.use_partial_commands( false ) assert_raises(CmdParse::InvalidCommandError, 'import') {cmd.parse(['impo'])} assert_raises(CmdParse::InvalidCommandError, 'implode') {cmd.parse(['impl'])} end end cmdparse-2.0.6/setup.rb0000644000004100000410000010650412335652375015053 0ustar www-datawww-data# # setup.rb # # Copyright (c) 2000-2005 Minero Aoki # # This program is free software. # You can distribute/modify this program under the terms of # the GNU LGPL, Lesser General Public License version 2.1. # unless Enumerable.method_defined?(:map) # Ruby 1.4.6 module Enumerable alias map collect end end unless File.respond_to?(:read) # Ruby 1.6 def File.read(fname) open(fname) {|f| return f.read } end end unless Errno.const_defined?(:ENOTEMPTY) # Windows? module Errno class ENOTEMPTY # We do not raise this exception, implementation is not needed. end end end def File.binread(fname) open(fname, 'rb') {|f| return f.read } end # for corrupted Windows' stat(2) def File.dir?(path) File.directory?((path[-1,1] == '/') ? path : path + '/') end class ConfigTable include Enumerable def initialize(rbconfig) @rbconfig = rbconfig @items = [] @table = {} # options @install_prefix = nil @config_opt = nil @verbose = true @no_harm = false end attr_accessor :install_prefix attr_accessor :config_opt attr_writer :verbose def verbose? @verbose end attr_writer :no_harm def no_harm? @no_harm end def [](key) lookup(key).resolve(self) end def []=(key, val) lookup(key).set val end def names @items.map {|i| i.name } end def each(&block) @items.each(&block) end def key?(name) @table.key?(name) end def lookup(name) @table[name] or setup_rb_error "no such config item: #{name}" end def add(item) @items.push item @table[item.name] = item end def remove(name) item = lookup(name) @items.delete_if {|i| i.name == name } @table.delete_if {|name, i| i.name == name } item end def load_script(path, inst = nil) if File.file?(path) MetaConfigEnvironment.new(self, inst).instance_eval File.read(path), path end end def savefile '.config' end def load_savefile begin File.foreach(savefile()) do |line| k, v = *line.split(/=/, 2) self[k] = v.strip end rescue Errno::ENOENT setup_rb_error $!.message + "\n#{File.basename($0)} config first" end end def save @items.each {|i| i.value } File.open(savefile(), 'w') {|f| @items.each do |i| f.printf "%s=%s\n", i.name, i.value if i.value? and i.value end } end def load_standard_entries standard_entries(@rbconfig).each do |ent| add ent end end def standard_entries(rbconfig) c = rbconfig rubypath = File.join(c['bindir'], c['ruby_install_name'] + c['EXEEXT']) major = c['MAJOR'].to_i minor = c['MINOR'].to_i teeny = c['TEENY'].to_i version = "#{major}.#{minor}" # ruby ver. >= 1.4.4? newpath_p = ((major >= 2) or ((major == 1) and ((minor >= 5) or ((minor == 4) and (teeny >= 4))))) if c['rubylibdir'] # V > 1.6.3 libruby = "#{c['prefix']}/lib/ruby" librubyver = c['rubylibdir'] librubyverarch = c['archdir'] siteruby = c['sitedir'] siterubyver = c['sitelibdir'] siterubyverarch = c['sitearchdir'] elsif newpath_p # 1.4.4 <= V <= 1.6.3 libruby = "#{c['prefix']}/lib/ruby" librubyver = "#{c['prefix']}/lib/ruby/#{version}" librubyverarch = "#{c['prefix']}/lib/ruby/#{version}/#{c['arch']}" siteruby = c['sitedir'] siterubyver = "$siteruby/#{version}" siterubyverarch = "$siterubyver/#{c['arch']}" else # V < 1.4.4 libruby = "#{c['prefix']}/lib/ruby" librubyver = "#{c['prefix']}/lib/ruby/#{version}" librubyverarch = "#{c['prefix']}/lib/ruby/#{version}/#{c['arch']}" siteruby = "#{c['prefix']}/lib/ruby/#{version}/site_ruby" siterubyver = siteruby siterubyverarch = "$siterubyver/#{c['arch']}" end parameterize = lambda {|path| path.sub(/\A#{Regexp.quote(c['prefix'])}/, '$prefix') } if arg = c['configure_args'].split.detect {|arg| /--with-make-prog=/ =~ arg } makeprog = arg.sub(/'/, '').split(/=/, 2)[1] else makeprog = 'make' end [ ExecItem.new('installdirs', 'std/site/home', 'std: install under libruby; site: install under site_ruby; home: install under $HOME')\ {|val, table| case val when 'std' table['rbdir'] = '$librubyver' table['sodir'] = '$librubyverarch' when 'site' table['rbdir'] = '$siterubyver' table['sodir'] = '$siterubyverarch' when 'home' setup_rb_error '$HOME was not set' unless ENV['HOME'] table['prefix'] = ENV['HOME'] table['rbdir'] = '$libdir/ruby' table['sodir'] = '$libdir/ruby' end }, PathItem.new('prefix', 'path', c['prefix'], 'path prefix of target environment'), PathItem.new('bindir', 'path', parameterize.call(c['bindir']), 'the directory for commands'), PathItem.new('libdir', 'path', parameterize.call(c['libdir']), 'the directory for libraries'), PathItem.new('datadir', 'path', parameterize.call(c['datadir']), 'the directory for shared data'), PathItem.new('mandir', 'path', parameterize.call(c['mandir']), 'the directory for man pages'), PathItem.new('sysconfdir', 'path', parameterize.call(c['sysconfdir']), 'the directory for system configuration files'), PathItem.new('localstatedir', 'path', parameterize.call(c['localstatedir']), 'the directory for local state data'), PathItem.new('libruby', 'path', libruby, 'the directory for ruby libraries'), PathItem.new('librubyver', 'path', librubyver, 'the directory for standard ruby libraries'), PathItem.new('librubyverarch', 'path', librubyverarch, 'the directory for standard ruby extensions'), PathItem.new('siteruby', 'path', siteruby, 'the directory for version-independent aux ruby libraries'), PathItem.new('siterubyver', 'path', siterubyver, 'the directory for aux ruby libraries'), PathItem.new('siterubyverarch', 'path', siterubyverarch, 'the directory for aux ruby binaries'), PathItem.new('rbdir', 'path', '$siterubyver', 'the directory for ruby scripts'), PathItem.new('sodir', 'path', '$siterubyverarch', 'the directory for ruby extentions'), PathItem.new('rubypath', 'path', rubypath, 'the path to set to #! line'), ProgramItem.new('rubyprog', 'name', rubypath, 'the ruby program using for installation'), ProgramItem.new('makeprog', 'name', makeprog, 'the make program to compile ruby extentions'), SelectItem.new('shebang', 'all/ruby/never', 'ruby', 'shebang line (#!) editing mode'), BoolItem.new('without-ext', 'yes/no', 'no', 'does not compile/install ruby extentions') ] end private :standard_entries def load_multipackage_entries multipackage_entries().each do |ent| add ent end end def multipackage_entries [ PackageSelectionItem.new('with', 'name,name...', '', 'ALL', 'package names that you want to install'), PackageSelectionItem.new('without', 'name,name...', '', 'NONE', 'package names that you do not want to install') ] end private :multipackage_entries ALIASES = { 'std-ruby' => 'librubyver', 'stdruby' => 'librubyver', 'rubylibdir' => 'librubyver', 'archdir' => 'librubyverarch', 'site-ruby-common' => 'siteruby', # For backward compatibility 'site-ruby' => 'siterubyver', # For backward compatibility 'bin-dir' => 'bindir', 'bin-dir' => 'bindir', 'rb-dir' => 'rbdir', 'so-dir' => 'sodir', 'data-dir' => 'datadir', 'ruby-path' => 'rubypath', 'ruby-prog' => 'rubyprog', 'ruby' => 'rubyprog', 'make-prog' => 'makeprog', 'make' => 'makeprog' } def fixup ALIASES.each do |ali, name| @table[ali] = @table[name] end @items.freeze @table.freeze @options_re = /\A--(#{@table.keys.join('|')})(?:=(.*))?\z/ end def parse_opt(opt) m = @options_re.match(opt) or setup_rb_error "config: unknown option #{opt}" m.to_a[1,2] end def dllext @rbconfig['DLEXT'] end def value_config?(name) lookup(name).value? end class Item def initialize(name, template, default, desc) @name = name.freeze @template = template @value = default @default = default @description = desc end attr_reader :name attr_reader :description attr_accessor :default alias help_default default def help_opt "--#{@name}=#{@template}" end def value? true end def value @value end def resolve(table) @value.gsub(%r<\$([^/]+)>) { table[$1] } end def set(val) @value = check(val) end private def check(val) setup_rb_error "config: --#{name} requires argument" unless val val end end class BoolItem < Item def config_type 'bool' end def help_opt "--#{@name}" end private def check(val) return 'yes' unless val case val when /\Ay(es)?\z/i, /\At(rue)?\z/i then 'yes' when /\An(o)?\z/i, /\Af(alse)\z/i then 'no' else setup_rb_error "config: --#{@name} accepts only yes/no for argument" end end end class PathItem < Item def config_type 'path' end private def check(path) setup_rb_error "config: --#{@name} requires argument" unless path path[0,1] == '$' ? path : File.expand_path(path) end end class ProgramItem < Item def config_type 'program' end end class SelectItem < Item def initialize(name, selection, default, desc) super @ok = selection.split('/') end def config_type 'select' end private def check(val) unless @ok.include?(val.strip) setup_rb_error "config: use --#{@name}=#{@template} (#{val})" end val.strip end end class ExecItem < Item def initialize(name, selection, desc, &block) super name, selection, nil, desc @ok = selection.split('/') @action = block end def config_type 'exec' end def value? false end def resolve(table) setup_rb_error "$#{name()} wrongly used as option value" end undef set def evaluate(val, table) v = val.strip.downcase unless @ok.include?(v) setup_rb_error "invalid option --#{@name}=#{val} (use #{@template})" end @action.call v, table end end class PackageSelectionItem < Item def initialize(name, template, default, help_default, desc) super name, template, default, desc @help_default = help_default end attr_reader :help_default def config_type 'package' end private def check(val) unless File.dir?("packages/#{val}") setup_rb_error "config: no such package: #{val}" end val end end class MetaConfigEnvironment def initialize(config, installer) @config = config @installer = installer end def config_names @config.names end def config?(name) @config.key?(name) end def bool_config?(name) @config.lookup(name).config_type == 'bool' end def path_config?(name) @config.lookup(name).config_type == 'path' end def value_config?(name) @config.lookup(name).config_type != 'exec' end def add_config(item) @config.add item end def add_bool_config(name, default, desc) @config.add BoolItem.new(name, 'yes/no', default ? 'yes' : 'no', desc) end def add_path_config(name, default, desc) @config.add PathItem.new(name, 'path', default, desc) end def set_config_default(name, default) @config.lookup(name).default = default end def remove_config(name) @config.remove(name) end # For only multipackage def packages raise '[setup.rb fatal] multi-package metaconfig API packages() called for single-package; contact application package vendor' unless @installer @installer.packages end # For only multipackage def declare_packages(list) raise '[setup.rb fatal] multi-package metaconfig API declare_packages() called for single-package; contact application package vendor' unless @installer @installer.packages = list end end end # class ConfigTable # This module requires: #verbose?, #no_harm? module FileOperations def mkdir_p(dirname, prefix = nil) dirname = prefix + File.expand_path(dirname) if prefix $stderr.puts "mkdir -p #{dirname}" if verbose? return if no_harm? # Does not check '/', it's too abnormal. dirs = File.expand_path(dirname).split(%r<(?=/)>) if /\A[a-z]:\z/i =~ dirs[0] disk = dirs.shift dirs[0] = disk + dirs[0] end dirs.each_index do |idx| path = dirs[0..idx].join('') Dir.mkdir path unless File.dir?(path) end end def rm_f(path) $stderr.puts "rm -f #{path}" if verbose? return if no_harm? force_remove_file path end def rm_rf(path) $stderr.puts "rm -rf #{path}" if verbose? return if no_harm? remove_tree path end def remove_tree(path) if File.symlink?(path) remove_file path elsif File.dir?(path) remove_tree0 path else force_remove_file path end end def remove_tree0(path) Dir.foreach(path) do |ent| next if ent == '.' next if ent == '..' entpath = "#{path}/#{ent}" if File.symlink?(entpath) remove_file entpath elsif File.dir?(entpath) remove_tree0 entpath else force_remove_file entpath end end begin Dir.rmdir path rescue Errno::ENOTEMPTY # directory may not be empty end end def move_file(src, dest) force_remove_file dest begin File.rename src, dest rescue File.open(dest, 'wb') {|f| f.write File.binread(src) } File.chmod File.stat(src).mode, dest File.unlink src end end def force_remove_file(path) begin remove_file path rescue end end def remove_file(path) File.chmod 0777, path File.unlink path end def install(from, dest, mode, prefix = nil) $stderr.puts "install #{from} #{dest}" if verbose? return if no_harm? realdest = prefix ? prefix + File.expand_path(dest) : dest realdest = File.join(realdest, File.basename(from)) if File.dir?(realdest) str = File.binread(from) if diff?(str, realdest) verbose_off { rm_f realdest if File.exist?(realdest) } File.open(realdest, 'wb') {|f| f.write str } File.chmod mode, realdest File.open("#{objdir_root()}/InstalledFiles", 'a') {|f| if prefix f.puts realdest.sub(prefix, '') else f.puts realdest end } end end def diff?(new_content, path) return true unless File.exist?(path) new_content != File.binread(path) end def command(*args) $stderr.puts args.join(' ') if verbose? system(*args) or raise RuntimeError, "system(#{args.map{|a| a.inspect }.join(' ')}) failed" end def ruby(*args) command config('rubyprog'), *args end def make(task = nil) command(*[config('makeprog'), task].compact) end def extdir?(dir) File.exist?("#{dir}/MANIFEST") or File.exist?("#{dir}/extconf.rb") end def files_of(dir) Dir.open(dir) {|d| return d.select {|ent| File.file?("#{dir}/#{ent}") } } end DIR_REJECT = %w( . .. CVS SCCS RCS CVS.adm .svn ) def directories_of(dir) Dir.open(dir) {|d| return d.select {|ent| File.dir?("#{dir}/#{ent}") } - DIR_REJECT } end end # This module requires: #srcdir_root, #objdir_root, #relpath module HookScriptAPI def get_config(key) @config[key] end alias config get_config # obsolete: use metaconfig to change configuration def set_config(key, val) @config[key] = val end # # srcdir/objdir (works only in the package directory) # def curr_srcdir "#{srcdir_root()}/#{relpath()}" end def curr_objdir "#{objdir_root()}/#{relpath()}" end def srcfile(path) "#{curr_srcdir()}/#{path}" end def srcexist?(path) File.exist?(srcfile(path)) end def srcdirectory?(path) File.dir?(srcfile(path)) end def srcfile?(path) File.file?(srcfile(path)) end def srcentries(path = '.') Dir.open("#{curr_srcdir()}/#{path}") {|d| return d.to_a - %w(. ..) } end def srcfiles(path = '.') srcentries(path).select {|fname| File.file?(File.join(curr_srcdir(), path, fname)) } end def srcdirectories(path = '.') srcentries(path).select {|fname| File.dir?(File.join(curr_srcdir(), path, fname)) } end end class ToplevelInstaller Version = '3.4.1' Copyright = 'Copyright (c) 2000-2005 Minero Aoki' TASKS = [ [ 'all', 'do config, setup, then install' ], [ 'config', 'saves your configurations' ], [ 'show', 'shows current configuration' ], [ 'setup', 'compiles ruby extentions and others' ], [ 'install', 'installs files' ], [ 'test', 'run all tests in test/' ], [ 'clean', "does `make clean' for each extention" ], [ 'distclean',"does `make distclean' for each extention" ] ] def ToplevelInstaller.invoke config = ConfigTable.new(load_rbconfig()) config.load_standard_entries config.load_multipackage_entries if multipackage? config.fixup klass = (multipackage?() ? ToplevelInstallerMulti : ToplevelInstaller) klass.new(File.dirname($0), config).invoke end def ToplevelInstaller.multipackage? File.dir?(File.dirname($0) + '/packages') end def ToplevelInstaller.load_rbconfig if arg = ARGV.detect {|arg| /\A--rbconfig=/ =~ arg } ARGV.delete(arg) load File.expand_path(arg.split(/=/, 2)[1]) $".push 'rbconfig.rb' else require 'rbconfig' end ::RbConfig::CONFIG end def initialize(ardir_root, config) @ardir = File.expand_path(ardir_root) @config = config # cache @valid_task_re = nil end def config(key) @config[key] end def inspect "#<#{self.class} #{__id__()}>" end def invoke run_metaconfigs case task = parsearg_global() when nil, 'all' parsearg_config init_installers exec_config exec_setup exec_install else case task when 'config', 'test' ; when 'clean', 'distclean' @config.load_savefile if File.exist?(@config.savefile) else @config.load_savefile end __send__ "parsearg_#{task}" init_installers __send__ "exec_#{task}" end end def run_metaconfigs @config.load_script "#{@ardir}/metaconfig" end def init_installers @installer = Installer.new(@config, @ardir, File.expand_path('.')) end # # Hook Script API bases # def srcdir_root @ardir end def objdir_root '.' end def relpath '.' end # # Option Parsing # def parsearg_global while arg = ARGV.shift case arg when /\A\w+\z/ setup_rb_error "invalid task: #{arg}" unless valid_task?(arg) return arg when '-q', '--quiet' @config.verbose = false when '--verbose' @config.verbose = true when '--help' print_usage $stdout exit 0 when '--version' puts "#{File.basename($0)} version #{Version}" exit 0 when '--copyright' puts Copyright exit 0 else setup_rb_error "unknown global option '#{arg}'" end end nil end def valid_task?(t) valid_task_re() =~ t end def valid_task_re @valid_task_re ||= /\A(?:#{TASKS.map {|task,desc| task }.join('|')})\z/ end def parsearg_no_options unless ARGV.empty? task = caller(0).first.slice(%r<`parsearg_(\w+)'>, 1) setup_rb_error "#{task}: unknown options: #{ARGV.join(' ')}" end end alias parsearg_show parsearg_no_options alias parsearg_setup parsearg_no_options alias parsearg_test parsearg_no_options alias parsearg_clean parsearg_no_options alias parsearg_distclean parsearg_no_options def parsearg_config evalopt = [] set = [] @config.config_opt = [] while i = ARGV.shift if /\A--?\z/ =~ i @config.config_opt = ARGV.dup break end name, value = *@config.parse_opt(i) if @config.value_config?(name) @config[name] = value else evalopt.push [name, value] end set.push name end evalopt.each do |name, value| @config.lookup(name).evaluate value, @config end # Check if configuration is valid set.each do |n| @config[n] if @config.value_config?(n) end end def parsearg_install @config.no_harm = false @config.install_prefix = '' while a = ARGV.shift case a when '--no-harm' @config.no_harm = true when /\A--prefix=/ path = a.split(/=/, 2)[1] path = File.expand_path(path) unless path[0,1] == '/' @config.install_prefix = path else setup_rb_error "install: unknown option #{a}" end end end def print_usage(out) out.puts 'Typical Installation Procedure:' out.puts " $ ruby #{File.basename $0} config" out.puts " $ ruby #{File.basename $0} setup" out.puts " # ruby #{File.basename $0} install (may require root privilege)" out.puts out.puts 'Detailed Usage:' out.puts " ruby #{File.basename $0} " out.puts " ruby #{File.basename $0} [] []" fmt = " %-24s %s\n" out.puts out.puts 'Global options:' out.printf fmt, '-q,--quiet', 'suppress message outputs' out.printf fmt, ' --verbose', 'output messages verbosely' out.printf fmt, ' --help', 'print this message' out.printf fmt, ' --version', 'print version and quit' out.printf fmt, ' --copyright', 'print copyright and quit' out.puts out.puts 'Tasks:' TASKS.each do |name, desc| out.printf fmt, name, desc end fmt = " %-24s %s [%s]\n" out.puts out.puts 'Options for CONFIG or ALL:' @config.each do |item| out.printf fmt, item.help_opt, item.description, item.help_default end out.printf fmt, '--rbconfig=path', 'rbconfig.rb to load',"running ruby's" out.puts out.puts 'Options for INSTALL:' out.printf fmt, '--no-harm', 'only display what to do if given', 'off' out.printf fmt, '--prefix=path', 'install path prefix', '' out.puts end # # Task Handlers # def exec_config @installer.exec_config @config.save # must be final end def exec_setup @installer.exec_setup end def exec_install @installer.exec_install end def exec_test @installer.exec_test end def exec_show @config.each do |i| printf "%-20s %s\n", i.name, i.value if i.value? end end def exec_clean @installer.exec_clean end def exec_distclean @installer.exec_distclean end end # class ToplevelInstaller class ToplevelInstallerMulti < ToplevelInstaller include FileOperations def initialize(ardir_root, config) super @packages = directories_of("#{@ardir}/packages") raise 'no package exists' if @packages.empty? @root_installer = Installer.new(@config, @ardir, File.expand_path('.')) end def run_metaconfigs @config.load_script "#{@ardir}/metaconfig", self @packages.each do |name| @config.load_script "#{@ardir}/packages/#{name}/metaconfig" end end attr_reader :packages def packages=(list) raise 'package list is empty' if list.empty? list.each do |name| raise "directory packages/#{name} does not exist"\ unless File.dir?("#{@ardir}/packages/#{name}") end @packages = list end def init_installers @installers = {} @packages.each do |pack| @installers[pack] = Installer.new(@config, "#{@ardir}/packages/#{pack}", "packages/#{pack}") end with = extract_selection(config('with')) without = extract_selection(config('without')) @selected = @installers.keys.select {|name| (with.empty? or with.include?(name)) \ and not without.include?(name) } end def extract_selection(list) a = list.split(/,/) a.each do |name| setup_rb_error "no such package: #{name}" unless @installers.key?(name) end a end def print_usage(f) super f.puts 'Inluded packages:' f.puts ' ' + @packages.sort.join(' ') f.puts end # # Task Handlers # def exec_config run_hook 'pre-config' each_selected_installers {|inst| inst.exec_config } run_hook 'post-config' @config.save # must be final end def exec_setup run_hook 'pre-setup' each_selected_installers {|inst| inst.exec_setup } run_hook 'post-setup' end def exec_install run_hook 'pre-install' each_selected_installers {|inst| inst.exec_install } run_hook 'post-install' end def exec_test run_hook 'pre-test' each_selected_installers {|inst| inst.exec_test } run_hook 'post-test' end def exec_clean rm_f @config.savefile run_hook 'pre-clean' each_selected_installers {|inst| inst.exec_clean } run_hook 'post-clean' end def exec_distclean rm_f @config.savefile run_hook 'pre-distclean' each_selected_installers {|inst| inst.exec_distclean } run_hook 'post-distclean' end # # lib # def each_selected_installers Dir.mkdir 'packages' unless File.dir?('packages') @selected.each do |pack| $stderr.puts "Processing the package `#{pack}' ..." if verbose? Dir.mkdir "packages/#{pack}" unless File.dir?("packages/#{pack}") Dir.chdir "packages/#{pack}" yield @installers[pack] Dir.chdir '../..' end end def run_hook(id) @root_installer.run_hook id end # module FileOperations requires this def verbose? @config.verbose? end # module FileOperations requires this def no_harm? @config.no_harm? end end # class ToplevelInstallerMulti class Installer FILETYPES = %w( bin lib ext data conf man ) include FileOperations include HookScriptAPI def initialize(config, srcroot, objroot) @config = config @srcdir = File.expand_path(srcroot) @objdir = File.expand_path(objroot) @currdir = '.' end def inspect "#<#{self.class} #{File.basename(@srcdir)}>" end def noop(rel) end # # Hook Script API base methods # def srcdir_root @srcdir end def objdir_root @objdir end def relpath @currdir end # # Config Access # # module FileOperations requires this def verbose? @config.verbose? end # module FileOperations requires this def no_harm? @config.no_harm? end def verbose_off begin save, @config.verbose = @config.verbose?, false yield ensure @config.verbose = save end end # # TASK config # def exec_config exec_task_traverse 'config' end alias config_dir_bin noop alias config_dir_lib noop def config_dir_ext(rel) extconf if extdir?(curr_srcdir()) end alias config_dir_data noop alias config_dir_conf noop alias config_dir_man noop def extconf ruby "#{curr_srcdir()}/extconf.rb", *@config.config_opt end # # TASK setup # def exec_setup exec_task_traverse 'setup' end def setup_dir_bin(rel) files_of(curr_srcdir()).each do |fname| update_shebang_line "#{curr_srcdir()}/#{fname}" end end alias setup_dir_lib noop def setup_dir_ext(rel) make if extdir?(curr_srcdir()) end alias setup_dir_data noop alias setup_dir_conf noop alias setup_dir_man noop def update_shebang_line(path) return if no_harm? return if config('shebang') == 'never' old = Shebang.load(path) if old $stderr.puts "warning: #{path}: Shebang line includes too many args. It is not portable and your program may not work." if old.args.size > 1 new = new_shebang(old) return if new.to_s == old.to_s else return unless config('shebang') == 'all' new = Shebang.new(config('rubypath')) end $stderr.puts "updating shebang: #{File.basename(path)}" if verbose? open_atomic_writer(path) {|output| File.open(path, 'rb') {|f| f.gets if old # discard output.puts new.to_s output.print f.read } } end def new_shebang(old) if /\Aruby/ =~ File.basename(old.cmd) Shebang.new(config('rubypath'), old.args) elsif File.basename(old.cmd) == 'env' and old.args.first == 'ruby' Shebang.new(config('rubypath'), old.args[1..-1]) else return old unless config('shebang') == 'all' Shebang.new(config('rubypath')) end end def open_atomic_writer(path, &block) tmpfile = File.basename(path) + '.tmp' begin File.open(tmpfile, 'wb', &block) File.rename tmpfile, File.basename(path) ensure File.unlink tmpfile if File.exist?(tmpfile) end end class Shebang def Shebang.load(path) line = nil File.open(path) {|f| line = f.gets } return nil unless /\A#!/ =~ line parse(line) end def Shebang.parse(line) cmd, *args = *line.strip.sub(/\A\#!/, '').split(' ') new(cmd, args) end def initialize(cmd, args = []) @cmd = cmd @args = args end attr_reader :cmd attr_reader :args def to_s "#! #{@cmd}" + (@args.empty? ? '' : " #{@args.join(' ')}") end end # # TASK install # def exec_install rm_f 'InstalledFiles' exec_task_traverse 'install' end def install_dir_bin(rel) install_files targetfiles(), "#{config('bindir')}/#{rel}", 0755 end def install_dir_lib(rel) install_files libfiles(), "#{config('rbdir')}/#{rel}", 0644 end def install_dir_ext(rel) return unless extdir?(curr_srcdir()) install_files rubyextentions('.'), "#{config('sodir')}/#{File.dirname(rel)}", 0555 end def install_dir_data(rel) install_files targetfiles(), "#{config('datadir')}/#{rel}", 0644 end def install_dir_conf(rel) # FIXME: should not remove current config files # (rename previous file to .old/.org) install_files targetfiles(), "#{config('sysconfdir')}/#{rel}", 0644 end def install_dir_man(rel) install_files targetfiles(), "#{config('mandir')}/#{rel}", 0644 end def install_files(list, dest, mode) mkdir_p dest, @config.install_prefix list.each do |fname| install fname, dest, mode, @config.install_prefix end end def libfiles glob_reject(%w(*.y *.output), targetfiles()) end def rubyextentions(dir) ents = glob_select("*.#{@config.dllext}", targetfiles()) if ents.empty? setup_rb_error "no ruby extention exists: 'ruby #{$0} setup' first" end ents end def targetfiles mapdir(existfiles() - hookfiles()) end def mapdir(ents) ents.map {|ent| if File.exist?(ent) then ent # objdir else "#{curr_srcdir()}/#{ent}" # srcdir end } end # picked up many entries from cvs-1.11.1/src/ignore.c JUNK_FILES = %w( core RCSLOG tags TAGS .make.state .nse_depinfo #* .#* cvslog.* ,* .del-* *.olb *~ *.old *.bak *.BAK *.orig *.rej _$* *$ *.org *.in .* ) def existfiles glob_reject(JUNK_FILES, (files_of(curr_srcdir()) | files_of('.'))) end def hookfiles %w( pre-%s post-%s pre-%s.rb post-%s.rb ).map {|fmt| %w( config setup install clean ).map {|t| sprintf(fmt, t) } }.flatten end def glob_select(pat, ents) re = globs2re([pat]) ents.select {|ent| re =~ ent } end def glob_reject(pats, ents) re = globs2re(pats) ents.reject {|ent| re =~ ent } end GLOB2REGEX = { '.' => '\.', '$' => '\$', '#' => '\#', '*' => '.*' } def globs2re(pats) /\A(?:#{ pats.map {|pat| pat.gsub(/[\.\$\#\*]/) {|ch| GLOB2REGEX[ch] } }.join('|') })\z/ end # # TASK test # TESTDIR = 'test' def exec_test unless File.directory?('test') $stderr.puts 'no test in this package' if verbose? return end $stderr.puts 'Running tests...' if verbose? begin require 'test/unit' rescue LoadError setup_rb_error 'test/unit cannot loaded. You need Ruby 1.8 or later to invoke this task.' end runner = Test::Unit::AutoRunner.new(true) runner.to_run << TESTDIR runner.run end # # TASK clean # def exec_clean exec_task_traverse 'clean' rm_f @config.savefile rm_f 'InstalledFiles' end alias clean_dir_bin noop alias clean_dir_lib noop alias clean_dir_data noop alias clean_dir_conf noop alias clean_dir_man noop def clean_dir_ext(rel) return unless extdir?(curr_srcdir()) make 'clean' if File.file?('Makefile') end # # TASK distclean # def exec_distclean exec_task_traverse 'distclean' rm_f @config.savefile rm_f 'InstalledFiles' end alias distclean_dir_bin noop alias distclean_dir_lib noop def distclean_dir_ext(rel) return unless extdir?(curr_srcdir()) make 'distclean' if File.file?('Makefile') end alias distclean_dir_data noop alias distclean_dir_conf noop alias distclean_dir_man noop # # Traversing # def exec_task_traverse(task) run_hook "pre-#{task}" FILETYPES.each do |type| if type == 'ext' and config('without-ext') == 'yes' $stderr.puts 'skipping ext/* by user option' if verbose? next end traverse task, type, "#{task}_dir_#{type}" end run_hook "post-#{task}" end def traverse(task, rel, mid) dive_into(rel) { run_hook "pre-#{task}" __send__ mid, rel.sub(%r[\A.*?(?:/|\z)], '') directories_of(curr_srcdir()).each do |d| traverse task, "#{rel}/#{d}", mid end run_hook "post-#{task}" } end def dive_into(rel) return unless File.dir?("#{@srcdir}/#{rel}") dir = File.basename(rel) Dir.mkdir dir unless File.dir?(dir) prevdir = Dir.pwd Dir.chdir dir $stderr.puts '---> ' + rel if verbose? @currdir = rel yield Dir.chdir prevdir $stderr.puts '<--- ' + rel if verbose? @currdir = File.dirname(rel) end def run_hook(id) path = [ "#{curr_srcdir()}/#{id}", "#{curr_srcdir()}/#{id}.rb" ].detect {|cand| File.file?(cand) } return unless path begin instance_eval File.read(path), path, 1 rescue raise if $DEBUG setup_rb_error "hook #{path} failed:\n" + $!.message end end end # class Installer class SetupError < StandardError; end def setup_rb_error(msg) raise SetupError, msg end if $0 == __FILE__ begin ToplevelInstaller.invoke rescue SetupError raise if $DEBUG $stderr.puts $!.message $stderr.puts "Try 'ruby #{$0} --help' for detailed usage." exit 1 end end cmdparse-2.0.6/VERSION0000644000004100000410000000000612335652375014424 0ustar www-datawww-data2.0.6 cmdparse-2.0.6/net.rb0000644000004100000410000000433112335652375014474 0ustar www-datawww-data#!/usr/bin/env ruby # if something is changed here -> change line numbers in doc/src/documentation.page $:.unshift "lib" require 'cmdparse' require 'ostruct' require 'yaml' class NetStatCommand < CmdParse::Command def initialize super('stat', false) self.short_desc = "Show network statistics" self.description = "This command shows very useful network statistics - eye catching!!!" end def execute(args) puts "Showing network statistics" if $verbose puts puts "Yeah, I will do something now..." puts 1.upto(10) do |row| puts " "*(20-row) + "#"*(row*2 - 1) end puts end end cmd = CmdParse::CommandParser.new(true, true) cmd.program_name = "net" cmd.program_version = [0, 1, 1] cmd.options = CmdParse::OptionParserWrapper.new do |opt| opt.separator "Global options:" opt.on("--verbose", "Be verbose when outputting info") {|t| $verbose = true } end cmd.add_command(CmdParse::HelpCommand.new) cmd.add_command(CmdParse::VersionCommand.new) cmd.add_command(NetStatCommand.new) # ipaddr ipaddr = CmdParse::Command.new('ipaddr', true, true) ipaddr.short_desc = "Manage IP addresses" cmd.add_command(ipaddr) # ipaddr add add = CmdParse::Command.new('add', false) add.short_desc = "Add an IP address" add.set_execution_block do |args| puts "Adding ip addresses: #{args.join(', ')}" if $verbose $ipaddrs += args end ipaddr.add_command(add) # ipaddr del del = CmdParse::Command.new('del', false) del.short_desc = "Delete an IP address" del.options = CmdParse::OptionParserWrapper.new do |opt| opt.on('-a', '--all', 'Delete all IP addresses') { $deleteAll = true } end del.set_execution_block do |args| if $deleteAll $ipaddrs = [] else puts "Deleting ip addresses: #{args.join(', ')}" if $verbose args.each {|ip| $ipaddrs.delete(ip) } end end ipaddr.add_command(del) # ipaddr list list = CmdParse::Command.new('list', false) list.short_desc = "Lists all IP addresses" list.set_execution_block do |args| puts "Listing ip addresses:" if $verbose puts $ipaddrs.to_yaml end ipaddr.add_command(list, true) if File.exists?('dumpnet') $ipaddrs = Marshal.load(File.read('dumpnet')) else $ipaddrs = [] end cmd.parse File.open('dumpnet', 'w+') {|f| f.write(Marshal.dump($ipaddrs)) } cmdparse-2.0.6/checksums.yaml.gz0000444000004100000410000000041512335652375016646 0ustar www-datawww-data[?Se;R0 D"#HDEä8Ё}w.o/|^?|ݴӁaVY ˳t%~\9S0kG E2&=Zǿ^.CPP.m&I![f荖S܊&t ]ub2=Ol败k1L|kɂ91 ލ2$<'5Ϛ)|,-ˏ8 ޛ с q=b=1.0.0 (webgen.gettalong.org) for building. ## Example There is an example of how to use cmdparse in the `net.rb` file. ## Contact Author: Thomas Leitner * Web: * e-Mail: cmdparse-2.0.6/COPYING0000644000004100000410000010451312335652375014417 0ustar www-datawww-data GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read .