Blame view

lapp.nim 11.2 KB
85eedc50   Göran Krampe   Added lapp.nim to...
1
  import strutils
5e811526   Göran Krampe   Added updated lap...
2
  import os
85eedc50   Göran Krampe   Added lapp.nim to...
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  import tables
  export tables.`[]`
  
  #### Simple string lexer ###
  type
    PLexer = ref TLexer
    TLexer = object
      str: string
      idx: int
    TLexType = enum
      tend
      tword
      tint
      tfloat
      trange
      telipsis
      tchar
386557e6   Göran Krampe   Added support for...
20
21
      toption
      tdivider
85eedc50   Göran Krampe   Added lapp.nim to...
22
23
24
25
26
27
  
  proc thisChar(L: PLexer):char = L.str[L.idx]
  proc next(L: PLexer) = L.idx += 1
  
  proc skipws(L: PLexer) =
    while thisChar(L) in Whitespace: next(L)
33f6041b   Andreas Rumpf   make blimp compil...
28
  
85eedc50   Göran Krampe   Added lapp.nim to...
29
30
31
32
33
34
35
  proc get(L: PLexer; t: var TLexType): string =
    skipws(L)
    let c = thisChar(L)
    t = tend
    if c == '\0': return nil
    result = ""
    result.add(c)
33f6041b   Andreas Rumpf   make blimp compil...
36
    next(L)
85eedc50   Göran Krampe   Added lapp.nim to...
37
38
39
    t = tchar
    case c
    of '-':  # '-", "--"
386557e6   Göran Krampe   Added support for...
40
      t = toption
85eedc50   Göran Krampe   Added lapp.nim to...
41
42
43
      if thisChar(L) == '-':
        result.add('-')
        next(L)
386557e6   Göran Krampe   Added support for...
44
45
        if thisChar(L) == '-': # "---..."
          t = tdivider
33f6041b   Andreas Rumpf   make blimp compil...
46
          result.add('-')
386557e6   Göran Krampe   Added support for...
47
48
          while thisChar(L) == '-':
            next(L)
85eedc50   Göran Krampe   Added lapp.nim to...
49
50
51
52
53
54
55
56
57
58
59
60
    of Letters: # word
      t = tword
      while thisChar(L) in Letters:
        result.add(thisChar(L))
        next(L)
    of Digits: # number
      t = tint
      while thisChar(L) in Digits:
        result.add(thisChar(L))
        next(L)
      if thisChar(L) == '.':
        t = tfloat
5e811526   Göran Krampe   Added updated lap...
61
        result.add(thisChar(L))
85eedc50   Göran Krampe   Added lapp.nim to...
62
63
        next(L)
        while thisChar(L) in Digits:
5e811526   Göran Krampe   Added updated lap...
64
          result.add(thisChar(L))
85eedc50   Göran Krampe   Added lapp.nim to...
65
66
67
68
69
70
71
72
73
74
75
          next(L)
    of '.': # ".", "..", "..."
      if thisChar(L) == '.':
        t = trange
        result.add('.')
        next(L)
        if thisChar(L) == '.':
          t = telipsis
          result.add('.')
          next(L)
    else: discard
33f6041b   Andreas Rumpf   make blimp compil...
76
77
  
  proc get(L: PLexer): string =
85eedc50   Göran Krampe   Added lapp.nim to...
78
79
    var t: TLexType
    get(L,t)
33f6041b   Andreas Rumpf   make blimp compil...
80
  
85eedc50   Göran Krampe   Added lapp.nim to...
81
82
83
84
85
86
87
  proc reset(L: PLexer, s: string) =
    L.str  = s
    L.idx = 0
  
  proc newLexer(s: string): PLexer =
    new(result)
    result.reset(s)
33f6041b   Andreas Rumpf   make blimp compil...
88
  
85eedc50   Göran Krampe   Added lapp.nim to...
89
  ### a container for values ###
33f6041b   Andreas Rumpf   make blimp compil...
90
  
85eedc50   Göran Krampe   Added lapp.nim to...
91
92
93
94
95
96
97
98
99
  type
    TValueKind = enum
      vInt,
      vFloat,
      vString,
      vBool,
      vFile,
      vSeq
  
5e811526   Göran Krampe   Added updated lap...
100
101
102
103
104
105
106
    PValue* = ref TValue
    TValue* = object
      case kind*: TValueKind
        of vInt: asInt*: int
        of vFloat: asFloat*: float
        of vString: asString*: string
        of vBool: asBool*: bool
