Skip to content
Oliver Delancey edited this page Dec 10, 2021 · 5 revisions

Welcome to the clapfn wiki! Here be documentation. 🏴‍☠️

ArgumentParser

Definition

type
  ArgumentParser* = ref object of RootObj
    programName*: string
    fullName*: string
    author*: string
    description*: string
    version*: string
    requiredArgs: seq[RequiredArgument]
    storeArgs: Table[string, StoreArgument]
    switchArgs: Table[string, SwitchArgument]

Initialize an argument parser with this command.

var parser = ArgumentParser(programName: "mcp", fullName: "My Cool Program",
                            description: "A test program.", version: "0.0.0",
                            author: "An Author <author@domain.com>")

addRequiredArgument

Definition:

proc addRequiredArgument*(argparser: ArgumentParser, name: string,
    help: string) =
  let cla = RequiredArgument(name: name, help: help)
  argparser.requiredArgs.add(cla)

Add a required argument to ArgumentParser's requiredArgs sequence.

parser.addRequiredArgument("in_file", "Input file.")

addStoreArgument

Definition:

proc addStoreArgument*(argparser: ArgumentParser, shortName: string,
    longName: string, usageInput: string, default: string, help: string) =
  let cla = StoreArgument(shortName: shortName, longName: longName,
      usageInput: usageInput, value: default, help: help)
  argparser.storeArgs[removeDashes(shortName)] = cla
  argparser.storeArgs[removeDashes(longName)] = cla

Add an optional "storage" argument to ArgumentParser's storeArgs table.

parser.addStoreArgument("-o", "--out", "output", "out.file",
                        "Specify the output file.")

addSwitchArgument

Definition:

proc addSwitchArgument*(argparser: ArgumentParser, shortName: string,
    longName: string, default: bool, help: string) =
  let cla = SwitchArgument(shortName: shortName, longName: longName,
      value: default, help: help)
  argparser.switchArgs[removeDashes(shortName)] = cla
  argparser.switchArgs[removeDashes(longName)] = cla

Add an optional "switch" argument to ArgumentParser's switchArgs table.

parser.addSwitchArgument("-d", "--debug", false, "Enable debug printing.")

parse

Definition:

proc parse*(argparser: ArgumentParser): Table[string, string] =

Parse the arguments and return a Table[string, string] containing all the arguments and flags.

let args = parser.parse()

echo args["out"]
echo args["debug"]

parse() returns string values for every parameter, so you will have to manually convert values to ints and bools as needed.

import strutils  # for parseBool()

let isDebug = parseBool(args["debug"])
Clone this wiki locally