File: Arg.pmod

package info (click to toggle)
pike8.0 8.0.1956-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 60,580 kB
  • sloc: ansic: 259,734; xml: 36,320; makefile: 3,748; sh: 1,713; cpp: 1,349; awk: 1,036; lisp: 655; javascript: 468; asm: 242; objc: 240; pascal: 157; sed: 34
file content (644 lines) | stat: -rw-r--r-- 15,041 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
// Argument parser
// By Martin Nilsson
//

//! Argument parsing module
//! This module supports two rather different methods of argument parsing.
//! The first is suitable quick argument parsing without much in the way of checking:
//!
//! @code
//! int main( int c, array(string) argv )
//! {
//!   mapping arguments = Arg.parse(argv);
//!   array files = arguments[Arg.REST];
//!   if( arguments->help ) print_help();
//!   ...
//! }
//! @endcode
//!
//! The @[Arg.parse] method will return a mapping from argument name
//! to the argument value, if any.
//!
//! Non-option arguments will be placed in the index Arg.REST
//!
//! The second way to use this module is to inherit the LowOptions
//! class and then start adding supported arguments:
//!
//! @code
//! class MyArguments {
//!    inherit Arg.LowOptions;
//!    Opt verbose = NoOpt("-v")|NoOpt("--verbose");
//!    Opt help = MaybeOpt("--help");
//!    Opt output = HasOpt("--output")|HasOpt("-o");
//! };
//! @endcode
//!
//! Then, in main:
//!
//! @code
//! MyArguments args = MyArguments(argv);
//! @endcode
//!
//! See the documentation for @[OptLibrary] for details about the various
//! Opt classes.

#pike __REAL_VERSION__