85eedc50   Göran Krampe   Added lapp.nim to...
107
        of vFile:
5e811526   Göran Krampe   Added updated lap...
108
109
110
          asFile*: File
          fileName*: string
        of vSeq: asSeq*: seq[PValue]
85eedc50   Göran Krampe   Added lapp.nim to...
111
112
  
  proc boolValue(c: bool): PValue =  PValue(kind: vBool, asBool: c)
33f6041b   Andreas Rumpf   make blimp compil...
113
  
85eedc50   Göran Krampe   Added lapp.nim to...
114
  proc fileValue(f: File, name: string): PValue =  PValue(kind: vFile, asFile: f, fileName: name)
33f6041b   Andreas Rumpf   make blimp compil...
115
116
117
  
  proc strValue(s: string): PValue =  PValue(kind: vString, asString: s)
  
85eedc50   Göran Krampe   Added lapp.nim to...
118
  proc intValue(v: int): PValue =   PValue(kind: vInt, asInt: v)
33f6041b   Andreas Rumpf   make blimp compil...
119
  
85eedc50   Göran Krampe   Added lapp.nim to...
120
  proc floatValue(v: float): PValue = PValue(kind: vFloat, asFloat: v)
33f6041b   Andreas Rumpf   make blimp compil...
121
  
85eedc50   Göran Krampe   Added lapp.nim to...
122
  proc seqValue(v: seq[PValue]): PValue = PValue(kind: vSeq, asSeq: v)
33f6041b   Andreas Rumpf   make blimp compil...
123
  
85eedc50   Göran Krampe   Added lapp.nim to...
124
125
126
127
128
  type
    PSpec = ref TSpec
    TSpec = object
      defVal: string
      ptype: string
386557e6   Göran Krampe   Added support for...
129
      group: int
85eedc50   Göran Krampe   Added lapp.nim to...
130
131
132
133
134
      needsValue, multiple, used: bool
  var
    progname, usage: string
    aliases: array[char,string]
    parm_spec =  initTable[string,PSpec]()
5e811526   Göran Krampe   Added updated lap...
135
  
85eedc50   Göran Krampe   Added lapp.nim to...
136
  proc fail(msg: string)  =
49df26ea   Göran Krampe   Updated for new Nim
137
    stderr.writeLine(progname & ": " & msg)
85eedc50   Göran Krampe   Added lapp.nim to...
138
139
    quit(usage)
  
33f6041b   Andreas Rumpf   make blimp compil...
140
  proc parseSpec(u: string) =
85eedc50   Göran Krampe   Added lapp.nim to...
141
142
143
    var
      L: PLexer
      tok: string
386557e6   Göran Krampe   Added support for...
144
      groupCounter: int
85eedc50   Göran Krampe   Added lapp.nim to...
145
      k = 1
33f6041b   Andreas Rumpf   make blimp compil...
146
  
85eedc50   Göran Krampe   Added lapp.nim to...
147
148
149
150
    let lines = u.splitLines
    L = newLexer(lines[0])
    progname = L.get
    usage = u
33f6041b   Andreas Rumpf   make blimp compil...
151
    for line in lines[1 .. ^1]:
85eedc50   Göran Krampe   Added lapp.nim to...
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
      var
        isarg = false
        multiple = false
        getnext = true
        name: string
        alias: char
      L.reset(line)
      tok = L.get
      if tok == "-" or tok == "--":  # flag
        if tok == "-": #short flag
          let flag = L.get
          if len(flag) != 1: fail("short option has one character!")
          tok = L.get
          if tok == ",": # which is alias for long flag
            tok = L.get
            if tok != "--": fail("expecting long --flag")
            name = L.get
            alias = flag[0]
          else: # only short flag
            name = flag
            alias = flag[0]
            getnext = false
        else: # only long flag
          name = L.get
          alias = '\0'
      elif tok == "<":  # argument
        isarg = true
        name = L.get
        alias = chr(k)
        k += 1
        tok = L.get
        if tok != ">": fail("argument must be enclosed in <...>")
386557e6   Göran Krampe   Added support for...
184
185
      elif tok == "---": # divider
        inc(groupCounter)
85eedc50   Göran Krampe   Added lapp.nim to...
186
187
188
189
190
      if getnext:  tok = L.get
      if tok == ":": # allowed to have colon after flags
        tok = L.get
      if tok == nil: continue
      # default types for flags and arguments
