Programming Search⌘K

Taskcore

Parse command-line arguments

Also called read command-line options, parse argv, read program arguments, getopt.

Turn the argument list of a program into options and file operands, with short and long options, a default value, the -- terminator and a usage error for bad input.

Task

Parse the arguments of a small tool with this syntax:

count [-v | --verbose] [-n N | --limit N | --limit=N] [--] [FILE...]

The function gets the arguments without the program name. It returns three values: verbose, limit and the list of files. verbose is true if -v or --verbose occurs. limit is 10 if no -n or --limit occurs. If the option occurs more than once, the last value applies. N is a decimal number of digits only. The files keep their order.

The first -- ends the options, and it is not a file. Each argument after it is a file, also an argument that starts with - or a second --. POSIX Guideline 10 gives this rule. A lone - is a file. POSIX Guideline 13 gives it the meaning of standard input. An empty list of files is valid.

The function reports a usage error for an unknown option, for an option with no value, for a value that is not a decimal number, and for a value after --verbose. It returns the error as a value or an exception. It must not exit the process, so that a test can check the error. The main of a real tool prints the message on standard error and exits with status 2, as argparse and Go flag do.

Parsers do not agree on some input. So the contract has four preconditions. No option follows a file. Short options are not grouped, as in -vn3, and the value of -n is a separate argument. A long option is not abbreviated. N has no sign and no leading zero.

Solutions

Each solution uses the parser of the standard library where one exists. The other solutions loop over the arguments and stop at the first file, as POSIX Guideline 9 expects.

  • Python. argparse.ArgumentParser with nargs="*" for the files and a type function for N. On an error, ArgumentParser.error ends the program with status 2. The argparse documentation shows an override of exit that raises an exception for a nonzero status, and the solution uses one. allow_abbrev=False turns off abbreviations. sys.argv[0] is the script name, so the arguments are sys.argv[1:].
  • JavaScript and TypeScript (Node.js). util.parseArgs with strict: true and allowPositionals: true. It throws for an unknown option and for a value of the wrong type. An option has the type boolean or string, so the code converts N. process.argv[0] is the path of node and process.argv[1] is the script. The TypeScript file adds types only.
  • Java. main gets a String[] without the class name (JLS 12.1). A switch over the strings handles each option. Integer.parseInt also accepts a sign and the digits of other scripts, so a check for ASCII digits comes first.
  • C#. Main gets a string[] without the program name. Environment.GetCommandLineArgs returns the executable file name first. A loop handles each option, and int.TryParse with NumberStyles.None accepts digits only. The C# guide suggests the System.CommandLine library for complex parsing.
  • Go. flag.NewFlagSet with flag.ContinueOnError returns an error and does not exit. SetOutput(io.Discard) stops the messages. The short and the long name point to one variable. os.Args starts with the program name, so the tool passes os.Args[1:].
  • Rust. A loop over std::env::args().skip(1). The first item is the path of the executable by tradition, but it can be any text.
  • C. getopt_long with the option string ":vn:". The leading : makes a missing value return ':'. argv[0] is the program name, and getopt_long starts at argv[1]. The solution sets opterr = 0 and returns an error code, and the caller prints the message.
  • C++. The caller copies argv + 1 to argv + argc into a vector of std::string_view, and parse_args loops over it as a std::span. getopt is a POSIX function and not part of C++. The loop keeps no global state. std::from_chars converts N, and parse_args returns std::expected (C++23).
  • Bash. getopts knows only one-letter options. A first case loop changes --verbose and --limit to -v and -n, then getopts ":vn:" reads them. The function declares local OPTIND=1, because the shell does not reset OPTIND between calls. "$@" gives each argument as one word.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl. The cases that must give a usage error are in cases/errors.jsonl.

  • no-args: no arguments at all. The result is the defaults and no files.
  • long-equals: --limit=7 holds the value in the same argument.
  • repeated: -n 3 --limit 5 gives 5, because the last value applies.
  • zero: -n 0 is valid. A check such as if (!limit) treats it as a missing value.
  • end-of-options: after --, the strings -n and --limit=4 are files. second-terminator: in -- --, the second -- is a file.
  • dash: a lone - is a file and not an option.
  • empty-arg, space and non-ascii: an empty argument, a name with a space and names with non-ASCII letters are files. Each one is a single argument.
  • Errors: -x, --color, -n or --limit at the end, -n ten, --limit=ten, --limit= and --verbose=yes.

Pitfalls

  • The first element of the raw list. In C, Python, Go and Rust, element 0 is the program or the script. In Node.js, the arguments start at index 2. Java and C# do not give the program name to main. These programs get the arguments -v --limit 3 a.txt:
import os
import sys

print(len(sys.argv), os.path.basename(sys.argv[0]))
print(sys.argv[1:])
Output
5 main.py
['-v', '--limit', '3', 'a.txt']
console.log(process.argv.length);
console.log(process.argv.slice(2));
Output
6
[ '-v', '--limit', '3', 'a.txt' ]
public class Main {
    public static void main(String[] args) {
        System.out.println(args.length);
        System.out.println(String.join(" ", args));
    }
}
Output
4
-v --limit 3 a.txt
#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
    const char *slash = strrchr(argv[0], '/');
    printf("%d %s\n", argc, slash != NULL ? slash + 1 : argv[0]);
    for (int i = 1; i < argc; i++) {
        printf("argv[%d] = %s\n", i, argv[i]);
    }
    return 0;
}
Output
5 main
argv[1] = -v
argv[2] = --limit
argv[3] = 3
argv[4] = a.txt
  • $* in Bash. "$@" gives each argument as a separate word. "$*" joins all the arguments into one word with the first character of IFS between them:
echo "$# $(basename "$0")"
printf '<%s> ' "$@"
echo
IFS=,
printf '<%s> ' "$*"
echo
Output
4 main.sh
<-v> <--limit> <3> <a.txt>
<-v,--limit,3,a.txt>
  • Options after a file. POSIX getopt and Go flag stop at the first operand. So Go reads a.txt -v as two files:
package main

import (
	"flag"
	"fmt"
)

func main() {
	verbose := flag.Bool("v", false, "print more")
	flag.Parse()
	fmt.Println("verbose:", *verbose)
	fmt.Println("files:", flag.Args())
}
Output
verbose: false
files: [a.txt -v]

argparse finds the option after the file:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-v", action="store_true")
parser.add_argument("files", nargs="*")
args = parser.parse_args()
print("verbose:", args.v)
print("files:", args.files)
Output
verbose: True
files: ['a.txt']

GNU getopt permutes argv by default, so the files move to the end and the options apply. POSIXLY_CORRECT or a leading + in the option string turns this off. On FreeBSD, getopt stops at the first operand, but getopt_long permutes. So the same C program can give a different result on two systems.

  • A value in the same argument. Go reads -n=3 as the value 3. POSIX getopt takes the rest of the argument after the option letter, so the value is =3. util.parseArgs does the same:
import { parseArgs } from "node:util";

