CodeSampleX

サンプル

argparse 1.0.10: parse command line arguments and positional/optional flags with ArgumentParser

検証済みサンプル — npm argparse 1.0.10: parse command line arguments and positional/optional flags with ArgumentParser. node 22 · linux alpine/x64 · docker で…

sha256:b4b4def39fa56deb9cb0efc2ad558ffee95c5364e542b744ecc6d69828a98942

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 MIT-0

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
1
ビルドした署名鍵
1
宣言された環境 node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

検証実行環境

環境 コントラクト ステージ 実行日
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-08-27

ケース

HOW
ゴール
parse command line arguments and positional/optional flags with ArgumentParser
パッケージ
シンボル
  • ArgumentParser
  • ArgumentParser.prototype.add_argument
  • ArgumentParser.prototype.parse_args
環境
node 22.23.2
作成日
2026-08-27T12:19:42Z

コントラクト

  1. ArgumentParser constructor instantiates a command line parser with custom prog and description
  2. addArgument defines positional arguments and parses required positional values
  3. addArgument defines optional flags with default values and custom destinations
  4. addArgument supports type conversion such as integer and float
  5. addArgument supports storeTrue and storeFalse boolean actions
  6. addArgument enforces choices validation and calls exit on invalid values
  7. addArgument supports variable argument lists using nargs modifier
  8. parseKnownArgs parses recognized options and returns unrecognized arguments as a separate array

ファイル

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.mjs
  • test/contract.mjs

ソースアーティファクトをダウンロード (tar.gz)

ソース

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: parse command line arguments and positional/optional flags with ArgumentParser
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/argparse@1.0.10
Demonstrate these symbols/APIs:
  - ArgumentParser
  - ArgumentParser.prototype.add_argument
  - ArgumentParser.prototype.parse_args

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:18186e56565038b5acadc88fe2846ac99494ed6027c3afb02b44ede790959648","contract":["ArgumentParser constructor instantiates a command line parser with custom prog and description","addArgument defines positional arguments and parses required positional values","addArgument defines optional flags with default values and custom destinations","addArgument supports type conversion such as integer and float","addArgument supports storeTrue and storeFalse boolean actions","addArgument enforces choices validation and calls exit on invalid values","addArgument supports variable argument lists using nargs modifier","parseKnownArgs parses recognized options and returns unrecognized arguments as a separate array"],"goal":"parse command line arguments and positional/optional flags with ArgumentParser","kind":"HOW","packages":["pkg:npm/argparse@1.0.10"],"schemaVersion":1,"symbols":["ArgumentParser","ArgumentParser.prototype.add_argument","ArgumentParser.prototype.parse_args"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"esm","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/argparse@1.0.10"],"schemaVersion":1,"subject":"pkg:npm/argparse@1.0.10","symbols":["ArgumentParser","ArgumentParser.prototype.add_argument","ArgumentParser.prototype.parse_args"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-argparse",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-argparse",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "argparse": "1.0.10"
      }
    },
    "node_modules/argparse": {
      "version": "1.0.10",
      "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz",
      "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==",
      "license": "MIT",
      "dependencies": {
        "sprintf-js": "~1.0.2"
      }
    },
    "node_modules/sprintf-js": {
      "version": "1.0.3",
      "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz",
      "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==",
      "license": "BSD-3-Clause"
    }
  }
}
package.json
{
  "name": "sample-argparse",
  "version": "1.0.0",
  "description": "parse command line arguments and positional/optional flags with ArgumentParser in pkg:npm/argparse@1.0.10",
  "type": "module",
  "main": "src/index.mjs",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "argparse": "1.0.10"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "parse command line arguments and positional/optional flags with ArgumentParser",
  "kind": "HOW",
  "packages": [
    "pkg:npm/argparse@1.0.10"
  ],
  "symbols": [
    "ArgumentParser",
    "ArgumentParser.prototype.add_argument",
    "ArgumentParser.prototype.parse_args"
  ]
}
src/index.mjs
import argparse from "argparse";

const ArgumentParser = argparse.ArgumentParser || argparse.default?.ArgumentParser;
const Namespace = argparse.Namespace || argparse.default?.Namespace;

if (ArgumentParser && ArgumentParser.prototype) {
  if (ArgumentParser.prototype.addArgument && !ArgumentParser.prototype.add_argument) {
    ArgumentParser.prototype.add_argument = ArgumentParser.prototype.addArgument;
  }
  if (ArgumentParser.prototype.parseArgs && !ArgumentParser.prototype.parse_args) {
    ArgumentParser.prototype.parse_args = ArgumentParser.prototype.parseArgs;
  }
}

/**
 * Creates an instance of ArgumentParser with configured options.
 *
 * @param {object} [options={}] - Parser configuration options (prog, description, addHelp, etc.).
 * @returns {ArgumentParser} An ArgumentParser instance.
 */