class OptLibrary
//!
{

  //! Base class for parsing an argument. Inherit this class to create
  //! custom made option types.
  class Opt
  {
    constant is_opt = 1;
    protected Opt next;

    //! Should return 1 for set options or a string containing the
    //! value of the option. Returning 0 means the option was not set
    //! (or matched). To properly chain arguments parsers, return
    //! @expr{::get_value(argv, env, previous)@} instead of @expr{0@},
    //! unless you want to explicitly stop the chain and not set this
    //! option.
    mixed get_value(array(string) argv, mapping(string:string) env,
                         int|string previous)
    {
      if(next) return next->get_value(argv, env, previous);
      return 0;
    }

    //! Should return a list of options that are parsed. To properly
    //! chain argument parsers, return @expr{your_opts +
    //! ::get_opts()@}.
    array(string) get_opts()
    {
      if(!next) return ({});
      return next->get_opts();
    }

    protected this_program `|(mixed thing)
    {
      if( !objectp(thing) || !thing->is_opt )
        error("Can only or %O with another %O.\n",
              this, this_program);

      if( next )
      {
        next = next | thing;
        return this;
      }

      next = thing;
      return this;
    }

    //! This function will be called by @expr{_sprintf@}, which
    //! handles formatting of chaining between objects.
    protected string __sprintf()
    {
      return sprintf("%O()", this_program);
    }

    protected string _sprintf(int t)
    {
      if( t!='O' ) return UNDEFINED;
      if( !next )
        return __sprintf();
      else
        return sprintf("%s|%O", __sprintf(), next);
    }
  }

  //! Parses an option without parameter, such as --help, -x or "x"
  //! from -axb.
  //!
  //! @example
  //!   Opt verbose = NoOpt("-v")|NoOpt("--verbose");
  class NoOpt
  {
    inherit Opt;
    protected string opt;
    protected int double;

    protected void create(string _opt)
    {
      if( sizeof(_opt)>2 && has_prefix(_opt, "--") )
        double = 1;
      else if( sizeof(_opt)!=2 || _opt[0]!='-' || _opt=="--" )
        error("%O not a valid option.\n", _opt);
      opt = _opt;
    }

    mixed get_value(array(string) argv, mapping(string:string) env, mixed previous)
    {
      if( !sizeof(argv) ) return previous || ::get_value(argv, env, previous);

      if( double )
      {
        if( argv[0]==opt )
        {
          argv[0] = 0;
          return (int)previous+1;
        }
        return previous || ::get_value(argv, env, previous);
      }

      if( sizeof(argv[0])>1 && argv[0][0]=='-' && argv[0][1]!='-' )
      {
        array parts = argv[0]/"=";
        if( has_value(parts[0], opt[1..1]) )
        {
          parts[0] -= opt[1..1];
          argv[0] = parts*"=";
          if(argv[0]=="-") argv[0] = 0;
          return (int)previous+1;
        }
      }

      return previous || ::get_value(argv, env, previous);
    }

    array(string) get_opts()
    {
      return ({ opt }) + ::get_opts();
    }

    protected string __sprintf()
    {
      return sprintf("Arg.NoOpt(%O)", opt);
    }
  }

  //! Environment fallback for an option. Can of course be used as
  //! only Opt source.
  //!
  //! @example
  //!   Opt debug = NoOpt("--debug")|Env("MY_DEBUG");
  class Env
  {
    inherit Opt;
    protected string name;

    protected void create(string _name)
    {
      name = _name;
    }

    mixed get_value(array(string) argv, mapping(string:string) env, mixed previous)
    {
      if( env[name] ) return env[name];
      return ::get_value(argv, env, previous);
    }

    protected string __sprintf()
    {
      return sprintf("Arg.Env(%O)", name);
    }
  }

  //! Default value for a setting.
  //!
  //! @example
  //!   Opt output = HasOpt("-o")|Default("a.out");
  class Default
  {
    inherit Opt;
    protected string value;

    protected void create(string _value)
    {
      value = _value;
    }

    string get_value(array(string) argv, mapping(string:string) env, mixed previous)
    {
      return value;
    }

    protected string __sprintf()
    {
      return sprintf("Arg.Default(%O)", value);
    }
  }

  //! Parses an option that may have a parameter. @tt{--foo@},
  //! @tt{-x@} and x in a sequence like @tt{-axb@} will set the
  //! variable to @expr{1@}. @tt{--foo=bar@}, @tt{-x bar@} and
  //! @tt{-x=bar@} will set the variable to @expr{bar@}.
  //!
  //! @example
  //!   Opt debug = MaybeOpt("--debug");
  class MaybeOpt
  {
    inherit NoOpt;

    mixed get_value(array(string) argv, mapping(string:string) env, mixed previous)
    {
      if( !sizeof(argv) ) return previous || ::get_value(argv, env, previous);

      if( double )
      {
        // --foo
        if( argv[0]==opt )
        {
          argv[0] = 0;
          return (int)previous+1;
        }

        // --foo=bar
        if( sscanf(argv[0], opt+"=%s", string ret)==1 )
        {
          argv[0] = 0;
          // FIXME: Make an array if previous is set?
          return ret;
        }

        return previous || ::get_value(argv, env, previous);
      }

      // -x
      if( sizeof(argv[0])>1 && argv[0][0]=='-' && argv[0][1]!='-' )
      {
        array parts = argv[0]/"=";

        if( has_value(parts[0], opt[1..1]) &&
            ( sizeof(parts)==1 ||
              parts[0][-1]!=opt[1] ) )
        {
          // -xy, -xy=z
          parts[0] -= opt[1..1];
          argv[0] = parts*"=";
          if(argv[0]=="-") argv[0] = 0;
          return (int)previous+1;
        }
        else if( sizeof(parts)>1 && parts[0][-1]==opt[1] )
        {
          // -yx=z
          parts[0] -= opt[1..1];
          if( parts[0]=="-" )
            argv[0] = 0;
          else
            argv[0] = parts[0];
          return parts[1..]*"=";
        }

        return previous || ::get_value(argv, env, previous);
      }

      return previous || ::get_value(argv, env, previous);
    }

    protected string __sprintf()
    {
      return sprintf("Arg.MaybeOpt(%O)", opt);
    }
  }

  //! Parses an option that has a parameter. @tt{--foo=bar@}, @tt{-x
  //! bar@} and @tt{-x=bar@} will set the variable to @expr{bar@}.
  //!
  //! @example
  //!   Opt user = HasOpt("--user")|HasOpt("-u");
  class HasOpt
  {
    inherit NoOpt;

    mixed get_value(array(string) argv, mapping(string:string) env, mixed previous)
    {
      if( !sizeof(argv) ) return previous || ::get_value(argv, env, previous);

      if( double )
      {
        // --foo bar
        if( argv[0]==opt )
        {
          if( sizeof(argv)>1 )
          {
            argv[0] = 0;
            string ret = argv[1];
            argv[1] = 0;
            return ret;
          }
          return 0; // FIXME: Signal failure
        }

        // --foo=bar
        if( sscanf(argv[0], opt+"=%s", string ret)==1 )
        {
          argv[0] = 0;
          return ret;
        }
        return previous || ::get_value(argv, env, previous);
      }

      if( sizeof(argv[0])>1 && argv[0][0]=='-' && argv[0][1]!='-' )
      {
        array parts = argv[0]/"=";
        if( sizeof(parts[0]) && parts[0][-1]==opt[1] )
        {
          if( sizeof(parts)==1 )
          {
            // "-xxxy z"
            if(sizeof(argv)>1)
            {
              parts[0] -= opt[1..1];
              if( parts[0]=="-" )
                argv[0] = 0;
              else
                argv[0] = parts[0];
              string ret = argv[1];
              argv[1] = 0;
              return ret;
            }

            // Fail. "-y" without any more elements in argv.
            return previous || ::get_value(argv, env, previous);
          }
          else
          {
            // "-xxxy=z"
            parts[0] -= opt[1..1];
            if( parts[0]=="-" )
              argv[0] = 0;
            else
              argv[0] = parts[0];
            return parts[1..]*"=";
          }
        }
      }

      return previous || ::get_value(argv, env, previous);
    }

    protected string __sprintf()
    {
      return sprintf("Arg.HasOpt(%O)", opt);
    }
  }

} // -- OptLibrary

object REST = class {
    protected string _sprintf(int t)
    {
      return "Arg.REST";
    }
  }();

//! @decl constant REST = REST();
//!
//! Constant used by Arg.parse() to indicate the remaining objects.


// FIXME: Support for rc files? ( Opt x = Opt("--x")|INIFile(path, name); )
// FIXME: Support for type casts? ( Opt level = Integer(Opt("--level"));

class LowOptions
  //!
{
  protected inherit OptLibrary;

  //!
  protected mapping(string:Opt) opts = ([]);

  //!
  protected mapping(string:int(1..1)|string) values = ([]);

  //!
  protected array(string) argv;

  //!
  protected string application;

  //!
  protected void create(array(string) _argv, void|mapping(string:string) env)
  {
    if(!env)
      env = getenv();

    // Make a list of all the arguments we can parse.
    foreach(
#if __BUILD__ < 368
	    // NB: Prior to 8.0.368 the new-style argument checking in _indices()
	    //     was broken.
	    ::_indices(2),
#else
	    ::_indices(this, 0),
#endif
	    string index)
    {
      mixed val = ::`[](index, this, 0);
      if(objectp(val) && val->is_opt) opts[index]=val;
    }

    application = _argv[0];
    argv = _argv[1..];
    mapping(string:Opt) unset = opts+([]);

    while(sizeof(argv))
    {
      array(string) pre = argv+({});
      foreach(opts; string index; Opt arg)
      {
        int(0..1)|string value = arg->get_value(argv, env, values[index]);
        if(value)
        {
          m_delete(unset, index);
          values[index] = value;
          argv -= ({ 0 });
        }
      }
      argv -= ({ 0 });

      if(equal(pre, argv))
      {
        unhandled_argument(argv, env);
        if(equal(pre, argv))
          break;
      }
    }

    if( sizeof(unset) )
    {
      int(0..1)|string value;
      foreach(unset; string index; Opt arg)
      {
        value = arg->get_value(({}), env, values[index]);
        if(value)
          values[index] = value;
      }
    }

  }

  //!
  protected int(0..1) unhandled_argument(array(string) argv,
                                      mapping(string:string) env)
  {
    return 0;
  }

  protected mixed cast(string to)
  {
    switch( to )
    {
    case "mapping":
      return values + ([ REST : argv ]);
    case "array":
      return argv;
    }
    return UNDEFINED;
  }
}

