cmdline(3tcl)

πŸ“¦
version 2.0 Β· 3 versions
, in debian trixie, ubuntu questing, ubuntu resolute, ubuntu stonking

πŸ’– cmdline β€” bestie's guide to command line & option processing πŸ’–

okay so cmdline is a Tcl package that gives you procedures to process command lines and options. that's the whole vibe. you pass it your args, it does the parsing, you get your values. no cap. ✨


✨ SYNOPSIS ✨

package require Tcl 8.5 9

package require cmdline ?1.5.3?

::cmdline::getopt argvVar optstring optVar valVar

::cmdline::getKnownOpt argvVar optstring optVar valVar

::cmdline::getoptions argvVar optlist ?usage?

::cmdline::getKnownOptions argvVar optlist ?usage?

::cmdline::usage optlist ?usage?

::cmdline::getfiles patterns quiet

::cmdline::getArgv0

🌸 DESCRIPTION 🌸

literally what it says on the tin, bestie: this package provides commands to parse command lines and options. that's it. that's the job. πŸ’…


πŸ¦‹ ::ARGV HANDLING πŸ¦‹

the most common variable you'll be doing all this with is ::argv, which holds the command line of the current application. iconic behavior. and it has a companion, ::argc, which gets initialized to the number of elements in ::argv at the beginning of the application. they're a package deal 🫢

⚠️ important!! the commands in this package will not modify the ::argc companion when called with ::argv. if you want them to stay consistent, that's on you, bestie β€” it's the responsibility of the caller. periodt.

πŸ‘‘ API πŸ‘‘

πŸ’– ::cmdline::getopt argvVar optstring optVar valVar

this one works kinda like the standard C-based getopt function. you give it an option string and a pointer to an array of args, and it processes the first argument and tells you how to proceed. it returns:

  • 1 β€” an option was found ✨
  • 0 β€” no more options were found πŸ˜”
  • -1 β€” an error happened πŸ’€

argvVar contains the name of the list of arguments to process. if options are found, the list gets modified and the processed arguments are removed from the start of the list.

optstring contains a list of command options that the application will accept. if the option ends in .arg, the command will use the next argument as an argument to the option β€” or extract it from the current argument if it's of the form option=value. otherwise the option is a boolean that gets set to 1 if it's present.

optVar refers to the variable the command will store the found option into (without the leading - and without the .arg extension).

valVar refers to the variable that stores either the value for the specified option upon success, or an error message in the case of failure. the stored value comes from the command line for .arg options; otherwise the value is 1.

πŸ’– ::cmdline::getKnownOpt argvVar optstring optVar valVar

like ::cmdline::getopt, except it ignores any unknown options in the input. chill of it honestly.

πŸ’– ::cmdline::getoptions argvVar optlist ?usage?

processes the entire set of command line options found in the list variable named by argvVar, and fills in defaults for the ones you didn't specify. it also generates an error message that lists the allowed flags if an incorrect flag shows up. the optional usage argument contains a string to include in front of the generated message. if it's not present, it defaults to "options:".

argvVar contains the name of the list of arguments to process. if options are found, the list is modified and the processed arguments are removed from the start of the list.

optlist contains a list of lists, where each element specifies an option in the form: flag default comment.

  • if flag ends in .arg then the value is taken from the command line.
  • otherwise it's a boolean and appears in the result if it's present on the command line.
  • if flag ends in .secret, it will not be displayed in the usage. 🀫

the options -?, -help, and -- are implicitly understood. the first two abort option processing by throwing an error and force the generation of the usage message, whereas the last one aborts option processing without an error, leaving all arguments coming after it for regular processing β€” even if they start with a dash. slay.

the result of the command is a dictionary mapping all options to their values, whether those be user-specified or defaults. πŸ’…

πŸ’– ::cmdline::getKnownOptions argvVar optlist ?usage?

like ::cmdline::getoptions, but ignores any unknown options in the input. same energy, less drama.

πŸ’– ::cmdline::usage optlist ?usage?

generates and returns an error message that lists the allowed flags. optlist is defined exactly as for ::cmdline::getoptions. the optional usage argument contains a string to include in front of the generated message. if it's not present it defaults to "options:".