const { values } = parseArgs({
  options: { limit: { type: "string", short: "n" } },
  allowPositionals: true,
});
console.log(values.limit);
Output
=3
  • Abbreviated long options. argparse accepts a prefix of a long option if the prefix is unique. GNU getopt_long does the same. So --lim 3 sets the limit:
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--limit", type=int, default=10)
print(parser.parse_args().limit)
Output
3
  • Number parsers accept more than digits. Go flag integer flags accept 0664, 0x1234 and negative values. Integer.parseInt in Java accepts a + or a - sign. std::from_chars accepts a - for a signed type. Each solution checks for ASCII digits first:
package main

import (
	"flag"
	"fmt"
)

func main() {
	n := flag.Int("n", 10, "the limit")
	flag.Parse()
	fmt.Println(*n)
}
Output
16
  • A parser that exits. By default argparse prints the usage and exits with status 2 on an error. The flag set of Go flag.Parse uses ExitOnError, which also exits with status 2. A test cannot check an error after an exit, so the solutions use ContinueOnError in Go and override exit in Python:

This code fails on purpose. The output below is the error.

import argparse

parser = argparse.ArgumentParser(prog="count")
parser.add_argument("-n", type=int, default=10)
parser.parse_args()
print("not reached")
Error output
usage: count [-h] [-n N]
count: error: argument -n: invalid int value: 'ten'
  • The global state of getopt. getopt keeps its position in the global optind. A second parse needs a reset, and the reset is not portable. POSIX leaves optind = 0 unspecified. glibc restarts with optind = 1, but it needs optind = 0 to read POSIXLY_CORRECT and the + or - prefix again. FreeBSD getopt needs optreset = 1 and a reset of optind. FreeBSD getopt_long resets when optind is 0. The C solution uses getopt_long and sets optind = 0. In Bash, OPTIND has the same problem, so the function declares it local.
  • Arguments that are not Unicode. On Unix the system passes each argument as bytes. Python decodes them with the surrogateescape handler. Rust std::env::args panics on an argument that is not valid Unicode. Use std::env::args_os to read such an argument.

Code

The build runs the native tests of each language in a pinned toolchain.

parse_args.pyI0tests passRawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/parse-command-line-arguments/.

import argparse
import sys
from typing import NamedTuple


class Args(NamedTuple):
    verbose: bool
    limit: int
    files: list[str]


class UsageError(Exception):
    """A usage error of the command line."""


class _Parser(argparse.ArgumentParser):
    def exit(self, status: int = 0, message: str | None = None) -> None:
        # argparse calls exit after it prints help (status 0) or an error
        # (status 2). An error becomes an exception, so the caller decides.
        if status:
            raise UsageError(message or "usage error")
        super().exit(status, message)

    def print_usage(self, file=None) -> None:
        # error() prints the usage before it calls exit. The caller prints
        # the message of UsageError instead.
        pass


def _parser() -> _Parser:
    p = _Parser(prog="count", allow_abbrev=False)
    p.add_argument("-v", "--verbose", action="store_true")
    p.add_argument("-n", "--limit", type=_count, default=10, metavar="N")
    p.add_argument("files", nargs="*", metavar="FILE")
    return p


def _count(text: str) -> int:
    # int() also accepts "+3", " 3" and "1_000"; the tool takes digits only.
    if not (text.isascii() and text.isdecimal()):
        raise ValueError(text)
    return int(text)


def parse_args(args: list[str]) -> Args:
    ns = _parser().parse_args(args)
    return Args(ns.verbose, ns.limit, ns.files)


if __name__ == "__main__":
    try:
        print(parse_args(sys.argv[1:]))
    except UsageError as e:
        print(e, file=sys.stderr, end="")
        sys.exit(2)
test_parse_args.py 52 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/parse-command-line-arguments/.

import pytest

from parse_args import Args, UsageError, parse_args

CASES = {
    "files-only": (["a.txt", "b.txt"], (False, 10, ["a.txt", "b.txt"])),
    "short-options": (["-v", "-n", "3", "a.txt"], (True, 3, ["a.txt"])),
    "long-options": (["--verbose", "--limit", "5", "a.txt", "b.txt"], (True, 5, ["a.txt", "b.txt"])),
    "no-args": ([], (False, 10, [])),
    "long-equals": (["--limit=7", "notes.md"], (False, 7, ["notes.md"])),
    "repeated": (["-n", "3", "--limit", "5", "a.txt"], (False, 5, ["a.txt"])),
    "zero": (["-n", "0", "a.txt"], (False, 0, ["a.txt"])),
    "end-of-options": (["-v", "--", "-n", "--limit=4"], (True, 10, ["-n", "--limit=4"])),
    "only-terminator": (["--"], (False, 10, [])),
    "second-terminator": (["--", "--"], (False, 10, ["--"])),
    "dash": (["-"], (False, 10, ["-"])),
    "dash-after-option": (["-n", "2", "-", "b.txt"], (False, 2, ["-", "b.txt"])),
    "empty-arg": ([""], (False, 10, [""])),
    "space": (["-v", "my file.txt"], (True, 10, ["my file.txt"])),
    "non-ascii": (["--limit=4", "日本語.txt", "café.md"], (False, 4, ["日本語.txt", "café.md"])),
}

ERRORS = {
    "unknown-short": ["-x", "a.txt"],
    "unknown-long": ["--color", "a.txt"],
    "missing-value": ["-n"],
    "missing-value-long": ["--limit"],
    "not-a-number": ["-n", "ten", "a.txt"],
    "not-a-number-long": ["--limit=ten"],
    "empty-value": ["--limit=", "a.txt"],
    "verbose-with-value": ["--verbose=yes"],
}


@pytest.mark.parametrize("name", CASES)
def test_cases(name):
    args, want = CASES[name]
    assert parse_args(args) == Args(*want)


@pytest.mark.parametrize("name", ERRORS)
def test_errors(name):
    with pytest.raises(UsageError):
        parse_args(ERRORS[name])


def test_abbreviation_is_unknown():
    with pytest.raises(UsageError):
        parse_args(["--lim", "3"])
parse_args.cppI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-command-line-arguments/.

#include "parse_args.hpp"

#include <charconv>
#include <cstddef>
#include <optional>
#include <system_error>

namespace {

// from_chars takes no '+' and no white space; the first check rejects '-'.
std::optional<int> decimal(std::string_view s) {
    if (s.empty() || s.front() < '0' || s.front() > '9') return std::nullopt;
    int n = 0;
    auto [end, ec] = std::from_chars(s.data(), s.data() + s.size(), n);
    if (ec != std::errc{} || end != s.data() + s.size()) return std::nullopt;
    return n;
}

}  // namespace

