CodeSampleX

Ejemplo

fs_extra 1.3.0: fs_extra::file

Muestra verificada para cargo fs_extra 1.3.0: fs_extra::file. El contrato se ejecutó en rust 1 · linux alpine/x64 · docker y pasó.

sha256:ac7f204e25f9fc8c3fbef188d9b0a70882d7bdd4f4d3e9666f057de25a6fa58e

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado linux · alpine · musl x64 cargo

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
rust 1 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · cargo@1rust:1-alpine@sha256:a10e64dd139b…
2026-11-22

Caso

HOW
Objetivo
verify fs_extra::file in pkg:cargo/fs_extra@1.3.0
Paquetes
Símbolos
  • fs_extra::file
Creado
2026-11-22T17:13:49Z

Contrato

  1. write_all and read_to_string round-trip file contents and return ErrorKind::InvalidFile for directory paths
  2. CopyOptions::new and Default initialize overwrite=false, skip_exist=false, buffer_size=64000 and builder methods update them
  3. copy enforces AlreadyExists by default, returns Ok(0) preserving destination on skip_exist, overwrites on overwrite=true, and returns NotFound/InvalidFile on invalid sources
  4. copy_with_progress chunks transfer using CopyOptions::buffer_size and reports TransitProcess progress up to total_bytes
  5. move_file and move_file_with_progress relocate files removing source, while skip_exist preserves both source and destination
  6. remove deletes an existing file and returns Ok(()) idempotently when the path does not exist

Archivos

  • Cargo.lock
  • Cargo.toml
  • PROMPT.md
  • csx.json
  • spec.json
  • src/lib.rs
  • test/contract.rs

Descargar el artefacto de código fuente (tar.gz)

Código fuente

Cargo.lock
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4

[[package]]
name = "fs_extra"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"

[[package]]
name = "sample-fs-extra-file"
version = "0.1.0"
dependencies = [
 "fs_extra",
]
Cargo.toml
[package]
name = "sample-fs-extra-file"
version = "0.1.0"
edition = "2021"

[dependencies]
fs_extra = "=1.3.0"

[[bin]]
name = "contract"
path = "test/contract.rs"
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 fs_extra::file in pkg:cargo/fs_extra@1.3.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:cargo/fs_extra@1.3.0
Demonstrate these symbols/APIs:
  - fs_extra::file

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:38005ed3301aff464ad56f9db203bc3a5a039678f1f0f53ea170f1d6548196f8","contract":["write_all and read_to_string round-trip file contents and return ErrorKind::InvalidFile for directory paths","CopyOptions::new and Default initialize overwrite=false, skip_exist=false, buffer_size=64000 and builder methods update them","copy enforces AlreadyExists by default, returns Ok(0) preserving destination on skip_exist, overwrites on overwrite=true, and returns NotFound/InvalidFile on invalid sources","copy_with_progress chunks transfer using CopyOptions::buffer_size and reports TransitProcess progress up to total_bytes","move_file and move_file_with_progress relocate files removing source, while skip_exist preserves both source and destination","remove deletes an existing file and returns Ok(()) idempotently when the path does not exist"],"goal":"verify fs_extra::file in pkg:cargo/fs_extra@1.3.0","kind":"HOW","packages":["pkg:cargo/fs_extra@1.3.0"],"schemaVersion":1,"symbols":["fs_extra::file"]},"contractCommand":["cargo","run","--offline"],"environment":{"arch":"x64","distro":"alpine","ecosystem":"cargo","libc":"musl","os":"linux","packageManager":"cargo","schemaVersion":1},"license":"MIT-0","packages":["pkg:cargo/fs_extra@1.3.0"],"schemaVersion":1,"subject":"pkg:cargo/fs_extra@1.3.0","symbols":["fs_extra::file"],"verifierAdapter":"cargo@1"}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify fs_extra::file in pkg:cargo/fs_extra@1.3.0",
  "kind": "HOW",
  "packages": [
    "pkg:cargo/fs_extra@1.3.0"
  ],
  "symbols": [
    "fs_extra::file"
  ]
}
src/lib.rs
//! Clean-room verification sample for fs_extra::file.