πŸ’– ::cmdline::getfiles patterns quiet

given a list of file patterns, this command computes the set of valid files. on Windows, file globbing is performed on each argument. on Unix</>, only file existence is tested. if a file argument produces no valid files, a warning is optionally generated (set quiet to true).

this code also uses the full path for each file. if it's not given, it prepends the current working directory to the filename. this ensures that these files will never conflict with files in a wrapped zip file. (the last sentence refers to the pro-tools.)

πŸ’– ::cmdline::getArgv0

returns the "sanitized" version of argv0. it strips off the leading path and removes the extension .bin. the latter is used by the TclPro applications because they must be wrapped by a shell script. iykyk 🧚


πŸ’€ ERROR CODES πŸ’€

starting with version 1.5, all errors thrown by the package have a proper ::errorCode for use with Tcl's try command. this code always has the word CMDLINE as its first element. that's your little signal, bestie β€” you can trap on it. πŸ”₯


🌈 EXAMPLES 🌈

πŸŽ€ CMDLINE::GETOPTIONS πŸŽ€

this example is taken from the package fileutil and slightly modified, and it demonstrates how to use cmdline::getoptions. first, a list of options is created, then the args list is passed to cmdline for processing. subsequently, different options are checked to see if they've been passed to the script, and what their value is. let's gooo:

package require Tcl 8.5
package require try         ;# Tcllib.
package require cmdline 1.5 ;# First version with proper error-codes.

# Notes:
# - Tcl 8.6+ has 'try' as a builtin command and therefore does not
#   need the 'try' package.
# - Before Tcl 8.5 we cannot support 'try' and have to use 'catch'.
#   This then requires a dedicated test (if) on the contents of
#   ::errorCode to separate the CMDLINE USAGE signal from actual errors.

set options {
    {a          "set the atime only"}
    {m          "set the mtime only"}
    {c          "do not create non-existent files"}
    {r.arg  ""  "use time from ref_file"}
    {t.arg  -1  "use specified time"}
}
set usage ": MyCommandName \[options] filename ...\noptions:"

try {
    array set params [::cmdline::getoptions argv $options $usage]

# Note: argv is modified now. The recognized options are
# removed from it, leaving the non-option arguments behind.
} trap {CMDLINE USAGE} {msg o} {
    # Trap the usage signal, print the message, and exit the application.
    # Note: Other errors are not caught and passed through to higher levels!
    puts $msg
    exit 1
}

if {  $params(a) } { set set_atime "true" }
set has_t [expr {$params(t) != -1}]
set has_r [expr {[string length $params(r)] > 0}]
if {$has_t && $has_r} {
    return -code error "Cannot specify both -r and -t"
} elseif {$has_t} {
    ...
}

πŸŽ€ CMDLINE::GETOPT πŸŽ€

this example shows the core loop of cmdline::getoptions from the previous example. it demonstrates how it uses cmdline::get to process the options one at a time. baby steps, but make it iconic:

while {[set err [getopt argv $opts opt arg]]} {
    if {$err < 0} {
        set result(?) ""
        break
    }
    set result($opt) $arg
}

😭 BUGS, IDEAS, FEEDBACK 😭

this document, and the package it describes, will undoubtedly contain bugs and other problems. not me being humble, it's just facts fr fr. please report such in the category cmdline of the Tcllib Trackers at [http://core.tcl.tk/tcllib/reportlist]. please also report any ideas for enhancements you may have for either the package and/or the documentation. we love feedback 🫢

when proposing code changes, please provide unified diffs, i.e the output of diff -u.

note further that attachments are strongly preferred over inlined patches. attachments can be made by going to the Edit form of the ticket immediately after its creation, and then using the left-most button in the secondary navigation bar. you got this πŸ’…


⭐ KEYWORDS ⭐

argument processing, argv, argv0, cmdline processing, command line processing


🌸 CATEGORY 🌸

Programming tools


πŸ’– and that's the whole page, bestie!! this doc is from tcllib, version 1.5.3, and it's the cmdline(3tcl) manual page. go forth and parse those options. you're the main character of your own CLI. periodt. βœ¨πŸŽ€πŸ¦‹πŸ‘‘
πŸ“¦ where this page comes from