std::expected<CountArgs, std::string> parse_args(std::span<const std::string_view> args) {
    CountArgs out;
    std::size_t i = 0;
    for (; i < args.size(); ++i) {
        std::string_view arg = args[i];
        std::optional<std::string_view> value;
        if (arg == "--") {
            ++i;
            break;
        } else if (arg == "-v" || arg == "--verbose") {
            out.verbose = true;
            continue;
        } else if (arg == "-n" || arg == "--limit") {
            if (i + 1 == args.size()) {
                return std::unexpected("option " + std::string(arg) + " needs a value");
            }
            value = args[++i];
        } else if (arg.starts_with("--limit=")) {
            value = arg.substr(std::string_view("--limit=").size());
        } else if (arg.starts_with('-') && arg != "-") {
            return std::unexpected("unknown option " + std::string(arg));
        } else {
            break;  // The first operand ends the options.
        }
        auto n = decimal(*value);
        if (!n) return std::unexpected("limit '" + std::string(*value) + "' is not a decimal number");
        out.limit = *n;
    }
    out.files.assign(args.begin() + static_cast<std::ptrdiff_t>(i), args.end());
    return out;
}
parse_args.hpp 22 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-command-line-arguments/.
// since: C++23 (std::expected)

#pragma once

#include <expected>
#include <span>
#include <string>
#include <string_view>
#include <vector>

struct CountArgs {
    bool verbose = false;
    int limit = 10;
    std::vector<std::string> files;
    bool operator==(const CountArgs&) const = default;
};

// Parses the arguments of "count [-v] [-n N] [--] [FILE...]" without the
// program name. The error is a message for the user.
std::expected<CountArgs, std::string> parse_args(std::span<const std::string_view> args);
test_parse_args.cpp 64 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-command-line-arguments/.

#include <cstdio>
#include <cstdlib>
#include <string>
#include <string_view>
#include <vector>

#include "parse_args.hpp"

namespace {

int failures = 0;

using Args = std::vector<std::string_view>;

void check(std::string_view name, const Args& args, const CountArgs& want) {
    auto got = parse_args(args);
    if (!got || *got != want) {
        std::fprintf(stderr, "case %.*s: wrong result\n", static_cast<int>(name.size()), name.data());
        ++failures;
    }
}

void check_error(std::string_view name, const Args& args) {
    if (parse_args(args)) {
        std::fprintf(stderr, "case %.*s: no error\n", static_cast<int>(name.size()), name.data());
        ++failures;
    }
}

}  // namespace

int main() {
    check("files-only", {"a.txt", "b.txt"}, {false, 10, {"a.txt", "b.txt"}});
    check("short-options", {"-v", "-n", "3", "a.txt"}, {true, 3, {"a.txt"}});
    check("long-options", {"--verbose", "--limit", "5", "a.txt", "b.txt"}, {true, 5, {"a.txt", "b.txt"}});
    check("no-args", {}, {false, 10, {}});
    check("long-equals", {"--limit=7", "notes.md"}, {false, 7, {"notes.md"}});
    check("repeated", {"-n", "3", "--limit", "5", "a.txt"}, {false, 5, {"a.txt"}});
    check("zero", {"-n", "0", "a.txt"}, {false, 0, {"a.txt"}});
    check("end-of-options", {"-v", "--", "-n", "--limit=4"}, {true, 10, {"-n", "--limit=4"}});
    check("only-terminator", {"--"}, {false, 10, {}});
    check("second-terminator", {"--", "--"}, {false, 10, {"--"}});
    check("dash", {"-"}, {false, 10, {"-"}});
    check("dash-after-option", {"-n", "2", "-", "b.txt"}, {false, 2, {"-", "b.txt"}});
    check("empty-arg", {""}, {false, 10, {""}});
    check("space", {"-v", "my file.txt"}, {true, 10, {"my file.txt"}});
    check("non-ascii", {"--limit=4", "日本語.txt", "café.md"}, {false, 4, {"日本語.txt", "café.md"}});

    check_error("unknown-short", {"-x", "a.txt"});
    check_error("unknown-long", {"--color", "a.txt"});
    check_error("missing-value", {"-n"});
    check_error("missing-value-long", {"--limit"});
    check_error("not-a-number", {"-n", "ten", "a.txt"});
    check_error("not-a-number-long", {"--limit=ten"});
    check_error("empty-value", {"--limit=", "a.txt"});
    check_error("verbose-with-value", {"--verbose=yes"});

    if (failures != 0) return EXIT_FAILURE;
    std::puts("ok");
    return EXIT_SUCCESS;
}
CountArgs.javaI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-command-line-arguments/.

import java.util.List;

/** The parsed arguments of the tool "count [-v] [-n N] [--] [FILE...]". */
public record CountArgs(boolean verbose, int limit, List<String> files) {
  public CountArgs {
    files = List.copyOf(files);
  }

  /** A usage error of the command line. */
  public static final class UsageException extends Exception {
    private static final long serialVersionUID = 1L;

    public UsageException(String message) {
      super(message);
    }
  }

  /** Parses the arguments that {@code main} gets. They do not hold the program name. */
  public static CountArgs parse(String... args) throws UsageException {
    boolean verbose = false;
    int limit = 10;
    int i = 0;
    loop:
    for (; i < args.length; i++) {
      String arg = args[i];
      switch (arg) {
        case "--" -> {
          i++;
          break loop;
        }
        case "-v", "--verbose" -> verbose = true;
        case "-n", "--limit" -> {
          if (i + 1 == args.length) {
            throw new UsageException("option " + arg + " needs a value");
          }
          limit = decimal(args[++i]);
        }
        default -> {
          if (arg.startsWith("--limit=")) {
            limit = decimal(arg.substring("--limit=".length()));
          } else if (arg.startsWith("-") && !arg.equals("-")) {
            throw new UsageException("unknown option " + arg);
          } else {
            break loop; // The first operand ends the options.
          }
        }
      }
    }
    return new CountArgs(verbose, limit, List.of(args).subList(i, args.length));
  }