33f6041b   Andreas Rumpf   make blimp compil...
191
      var
85eedc50   Göran Krampe   Added lapp.nim to...
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
        ftype = if isarg: "string" else: "bool"
        defValue = ""
      if tok == "(": # typed flag/argument
        var t = tchar
        tok = L.get(t)
        if tok == "default":  # type from default value
          defValue = L.get(t)
          if t == tint: ftype = "int"
          elif t == tfloat: ftype = "float"
          elif t == tword:
            if defValue == "stdin": ftype = "infile"
            elif defValue == "stdout": ftype = "outfile"
            else: ftype = "string"
          else: fail("unknown default value " & tok)
        else: # explicit type
          if t == tword:
            ftype = tok
            if tok == "bool": defValue = "false"
          else: fail("unknown type " & tok)
        discard L.get(t)
        multiple = t == telipsis
      elif ftype == "bool": # no type or default
        defValue = "false"
33f6041b   Andreas Rumpf   make blimp compil...
215
  
85eedc50   Göran Krampe   Added lapp.nim to...
216
      if name != nil:
386557e6   Göran Krampe   Added support for...
217
218
        #echo("Param: " & name & " type: " & $ftype & " group: " & $groupCounter & " needsvalue: " & $(ftype != "bool") & " default: " & $defValue & " multiple: " & $multiple)
        let spec = PSpec(defVal:defValue, ptype: ftype, group: groupCounter, needsValue: ftype != "bool",multiple:multiple)
33f6041b   Andreas Rumpf   make blimp compil...
219
        aliases[alias] = name
85eedc50   Göran Krampe   Added lapp.nim to...
220
221
        parm_spec[name] = spec
  
33f6041b   Andreas Rumpf   make blimp compil...
222
  proc tail(s: string): string = s[1..^1]
85eedc50   Göran Krampe   Added lapp.nim to...
223
  
33f6041b   Andreas Rumpf   make blimp compil...
224
  var
5e811526   Göran Krampe   Added updated lap...
225
    files = newSeq[File]()
85eedc50   Göran Krampe   Added lapp.nim to...
226
227
  
  proc closeFiles() {.noconv.} =
5e811526   Göran Krampe   Added updated lap...
228
229
    for f in files:
      f.close()
85eedc50   Göran Krampe   Added lapp.nim to...
230
  
5e811526   Göran Krampe   Added updated lap...
231
  proc parseArguments*(usage: string, args: seq[string]): Table[string,PValue] =
85eedc50   Göran Krampe   Added lapp.nim to...
232
233
234
235
236
    var
      vars = initTable[string,PValue]()
      n = len(args) - 1
      i = 1
      k = 1
33f6041b   Andreas Rumpf   make blimp compil...
237
      flag,value, arg: string
85eedc50   Göran Krampe   Added lapp.nim to...
238
239
240
      info: PSpec
      short: bool
      flagvalues: seq[seq[string]]
33f6041b   Andreas Rumpf   make blimp compil...
241
  
85eedc50   Göran Krampe   Added lapp.nim to...
242
243
244
245
    proc next(): string =
      if i > n: fail("an option required a value!")
      result = args[i]
      i += 1
33f6041b   Andreas Rumpf   make blimp compil...
246
  
85eedc50   Göran Krampe   Added lapp.nim to...
247
248
249
250
251
252
253
254
    proc get_alias(c: char): string =
      result = aliases[c]
      if result == nil:
        n = ord(c)
        if n < 20:
          fail("no such argument: " & $n)
        else:
          fail("no such option: " & c)
33f6041b   Andreas Rumpf   make blimp compil...
255
  
85eedc50   Göran Krampe   Added lapp.nim to...
256
    proc get_spec(name: string): PSpec =
49df26ea   Göran Krampe   Updated for new Nim
257
      result = parm_spec.getOrDefault(name)
85eedc50   Göran Krampe   Added lapp.nim to...
258
259
260
261
262
263
264
      if result == nil:
        fail("no such option: " & name)
  
    newSeq(flagvalues, 0)
    parseSpec(usage)
    addQuitProc(closeFiles)
  
5e811526   Göran Krampe   Added updated lap...
265
266
    # Collect failures
    var failures = newSeq[string]()
33f6041b   Andreas Rumpf   make blimp compil...
267
  
