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에서 contract를…

sha256:b4b4def39fa56deb9cb0efc2ad558ffee95c5364e542b744ecc6d69828a98942

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. 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);
});

오리진 시더

익명