  // Integer.parseInt also accepts a sign and the digits of other scripts.
  private static int decimal(String s) throws UsageException {
    if (s.isEmpty() || !s.chars().allMatch(c -> c >= '0' && c <= '9')) {
      throw new UsageException("limit '" + s + "' is not a decimal number");
    }
    try {
      return Integer.parseInt(s);
    } catch (NumberFormatException e) {
      throw new UsageException("limit '" + s + "' is too large");
    }
  }
}
CountArgsTest.java 56 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-command-line-arguments/.

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class CountArgsTest {
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("files-only", List.of("a.txt", "b.txt"), new CountArgs(false, 10, List.of("a.txt", "b.txt"))),
        Arguments.of("short-options", List.of("-v", "-n", "3", "a.txt"), new CountArgs(true, 3, List.of("a.txt"))),
        Arguments.of("long-options", List.of("--verbose", "--limit", "5", "a.txt", "b.txt"), new CountArgs(true, 5, List.of("a.txt", "b.txt"))),
        Arguments.of("no-args", List.of(), new CountArgs(false, 10, List.of())),
        Arguments.of("long-equals", List.of("--limit=7", "notes.md"), new CountArgs(false, 7, List.of("notes.md"))),
        Arguments.of("repeated", List.of("-n", "3", "--limit", "5", "a.txt"), new CountArgs(false, 5, List.of("a.txt"))),
        Arguments.of("zero", List.of("-n", "0", "a.txt"), new CountArgs(false, 0, List.of("a.txt"))),
        Arguments.of("end-of-options", List.of("-v", "--", "-n", "--limit=4"), new CountArgs(true, 10, List.of("-n", "--limit=4"))),
        Arguments.of("only-terminator", List.of("--"), new CountArgs(false, 10, List.of())),
        Arguments.of("second-terminator", List.of("--", "--"), new CountArgs(false, 10, List.of("--"))),
        Arguments.of("dash", List.of("-"), new CountArgs(false, 10, List.of("-"))),
        Arguments.of("dash-after-option", List.of("-n", "2", "-", "b.txt"), new CountArgs(false, 2, List.of("-", "b.txt"))),
        Arguments.of("empty-arg", List.of(""), new CountArgs(false, 10, List.of(""))),
        Arguments.of("space", List.of("-v", "my file.txt"), new CountArgs(true, 10, List.of("my file.txt"))),
        Arguments.of("non-ascii", List.of("--limit=4", "日本語.txt", "café.md"), new CountArgs(false, 4, List.of("日本語.txt", "café.md"))));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void parses(String name, List<String> args, CountArgs want) throws CountArgs.UsageException {
    assertEquals(want, CountArgs.parse(args.toArray(String[]::new)), name);
  }

  static Stream<Arguments> errors() {
    return Stream.of(
        Arguments.of("unknown-short", List.of("-x", "a.txt")),
        Arguments.of("unknown-long", List.of("--color", "a.txt")),
        Arguments.of("missing-value", List.of("-n")),
        Arguments.of("missing-value-long", List.of("--limit")),
        Arguments.of("not-a-number", List.of("-n", "ten", "a.txt")),
        Arguments.of("not-a-number-long", List.of("--limit=ten")),
        Arguments.of("empty-value", List.of("--limit=", "a.txt")),
        Arguments.of("verbose-with-value", List.of("--verbose=yes")));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("errors")
  void rejects(String name, List<String> args) {
    assertThrows(CountArgs.UsageException.class, () -> CountArgs.parse(args.toArray(String[]::new)), name);
  }
}
parse_args.cI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-command-line-arguments/.

#include "parse_args.h"

#include <errno.h>
#include <getopt.h>
#include <limits.h>
#include <stdlib.h>

// Converts a string of ASCII digits. strtol alone also accepts white space
// and a sign.
static bool decimal(const char *s, int *n) {
    if (*s == '\0') return false;
    for (const char *p = s; *p != '\0'; p++) {
        if (*p < '0' || *p > '9') return false;
    }
    errno = 0;
    long v = strtol(s, nullptr, 10);
    if (errno == ERANGE || v > INT_MAX) return false;
    *n = (int)v;
    return true;
}

enum parse_result parse_args(int argc, char *argv[], struct count_args *out) {
    static const struct option longopts[] = {
        {"verbose", no_argument, nullptr, 'v'},
        {"limit", required_argument, nullptr, 'n'},
        {nullptr, 0, nullptr, 0},
    };
    *out = (struct count_args){.verbose = false, .limit = 10};
    // optind = 0 makes getopt_long start again with the glibc, musl and BSD
    // libraries. opterr = 0 stops the messages on stderr.
    optind = 0;
    opterr = 0;
    int c;
    // The leading ':' makes a missing value return ':' and not '?'.
    while ((c = getopt_long(argc, argv, ":vn:", longopts, nullptr)) != -1) {
        switch (c) {
        case 'v':
            out->verbose = true;
            break;
        case 'n':
            if (!decimal(optarg, &out->limit)) return PARSE_BAD_VALUE;
            break;
        case ':':
            return PARSE_MISSING_VALUE;
        default:
            return PARSE_UNKNOWN_OPTION;
        }
    }
    out->files = argv + optind;
    out->nfiles = (size_t)(argc - optind);
    return PARSE_OK;
}
parse_args.h 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-command-line-arguments/.

#ifndef PARSE_ARGS_H
#define PARSE_ARGS_H

#include <stddef.h>

struct count_args {
    bool verbose;
    int limit;
    char **files;  // points into argv
    size_t nfiles;
};

enum parse_result {
    PARSE_OK = 0,
    PARSE_UNKNOWN_OPTION,
    PARSE_MISSING_VALUE,
    PARSE_BAD_VALUE,
};

// parse_args parses argv[1] to argv[argc - 1] for the tool
// "count [-v] [-n N] [--] [FILE...]" with getopt_long. argv[0] is the
// program name. It prints no message: the caller does that. It uses the
// global state of getopt and resets it first, so it is not thread-safe.
enum parse_result parse_args(int argc, char *argv[], struct count_args *out);

#endif
test_parse_args.c 79 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-command-line-arguments/.

#include "parse_args.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static int failures = 0;

#define MAX_ARGS 8

// run copies the arguments into a mutable argv with a program name first,
// because getopt_long can permute argv.
static enum parse_result run(const char *const *args, struct count_args *out, char **argv) {
    int argc = 0;
    argv[argc++] = (char *)"count";
    for (; args[argc - 1] != nullptr; argc++) argv[argc] = (char *)args[argc - 1];
    argv[argc] = nullptr;
    return parse_args(argc, argv, out);
}

static void check(const char *name, const char *const *args, bool verbose, int limit,
                  const char *const *files) {
    char *argv[MAX_ARGS + 2];
    struct count_args got;
    bool ok = run(args, &got, argv) == PARSE_OK && got.verbose == verbose && got.limit == limit;
    size_t n = 0;
    while (files[n] != nullptr) n++;
    ok = ok && got.nfiles == n;
    for (size_t i = 0; ok && i < n; i++) ok = strcmp(got.files[i], files[i]) == 0;
    if (!ok) {
        fprintf(stderr, "case %s: wrong result\n", name);
        failures++;
    }
}

static void check_error(const char *name, const char *const *args) {
    char *argv[MAX_ARGS + 2];
    struct count_args got;
    if (run(args, &got, argv) == PARSE_OK) {
        fprintf(stderr, "case %s: no error\n", name);
        failures++;
    }
}

#define L(...) ((const char *const[]){__VA_ARGS__ __VA_OPT__(, ) nullptr})

int main(void) {
    check("files-only", L("a.txt", "b.txt"), false, 10, L("a.txt", "b.txt"));
    check("short-options", L("-v", "-n", "3", "a.txt"), true, 3, L("a.txt"));
    check("long-options", L("--verbose", "--limit", "5", "a.txt", "b.txt"), true, 5, L("a.txt", "b.txt"));
    check("no-args", L(), false, 10, L());
    check("long-equals", L("--limit=7", "notes.md"), false, 7, L("notes.md"));
    check("repeated", L("-n", "3", "--limit", "5", "a.txt"), false, 5, L("a.txt"));
    check("zero", L("-n", "0", "a.txt"), false, 0, L("a.txt"));
    check("end-of-options", L("-v", "--", "-n", "--limit=4"), true, 10, L("-n", "--limit=4"));
    check("only-terminator", L("--"), false, 10, L());
    check("second-terminator", L("--", "--"), false, 10, L("--"));
    check("dash", L("-"), false, 10, L("-"));
    check("dash-after-option", L("-n", "2", "-", "b.txt"), false, 2, L("-", "b.txt"));
    check("empty-arg", L(""), false, 10, L(""));
    check("space", L("-v", "my file.txt"), true, 10, L("my file.txt"));
    check("non-ascii", L("--limit=4", "日本語.txt", "café.md"), false, 4, L("日本語.txt", "café.md"));

    check_error("unknown-short", L("-x", "a.txt"));
    check_error("unknown-long", L("--color", "a.txt"));
    check_error("missing-value", L("-n"));
    check_error("missing-value-long", L("--limit"));
    check_error("not-a-number", L("-n", "ten", "a.txt"));
    check_error("not-a-number-long", L("--limit=ten"));
    check_error("empty-value", L("--limit=", "a.txt"));
    check_error("verbose-with-value", L("--verbose=yes"));

    if (failures != 0) return EXIT_FAILURE;
    puts("ok");
    return EXIT_SUCCESS;
}
CountArgs.csI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-command-line-arguments/.