pub use fs_extra::file;
test/contract.rs
use fs_extra::error::ErrorKind;
use fs_extra::file::{self, CopyOptions, TransitProcess};
use std::fs;
use std::path::{Path, PathBuf};
use std::process;
use std::time::{SystemTime, UNIX_EPOCH};

struct TempDir {
    path: PathBuf,
}

impl TempDir {
    fn new(label: &str) -> Self {
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("system time after epoch")
            .as_nanos();
        let path = std::env::temp_dir().join(format!(
            "csx_{}_{}_{}",
            label,
            process::id(),
            nanos
        ));
        fs::create_dir_all(&path).expect("create temp dir");
        Self { path }
    }

    fn path(&self) -> &Path {
        &self.path
    }
}

impl Drop for TempDir {
    fn drop(&mut self) {
        let _ = fs::remove_dir_all(&self.path);
    }
}

fn main() {
    let dir = TempDir::new("fs_extra_file");
    let base = dir.path();

    // 1. write_all and read_to_string round-trip file contents and reject directory paths
    let src_a = base.join("a.txt");
    let content_a = "hello fs_extra\nline two";
    file::write_all(&src_a, content_a).expect("write_all a.txt");
    let read_back = file::read_to_string(&src_a).expect("read_to_string a.txt");
    assert_eq!(read_back, content_a);

    let sub_dir = base.join("subdir");
    fs::create_dir(&sub_dir).expect("create subdir");
    let err_read_dir = file::read_to_string(&sub_dir).expect_err("read_to_string on dir");
    assert!(matches!(err_read_dir.kind, ErrorKind::InvalidFile));
    let err_write_dir = file::write_all(&sub_dir, "nope").expect_err("write_all on dir");
    assert!(matches!(err_write_dir.kind, ErrorKind::InvalidFile));

    // 2. CopyOptions defaults and builder methods
    let opt_new = CopyOptions::new();
    assert!(!opt_new.overwrite);
    assert!(!opt_new.skip_exist);
    assert_eq!(opt_new.buffer_size, 64000);

    let opt_default = CopyOptions::default();
    assert!(!opt_default.overwrite);
    assert!(!opt_default.skip_exist);
    assert_eq!(opt_default.buffer_size, 64000);

    let opt_built = CopyOptions::new()
        .overwrite(true)
        .skip_exist(true)
        .buffer_size(64);
    assert!(opt_built.overwrite);
    assert!(opt_built.skip_exist);
    assert_eq!(opt_built.buffer_size, 64);

    // 3. copy: default, AlreadyExists, skip_exist, overwrite, NotFound, InvalidFile
    let dst_copy = base.join("copy.txt");
    let copied = file::copy(&src_a, &dst_copy, &CopyOptions::new()).expect("copy a -> copy");
    assert_eq!(copied, content_a.len() as u64);
    assert_eq!(
        file::read_to_string(&dst_copy).expect("read copy.txt"),
        content_a
    );

    let err_exists =
        file::copy(&src_a, &dst_copy, &CopyOptions::new()).expect_err("duplicate copy must fail");
    assert!(matches!(err_exists.kind, ErrorKind::AlreadyExists));

    let src_b = base.join("b.txt");
    let content_b = "updated content for overwrite";
    file::write_all(&src_b, content_b).expect("write_all b.txt");

    let skip_opts = CopyOptions::new().skip_exist(true);
    let skipped = file::copy(&src_b, &dst_copy, &skip_opts).expect("copy with skip_exist");
    assert_eq!(skipped, 0);
    assert_eq!(
        file::read_to_string(&dst_copy).expect("destination preserved on skip_exist"),
        content_a
    );

    let overwrite_opts = CopyOptions::new().overwrite(true);
    let overwritten = file::copy(&src_b, &dst_copy, &overwrite_opts).expect("copy with overwrite");
    assert_eq!(overwritten, content_b.len() as u64);
    assert_eq!(
        file::read_to_string(&dst_copy).expect("destination overwritten"),
        content_b
    );

    let missing = base.join("does_not_exist.txt");
    let err_not_found =
        file::copy(&missing, &dst_copy, &overwrite_opts).expect_err("missing source must fail");
    assert!(matches!(err_not_found.kind, ErrorKind::NotFound));

    let err_invalid_file =
        file::copy(&sub_dir, &dst_copy, &overwrite_opts).expect_err("dir source must fail");
    assert!(matches!(err_invalid_file.kind, ErrorKind::InvalidFile));

    // 4. copy_with_progress chunks by buffer_size and reports TransitProcess
    let src_chunked = base.join("chunked.txt");
    let payload = "0123456789".repeat(20); // 200 bytes
    file::write_all(&src_chunked, &payload).expect("write chunked.txt");

    let dst_chunked = base.join("chunked_copy.txt");
    let mut progress_log: Vec<(u64, u64)> = Vec::new();
    let chunk_opts = CopyOptions::new().buffer_size(64);
    let total = file::copy_with_progress(
        &src_chunked,
        &dst_chunked,
        &chunk_opts,
        |tp: TransitProcess| {
            progress_log.push((tp.copied_bytes, tp.total_bytes));
        },
    )
    .expect("copy_with_progress");

    assert_eq!(total, payload.len() as u64);
    assert!(progress_log.len() >= 4, "expected chunked callbacks");
    let mut prev = 0u64;
    for &(done, all) in &progress_log {
        assert_eq!(all, payload.len() as u64);
        assert!(done > prev);
        prev = done;
    }
    assert_eq!(prev, payload.len() as u64);
    assert_eq!(
        file::read_to_string(&dst_chunked).expect("read chunked_copy.txt"),
        payload
    );

    // 5. move_file and move_file_with_progress
    let move_src = base.join("move_src.txt");
    let move_content = "payload to move across paths";
    file::write_all(&move_src, move_content).expect("write move_src.txt");

    // skip_exist against existing destination preserves both source and destination
    let move_skipped =
        file::move_file(&move_src, &dst_copy, &skip_opts).expect("move_file skip_exist");
    assert_eq!(move_skipped, 0);
    assert!(move_src.exists(), "source must remain when skip_exist skips");
    assert_eq!(
        file::read_to_string(&dst_copy).expect("read dst_copy"),
        content_b
    );

    let move_dst = base.join("move_dst.txt");
    let moved_bytes =
        file::move_file(&move_src, &move_dst, &CopyOptions::new()).expect("move_file");
    assert_eq!(moved_bytes, move_content.len() as u64);
    assert!(!move_src.exists(), "source must be removed after move_file");
    assert_eq!(
        file::read_to_string(&move_dst).expect("read move_dst.txt"),
        move_content
    );

    let move_prog_dst = base.join("move_prog_dst.txt");
    let mut move_events: Vec<(u64, u64)> = Vec::new();
    let move_prog_opts = CopyOptions::new().buffer_size(10);
    let moved_prog_bytes = file::move_file_with_progress(
        &move_dst,
        &move_prog_dst,
        &move_prog_opts,
        |tp: TransitProcess| {
            move_events.push((tp.copied_bytes, tp.total_bytes));
        },
    )
    .expect("move_file_with_progress");

    assert_eq!(moved_prog_bytes, move_content.len() as u64);
    assert!(
        !move_dst.exists(),
        "source must be removed after move_file_with_progress"
    );
    assert!(!move_events.is_empty());
    assert_eq!(
        *move_events.last().expect("at least one progress event"),
        (move_content.len() as u64, move_content.len() as u64)
    );
    assert_eq!(
        file::read_to_string(&move_prog_dst).expect("read move_prog_dst.txt"),
        move_content
    );

    // 6. remove deletes existing file and succeeds idempotently on missing path
    assert!(move_prog_dst.exists());
    file::remove(&move_prog_dst).expect("remove existing file");
    assert!(!move_prog_dst.exists());
    file::remove(&move_prog_dst).expect("remove missing file is Ok(())");

    println!("All fs_extra::file contract assertions passed.");
}

Seeder de origen

anónimo