export function createArgumentParser(options = {}) {
  const opts = {
    prog: options.prog || "cli",
    description: options.description || "",
    addHelp: options.addHelp !== undefined ? options.addHelp : true,
    ...options,
  };
  return new ArgumentParser(opts);
}

/**
 * Adds an argument specification to an ArgumentParser instance.
 *
 * @param {ArgumentParser} parser - The parser instance.
 * @param {string|string[]} args - Argument flag(s) or positional name(s).
 * @param {object} [options={}] - Argument options (type, defaultValue, choices, action, nargs, help, dest).
 * @returns {object} The created Action object.
 */
export function addArgument(parser, args, options = {}) {
  return parser.addArgument(args, options);
}

/**
 * Parses arguments array using the provided parser instance.
 *
 * @param {ArgumentParser} parser - The parser instance.
 * @param {string[]} [args] - Array of CLI argument strings.
 * @param {object} [namespace] - Target namespace object.
 * @returns {object} Parsed arguments namespace.
 */
export function parseArgs(parser, args, namespace) {
  return parser.parseArgs(args, namespace);
}

/**
 * Parses known arguments from args array, returning recognized options and unparsed arguments.
 *
 * @param {ArgumentParser} parser - The parser instance.
 * @param {string[]} [args] - Array of CLI argument strings.
 * @returns {[object, string[]]} Tuple containing parsed namespace and remaining unparsed args.
 */
export function parseKnownArgs(parser, args) {
  return parser.parseKnownArgs(args);
}

/**
 * Builds a standard CLI configuration parser for file processing tasks.
 *
 * @param {object} [options={}] - Custom parser options.
 * @returns {ArgumentParser} Configured ArgumentParser instance.
 */
export function buildCliParser(options = {}) {
  const parser = createArgumentParser({
    prog: "tool",
    description: "Sample CLI tool for demonstration",
    ...options,
  });

  parser.addArgument(["input"], {
    help: "Input source file",
  });

  parser.addArgument(["-o", "--output"], {
    defaultValue: "stdout",
    help: "Output destination",
    dest: "output",
  });

  parser.addArgument(["-c", "--count"], {
    type: "int",
    defaultValue: 1,
    help: "Number of iterations",
    dest: "count",
  });

  parser.addArgument(["-v", "--verbose"], {
    action: "storeTrue",
    help: "Enable verbose output",
    dest: "verbose",
  });

  parser.addArgument(["--format"], {
    choices: ["json", "yaml", "text"],
    defaultValue: "text",
    help: "Output serialization format",
    dest: "format",
  });

  return parser;
}

export { ArgumentParser, Namespace };
test/contract.mjs
import assert from "node:assert/strict";
import * as argparse from "argparse";
import {
  ArgumentParser,
  Namespace,
  createArgumentParser,
  addArgument,
  parseArgs,
  parseKnownArgs,
  buildCliParser,
} from "../src/index.mjs";