using System.Globalization;

/// <summary>A usage error of the command line.</summary>
public sealed class UsageException(string message) : Exception(message);

/// <summary>The parsed arguments of the tool "count [-v] [-n N] [--] [FILE...]".</summary>
public sealed record CountArgs(bool Verbose, int Limit, IReadOnlyList<string> Files)
{
    /// <summary>Parses the arguments that Main gets. They do not hold the program name.</summary>
    public static CountArgs Parse(IReadOnlyList<string> args)
    {
        bool verbose = false;
        int limit = 10;
        int i = 0;
        for (; i < args.Count; i++)
        {
            string arg = args[i];
            if (arg == "--")
            {
                i++;
                break;
            }
            else if (arg is "-v" or "--verbose")
            {
                verbose = true;
            }
            else if (arg is "-n" or "--limit")
            {
                if (i + 1 == args.Count)
                {
                    throw new UsageException($"option {arg} needs a value");
                }
                limit = Decimal(args[++i]);
            }
            else if (arg.StartsWith("--limit=", StringComparison.Ordinal))
            {
                limit = Decimal(arg["--limit=".Length..]);
            }
            else if (arg.StartsWith('-') && arg != "-")
            {
                throw new UsageException($"unknown option {arg}");
            }
            else
            {
                break; // The first operand ends the options.
            }
        }
        return new CountArgs(verbose, limit, args.Skip(i).ToArray());
    }

    // NumberStyles.None allows decimal digits only: no sign and no white space.
    private static int Decimal(string s) =>
        int.TryParse(s, NumberStyles.None, CultureInfo.InvariantCulture, out int n)
            ? n
            : throw new UsageException($"limit '{s}' is not a decimal number");

    // A record compares a list by reference, so equality compares the items.
    public bool Equals(CountArgs? other) =>
        other is not null && Verbose == other.Verbose && Limit == other.Limit && Files.SequenceEqual(other.Files);

    public override int GetHashCode() => HashCode.Combine(Verbose, Limit, Files.Count);
}
CountArgsTests.cs 54 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-command-line-arguments/.

using Xunit;