//! The option parser class that contains all the argument objects.
//!
class Options
{
  inherit LowOptions;

  protected string|int `[](string id)
  {
    return values[id];
  }

  protected string|int `->(string id)
  {
    return values[id];
  }

  //!
  protected int(0..1)|string unhandled_argument(array(string) argv,
                                             mapping(string:string) env)
  {
    if( !sizeof(argv) || argv[0]!="--help" ) return 0;

    string s = index("help_pre");
    if( s )
      write( s+"\n" );

    foreach(opts; string i; Opt opt)
    {
      write( opt->get_opts()*", " + "\n");
      s = index(i+"_help");
      if( s )
        write( s ); // FIXME: Format
    }

    s = index("help_post");
    if( s )
      write( "\n"+s );
  }

  protected string index(string i)
  {
    string s = ::`[](i, this, 0);
    if( !s ) return 0;
    if( !stringp(s) ) error("%O is not a string.\n", i);
    if( sizeof(s) )
    {
      if( s[-1]!='\n' )
        s += "\n";
      return s;
    }
    return 0;
  }
}


// --- Simple interface

class SimpleOptions
//! Options parser with a unhandled_argument implementation that
//! parses most common argument formats.
{
  inherit LowOptions;

 //! Handles arguments as described in @[Arg.parse]
  int(0..1) unhandled_argument(array(string) argv, mapping(string:string) env)
  {
    string arg = argv[0];
    if(!sizeof(arg) || arg[0]!='-') return 0;

    string name,value;

    if( has_prefix(arg, "--") )
    {
      sscanf( arg, "--%s=%s", name, value ) || sscanf( arg, "--%s", name );
      if(!name) return 0; // arg == "--"
      if( value )
        values[name] = value;
      else
        values[name]++;
      argv[0]=0;
      return 1;
    }

    sscanf( arg, "-%s=%s", name, value ) || sscanf( arg, "-%s", name );
    if( !name || !sizeof(name) ) return 0;
    foreach( name/1; int pos; string c )
    {
      if( value && pos == sizeof(name)-1 )
        values[c] = value;
      else
        values[c]++;
    }
    argv[0]=0;
    return 1;
  }
}

// Handles
// --foo         ->  "foo":1
// --foo=bar     ->  "foo":"bar"
// -bar          ->  "b":1,"a":1,"r":1
// -bar=foo      ->  "b":1,"a":1,"r":"foo" (?)
// --foo --bar   ->  "foo":1,"bar":1
// --foo - --bar ->  "foo":1
// --foo x --bar ->  "foo":1 (?)
// -foo          ->  "f":1,"o":2
// -x -x -x      ->  "x":3
//
// void main(int n, array argv)
// {
//   mapping opts = Arg.parse(argv);
//   argv = opts[Arg.REST];
// }

//! Convenience function for simple argument parsing.
//!
//! Handles the most common cases.
//!
//! The return value is a mapping from option name to the option value.
//!
//! The special index Arg.REST will be set to the remaining arguments
//! after all options have been parsed.
//!
//! The following argument syntaxes are supported:
//!
//! @code
//! --foo         ->  "foo":1
//! --foo=bar     ->  "foo":"bar"
//! -bar          ->  "b":1,"a":1,"r":1
//! -bar=foo      ->  "b":1,"a":1,"r":"foo" (?)
//! --foo --bar   ->  "foo":1,"bar":1
//! --foo - --bar ->  "foo":1
//! --foo x --bar ->  "foo":1 (?)
//! -foo          ->  "f":1,"o":2
//! -x -x -x      ->  "x":3
//! @endcode
//!
//! @example
//! @code
//! void main(int n, array argv)
//! {
//!   mapping opts = Arg.parse(argv);
//!   argv = opts[Arg.REST];
//!   if( opts->help ) /*... */
//! }
//! @endcode
mapping(string:string|int(1..)) parse(array(string) argv)
{
  return (mapping)SimpleOptions(argv);
}