85eedc50   Göran Krampe   Added lapp.nim to...
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
    # parse the flags and arguments
    while i <= n:
      arg = next()
      if arg[0] == '-':  #flag
        short = arg[1] != '-'
        arg = arg.tail
        if short: # all short args are aliases, even if only to themselves
          flag = get_alias(arg[0])
        else:
          flag = arg[1..high(arg)]
        info = get_spec(flag)
        if info.needsValue:
          if short and len(arg) > 1: # value can follow short flag
            value = arg.tail
          else:  # grab next argument
            value = next()
        else:
          value = "true"
          if short and len(arg) > 0: # short flags can be combined
            for c in arg.tail:
              let f = get_alias(c)
              let i = get_spec(f)
5e811526   Göran Krampe   Added updated lap...
290
291
              if i.needsValue:
                failures.add("option " & f & " needs a value")
85eedc50   Göran Krampe   Added lapp.nim to...
292
293
294
295
296
297
298
299
300
301
              flagvalues.add(@[f,"true"])
              i.used = true
      else: # argument (stored as \001, \002, etc
        flag = get_alias(chr(k))
        value = arg
        info = get_spec(flag)
        # don't move on if this is a varags last param
        if not info.multiple:  k += 1
      flagvalues.add(@[flag,value])
      info.used = true
33f6041b   Andreas Rumpf   make blimp compil...
302
  
5e811526   Göran Krampe   Added updated lap...
303
304
305
306
307
308
    # Some options disables checking
    var enableChecks = true
    for flag,info in parm_spec:
      if info.used:
        if flag == "help" or flag == "version":
          enableChecks = false
33f6041b   Andreas Rumpf   make blimp compil...
309
  
386557e6   Göran Krampe   Added support for...
310
311
312
313
314
315
    # Check maximum group used
    var maxGroup = 0
    for item in flagvalues:
      info = get_spec(item[0])
      if maxGroup < info.group:
        maxGroup = info.group
33f6041b   Andreas Rumpf   make blimp compil...
316
  
85eedc50   Göran Krampe   Added lapp.nim to...
317
318
319
    # any flags not mentioned?
    for flag,info in parm_spec:
      if not info.used:
386557e6   Göran Krampe   Added support for...
320
        # Is there no default and we have used options in this group?
33f6041b   Andreas Rumpf   make blimp compil...
321
        if info.defVal == "" and info.group <= maxGroup:
5e811526   Göran Krampe   Added updated lap...
322
323
324
325
326
327
328
329
330
          failures.add("required option or argument missing: " & flag)
        else:
          flagvalues.add(@[flag,info.defVal])
  
    if enableChecks:
      # any failures up until now - then we fail
      if failures.len > 0:
        fail(failures.join("\n") & "\n")
  
85eedc50   Göran Krampe   Added lapp.nim to...
331
332
333
334
335
336
337
338
339
340
341
342
343
    # cool, we have the info, can convert known flags
    for item in flagvalues:
      var pval: PValue;
      let
        flag = item[0]
        value = item[1]
        info = get_spec(flag)
      case info.ptype
      of "int":
        var v: int
        try:
          v = value.parseInt
        except:
5e811526   Göran Krampe   Added updated lap...
344
          fail("bad integer for " & flag)
85eedc50   Göran Krampe   Added lapp.nim to...
345
346
347
348
349
350
        pval = intValue(v)
      of "float":
        var v: float
        try:
          v = value.parseFloat
        except:
5e811526   Göran Krampe   Added updated lap...
351
          fail("bad float for " & flag)
85eedc50   Göran Krampe   Added lapp.nim to...
352
353
354
355
356
357
358
359
360
        pval = floatValue(v)
      of "bool":
        pval = boolValue(value.parseBool)
      of "string":
        pval = strValue(value)
      of "infile","outfile": # we open files for the app...
        var f: File
        try:
          if info.ptype == "infile":
5e811526   Göran Krampe   Added updated lap...
361
362
363
364
            if value == "stdin":
              f = stdin
            else:
              f = open(value, fmRead)
85eedc50   Göran Krampe   Added lapp.nim to...
365
          else:
5e811526   Göran Krampe   Added updated lap...
366
367
368
369
            if value == "stdout":
              f = stdout
            else:
              f = open(value, fmWrite)
85eedc50   Göran Krampe   Added lapp.nim to...
370
          # they will be closed automatically on program exit