public sealed class CountArgsTests
{
    public static TheoryData<string, string[], bool, int, string[]> Cases => new()
    {
        { "files-only", ["a.txt", "b.txt"], false, 10, ["a.txt", "b.txt"] },
        { "short-options", ["-v", "-n", "3", "a.txt"], true, 3, ["a.txt"] },
        { "long-options", ["--verbose", "--limit", "5", "a.txt", "b.txt"], true, 5, ["a.txt", "b.txt"] },
        { "no-args", [], false, 10, [] },
        { "long-equals", ["--limit=7", "notes.md"], false, 7, ["notes.md"] },
        { "repeated", ["-n", "3", "--limit", "5", "a.txt"], false, 5, ["a.txt"] },
        { "zero", ["-n", "0", "a.txt"], false, 0, ["a.txt"] },
        { "end-of-options", ["-v", "--", "-n", "--limit=4"], true, 10, ["-n", "--limit=4"] },
        { "only-terminator", ["--"], false, 10, [] },
        { "second-terminator", ["--", "--"], false, 10, ["--"] },
        { "dash", ["-"], false, 10, ["-"] },
        { "dash-after-option", ["-n", "2", "-", "b.txt"], false, 2, ["-", "b.txt"] },
        { "empty-arg", [""], false, 10, [""] },
        { "space", ["-v", "my file.txt"], true, 10, ["my file.txt"] },
        { "non-ascii", ["--limit=4", "日本語.txt", "café.md"], false, 4, ["日本語.txt", "café.md"] },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Parses(string name, string[] args, bool verbose, int limit, string[] files)
    {
        Assert.False(string.IsNullOrEmpty(name));
        Assert.Equal(new CountArgs(verbose, limit, files), CountArgs.Parse(args));
    }

    public static TheoryData<string, string[]> Errors => new()
    {
        { "unknown-short", ["-x", "a.txt"] },
        { "unknown-long", ["--color", "a.txt"] },
        { "missing-value", ["-n"] },
        { "missing-value-long", ["--limit"] },
        { "not-a-number", ["-n", "ten", "a.txt"] },
        { "not-a-number-long", ["--limit=ten"] },
        { "empty-value", ["--limit=", "a.txt"] },
        { "verbose-with-value", ["--verbose=yes"] },
    };

    [Theory]
    [MemberData(nameof(Errors))]
    public void Rejects(string name, string[] args)
    {
        Assert.False(string.IsNullOrEmpty(name));
        Assert.Throws<UsageException>(() => CountArgs.Parse(args));
    }
}
parseArgs.jsI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-command-line-arguments/.

import { parseArgs as parse } from "node:util";

/** A usage error of the command line. */
export class UsageError extends Error {}

const options = {
  verbose: { type: "boolean", short: "v", default: false },
  limit: { type: "string", short: "n", default: "10" },
};

/**
 * Parses the arguments of "count [-v] [-n N] [--] [FILE...]" without the
 * program name. Throws UsageError for an unknown option, a missing value or
 * a value that is not a decimal number.
 * @param {string[]} args
 * @returns {{verbose: boolean, limit: number, files: string[]}}
 */
export function parseArgs(args) {
  let parsed;
  try {
    parsed = parse({ args, options, strict: true, allowPositionals: true });
  } catch (err) {
    throw new UsageError(err.message, { cause: err });
  }
  const { values, positionals } = parsed;
  // parseArgs has no number type, so the code converts the string.
  if (!/^[0-9]+$/.test(values.limit)) {
    throw new UsageError(`option --limit needs a number, not '${values.limit}'`);
  }
  return {
    verbose: values.verbose,
    limit: Number(values.limit),
    files: positionals,
  };
}
parseArgs.test.js 48 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-command-line-arguments/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { parseArgs, UsageError } from "./parseArgs.js";

const cases = [
  ["files-only", ["a.txt", "b.txt"], [false, 10, ["a.txt", "b.txt"]]],
  ["short-options", ["-v", "-n", "3", "a.txt"], [true, 3, ["a.txt"]]],
  ["long-options", ["--verbose", "--limit", "5", "a.txt", "b.txt"], [true, 5, ["a.txt", "b.txt"]]],
  ["no-args", [], [false, 10, []]],
  ["long-equals", ["--limit=7", "notes.md"], [false, 7, ["notes.md"]]],
  ["repeated", ["-n", "3", "--limit", "5", "a.txt"], [false, 5, ["a.txt"]]],
  ["zero", ["-n", "0", "a.txt"], [false, 0, ["a.txt"]]],
  ["end-of-options", ["-v", "--", "-n", "--limit=4"], [true, 10, ["-n", "--limit=4"]]],
  ["only-terminator", ["--"], [false, 10, []]],
  ["second-terminator", ["--", "--"], [false, 10, ["--"]]],
  ["dash", ["-"], [false, 10, ["-"]]],
  ["dash-after-option", ["-n", "2", "-", "b.txt"], [false, 2, ["-", "b.txt"]]],
  ["empty-arg", [""], [false, 10, [""]]],
  ["space", ["-v", "my file.txt"], [true, 10, ["my file.txt"]]],
  ["non-ascii", ["--limit=4", "日本語.txt", "café.md"], [false, 4, ["日本語.txt", "café.md"]]],
];

const errors = [
  ["unknown-short", ["-x", "a.txt"]],
  ["unknown-long", ["--color", "a.txt"]],
  ["missing-value", ["-n"]],
  ["missing-value-long", ["--limit"]],
  ["not-a-number", ["-n", "ten", "a.txt"]],
  ["not-a-number-long", ["--limit=ten"]],
  ["empty-value", ["--limit=", "a.txt"]],
  ["verbose-with-value", ["--verbose=yes"]],
];

for (const [name, args, [verbose, limit, files]] of cases) {
  test(name, () => {
    assert.deepEqual(parseArgs(args), { verbose, limit, files });
  });
}

for (const [name, args] of errors) {
  test(name, () => {
    assert.throws(() => parseArgs(args), UsageError);
  });
}
parseArgs.tsI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-command-line-arguments/.

import { parseArgs as parse } from "node:util";

/** A usage error of the command line. */
export class UsageError extends Error {}

export interface Args {
  verbose: boolean;
  limit: number;
  files: string[];
}

const options = {
  verbose: { type: "boolean", short: "v", default: false },
  limit: { type: "string", short: "n", default: "10" },
} as const;

/**
 * Parses the arguments of "count [-v] [-n N] [--] [FILE...]" without the
 * program name. Throws UsageError for an unknown option, a missing value or
 * a value that is not a decimal number.
 */
export function parseArgs(args: string[]): Args {
  let parsed;
  try {
    parsed = parse({ args, options, strict: true, allowPositionals: true });
  } catch (err) {
    throw new UsageError((err as Error).message, { cause: err });
  }
  const { values, positionals } = parsed;
  // parseArgs has no number type, so the code converts the string.
  if (!/^[0-9]+$/.test(values.limit)) {
    throw new UsageError(`option --limit needs a number, not '${values.limit}'`);
  }
  return { verbose: values.verbose, limit: Number(values.limit), files: positionals };
}
parseArgs.test.ts 48 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-command-line-arguments/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { parseArgs, UsageError } from "./parseArgs.ts";

const cases: [string, string[], [boolean, number, string[]]][] = [
  ["files-only", ["a.txt", "b.txt"], [false, 10, ["a.txt", "b.txt"]]],
  ["short-options", ["-v", "-n", "3", "a.txt"], [true, 3, ["a.txt"]]],
  ["long-options", ["--verbose", "--limit", "5", "a.txt", "b.txt"], [true, 5, ["a.txt", "b.txt"]]],
  ["no-args", [], [false, 10, []]],
  ["long-equals", ["--limit=7", "notes.md"], [false, 7, ["notes.md"]]],
  ["repeated", ["-n", "3", "--limit", "5", "a.txt"], [false, 5, ["a.txt"]]],
  ["zero", ["-n", "0", "a.txt"], [false, 0, ["a.txt"]]],
  ["end-of-options", ["-v", "--", "-n", "--limit=4"], [true, 10, ["-n", "--limit=4"]]],
  ["only-terminator", ["--"], [false, 10, []]],
  ["second-terminator", ["--", "--"], [false, 10, ["--"]]],
  ["dash", ["-"], [false, 10, ["-"]]],
  ["dash-after-option", ["-n", "2", "-", "b.txt"], [false, 2, ["-", "b.txt"]]],
  ["empty-arg", [""], [false, 10, [""]]],
  ["space", ["-v", "my file.txt"], [true, 10, ["my file.txt"]]],
  ["non-ascii", ["--limit=4", "日本語.txt", "café.md"], [false, 4, ["日本語.txt", "café.md"]]],
];

const errors: [string, string[]][] = [
  ["unknown-short", ["-x", "a.txt"]],
  ["unknown-long", ["--color", "a.txt"]],
  ["missing-value", ["-n"]],
  ["missing-value-long", ["--limit"]],
  ["not-a-number", ["-n", "ten", "a.txt"]],
  ["not-a-number-long", ["--limit=ten"]],
  ["empty-value", ["--limit=", "a.txt"]],
  ["verbose-with-value", ["--verbose=yes"]],
];

for (const [name, args, [verbose, limit, files]] of cases) {
  test(name, () => {
    assert.deepEqual(parseArgs(args), { verbose, limit, files });
  });
}

for (const [name, args] of errors) {
  test(name, () => {
    assert.throws(() => parseArgs(args), UsageError);
  });
}
parse_args.goI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-command-line-arguments/.

// Package parseargs parses the arguments of the tool
// "count [-v] [-n N] [--] [FILE...]".
package parseargs

import (
	"flag"
	"fmt"
	"io"
	"strconv"
	"strings"
)

// Args holds the result of ParseArgs.
type Args struct {
	Verbose bool
	Limit   int
	Files   []string
}

// ParseArgs parses args, the arguments without the program name. It returns
// an error for an unknown option, a missing value or a value that is not a
// decimal number. It does not print and does not exit.
func ParseArgs(args []string) (Args, error) {
	var a Args
	fs := flag.NewFlagSet("count", flag.ContinueOnError)
	fs.SetOutput(io.Discard)
	fs.BoolVar(&a.Verbose, "v", false, "print more")
	fs.BoolVar(&a.Verbose, "verbose", false, "print more")
	// flag.IntVar would accept 0x10, 010 and -5, so the value is a string
	// that the code converts.
	limit := "10"
	fs.StringVar(&limit, "n", limit, "the limit")
	fs.StringVar(&limit, "limit", limit, "the limit")
	if err := fs.Parse(args); err != nil {
		return Args{}, err
	}
	n, err := decimal(limit)
	if err != nil {
		return Args{}, err
	}
	a.Limit = n
	a.Files = fs.Args()
	return a, nil
}

// decimal converts a string of ASCII digits. strconv.Atoi alone would also
// accept a sign.
func decimal(s string) (int, error) {
	n, err := strconv.Atoi(s)
	if err != nil || strings.IndexFunc(s, func(r rune) bool { return r < '0' || r > '9' }) >= 0 {
		return 0, fmt.Errorf("invalid value %q for flag -limit: not a decimal number", s)
	}
	return n, nil
}
parse_args_test.go 67 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-command-line-arguments/.

package parseargs

import (
	"reflect"
	"testing"
)

func TestCases(t *testing.T) {
	cases := []struct {
		name string
		args []string
		want Args
	}{
		{"files-only", []string{"a.txt", "b.txt"}, Args{false, 10, []string{"a.txt", "b.txt"}}},
		{"short-options", []string{"-v", "-n", "3", "a.txt"}, Args{true, 3, []string{"a.txt"}}},
		{"long-options", []string{"--verbose", "--limit", "5", "a.txt", "b.txt"}, Args{true, 5, []string{"a.txt", "b.txt"}}},
		{"no-args", []string{}, Args{false, 10, []string{}}},
		{"long-equals", []string{"--limit=7", "notes.md"}, Args{false, 7, []string{"notes.md"}}},
		{"repeated", []string{"-n", "3", "--limit", "5", "a.txt"}, Args{false, 5, []string{"a.txt"}}},
		{"zero", []string{"-n", "0", "a.txt"}, Args{false, 0, []string{"a.txt"}}},
		{"end-of-options", []string{"-v", "--", "-n", "--limit=4"}, Args{true, 10, []string{"-n", "--limit=4"}}},
		{"only-terminator", []string{"--"}, Args{false, 10, []string{}}},
		{"second-terminator", []string{"--", "--"}, Args{false, 10, []string{"--"}}},
		{"dash", []string{"-"}, Args{false, 10, []string{"-"}}},
		{"dash-after-option", []string{"-n", "2", "-", "b.txt"}, Args{false, 2, []string{"-", "b.txt"}}},
		{"empty-arg", []string{""}, Args{false, 10, []string{""}}},
		{"space", []string{"-v", "my file.txt"}, Args{true, 10, []string{"my file.txt"}}},
		{"non-ascii", []string{"--limit=4", "日本語.txt", "café.md"}, Args{false, 4, []string{"日本語.txt", "café.md"}}},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			got, err := ParseArgs(c.args)
			if err != nil {
				t.Fatalf("ParseArgs(%q): %v", c.args, err)
			}
			if !reflect.DeepEqual(got, c.want) {
				t.Errorf("ParseArgs(%q) = %#v, want %#v", c.args, got, c.want)
			}
		})
	}
}

