/* * Copyright (C)2005-2022 Haxe Foundation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ type argtype { Void : void -> void; String : string -> void; Int : int -> void; } exception Invalid; function help(head,decl) { print head; print "\n Options :\n"; List.iter (function((name,_,help)) { printf " %s %s\n" (name,help); }) decl; Sys.exit(1) } function parse_args(args,head,decl,def) { var i = &0; var l = Array.length args; var h = Hashtbl.create(); var hdecl = Void (function() { help head decl }); Hashtbl.add h "-help" hdecl; Hashtbl.add h "--help" hdecl; List.iter (function((name,decl,_)) { Hashtbl.add h name decl; }) decl; try { while *i < l { var arg = args.[*i]; i := *i + 1; var d = try { Hashtbl.find h arg; } catch { Not_found -> Void (function() { def arg }) }; match d { | Void f -> f() | String f -> if *i == l then throw Invalid; var param = args.[*i]; i := *i + 1; f param | Int f -> if *i == l then throw Invalid; var param = args.[*i]; i := *i + 1; var pval = try { int param } catch { _ -> throw Invalid }; f pval } } } catch { Invalid -> var arg = args.[*i - 1]; print "Invalid argument : "; print arg; print "\n"; help head decl } } function parse(head,decl,def) { parse_args(Sys.args(),head,decl,def); }