CodeSampleX

示例

dir-compare 4.2.0: dircompare.compare

已验证示例 — npm dir-compare 4.2.0: dircompare.compare. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过: compare compares two directory trees asynchronously…

sha256:bb6497031eafeebb26b4d81b43042017e09ecb2c3a73785dbc792081be365528

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 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
目标
verify dircompare.compare in pkg:npm/dir-compare@4.2.0
包
符号
  • dircompare.compare
创建时间
2026-08-26T10:44:25Z

契约

  1. compare compares two directory trees asynchronously returning a Promise that resolves to the comparison Result
  2. compareDirectories helper compares two directory trees asynchronously and returns equal Result for identical directories
  3. compareDirectoriesWithContent with compareContent true detects file content differences and reports distinct files with reason different-content
  4. compare with compareSize true detects file size differences and reports distinct files with reason different-size
  5. compare with includeFilter and excludeFilter filters processed files using glob patterns
  6. compare with skipSubdirs true compares root level entries without descending into subdirectories
  7. compareDirectoriesLineByLine uses lineBasedFileCompare.compareAsync 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: verify dircompare.compare in pkg:npm/dir-compare@4.2.0
Kind: HOW

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

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:7362408205b2553e9b26261bfc9e2ac4ecc968ef0806fb6464c72cd10490e370","contract":["compare compares two directory trees asynchronously returning a Promise that resolves to the comparison Result","compareDirectories helper compares two directory trees asynchronously and returns equal Result for identical directories","compareDirectoriesWithContent with compareContent true detects file content differences and reports distinct files with reason different-content","compare with compareSize true detects file size differences and reports distinct files with reason different-size","compare with includeFilter and excludeFilter filters processed files using glob patterns","compare with skipSubdirs true compares root level entries without descending into subdirectories","compareDirectoriesLineByLine uses lineBasedFileCompare.compareAsync to ignore trailing whitespace and line ending differences"],"goal":"verify dircompare.compare in pkg:npm/dir-compare@4.2.0","kind":"HOW","packages":["pkg:npm/dir-compare@4.2.0"],"schemaVersion":1,"symbols":["dircompare.compare"]},"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":["dircompare.compare"],"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": "verify dircompare.compare in pkg:npm/dir-compare@4.2.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/dir-compare@4.2.0"
  ],
  "symbols": [
    "dircompare.compare"
  ]
}
src/index.mjs
import { compare, fileCompareHandlers } from 'dir-compare';

/**
 * 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 compareDirectories(path1, path2, options = {}) {
  return await compare(path1, path2, options);
}

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

/**
 * Compares two directory trees asynchronously using custom line-by-line file comparison handler.
 * @param {string} path1 First directory path
 * @param {string} path2 Second directory path
 * @param {import('dir-compare').Options} [options] Additional options
 * @returns {Promise<import('dir-compare').Result>}
 */
export async function compareDirectoriesLineByLine(path1, path2, options = {}) {
  return await compare(path1, path2, {
    compareContent: true,
    compareFileAsync: fileCompareHandlers.lineBasedFileCompare.compareAsync,
    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 } from 'dir-compare';
import {
  compareDirectories,
  compareDirectoriesWithContent,
  compareDirectoriesLineByLine,
} 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('csx-dir-cmp-a-');
  const dirB = createTempDir('csx-dir-cmp-b-');

  try {
    // Setup directory structure
    fs.mkdirSync(path.join(dirA, 'nested'), { recursive: true });
    fs.mkdirSync(path.join(dirB, 'nested'), { recursive: true });

    fs.writeFileSync(path.join(dirA, 'file1.txt'), 'hello world');
    fs.writeFileSync(path.join(dirB, 'file1.txt'), 'hello world');

    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, 'nested', 'same.txt'), 'nested content');
    fs.writeFileSync(path.join(dirB, 'nested', 'same.txt'), 'nested content');

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

    // 1. compare compares two directory trees asynchronously returning a Promise that resolves to the comparison Result
    const res = await compare(dirA, dirB, { compareContent: true });
    assert.equal(typeof res.same, 'boolean');
    assert.equal(res.same, false);
    assert.equal(res.equalDirs, 1);
    assert.equal(res.equalFiles, 2);
    assert.equal(res.leftFiles, 2);
    assert.equal(res.rightFiles, 2);
    assert.equal(res.differences, res.distinct + res.left + res.right);
    assert.equal(res.total, res.differences + res.equal);

    // 2. compareDirectories helper compares two directory trees asynchronously and returns equal Result for identical directories
    const resEqual = await compareDirectories(dirA, dirA);
    assert.equal(resEqual.same, true);
    assert.equal(resEqual.distinct, 0);
    assert.equal(resEqual.left, 0);
    assert.equal(resEqual.right, 0);
    assert.ok(resEqual.equal > 0);

    // 3. compareDirectoriesWithContent with compareContent true detects file content differences and reports distinct files with reason different-content
    const contentDirA = createTempDir('csx-cmp-content-a-');
    const contentDirB = createTempDir('csx-cmp-content-b-');
    try {
      fs.writeFileSync(path.join(contentDirA, 'data.txt'), 'version A');
      fs.writeFileSync(path.join(contentDirB, 'data.txt'), 'version B');
      const contentRes = await compareDirectoriesWithContent(contentDirA, contentDirB);
      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. compare with compareSize true detects file size differences and reports distinct files with reason different-size
    const sizeDirA = createTempDir('csx-cmp-size-a-');
    const sizeDirB = createTempDir('csx-cmp-size-b-');
    try {
      fs.writeFileSync(path.join(sizeDirA, 'file.bin'), 'short');
      fs.writeFileSync(path.join(sizeDirB, 'file.bin'), 'longer content buffer');
      const sizeRes = await compare(sizeDirA, sizeDirB, { compareSize: true });
      assert.equal(sizeRes.same, false);
      assert.equal(sizeRes.distinctFiles, 1);
      const diffItem = sizeRes.diffSet?.find((d) => d.name1 === 'file.bin' || d.name2 === 'file.bin');
      assert.ok(diffItem);
      assert.equal(diffItem.state, 'distinct');
      assert.equal(diffItem.reason, 'different-size');
    } finally {
      cleanupDir(sizeDirA);
      cleanupDir(sizeDirB);
    }

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

    // 6. compare with skipSubdirs true compares root level entries without descending into subdirectories
    const skipDirA = createTempDir('csx-cmp-skip-a-');
    const skipDirB = createTempDir('csx-cmp-skip-b-');
    try {
      fs.mkdirSync(path.join(skipDirA, 'subdir'), { recursive: true });
      fs.mkdirSync(path.join(skipDirB, 'subdir'), { recursive: true });
      fs.writeFileSync(path.join(skipDirA, 'root.txt'), 'same');
      fs.writeFileSync(path.join(skipDirB, 'root.txt'), 'same');
      fs.writeFileSync(path.join(skipDirA, 'subdir', 'diff.txt'), 'left-val');
      fs.writeFileSync(path.join(skipDirB, 'subdir', 'diff.txt'), 'right-val');

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

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

    // 7. compareDirectoriesLineByLine uses lineBasedFileCompare.compareAsync to ignore trailing whitespace and line ending differences
    const wsDirA = createTempDir('csx-cmp-ws-a-');
    const wsDirB = createTempDir('csx-cmp-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 = await compare(wsDirA, wsDirB, { compareContent: true });
      assert.equal(normalRes.same, false);

      const lineRes = await compareDirectoriesLineByLine(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);
});

原始种子者

匿名