func TestErrors(t *testing.T) {
	errs := []struct {
		name string
		args []string
	}{
		{"unknown-short", []string{"-x", "a.txt"}},
		{"unknown-long", []string{"--color", "a.txt"}},
		{"missing-value", []string{"-n"}},
		{"missing-value-long", []string{"--limit"}},
		{"not-a-number", []string{"-n", "ten", "a.txt"}},
		{"not-a-number-long", []string{"--limit=ten"}},
		{"empty-value", []string{"--limit=", "a.txt"}},
		{"verbose-with-value", []string{"--verbose=yes"}},
	}
	for _, c := range errs {
		t.Run(c.name, func(t *testing.T) {
			if got, err := ParseArgs(c.args); err == nil {
				t.Errorf("ParseArgs(%q) = %#v, want an error", c.args, got)
			}
		})
	}
}
parse_args.rsI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-command-line-arguments/.

//! Parses the arguments of the tool "count [-v] [-n N] [--] [FILE...]".

use std::fmt;

/// The result of [`parse_args`].
#[derive(Debug, PartialEq, Eq)]
pub struct Args {
    pub verbose: bool,
    pub limit: u32,
    pub files: Vec<String>,
}

/// A usage error of the command line.
#[derive(Debug, PartialEq, Eq)]
pub enum UsageError {
    UnknownOption(String),
    MissingValue(String),
    BadValue(String),
}

impl fmt::Display for UsageError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            UsageError::UnknownOption(o) => write!(f, "unknown option {o}"),
            UsageError::MissingValue(o) => write!(f, "option {o} needs a value"),
            UsageError::BadValue(v) => write!(f, "limit {v:?} is not a decimal number"),
        }
    }
}

impl std::error::Error for UsageError {}

/// Parses the arguments without the program name, for example
/// `parse_args(std::env::args().skip(1))`.
pub fn parse_args<I>(args: I) -> Result<Args, UsageError>
where
    I: IntoIterator<Item = String>,
{
    let mut args = args.into_iter();
    let mut out = Args { verbose: false, limit: 10, files: Vec::new() };
    while let Some(arg) = args.next() {
        match arg.as_str() {
            "--" => break,
            "-v" | "--verbose" => out.verbose = true,
            "-n" | "--limit" => {
                let value = args.next().ok_or_else(|| UsageError::MissingValue(arg.clone()))?;
                out.limit = decimal(&value)?;
            }
            _ => {
                if let Some(value) = arg.strip_prefix("--limit=") {
                    out.limit = decimal(value)?;
                } else if arg.starts_with('-') && arg != "-" {
                    return Err(UsageError::UnknownOption(arg));
                } else {
                    // The first operand ends the options.
                    out.files.push(arg);
                    break;
                }
            }
        }
    }
    out.files.extend(args);
    Ok(out)
}

/// Converts a string of ASCII digits. `str::parse` alone also accepts a `+`.
fn decimal(s: &str) -> Result<u32, UsageError> {
    if s.is_empty() || !s.bytes().all(|b| b.is_ascii_digit()) {
        return Err(UsageError::BadValue(s.to_string()));
    }
    s.parse().map_err(|_| UsageError::BadValue(s.to_string()))
}
tests/parse_args_test.rs 50 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-command-line-arguments/.

use algo_parse_command_line_arguments::{Args, parse_args};

fn strings(v: &[&str]) -> Vec<String> {
    v.iter().map(|s| s.to_string()).collect()
}

#[test]
fn cases() {
    let cases: [(&str, &[&str], (bool, u32, &[&str])); 15] = [
        ("files-only", &["a.txt", "b.txt"], (false, 10, &["a.txt", "b.txt"])),
        ("short-options", &["-v", "-n", "3", "a.txt"], (true, 3, &["a.txt"])),
        ("long-options", &["--verbose", "--limit", "5", "a.txt", "b.txt"], (true, 5, &["a.txt", "b.txt"])),
        ("no-args", &[], (false, 10, &[])),
        ("long-equals", &["--limit=7", "notes.md"], (false, 7, &["notes.md"])),
        ("repeated", &["-n", "3", "--limit", "5", "a.txt"], (false, 5, &["a.txt"])),
        ("zero", &["-n", "0", "a.txt"], (false, 0, &["a.txt"])),
        ("end-of-options", &["-v", "--", "-n", "--limit=4"], (true, 10, &["-n", "--limit=4"])),
        ("only-terminator", &["--"], (false, 10, &[])),
        ("second-terminator", &["--", "--"], (false, 10, &["--"])),
        ("dash", &["-"], (false, 10, &["-"])),
        ("dash-after-option", &["-n", "2", "-", "b.txt"], (false, 2, &["-", "b.txt"])),
        ("empty-arg", &[""], (false, 10, &[""])),
        ("space", &["-v", "my file.txt"], (true, 10, &["my file.txt"])),
        ("non-ascii", &["--limit=4", "日本語.txt", "café.md"], (false, 4, &["日本語.txt", "café.md"])),
    ];
    for (name, args, (verbose, limit, files)) in cases {
        let want = Args { verbose, limit, files: strings(files) };
        assert_eq!(parse_args(strings(args)), Ok(want), "case {name}");
    }
}

