CodeSampleX

サンプル

dir-compare 4.2.0: compare directories synchronously and asynchronously with dir-compare

検証済みサンプル — npm dir-compare 4.2.0: compare directories synchronously and asynchronously with dir-compare. node 22 · linux alpine/x64 · docker で contract…

sha256:f1e7630df605530d40b7e61b1055321b71fd84fb82c0042f3b0cb7c70d18ef09

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

実行証拠

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

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

検証実行環境

環境 コントラクト ステージ 実行日
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-26

ケース

HOW
ゴール
compare directories synchronously and asynchronously with dir-compare
パッケージ
シンボル
  • compare
  • compareSync
作成日
2026-08-26T09:06:50Z

コントラクト

  1. compareSync compares two directory trees synchronously and reports equality, distinct entries, left-only entries, and right-only entries
  2. compare compares two directory trees asynchronously returning a Promise that resolves to the comparison Result
  3. compareSync with compareContent true detects file content differences and reports distinct files with reason different-content
  4. compareSync with compareSize true detects file size differences and reports distinct files with reason different-size
  5. compareSync with includeFilter and excludeFilter filters processed files using glob patterns
  6. compareSync with skipSubdirs true compares root level entries without descending into subdirectories
  7. compareDirsLineByLine uses lineBasedFileCompare to ignore trailing whitespace and line ending differences