5e811526   Göran Krampe   Added updated lap...
371
          files.add(f)
85eedc50   Göran Krampe   Added lapp.nim to...
372
373
374
375
        except:
          fail("cannot open " & value)
        pval = fileValue(f,value)
      else: discard
33f6041b   Andreas Rumpf   make blimp compil...
376
  
49df26ea   Göran Krampe   Updated for new Nim
377
      var oval = vars.getOrDefault(flag)
85eedc50   Göran Krampe   Added lapp.nim to...
378
379
380
381
382
383
384
385
386
387
388
389
390
      if info.multiple: # multiple flags are sequence values
        if oval == nil: # first value!
          pval = seqValue(@[pval])
        else: # just add to existing sequence
          oval.asSeq.add(pval)
          pval = oval
      elif oval != nil: # cannot repeat a single flag!
        fail("cannot use '" & flag & "' more than once")
      vars[flag] = pval
  
    return vars
  
  proc parse*(usage: string): Table[string,PValue] =
33f6041b   Andreas Rumpf   make blimp compil...
391
    var
85eedc50   Göran Krampe   Added lapp.nim to...
392
393
394
395
396
      args: seq[string]
      n = paramCount()
    newSeq(args,n+1)
    for i in 0..n:
      args[i] = paramStr(i)
33f6041b   Andreas Rumpf   make blimp compil...
397
    return parseArguments(usage,args)
85eedc50   Göran Krampe   Added lapp.nim to...
398
  
5e811526   Göran Krampe   Added updated lap...
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
  # Helper proc for verbosity level.
  proc verbosityLevel*(args: Table[string,PValue]): int =
    if args.hasKey("verbose"):
      let verbosity = args["verbose"].asSeq
      result = verbosity.len
      if not verbosity[0].asBool:
        result = 0
    else:
      result = 0
  
  # Helper to check if we should show version
  proc showVersion*(args: Table[string,PValue]): bool =
    args["version"].asBool
  
  # Helper to check if we should show help
  proc showHelp*(args: Table[string,PValue]): bool =
    args["help"].asBool
  
  
  # Typical usage
85eedc50   Göran Krampe   Added lapp.nim to...
419
  when isMainModule:
5e811526   Göran Krampe   Added updated lap...
420
421
422
423
424
425
426
427
    let help = """
    head [flags] files... [out]
      -h,--help                     Show this help
      --version                     Show version
      -n: (default 10)              Number of lines to show
      -v,--verbose: (bool...)       Verbosity level, ignored
      -o,--out: (default stdout)    Optional outfile, defaults to stdout
      <files>: (default stdin...)   Files to take head of
85eedc50   Göran Krampe   Added lapp.nim to...
428
    """
5e811526   Göran Krampe   Added updated lap...
429
430
    # On parsing failure this will show usage automatically
    var args = parse(help)
85eedc50   Göran Krampe   Added lapp.nim to...
431
  
5e811526   Göran Krampe   Added updated lap...
432
433
434
    # These two are special, they short out
    if args.showHelp: quit(help)
    if args.showVersion: quit("Version: 1.99")
33f6041b   Andreas Rumpf   make blimp compil...
435
  
5e811526   Göran Krampe   Added updated lap...
436
437
    # Ok, so what did we get...
    let n = args["n"].asInt
33f6041b   Andreas Rumpf   make blimp compil...
438
  
5e811526   Göran Krampe   Added updated lap...
439
440
    # This one is a helper
    let v = verbosityLevel(args)
33f6041b   Andreas Rumpf   make blimp compil...
441
  
5e811526   Göran Krampe   Added updated lap...
442
    echo "Lines to show: " & $n
49df26ea   Göran Krampe   Updated for new Nim
443
    echo "Verbosity level: " & $v
33f6041b   Andreas Rumpf   make blimp compil...
444
  
85eedc50   Göran Krampe   Added lapp.nim to...
445
    let myfiles = args["files"].asSeq
5e811526   Göran Krampe   Added updated lap...
446
    var outFile = args["out"].asFile
33f6041b   Andreas Rumpf   make blimp compil...
447
  
85eedc50   Göran Krampe   Added lapp.nim to...
448
    for f in myfiles:
5e811526   Göran Krampe   Added updated lap...
449
      for i in 1..n:
49df26ea   Göran Krampe   Updated for new Nim
450
        writeLine(outFile, string(f.asFile.readLine()))