#[test]
fn errors() {
    let errors: [(&str, &[&str]); 8] = [
        ("unknown-short", &["-x", "a.txt"]),
        ("unknown-long", &["--color", "a.txt"]),
        ("missing-value", &["-n"]),
        ("missing-value-long", &["--limit"]),
        ("not-a-number", &["-n", "ten", "a.txt"]),
        ("not-a-number-long", &["--limit=ten"]),
        ("empty-value", &["--limit=", "a.txt"]),
        ("verbose-with-value", &["--verbose=yes"]),
    ];
    for (name, args) in errors {
        assert!(parse_args(strings(args)).is_err(), "case {name}");
    }
}
parse_args.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/parse-command-line-arguments/.

# parse_args ARG... parses the arguments of "count [-v] [-n N] [--] [FILE...]".
# It sets the global variables verbose (true or false), limit, and the array
# files. On a usage error it prints a message on stderr and returns 2.
parse_args() {
  verbose=false
  limit=10
  files=()

  # getopts knows only one-letter options, so a first loop changes each long
  # option to its short form. It stops at the first operand or at "--".
  local -a short=()
  while (($# > 0)); do
    case $1 in
      --) break ;;
      --verbose) short+=(-v) ;;
      --limit)
        short+=(-n)
        (($# > 1)) && { short+=("$2"); shift; }
        ;;
      --limit=*) short+=(-n "${1#--limit=}") ;;
      --*)
        echo "count: unknown option $1" >&2
        return 2
        ;;
      -n)
        short+=(-n)
        (($# > 1)) && { short+=("$2"); shift; }
        ;;
      -?*) short+=("$1") ;;
      *) break ;;
    esac
    shift
  done
  set -- "${short[@]}" "$@"

  local opt OPTARG OPTIND=1
  while getopts ":vn:" opt; do
    case $opt in
      v) verbose=true ;;
      n)
        if [[ ! $OPTARG =~ ^[0-9]+$ ]]; then
          echo "count: limit '$OPTARG' is not a decimal number" >&2
          return 2
        fi
        limit=$((10#$OPTARG))
        ;;
      :)
        echo "count: option -$OPTARG needs a value" >&2
        return 2
        ;;
      *)
        echo "count: unknown option -$OPTARG" >&2
        return 2
        ;;
    esac
  done
  shift $((OPTIND - 1))
  files=("$@")
}
test_parse_args.bats 52 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/parse-command-line-arguments/.

bats_require_minimum_version 1.5.0

setup() {
  source "$BATS_TEST_DIRNAME/parse_args.sh"
}

check() { # check VERBOSE LIMIT COUNT FILE... ARG...: COUNT is the number of FILEs
  local want_verbose=$1 want_limit=$2
  local -a want_files=("${@:4:$3}")
  shift $((3 + $3))
  parse_args "$@"
  [ "$verbose" = "$want_verbose" ]
  [ "$limit" = "$want_limit" ]
  [ "${#files[@]}" -eq "${#want_files[@]}" ]
  local i
  for i in "${!want_files[@]}"; do
    [ "${files[i]}" = "${want_files[i]}" ]
  done
}

rejects() { # rejects ARG...
  run -2 parse_args "$@"
}

@test "files-only" { check false 10 2 a.txt b.txt a.txt b.txt; }
@test "short-options" { check true 3 1 a.txt -v -n 3 a.txt; }
@test "long-options" { check true 5 2 a.txt b.txt --verbose --limit 5 a.txt b.txt; }
@test "no-args" { check false 10 0; }
@test "long-equals" { check false 7 1 notes.md --limit=7 notes.md; }
@test "repeated" { check false 5 1 a.txt -n 3 --limit 5 a.txt; }
@test "zero" { check false 0 1 a.txt -n 0 a.txt; }
@test "end-of-options" { check true 10 2 -n --limit=4 -v -- -n --limit=4; }
@test "only-terminator" { check false 10 0 --; }
@test "second-terminator" { check false 10 1 -- -- --; }
@test "dash" { check false 10 1 - -; }
@test "dash-after-option" { check false 2 2 - b.txt -n 2 - b.txt; }
@test "empty-arg" { check false 10 1 "" ""; }
@test "space" { check true 10 1 "my file.txt" -v "my file.txt"; }
@test "non-ascii" { check false 4 2 日本語.txt café.md --limit=4 日本語.txt café.md; }

@test "unknown-short" { rejects -x a.txt; }
@test "unknown-long" { rejects --color a.txt; }
@test "missing-value" { rejects -n; }
@test "missing-value-long" { rejects --limit; }
@test "not-a-number" { rejects -n ten a.txt; }
@test "not-a-number-long" { rejects --limit=ten; }
@test "empty-value" { rejects --limit= a.txt; }
@test "verbose-with-value" { rejects --verbose=yes; }

References

  1. The Open Group, POSIX.1-2024, Base Definitions, Chapter 12, Utility Conventions, 12.2 Utility Syntax Guidelines, Guidelines 5, 6, 9, 10 and 13
  2. The Open Group, POSIX.1-2024, getopt, Description; Return Value
  3. The GNU C Library Reference Manual, Program Argument Syntax Conventions, 26.1.1
  4. The GNU C Library Reference Manual, Using the getopt function, 26.2.1, the permutation of argv and POSIXLY_CORRECT
  5. Linux man-pages, getopt(3), Description (optind); Notes (reset of optind to 0)
  6. FreeBSD Library Functions Manual, getopt(3), Description (optreset)
  7. FreeBSD Library Functions Manual, getopt_long(3), Description (the leading +); Bugs (optind set to 0)
  8. cppreference.com, Main function (C), Parameters, argv
  9. cppreference.com, std::from_chars
  10. The Python Standard Library, argparse, allow_abbrev; exit_on_error; Arguments containing -; ArgumentParser.exit; ArgumentParser.error
  11. The Python Standard Library, sys, sys.argv
  12. Node.js documentation, Util, util.parseArgs([config])
  13. Node.js documentation, Process, process.argv
  14. The Java Language Specification, Java SE 25 Edition, 12.1 Java Virtual Machine Startup; 12.1.4 Invoke a main Method
  15. Java SE 25 API, java.lang.Integer, parseInt(String, int)
  16. C# guide, Main() and command-line arguments, Overview; Command-line arguments
  17. .NET API reference, Environment.GetCommandLineArgs, Returns; Remarks
  18. .NET API reference, NumberStyles, the None field
  19. Go standard library, package flag, Command line flag syntax; ErrorHandling; FlagSet.SetOutput; FlagSet.Args
  20. Go standard library, package os, Args
  21. The Rust Standard Library, std::env::args, description; Panics
  22. GNU Bash Reference Manual, Bourne Shell Builtins, getopts
  23. GNU Bash Reference Manual, Special Parameters, *, @, # and 0

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (cpp)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (csharp)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (go)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (java)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (javascript)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (python)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (rust)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (typescript)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source

The native tests pass in 9 of 10 languages in this build.