ファイル

  • 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: compare directories synchronously and asynchronously with dir-compare
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/dir-compare@4.2.0
Demonstrate these symbols/APIs:
  - compare
  - compareSync

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:e722ae25d55575d95dd59c43d206f3af2959bed852dc210e083fe66cbbd19e2c","contract":["compareSync compares two directory trees synchronously and reports equality, distinct entries, left-only entries, and right-only entries","compare compares two directory trees asynchronously returning a Promise that resolves to the comparison Result","compareSync with compareContent true detects file content differences and reports distinct files with reason different-content","compareSync with compareSize true detects file size differences and reports distinct files with reason different-size","compareSync with includeFilter and excludeFilter filters processed files using glob patterns","compareSync with skipSubdirs true compares root level entries without descending into subdirectories","compareDirsLineByLine uses lineBasedFileCompare to ignore trailing whitespace and line ending differences"],"goal":"compare directories synchronously and asynchronously with dir-compare","kind":"HOW","packages":["pkg:npm/dir-compare@4.2.0"],"schemaVersion":1,"symbols":["compare","compareSync"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/dir-compare@4.2.0"],"schemaVersion":1,"subject":"pkg:npm/dir-compare@4.2.0","symbols":["compare","compareSync"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-dir-compare",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-dir-compare",
      "version": "1.0.0",
      "dependencies": {
        "dir-compare": "4.2.0"
      }
    },
    "node_modules/balanced-match": {
      "version": "1.0.2",
      "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
      "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
      "license": "MIT"
    },
    "node_modules/brace-expansion": {
      "version": "1.1.18",
      "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.18.tgz",
      "integrity": "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==",
      "license": "MIT",
      "dependencies": {
        "balanced-match": "^1.0.0",
        "concat-map": "0.0.1"
      }
    },
    "node_modules/concat-map": {
      "version": "0.0.1",
      "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
      "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==",
      "license": "MIT"
    },
    "node_modules/dir-compare": {
      "version": "4.2.0",
      "resolved": "https://registry.npmjs.org/dir-compare/-/dir-compare-4.2.0.tgz",
      "integrity": "sha512-2xMCmOoMrdQIPHdsTawECdNPwlVFB9zGcz3kuhmBO6U3oU+UQjsue0i8ayLKpgBcm+hcXPMVSGUN9d+pvJ6+VQ==",
      "license": "MIT",
      "dependencies": {
        "minimatch": "^3.0.5",
        "p-limit": "^3.1.0 "
      }
    },
    "node_modules/minimatch": {
      "version": "3.1.5",
      "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",
      "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",
      "license": "ISC",
      "dependencies": {
        "brace-expansion": "^1.1.7"
      },
      "engines": {
        "node": "*"
      }
    },
    "node_modules/p-limit": {
      "version": "3.1.0",
      "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz",
      "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==",
      "license": "MIT",
      "dependencies": {
        "yocto-queue": "^0.1.0"
      },
      "engines": {
        "node": ">=10"
      },
      "funding": {
        "url": "https://github.com/sponsors/sindresorhus"
      }
    },
    "node_modules/yocto-queue": {
      "version": "0.1.0",
      "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",
      "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==",
      "license": "MIT",
      "engines": {
        "node": ">=10"
      },
      "funding": {
        "url": "https://github.com/sponsors/sindresorhus"
      }
    }
  }
}
package.json
{
  "name": "sample-dir-compare",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "dependencies": {
    "dir-compare": "4.2.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "compare directories synchronously and asynchronously with dir-compare",
  "kind": "HOW",
  "packages": [
    "pkg:npm/dir-compare@4.2.0"
  ],
  "symbols": [
    "compare",
    "compareSync"
  ]
}
src/index.mjs
import { compare, compareSync, fileCompareHandlers } from 'dir-compare';

/**
 * Compares two directory trees synchronously.
 * @param {string} path1 First directory path
 * @param {string} path2 Second directory path
 * @param {import('dir-compare').Options} [options] Comparison options
 * @returns {import('dir-compare').Result}
 */
export function compareDirsSync(path1, path2, options = {}) {
  return compareSync(path1, path2, options);
}

/**
 * Compares two directory trees asynchronously.
 * @param {string} path1 First directory path
 * @param {string} path2 Second directory path
 * @param {import('dir-compare').Options} [options] Comparison options
 * @returns {Promise<import('dir-compare').Result>}
 */
export async function compareDirsAsync(path1, path2, options = {}) {
  return await compare(path1, path2, options);
}

/**
 * Compares directories line-by-line ignoring whitespace and line endings.
 * @param {string} path1 First directory path
 * @param {string} path2 Second directory path
 * @param {import('dir-compare').Options} [options] Additional options
 * @returns {import('dir-compare').Result}
 */
export function compareDirsLineByLine(path1, path2, options = {}) {
  return compareSync(path1, path2, {
    compareContent: true,
    compareFileSync: fileCompareHandlers.lineBasedFileCompare.compareSync,
    ignoreWhiteSpaces: true,
    ignoreLineEnding: true,
    ...options,
  });
}
test/contract.mjs
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import { compare, compareSync } from 'dir-compare';
import {
  compareDirsSync,
  compareDirsAsync,
  compareDirsLineByLine,
} from '../src/index.mjs';

function createTempDir(prefix) {
  return fs.mkdtempSync(path.join(os.tmpdir(), prefix));
}

function cleanupDir(dir) {
  try {
    fs.rmSync(dir, { recursive: true, force: true });
  } catch {}
}

async function runContract() {
  const dirA = createTempDir('dir-cmp-test-a-');
  const dirB = createTempDir('dir-cmp-test-b-');

  try {
    // Setup test tree
    fs.mkdirSync(path.join(dirA, 'sub'), { recursive: true });
    fs.mkdirSync(path.join(dirB, 'sub'), { recursive: true });

    fs.writeFileSync(path.join(dirA, 'identical.txt'), 'same file content');
    fs.writeFileSync(path.join(dirB, 'identical.txt'), 'same file content');

    fs.writeFileSync(path.join(dirA, 'left-only.txt'), 'only in A');
    fs.writeFileSync(path.join(dirB, 'right-only.txt'), 'only in B');

    fs.writeFileSync(path.join(dirA, 'sub', 'nested.txt'), 'nested content');
    fs.writeFileSync(path.join(dirB, 'sub', 'nested.txt'), 'nested content');

    fs.writeFileSync(path.join(dirA, 'sub', 'sub-left.txt'), 'left in sub');
    fs.writeFileSync(path.join(dirB, 'sub', 'sub-right.txt'), 'right in sub');

    // 1. compareSync compares two directory trees synchronously and reports equality, distinct entries, left-only entries, and right-only entries
    const resSync = compareSync(dirA, dirB, { compareContent: true });
    assert.equal(typeof resSync.same, 'boolean');
    assert.equal(resSync.same, false);
    assert.equal(resSync.equalDirs, 1);
    assert.equal(resSync.equalFiles, 2);
    assert.equal(resSync.leftFiles, 2);
    assert.equal(resSync.rightFiles, 2);
    assert.equal(resSync.differences, resSync.distinct + resSync.left + resSync.right);
    assert.equal(resSync.total, resSync.differences + resSync.equal);

    // 2. compare compares two directory trees asynchronously returning a Promise that resolves to the comparison Result
    const resAsync = await compare(dirA, dirB, { compareContent: true });
    assert.equal(resAsync.same, false);
    assert.equal(resAsync.equalFiles, resSync.equalFiles);
    assert.equal(resAsync.leftFiles, resSync.leftFiles);
    assert.equal(resAsync.rightFiles, resSync.rightFiles);
    assert.equal(resAsync.differences, resSync.differences);

    // 3. compareSync with compareContent true detects file content differences and reports distinct files with reason different-content
    const contentDirA = createTempDir('dir-content-a-');
    const contentDirB = createTempDir('dir-content-b-');
    try {
      fs.writeFileSync(path.join(contentDirA, 'data.txt'), 'alpha');
      fs.writeFileSync(path.join(contentDirB, 'data.txt'), 'omega');
      const contentRes = compareDirsSync(contentDirA, contentDirB, { compareContent: true });
      assert.equal(contentRes.same, false);
      assert.equal(contentRes.distinctFiles, 1);
      const diffItem = contentRes.diffSet?.find((d) => d.name1 === 'data.txt' || d.name2 === 'data.txt');
      assert.ok(diffItem);
      assert.equal(diffItem.state, 'distinct');
      assert.equal(diffItem.reason, 'different-content');
    } finally {
      cleanupDir(contentDirA);
      cleanupDir(contentDirB);
    }

    // 4. compareSync with compareSize true detects file size differences and reports distinct files with reason different-size
    const sizeDirA = createTempDir('dir-size-a-');
    const sizeDirB = createTempDir('dir-size-b-');
    try {
      fs.writeFileSync(path.join(sizeDirA, 'sized.txt'), '123');
      fs.writeFileSync(path.join(sizeDirB, 'sized.txt'), '123456789');
      const sizeRes = compareDirsSync(sizeDirA, sizeDirB, { compareSize: true });
      assert.equal(sizeRes.same, false);
      assert.equal(sizeRes.distinctFiles, 1);
      const diffItem = sizeRes.diffSet?.find((d) => d.name1 === 'sized.txt' || d.name2 === 'sized.txt');
      assert.ok(diffItem);
      assert.equal(diffItem.state, 'distinct');
      assert.equal(diffItem.reason, 'different-size');
    } finally {
      cleanupDir(sizeDirA);
      cleanupDir(sizeDirB);
    }

    // 5. compareSync with includeFilter and excludeFilter filters processed files using glob patterns
    const filterRes = compareDirsSync(dirA, dirB, {
      compareContent: true,
      includeFilter: 'identical.txt,sub/**',
      excludeFilter: '**/*left*,**/*right*',
    });
    assert.equal(filterRes.same, true);
    assert.equal(filterRes.distinct, 0);
    assert.equal(filterRes.left, 0);
    assert.equal(filterRes.right, 0);

    // 6. compareSync with skipSubdirs true compares root level entries without descending into subdirectories
    const skipDirA = createTempDir('dir-skip-a-');
    const skipDirB = createTempDir('dir-skip-b-');
    try {
      fs.mkdirSync(path.join(skipDirA, 'sub'), { recursive: true });
      fs.mkdirSync(path.join(skipDirB, 'sub'), { recursive: true });
      fs.writeFileSync(path.join(skipDirA, 'root.txt'), 'same');
      fs.writeFileSync(path.join(skipDirB, 'root.txt'), 'same');
      fs.writeFileSync(path.join(skipDirA, 'sub', 'diff.txt'), 'value-1');
      fs.writeFileSync(path.join(skipDirB, 'sub', 'diff.txt'), 'value-2');

      const fullRes = compareDirsSync(skipDirA, skipDirB, { compareContent: true });
      assert.equal(fullRes.same, false);

      const skipRes = compareDirsSync(skipDirA, skipDirB, {
        compareContent: true,
        skipSubdirs: true,
      });
      assert.equal(skipRes.same, true);
      assert.equal(skipRes.distinctFiles, 0);
    } finally {
      cleanupDir(skipDirA);
      cleanupDir(skipDirB);
    }

    // 7. compareDirsLineByLine uses lineBasedFileCompare to ignore trailing whitespace and line ending differences
    const wsDirA = createTempDir('dir-ws-a-');
    const wsDirB = createTempDir('dir-ws-b-');
    try {
      fs.writeFileSync(path.join(wsDirA, 'format.txt'), 'line 1  \r\nline 2   \r\n');
      fs.writeFileSync(path.join(wsDirB, 'format.txt'), 'line 1\nline 2\n');

      const normalRes = compareDirsSync(wsDirA, wsDirB, { compareContent: true });
      assert.equal(normalRes.same, false);

      const lineRes = compareDirsLineByLine(wsDirA, wsDirB);
      assert.equal(lineRes.same, true);
      assert.equal(lineRes.distinctFiles, 0);
    } finally {
      cleanupDir(wsDirA);
      cleanupDir(wsDirB);
    }

    console.log('Contract tests passed successfully.');
  } finally {
    cleanupDir(dirA);
    cleanupDir(dirB);
  }
}

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

オリジンシーダー

匿名