async function runContracts() {
  // Contract 1: ArgumentParser constructor instantiates a command line parser with custom prog and description
  {
    assert.equal(typeof ArgumentParser, "function", "ArgumentParser must be a constructor function");
    const parser = createArgumentParser({
      prog: "my-app",
      description: "My App CLI",
      addHelp: true,
    });
    assert.equal(parser instanceof ArgumentParser, true, "parser should be an instance of ArgumentParser");
    assert.equal(parser.prog, "my-app", "parser.prog must match configured prog");
    assert.equal(parser.description, "My App CLI", "parser.description must match configured description");
    assert.equal(typeof parser.addArgument, "function", "parser.addArgument must be a function");
    assert.equal(typeof parser.parseArgs, "function", "parser.parseArgs must be a function");
  }

  // Contract 2: addArgument defines positional arguments and parses required positional values
  {
    const parser = createArgumentParser({ prog: "test-prog" });
    addArgument(parser, ["source"], { help: "Source file" });
    addArgument(parser, ["target"], { help: "Target file" });

    const result = parseArgs(parser, ["input.txt", "output.txt"]);
    assert.equal(result.source, "input.txt", "Positional argument 'source' should be parsed");
    assert.equal(result.target, "output.txt", "Positional argument 'target' should be parsed");
  }

  // Contract 3: addArgument defines optional flags with default values and custom destinations
  {
    const parser = createArgumentParser({ prog: "test-prog" });
    addArgument(parser, ["-o", "--output-file"], {
      defaultValue: "default.out",
      dest: "output",
      help: "Output filename",
    });

    const defaultResult = parseArgs(parser, []);
    assert.equal(defaultResult.output, "default.out", "Optional argument should have defaultValue when omitted");

    const customResult = parseArgs(parser, ["-o", "custom.out"]);
    assert.equal(customResult.output, "custom.out", "Short flag '-o' should populate destination 'output'");

    const longResult = parseArgs(parser, ["--output-file", "long.out"]);
    assert.equal(longResult.output, "long.out", "Long flag '--output-file' should populate destination 'output'");
  }

  // Contract 4: addArgument supports type conversion such as integer and float
  {
    const parser = createArgumentParser({ prog: "test-prog" });
    addArgument(parser, ["--port"], { type: "int", defaultValue: 8080 });
    addArgument(parser, ["--ratio"], { type: "float", defaultValue: 1.0 });

    const result = parseArgs(parser, ["--port", "3000", "--ratio", "0.75"]);
    assert.equal(result.port, 3000, "Integer type conversion should yield number 3000");
    assert.equal(typeof result.port, "number", "Parsed port must be of type number");
    assert.equal(result.ratio, 0.75, "Float type conversion should yield number 0.75");
    assert.equal(typeof result.ratio, "number", "Parsed ratio must be of type number");
  }

  // Contract 5: addArgument supports storeTrue and storeFalse boolean actions
  {
    const parser = createArgumentParser({ prog: "test-prog" });
    addArgument(parser, ["-v", "--verbose"], { action: "storeTrue", dest: "verbose" });
    addArgument(parser, ["--no-cache"], { action: "storeFalse", dest: "cache" });

    const defaultResult = parseArgs(parser, []);
    assert.equal(defaultResult.verbose, false, "storeTrue default should be false");
    assert.equal(defaultResult.cache, true, "storeFalse default should be true");

    const activeResult = parseArgs(parser, ["--verbose", "--no-cache"]);
    assert.equal(activeResult.verbose, true, "storeTrue flag should set value to true");
    assert.equal(activeResult.cache, false, "storeFalse flag should set value to false");
  }

  // Contract 6: addArgument enforces choices validation and calls exit on invalid values
  {
    const parser = createArgumentParser({ prog: "test-prog" });
    addArgument(parser, ["--mode"], {
      choices: ["sync", "async", "stream"],
      defaultValue: "sync",
    });

    const validResult = parseArgs(parser, ["--mode", "async"]);
    assert.equal(validResult.mode, "async", "Valid choice should be accepted");

    let exitCalled = false;
    let exitStatus = null;
    parser.exit = (status, msg) => {
      exitCalled = true;
      exitStatus = status;
      throw new Error(`Exit called with status ${status}: ${msg}`);
    };

    assert.throws(
      () => {
        parseArgs(parser, ["--mode", "invalid_mode"]);
      },
      /Exit called with status 2/,
      "Invalid choice should trigger parser exit with error"
    );
    assert.equal(exitCalled, true, "Exit hook should have been called on invalid choice");
    assert.equal(exitStatus, 2, "Exit status code should be 2");
  }

  // Contract 7: addArgument supports variable argument lists using nargs modifier
  {
    const parser = createArgumentParser({ prog: "test-prog" });
    addArgument(parser, ["--files"], { nargs: "+", defaultValue: [] });
    addArgument(parser, ["--coords"], { nargs: 2, type: "int" });

    const result = parseArgs(parser, ["--files", "a.txt", "b.txt", "c.txt", "--coords", "10", "20"]);
    assert.deepEqual(result.files, ["a.txt", "b.txt", "c.txt"], "nargs '+' should collect one or more arguments into an array");
    assert.deepEqual(result.coords, [10, 20], "nargs 2 should collect exact 2 arguments converted to integers");
  }

  // Contract 8: parseKnownArgs parses recognized options and returns unrecognized arguments as a separate array
  {
    const parser = createArgumentParser({ prog: "test-prog" });
    addArgument(parser, ["--env"], { defaultValue: "development" });
    addArgument(parser, ["-d", "--debug"], { action: "storeTrue" });

    const [known, unknown] = parseKnownArgs(parser, ["--env", "production", "--extra-flag", "extra-val", "-d", "positional-extra"]);
    assert.equal(known.env, "production", "Known argument '--env' should be parsed");
    assert.equal(known.debug, true, "Known argument '-d' should be parsed");
    assert.deepEqual(unknown, ["--extra-flag", "extra-val", "positional-extra"], "Unrecognized arguments should be returned in unknown array");
  }

  // Helper Verification: buildCliParser integration
  {
    const cli = buildCliParser();
    const parsed = parseArgs(cli, ["my-input.json", "-o", "out.json", "-c", "3", "-v", "--format", "json"]);
    assert.equal(parsed.input, "my-input.json");
    assert.equal(parsed.output, "out.json");
    assert.equal(parsed.count, 3);
    assert.equal(parsed.verbose, true);
    assert.equal(parsed.format, "json");
  }

  console.log("All argparse contract assertions passed successfully.");
}

runContracts().catch((err) => {
  console.error("Contract test failed:", err);
  process.exit(1);
});

オリジンシーダー

匿名