diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..d207b18 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +*.go text eol=lf diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..8e70045 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,61 @@ +name: Verify and package + +on: [push, pull_request] + +permissions: + contents: read + +env: + CGO_ENABLED: '0' + GOTOOLCHAIN: local + +jobs: + verify: + name: Native verification (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + timeout-minutes: 15 + strategy: + fail-fast: false + matrix: + os: [ubuntu-24.04, windows-2025, macos-15] + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + persist-credentials: false + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 + with: + go-version: '1.27.4' + cache-dependency-path: go.sum + - name: Verify native CLI + shell: pwsh + run: ./scripts/verify.ps1 + - name: Scan Go dependencies + if: runner.os == 'Linux' + run: go run golang.org/x/vuln/cmd/govulncheck@v1.10.0 ./... + - name: Scan Git history for secrets + if: runner.os == 'Linux' + run: go run github.com/zricethezav/gitleaks/v8@v8.30.1 git --redact --no-banner . + + package: + name: Package binaries + needs: verify + runs-on: ubuntu-24.04 + timeout-minutes: 15 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 + with: + go-version: '1.27.4' + cache-dependency-path: go.sum + - name: Build packages + shell: pwsh + run: ./scripts/package.ps1 + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: dct-packages + path: dist/dct-*/* + if-no-files-found: error + retention-days: 7 diff --git a/AGENTS.md b/AGENTS.md index c1d0e84..798c4e5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,6 +1,6 @@ # AGENTS.md — Engineering Mastery project policy -You are working on ONE ORIGINAL implementation project inside the user's F: workspace. +Work directly in the current VS Code Codex session on this original project inside the user's F: workspace. Keep the workspace manifest and progress report current. ## Scope and ethics - Never access, rewrite, delete or search outside the active project directory. @@ -8,12 +8,12 @@ You are working on ONE ORIGINAL implementation project inside the user's F: work - No employer-owned source, production secrets, private personal data or real customer records. - Security testing must use only local authorized fixtures. No external target testing. - Do not provision paid cloud services, purchase assets, publish publicly, or rotate credentials. -- Do not push/merge to GitHub; a separate gated runner or the human handles these actions. +- Do not push or merge to GitHub from the IDE. A separately authorized private GitHub workflow or the human handles remote operations. ## Engineering behavior - Inspect existing code, tests, current git status and decisions first. - Maintain README.md, docs/TASKS.md, docs/EVIDENCE.md and PROJECT_STATE.json. -- One small, valuable, unblocked feature or repair per invocation. Prefer correctness to velocity. +- Complete one small, verifiable milestone at a time and continue while the IDE session and daily budget permit. - Produce real runnable code; use reproducible synthetic fixtures and test first where sensible. - Every nontrivial public API needs contract and misuse tests. Document decisions with ADRs. - Create scripts/verify.ps1 with REAL nontrivial checks. Never make it an always-success shim. @@ -21,5 +21,5 @@ You are working on ONE ORIGINAL implementation project inside the user's F: work - Commit only actual completed changes, with one logical purpose per commit. No empty/vanity commits. - Record test output and any honest limitations in docs/EVIDENCE.md. - If blocked, record why and what exact human action is necessary. -- Set PROJECT_STATE.json.status to review only if MVP works and verification passes. +- Set `PROJECT_STATE.json` status to `release_review` after the working MVP, required verification, and release materials are complete. Wait for explicit user acceptance before recording completion or advancing the queue. - End each invocation with a short summary: modified files, commits, tests, next task, blockers. diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..3702d16 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,12 @@ +# Changelog + +## 0.1.0 — Release candidate + +- Search UTF-8 text recursively for a case-sensitive literal. +- Inspect regular files and report their relative paths and byte sizes. +- Filter either command by repeatable suffixes and emit newline-delimited JSON. +- Return documented exit codes for matches, empty results, and failures. +- Build archives for Windows amd64, Linux amd64, and macOS arm64 with SHA-256 checksums and dependency notices. +- Keep Go sources in LF format during Git checkout so native Windows formatting verification sees the same source bytes as Linux and macOS. + +Native CI passed on Windows, Linux, and macOS. The packaging job uploaded all three target archives, and a Windows executable extracted from the verified hosted package passed a synthetic CLI smoke check. See `docs/RELEASE_EVIDENCE.md` in the source repository for the exact commit, verification coverage, and review items. diff --git a/PROJECT_STATE.json b/PROJECT_STATE.json index c891685..9e5e304 100644 --- a/PROJECT_STATE.json +++ b/PROJECT_STATE.json @@ -1,6 +1,15 @@ { - "next_action": "Create specification and first executable test", - "status": "in_progress", - "blocker": null, - "verified": false + "next_action": "Await explicit user acceptance of the A02 release review", + "status": "release_review", + "blocker": null, + "evidence": "docs/RELEASE_EVIDENCE.md", + "candidate_version": "0.1.0", + "verified_implementation_commit": "482ebacf9d2dcc940c1e6931652b49610dee797a", + "verified_release_source_commit": "1d41dcc0184a7fad5e09e1e7c9ee6cefc37dd930", + "verified_ci_run": 44523796632, + "verified_release_artifact": 14528472864, + "verified_release_sha256": "2261c04556de25eb3d793d1b1da5ebc716171ccf450ec944d841d20652ef7fa1", + "verified_windows": true, + "verified_hosted_linux_macos": true, + "verified": true } diff --git a/README.md b/README.md index 7b38647..302d07f 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,90 @@ # Developer CLI Toolkit -Reference: ripgrep — https://github.com/BurntSushi/ripgrep +`dct` searches workspace text for a literal and lists regular files with their byte sizes. Both commands produce sorted, relative paths and can emit newline-delimited JSON (NDJSON) for scripts. -Original MVP: Build a fast file-search and workspace-inspection CLI with filters, JSON output and error codes. +The original Go/Cobra implementation takes inspiration from the recursive search and file filters in [ripgrep](https://github.com/BurntSushi/ripgrep). `dct` includes hidden files, uses case-sensitive literal matching, and applies only explicit suffix filters. Its scope and performance goals are defined by the [v0.1 contract](docs/SPEC.md). -Proof: Cross-platform integration tests, binary packaging and sample workflows. +## Install the 0.1.0 candidate -See docs/TASKS.md for work items. +Use the `dct-packages` bundle from CI run `44523796632` at source commit `1d41dcc0184a7fad5e09e1e7c9ee6cefc37dd930`. GitHub listed November 26, 2026 at 13:27:23 CET as the download expiration. The outer archive, the three target ZIPs, and `SHA256SUMS.txt` are retained privately in `dist/hosted-44523796632/` in the original workspace. [Private artifact 14528472864](https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44523796632/artifacts/14528472864) +Compare the outer ZIP's SHA-256 with the digest in the release evidence. From the extracted bundle directory, compare `SHA256SUMS.txt` with the checked-in manifest and verify the three target ZIPs before choosing the archive for your platform. The candidate packages are unsigned. [Release evidence](docs/RELEASE_EVIDENCE.md) · [Pinned SHA-256 manifest](docs/RELEASE_SHA256SUMS.txt) + +| Target | Archive | Executable | +| --- | --- | --- | +| Windows amd64 | `dct-windows-amd64.zip` | `dct.exe` | +| Linux amd64 | `dct-linux-amd64.zip` | `dct` | +| macOS arm64 | `dct-darwin-arm64.zip` | `dct` | + +```powershell +Get-Content SHA256SUMS.txt | ForEach-Object { + $expected, $name = $_ -split '\s+', 2 + $actual = (Get-FileHash -LiteralPath $name -Algorithm SHA256).Hash + if ($actual -ine $expected) { throw "Checksum mismatch for $name" } +} +Expand-Archive -LiteralPath dct-windows-amd64.zip -DestinationPath dct-windows +.\dct-windows\dct.exe --version +``` + +On Linux, verify with `sha256sum -c SHA256SUMS.txt`. On macOS, use `shasum -a 256 -c SHA256SUMS.txt`. Extract the target ZIP, set its run permission with `chmod +x dct` if needed, and run `./dct --version`. The packaged executable runs without a local Go installation. + +## Build and verify + +Use Go 1.26 or newer. Use Go 1.27.4 to match the verified native CI and packaging toolchain. + +```powershell +powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/verify.ps1 +``` + +The verifier checks formatting, module integrity, vet, tests, and the native build. It writes `bin/dct.exe` on Windows and `bin/dct` on Linux and macOS. Use `pwsh -NoProfile -File scripts/verify.ps1` with PowerShell 7. + +Git checks out Go sources with LF endings on every platform so `gofmt` sees the same source bytes on Windows and Unix. + +## Usage + +```text +dct search [root] [--ext ]... [--json] +dct inspect [root] [--ext ]... [--json] +dct --help +dct --version +``` + +`root` defaults to the current directory. Put any flags before `--` when passing a literal or a path that starts with `-`. Repeat `--ext` to include files matching any supplied suffix. Suffixes are case-sensitive, start with a dot, and may contain multiple dots. + +Search emits one record per matching line and skips files containing NUL or invalid UTF-8. Inspect includes all regular files that pass the suffix filter. Both commands skip symlink entries and reject symlink roots. + +| Exit code | Meaning | +| --- | --- | +| 0 | Search found matches, or inspection succeeded. | +| 1 | Search completed with no matches. | +| 2 | Invalid invocation, filesystem failure, or output failure. Diagnostics go to stderr. | + +Check the exit code before treating output as complete. Errors may follow partial results. + +## Sample workflow + +In PowerShell from the project directory, create a synthetic workspace and run the built binary. + +```powershell +$demo = Join-Path (Get-Location).Path ('bin/dct-demo-' + [guid]::NewGuid().ToString('N')) +New-Item -ItemType Directory -Path $demo | Out-Null +[IO.File]::WriteAllBytes((Join-Path $demo 'notes.txt'), [Text.Encoding]::ASCII.GetBytes("TODO: review the change`n")) +.\bin\dct.exe search TODO $demo --ext .txt --json +# {"path":"notes.txt","line":1,"text":"TODO: review the change"} +.\bin\dct.exe inspect $demo --json +# {"path":"notes.txt","bytes":24} +``` + +Use NDJSON when paths or contents can contain output delimiters. Read it one line at a time and decode each record independently. + +## Packaging + +Run `pwsh -NoProfile -File scripts/package.ps1` with Go 1.27.4. On Windows PowerShell, use `powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/package.ps1`. A successful run creates a directory under `dist/` with ZIP archives for Linux amd64, Windows amd64, and macOS arm64, plus `SHA256SUMS.txt`. Verify each archive's SHA-256 before extraction. On a Unix host, run `chmod +x dct` if the extracted binary lacks the execute bit. + +The [CI workflow](.github/workflows/ci.yml) runs native integration tests and builds on Windows, Linux and macOS, and makes archive upload depend on those jobs. The [release evidence](docs/RELEASE_EVIDENCE.md) records the tested commit, checksum results, and what ran on each platform. + +## Architecture and limits + +`main.go` parses commands with Cobra, renders output and maps errors to exit codes. `workspace.go` scopes filesystem access to the opened directory, sorts relative paths, and checks each search file before matching its lines. Memory usage grows with the number of selected paths and the size of the largest searched file. Results describe a live filesystem, so keep the tree stable for reproducible output. On Unix, filenames with invalid UTF-8 bytes are represented with replacement characters in JSON. Search takes its literal and root from command arguments. Regex matching, stdin search, ignore-file rules and numeric performance targets are outside the 0.1.0 contract. + +See the [Persian tutorial](docs/LEARNING_FA.md), [technical article](docs/WEBSITE_EN.md), [design decisions](docs/adr/), [test evidence](docs/EVIDENCE.md), and [third-party notices](THIRD_PARTY_NOTICES.md). diff --git a/REVIEW_INDEX.md b/REVIEW_INDEX.md new file mode 100644 index 0000000..2d047e5 --- /dev/null +++ b/REVIEW_INDEX.md @@ -0,0 +1,25 @@ +# A02 Developer CLI Toolkit v0.1.0 review index + +A02 is in `release_review`. The implementation, tests, and review documents follow their repository paths in the review ZIP. Extract the whole archive into one directory and open this file to follow the relative links offline. + +## Documentation + +- [README](README.md) covers setup, installation, and command examples. +- [Changelog](CHANGELOG.md) describes the v0.1.0 changes. +- [Persian learning guide](docs/LEARNING_FA.md), [English portfolio article](docs/WEBSITE_EN.md), and [English Instagram copy](docs/INSTAGRAM_EN.md) are ready for content review. +- [Project state](PROJECT_STATE.json) records the release review status. [Project tasks](docs/TASKS.md) record the outstanding approval. + +## Implementation and verification + +- [CLI specification](docs/SPEC.md), [CLI contract decision](docs/adr/0001-cli-contract.md), and [workspace I/O decision](docs/adr/0002-workspace-io.md) explain the implemented behavior. +- [Command entry points](main.go) and [workspace traversal, search, and inspection](workspace.go) contain the implementation. +- [Search integration tests](search_test.go), [inspection and options integration tests](options_test.go), and [Windows sharing-violation test](search_windows_test.go) exercise the executable. +- [Test summary](docs/TEST_SUMMARY.md), [release evidence](docs/RELEASE_EVIDENCE.md), and [verification history](docs/EVIDENCE.md) record the checked results and their scope. +- [Local verifier](scripts/verify.ps1), [packaging script](scripts/package.ps1), and [GitHub Actions workflow](.github/workflows/ci.yml) define the runnable checks. +- [Release SHA-256 manifest](docs/RELEASE_SHA256SUMS.txt) lists the three distribution archive digests. [Third-party notices](THIRD_PARTY_NOTICES.md) identify their redistributed components. + +## Release candidate package + +The v0.1.0 binary candidate comes from run `44523796632` at `1d41dcc0184a7fad5e09e1e7c9ee6cefc37dd930` on `codex/a02`. The link to the artifact requires repository access and is subject to GitHub Actions retention. [Private candidate CI run](https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44523796632) · [Private candidate artifact 14528472864](https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44523796632/artifacts/14528472864) · [Private draft PR #1](https://github.com/soroushneyestani/developer-cli-toolkit/pull/1) + +In the extracted review ZIP, `artifacts/dct-packages.zip` is the preserved copy of the candidate artifact. Its outer digest is recorded in the [test summary](docs/TEST_SUMMARY.md). Extract it into a separate directory to see the three target ZIPs and their bundled checksum manifest. The review ZIP also includes `SOURCE_OVERVIEW.md`, `RELEASE_CHECKLIST.md`, `REVIEW_PACKAGE_CHANGES.md`, and saved CI metadata and verification output for offline review. diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md new file mode 100644 index 0000000..ddde81a --- /dev/null +++ b/THIRD_PARTY_NOTICES.md @@ -0,0 +1,10 @@ +# Third-party notices + +The command uses the Go standard library and runtime and these Go modules. Redistributed binaries should be accompanied by this notice and the license texts in `licenses/`. + +| Component | Version | License | +| --- | --- | --- | +| [Go runtime and standard library](https://github.com/golang/go/tree/go1.27.4) | 1.27.4 in packaged builds | [BSD 3-Clause](licenses/go.txt) | +| [Cobra](https://github.com/spf13/cobra/tree/v1.10.2) | 1.10.2 | [Apache 2.0](licenses/cobra.txt) | +| [pflag](https://github.com/spf13/pflag/tree/v1.0.9) | 1.0.9 | [BSD 3-Clause](licenses/pflag.txt) | +| [mousetrap](https://github.com/inconshreveable/mousetrap/tree/v1.1.0) | 1.1.0 | [Apache 2.0](licenses/mousetrap.txt) | diff --git a/docs/EVIDENCE.md b/docs/EVIDENCE.md index 6e47f29..243e073 100644 --- a/docs/EVIDENCE.md +++ b/docs/EVIDENCE.md @@ -1,4 +1,72 @@ -# Evidence +# Evidence -No tests or usage claims have been verified yet. +## 2026-11-15 — Initial contract and verification gate +Bounded task: define the original v0.1 interface and executable verification gate. +Read AGENTS.md, README.md, TASKS.md, EVIDENCE.md, PROJECT_STATE.json, git history/status, and all existing file paths. Baseline was clean at 1dbf562, with no code or unfinished implementation. + +Changes: docs/SPEC.md defines commands, filters, JSON schemas, error codes, safety rules, and synthetic cross-platform integration cases. ADR 0001 retains Go/Cobra. scripts/verify.ps1 requires source/tests and runs formatting, vet, tests, and native build once bootstrapped. + +Observed checks: +- PowerShell parser: PASS, no syntax errors in scripts/verify.ps1. +- PROJECT_STATE.json parsing: PASS; status in_progress, verified false. +- git diff --check: PASS (line-ending normalization warnings only). +- powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/verify.ps1: exit 1, expected diagnostic: Go is required on PATH. This verifies the missing-tool failure path only. +- pwsh -NoProfile -File scripts/verify.ps1: not run successfully; installed launcher cannot be accessed by the system. +- Go formatting/vet/tests/build, native integration, packaging: NOT RUN. No Go toolchain on PATH; no implementation/module exists yet. + +Exact next action: install Go with go and gofmt on PATH, reopen the shell, then implement the Go/Cobra literal-search slice and contract/misuse tests. Use Windows PowerShell to invoke verification if pwsh remains inaccessible. Tool installation was not attempted outside the authorized repository. + +Git ownership mismatch was handled using per-command safe.directory configuration scoped to this repository; no global configuration changed. No push or external target testing occurred. + +## 2026-11-15 - Bootstrap prerequisite recheck + +Attempted next task: Go/Cobra literal-search bootstrap. Read all required files, SPEC, ADR, verification script, history and status. Baseline was clean at 170dc70 with no unfinished implementation. + +- Get-Command found neither go nor gofmt on PATH. +- Windows PowerShell invocation of scripts/verify.ps1: exit 1, diagnostic: Go is required on PATH. Install Go, reopen the shell, and rerun scripts/verify.ps1. +- Formatting, vet, tests, native build, integration and packaging: NOT RUN; toolchain unavailable and no module exists. + +Human action: install Go with go and gofmt on PATH, reopen the shell and confirm go version and gofmt -h resolve. No installation outside the repository was attempted. Status remains in_progress; v0.1 is not runnable or verified. Existing substantive verification checks were preserved. + +## 2026-11-18 — Runnable CLI and Windows contract tests + +- Go and gofmt resolved on PATH. `go version` reported `go1.27.4 windows/amd64`. No install was required. The `pwsh` launcher remains inaccessible, so local script checks use Windows PowerShell. +- Added search and inspect, suffix filters, NDJSON, deterministic sorting, scoped read-only traversal, and the documented exit statuses. +- `go test -count=1 -v ./...` passed on Windows (3.608 s). File and directory symlink fixtures ran and passed. The POSIX chmod and colon/tab filename fixtures skipped with explicit reasons. +- `go test -mod=readonly -run '^TestSearchReportsWindowsSharingViolation$' -v` passed (1.902 s). A Windows sharing lock prevented reading a fixture. The process returned exit 2 with a diagnostic after emitting the prior match. +- `go vet -mod=readonly ./...` and `go build -mod=readonly -buildvcs=false -trimpath -o bin/dct.exe .` passed. The executable printed `dct version 0.1.0`. +- Cross-compilation, workflow lint and native Linux/macOS checks remain separate release evidence. + +## 2026-11-18 — Release packaging and verification + +- Windows PowerShell `scripts/verify.ps1` exited 0. Formatting, module integrity, vet, process-level contract tests and native build passed. The Go test package reported 4.961 s. The Windows sharing-violation test passed, and two POSIX-specific fixtures skipped. An isolated unformatted Go fixture caused the verifier to fail with exit 1. +- The README search and inspection examples passed on a synthetic workspace. +- `scripts/package.ps1` built CGO-disabled Linux amd64, Windows amd64 and macOS arm64 archives. Independently checked ZIP CRCs, SHA-256 digests, target binary headers, release notes and dependency notices. The extracted Windows binary produced the expected search result. Invalid build flags produced a nonzero exit and left prior release directories intact. +- Local archives: `dist/dct-20261118T114738Z-993774766c8e4d81bedd4c47b3feb139/`, with digests in `SHA256SUMS.txt`. +- `actionlint v1.7.12` found zero GitHub Actions workflow errors. ShellCheck and Pyflakes were unavailable. The workflow invokes checked-in PowerShell scripts. +- `govulncheck v1.10.0` exited 0 with no vulnerabilities found. `gitleaks v8.30.1` exited 0 with no leaks across four commits and the staged release changes. Scans ran locally against this repository. +- `go test -c -mod=readonly -buildvcs=false` compiled the Linux amd64 and macOS arm64 test binaries separately. +- Native Linux/macOS tests and hosted CI were not run. WSL access was denied in this session and the repository has no remote. An authorized private feature-branch matrix run or native Linux and macOS hosts are needed before release review. Cross-compilation demonstrates buildability for those targets. + +## 2026-11-18 — Native CI checkout consistency + +- The first [private hosted matrix](https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44305452488) passed on Linux and macOS. Windows reported all five Go sources as unformatted and packaging was skipped. +- A local index checkout with `core.autocrlf=true` reproduced the same five `gofmt` findings. After declaring LF checkout for Go files, the same fixture produced zero formatting findings. The native Windows verifier passed. +- The corrected hosted Windows and packaging jobs await the next feature-branch run. + +## 2026-11-19 — Release-review verification + +- GitHub returned a private Draft PR with head `482ebacf9d2dcc940c1e6931652b49610dee797a`. [Run 44307143679](https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44307143679) returned success for native Windows, Linux, macOS, and packaging. The Windows CRLF checkout blocker is resolved. +- The Windows-hosted delimiter and chmod-based unreadable-file fixtures skipped. The sharing-violation case accounts for Windows read-error coverage. The Linux dependency and history scanners completed successfully. +- Downloaded artifact `14428662773` and matched its reported SHA-256. All three target ZIP hashes matched `SHA256SUMS.txt`. ZIP CRCs, binary headers, build settings, and included notices passed. The executable payloads match the earlier local archives. +- Ran the hosted Windows package's executable from ignored local scratch against synthetic fixtures. Version, filtered search, inspection, no-match exit 1, and malformed suffix exit 2 matched their contracts. The README and education examples use verified outputs. +- Completed release review materials and recorded package and platform limits in [release evidence](RELEASE_EVIDENCE.md). +- The first synchronization preflight found that an educational `.go` fixture under a visible `bin/` subdirectory entered `go list ./...`. The tutorial now generates valid Go text under a dot-prefixed scratch directory. The revised example and the Windows verifier passed together. + +## 2026-11-19 — Release-evidence audit + +- Authenticated GitHub Actions evidence confirmed the successful native Windows, Linux, macOS, and packaging jobs for candidate source `1d41dcc0184a7fad5e09e1e7c9ee6cefc37dd930`. The Linux logs reported no vulnerabilities from `govulncheck` and no leaks from `gitleaks`. The two platform-specific Windows skips are recorded in the release evidence. [Private workflow run 44523796632](https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44523796632) +- The authenticated download for artifact `14528472864` matched the retained local outer archive byte for byte. SHA-256 and CRC verification passed for the outer ZIP and three target ZIPs. The retained manifest matches the outer ZIP member, and each target digest matches that manifest. The three candidate executable payloads match their historical equivalents byte for byte. +- Ran the Windows executable extracted from artifact `14528472864` against synthetic fixtures. It reported `dct version 0.1.0` and produced the expected README and Persian tutorial NDJSON with inspection sizes of 24 and 29 bytes. The no-match case returned 1 and the malformed suffix case returned 2. Linux and macOS archive payloads were checked for integrity and executable format. Native execution on those platforms was exercised by CI's native builds. +- The canonical artifact, retained local paths, and checksum manifest are now aligned for `release_review`. Final acceptance is pending. [Release evidence](RELEASE_EVIDENCE.md) · [Pinned manifest](RELEASE_SHA256SUMS.txt) diff --git a/docs/INSTAGRAM_EN.md b/docs/INSTAGRAM_EN.md new file mode 100644 index 0000000..2e3d1da --- /dev/null +++ b/docs/INSTAGRAM_EN.md @@ -0,0 +1,11 @@ +# Developer CLI Toolkit + +A script should be able to distinguish an empty search from a failed run. That requirement shaped `dct`, a Go and Cobra CLI I built for workspace automation. + +`dct search` finds literal text. `dct inspect` lists files with their byte sizes. Both support suffix filters, sorted relative paths, and newline-delimited JSON. I designed the exit codes so scripts can handle a match, an empty search, and an error explicitly. + +The release candidate passed native CI on Windows, Linux, and macOS. A separate packaging job built three platform archives and generated SHA-256 checksums. + +The engineering lesson was to treat the command line as an interface. Output, error messages, and exit codes all need a documented contract and tests. + +#GoLang #DeveloperTools #CLI #SoftwareEngineering #EngineeringMastery diff --git a/docs/LEARNING_FA.md b/docs/LEARNING_FA.md new file mode 100644 index 0000000..36b3144 --- /dev/null +++ b/docs/LEARNING_FA.md @@ -0,0 +1,140 @@ +# راهنمای فنی و آموزشی جعبه‌ابزار خط فرمان توسعه‌دهنده + +`dct` نسخهٔ `0.1.0` برای دو کار در یک پوشهٔ کاری ساخته شده است. با `search` می‌توان یک عبارت مشخص را در فایل‌های متنی پیدا کرد. با `inspect` می‌توان فهرستی مرتب از مسیر فایل‌ها و اندازهٔ آن‌ها به بایت گرفت. هر دو دستور می‌توانند نتیجه را برای خواندن در ترمینال یا پردازش در یک اسکریپت چاپ کنند. + +## در چه موقعیتی به کار می‌آید؟ + +- پیش از بازبینی یک تغییر، عبارت `TODO` را فقط در فایل‌هایی با پسوند `.go` و `.md` پیدا کنید. +- برای یک اسکریپت بررسی، مسیرهای نسبی و اندازهٔ فایل‌های عادی یک نمونهٔ محلی را به شکل رکوردهای JSON دریافت کنید. +- در یک گردش‌کار خودکار، با کد خروج تشخیص دهید که جست‌وجو نتیجه داشته، بدون نتیجه تمام شده یا به خطایی رسیده است. + +ایدهٔ پیمایش بازگشتی و فیلتر فایل از مطالعهٔ ripgrep آمده است. این پروژه قرارداد خط فرمان و پیاده‌سازی مستقل خودش را دارد. جزئیات رفتار در [قرارداد v0.1](SPEC.md) آمده است. + +## نصب از بستهٔ اجرایی + +| سیستم و معماری مقصد | نام بسته | فایل اجرایی | +| --- | --- | --- | +| Windows amd64 | `dct-windows-amd64.zip` | `dct.exe` | +| Linux amd64 | `dct-linux-amd64.zip` | `dct` | +| macOS arm64 | `dct-darwin-arm64.zip` | `dct` | + +از [شواهد انتشار](RELEASE_EVIDENCE.md) به خروجی خصوصی `dct-packages` در CI برسید. پس از استخراج فایل دریافتی از CI، سه ZIP هدف و `SHA256SUMS.txt` در دسترس‌اند. ابتدا بستهٔ سیستم خود را با مقدار متناظر در همان فایل مقایسه کنید. نمونهٔ زیر را در پوشه‌ای اجرا کنید که بسته و فایل checksum در آن قرار دارند. + +```powershell +$archive = 'dct-windows-amd64.zip' +$rows = @(Get-Content -LiteralPath SHA256SUMS.txt | Where-Object { + ($_ -split '\s+', 2)[1] -eq $archive +}) +if ($rows.Count -ne 1) { throw "Missing or ambiguous checksum for $archive" } +$expected = ($rows[0] -split '\s+', 2)[0] +$actual = (Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash +if ($actual -ne $expected) { throw "Checksum mismatch for $archive" } +Expand-Archive -LiteralPath $archive -DestinationPath dct-windows +.\dct-windows\dct.exe --version +``` + +وقتی هر سه بسته کنار فایل checksum باشند، در Linux از `sha256sum -c SHA256SUMS.txt` و در macOS از `shasum -a 256 -c SHA256SUMS.txt` می‌توان استفاده کرد. پس از تطبیق checksum، بستهٔ متناسب با دستگاه را استخراج کنید و `./dct --version` را اجرا کنید. اگر مجوز اجرا هنگام استخراج منتقل نشده بود، ابتدا `chmod +x dct` بزنید. فایل `THIRD_PARTY_NOTICES.md` و پوشهٔ `licenses/` همراه بسته نگه‌داری می‌شوند. + +خروجی نسخه به این شکل است. + +```text +dct version 0.1.0 +``` + +## ساخت از سورس + +در ریشهٔ مخزن پروژه، Go و `gofmt` باید در `PATH` باشند. حداقل نسخه در `go.mod` برابر `1.26.0` است و CI از `1.27.4` استفاده می‌کند. در PowerShell 7 دستور زیر آزمون‌ها را اجرا و باینری بومی را در `bin/dct.exe` روی Windows یا `bin/dct` روی Linux و macOS می‌سازد. + +```powershell +pwsh -NoProfile -File scripts/verify.ps1 +``` + +در Windows PowerShell نیز می‌توان از `powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/verify.ps1` استفاده کرد. برای ساخت سه بستهٔ هدف، `pwsh -NoProfile -File scripts/package.ps1` را با Go `1.27.4` اجرا کنید. هر اجرا در `dist/` یک پوشهٔ جداگانه برای بسته‌ها و `SHA256SUMS.txt` می‌سازد. + +## اجرای یک نمونهٔ قابل بازتولید + +از ریشهٔ مخزن، پس از ساخت باینری در Windows، یک پوشهٔ مصنوعی تازه بسازید. این نمونه از فایل‌هایی با پایان خط LF و CRLF استفاده می‌کند. نام پوشه با نقطه شروع می‌شود تا فایل نمونهٔ Go وارد اجرای `go list ./...` نشود. + +```powershell +$demo = Join-Path (Get-Location).Path ('bin/.dct-learning-' + [guid]::NewGuid().ToString('N')) +New-Item -ItemType Directory -Path (Join-Path $demo 'src') -Force | Out-Null +$utf8 = [Text.UTF8Encoding]::new($false) +[IO.File]::WriteAllText((Join-Path $demo 'notes.txt'), "TODO: review`n", $utf8) +[IO.File]::WriteAllText((Join-Path $demo 'src/build.go'), "package demo`r`n// TODO: TODO`r`n", $utf8) +[IO.File]::WriteAllText((Join-Path $demo 'src/example.md'), "TODO: omitted`n", $utf8) + +.\bin\dct.exe search TODO $demo --ext .txt --ext .go --json +.\bin\dct.exe inspect $demo --ext .go --json +``` + +خروجی مشاهده‌شدهٔ دستور اول دو رکورد است. فایل `.md` خارج از فیلتر است و تکرار `TODO` در یک خط همچنان یک رکورد تولید می‌کند. + +```json +{"path":"notes.txt","line":1,"text":"TODO: review"} +{"path":"src/build.go","line":2,"text":"// TODO: TODO"} +``` + +خروجی دستور دوم اندازهٔ فایل را به بایت گزارش می‌کند. اندازه شامل بایت‌های CRLF است، درحالی‌که جست‌وجو آن‌ها را از متن رکورد کنار می‌گذارد. + +```json +{"path":"src/build.go","bytes":29} +``` + +برای دیدن تفاوت «بدون نتیجه» و «خطا»، همان پوشه را نگه دارید و دو دستور زیر را اجرا کنید. + +```powershell +.\bin\dct.exe search NEVER_IN_DEMO $demo +$LASTEXITCODE # 1 +.\bin\dct.exe inspect $demo --ext txt +$LASTEXITCODE # 2 +``` + +جست‌وجوی بدون نتیجه خروجی ندارد. دستور دوم پیام `dct: invalid extension "txt": expected a dot-prefixed suffix without path separators` را در `stderr` می‌نویسد. این دو حالت در PowerShell با باینری موجود و دادهٔ مصنوعی بررسی شدند. + +## قرارداد خط فرمان + +```text +dct search [root] [--ext ]... [--json] +dct inspect [root] [--ext ]... [--json] +dct --help +dct --version +``` + +- اگر `root` حذف شود، پوشهٔ جاری استفاده می‌شود. ریشه باید پوشه باشد و symlink به عنوان ریشه رد می‌شود. ورودی محتوا از فایل‌های آن درخت خوانده می‌شود. انتخاب منبع از `stdin` در قرارداد این نسخه وجود ندارد. +- جست‌وجو برای متن ثابت، غیرخالی و UTF-8 است و به بزرگی و کوچکی حروف حساس است. اگر عبارت یا مسیر با `-` آغاز می‌شود، گزینه‌های دستور را پیش از `--` و آرگومان را بعد از آن بنویسید. برای مثال `dct search --json -- -debug .`. +- هر `--ext` باید با نقطه شروع شود و جداکنندهٔ مسیر نداشته باشد. فیلترها با منطق OR کار می‌کنند و تطبیق انتهای نام به حروف حساس است. پسوند ترکیبی مانند `.tar.gz` نیز معتبر است. +- خروجی متنی جست‌وجو `path:line:text` و خروجی متنی بازرسی `pathbytes` است. شمارهٔ خط از ۱ آغاز می‌شود. مسیرها نسبی، مرتب‌شده و با جداکنندهٔ `/` هستند. +- `--json` خروجی NDJSON می‌دهد. هر خط یک شیء مستقل است. جست‌وجو فیلدهای `path`، `line` و `text` و بازرسی فیلدهای `path` و `bytes` دارد. برای نام فایل یا متنی که جداکننده‌های خروجی متنی را در خود دارد، NDJSON راه روشن‌تری برای پردازش ماشینی است. + +| کد خروج | معنای عملی | +| ---: | --- | +| `0` | جست‌وجو حداقل یک تطبیق دارد یا بازرسی موفق است، حتی اگر پوشه خالی باشد. راهنما و نسخه نیز با این کد خارج می‌شوند. | +| `1` | جست‌وجو کامل شد و تطبیقی پیدا نشد. | +| `2` | آرگومان، ریشه، پیمایش، خواندن یا نوشتن خروجی به خطا رسیده است. پیام تشخیصی در `stderr` می‌آید. | + +ممکن است قبل از خطای خواندن یک فایل، نتیجهٔ فایل‌های قبلی به `stdout` رسیده باشد. در اسکریپت‌ها، پیش از پذیرش خروجی به‌عنوان نتیجهٔ کامل، کد خروج را بررسی کنید. + +## معماری و تصمیم‌های مهندسی + +1. [main.go](../main.go) با Cobra فرمان‌ها و گزینه‌ها را تعریف می‌کند. تابع `run` آرگومان و مقصدهای خروجی را می‌گیرد، ورودی را اعتبارسنجی می‌کند و نتیجهٔ لایهٔ فایل را به متن یا NDJSON تبدیل می‌کند. جدا بودن `stdout` و `stderr` قرارداد اجرای اسکریپتی را روشن می‌کند. +2. [workspace.go](../workspace.go) ریشه را بررسی و با `os.OpenRoot` باز می‌کند. پیمایش بازگشتی با `fs.WalkDir` انجام می‌شود. فایل‌های عادی پس از فیلترشدن بر اساس پسوند، با مسیر نسبی و مستقل از ترتیب بازگشت سیستم‌فایل مرتب می‌شوند. این مرتب‌سازی باعث می‌شود یک درخت ثابت خروجی قابل مقایسه‌ای بدهد. +3. موتور جست‌وجو یک فایل را کامل می‌خواند و پیش از انتشار هر نتیجه، وجود NUL و اعتبار UTF-8 آن را بررسی می‌کند. در نتیجه، حتی اگر بایت نامعتبر بعد از یک خطِ منطبق آمده باشد، از همان فایل رکوردی منتشر نمی‌شود. سپس خطوط LF، CRLF و خط پایانی بدون جداکننده را جدا و با `bytes.Contains` مقایسه می‌کند. +4. مسیر بازرسی از `Lstat` برای خواندن اندازه و نوع فایل استفاده می‌کند. بازرسی برای گزارش بایت‌ها محتوای فایل را باز نمی‌کند، بنابراین فایل عادیِ دارای دادهٔ دودویی نیز می‌تواند در فهرست ظاهر شود. + +Go برای دسترسی به فایل‌ها، UTF-8، JSON و آزمون فرایند ابزارهای استاندارد دارد. Cobra `1.10.2` بخش تعریف فرمان و اعتبارسنجی گزینه‌ها را بر عهده دارد. `go.mod` و `go.sum` نسخه‌ها و checksum وابستگی‌ها را ثبت می‌کنند. دلیل این انتخاب‌ها و موازنهٔ حافظه و صحت در [ADR 0001](adr/0001-cli-contract.md) و [ADR 0002](adr/0002-workspace-io.md) ثبت شده است. نسخه و مجوز اجزای ثالث در [اعلامیهٔ وابستگی‌ها](../THIRD_PARTY_NOTICES.md) آمده است. + +## روند ساخت و شواهد آزمون + +ابتدا دستورها، شکل خروجی و کدهای خروج در قرارداد تعریف شدند. سپس پیاده‌سازی جست‌وجو و بازرسی و آزمون‌های فرایندی اضافه شدند. مرحلهٔ بعد بسته‌بندی، گزارش checksum و ماتریس CI بود. در نخستین اجرای میزبان Windows، تبدیل خط‌پایان هنگام checkout باعث خطای `gofmt` شد. فایل `.gitattributes` اکنون سورس‌های Go را با LF نگه می‌دارد. اجرای بومی Windows، Linux و macOS و ساخت بسته‌ها در اجرای بعدی موفق بود. [اجرای موفق CI](https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44307143679) + +اسکریپت `scripts/verify.ps1` قالب فایل‌های Go، یکپارچگی ماژول‌ها، `go vet`، آزمون‌های Go و ساخت بومی را بررسی می‌کند. آزمون‌ها یک باینری واقعی می‌سازند، آن را روی فایل‌های مصنوعی با `os/exec` اجرا می‌کنند و `stdout`، `stderr` و کد خروج را جداگانه می‌سنجند. نمونه‌های آزمون شامل ترتیب مسیر، متن Unicode، خطوط بلند، پسوندهای تکرارشونده، فایل‌های دارای NUL، UTF-8 نامعتبر و آرگومان نامعتبر است. آزمون اختصاصی Windows با یک فایل قفل‌شده نشان می‌دهد که خطای خواندن پس از چاپ نتایج قبلی چگونه گزارش می‌شود. اگر میزبان امکانات لازم برای بعضی نمونه‌های نام فایل، مجوز یا ساخت symlink را نداشته باشد، آزمون با دلیل مشخص به‌صورت `SKIP` ثبت می‌شود. + +در CI، مرحلهٔ بسته‌بندی بعد از موفقیت هر سه اجرای بومی آغاز می‌شود. اسکریپت با `CGO_ENABLED=0` برای سه مقصد باینری می‌سازد، باینری و اعلامیه‌ها را در ZIP قرار می‌دهد و SHA-256 هر ZIP را ثبت می‌کند. کامپایل برای مقصدهای مختلف باینری قابل بسته‌بندی تولید می‌کند. شواهد اجرای بومی از آزمون‌هایی می‌آید که باینری را روی همان خانوادهٔ سیستم‌عامل ساخته و اجرا کرده‌اند. [شواهد آزمون](EVIDENCE.md) · [شواهد انتشار](RELEASE_EVIDENCE.md) + +## محدودیت‌ها و شیوهٔ استفادهٔ مطمئن + +- دامنهٔ نسخهٔ فعلی جست‌وجوی literal روی فایل UTF-8، فیلتر پسوند و فهرست متادیتاست. فایل‌های پنهان در پیمایش لحاظ می‌شوند و قواعد فایل‌های ignore به انتخاب فایل اعمال نمی‌شوند. برای کنترل دامنه، ریشه و پسوندها را صریح انتخاب کنید. +- برنامه فهرست مسیرهای انتخاب‌شده را در حافظه مرتب می‌کند و حداکثر محتوای یک فایل جست‌وجو را در هر مرحله پردازش می‌کند. به همین دلیل، تعداد مسیرها و اندازهٔ بزرگ‌ترین فایل روی مصرف حافظه اثر دارند. عددی به‌عنوان سرعت یا کارایی تضمین‌شده منتشر نشده است. +- درخت فایل زنده است. تغییر هم‌زمان فایل یا جایگزینی مسیر داخل ریشه می‌تواند نتیجه یا خطای خواندن را تغییر دهد. برای بازتولید خروجی، هنگام اجرا درخت را ثابت نگه دارید. +- در Unix، بایت نامعتبر UTF-8 در نام مسیر هنگام تولید JSON با نویسهٔ جایگزین نمایش داده می‌شود. NDJSON برای نام‌های عادی و دادهٔ ماشینی مناسب است و برای نگه‌داری نام‌های بایتی نامعتبر به‌صورت بدون اتلاف طراحی نشده است. +- checksum تطابق بایت‌های بسته با فهرست همان اجرا را می‌سنجد. شواهد اصالت به منبع قابل‌اعتماد بسته و اجرای CI وابسته‌اند. بسته‌های این نسخه در برابر manifest همان اجرا بررسی می‌شوند. diff --git a/docs/RELEASE_EVIDENCE.md b/docs/RELEASE_EVIDENCE.md new file mode 100644 index 0000000..7991ce4 --- /dev/null +++ b/docs/RELEASE_EVIDENCE.md @@ -0,0 +1,60 @@ +# A02 Developer CLI Toolkit release evidence + +## Candidate and source + +- Version `0.1.0`. The candidate archive was built from commit `1d41dcc0184a7fad5e09e1e7c9ee6cefc37dd930` on `codex/a02`. The pull request CI run started on November 19, 2026 at 13:25:48 CET and recorded success at 13:27:29 CET. [Private workflow run 44523796632](https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44523796632) +- Subsequent documentation-only CI runs verify their own source revisions. The candidate package remains pinned to run `44523796632` and artifact `14528472864` so readers can independently verify the exact archive reviewed here. +- The repository is private and the pull request targeting `main` is still Draft. [Draft pull request #1](https://github.com/soroushneyestani/developer-cli-toolkit/pull/1) + +## What was verified + +| Gate | Result and scope | +| --- | --- | +| Windows native `windows-2025` | Passed formatting, `go mod verify`, `go vet`, process-level integration tests, and build. The Windows filename-delimiter and chmod-based unreadable-file fixtures skipped. The Windows-specific sharing-violation test covers a read failure. | +| Linux native `ubuntu-24.04` | Passed formatting, module integrity, vet, integration tests, and build. The dependency and Git history scans ran in this job. | +| macOS native `macos-15` | Passed formatting, module integrity, vet, integration tests, and build. | +| Dependency and history scans | On Linux, `govulncheck v1.10.0` reported no vulnerabilities and `gitleaks v8.30.1` reported no leaks. Findings are scoped to the workflow's scans and commit. | +| Packaging | Passed and uploaded three target ZIPs with `SHA256SUMS.txt`. Go `1.27.4` used `CGO_ENABLED=0`, `-trimpath`, and `-buildvcs=false`. | +| Hosted artifact integrity | The downloaded outer ZIP matched GitHub's SHA-256 and passed its ZIP CRC check. All three target ZIPs passed CRC checks and matched the bundled manifest. The target executable headers, embedded build flags, candidate changelog, notices and licenses were checked. | +| Packaged Windows execution | The executable extracted from candidate artifact `14528472864` reported `dct version 0.1.0`. A no-match search returned 1 with empty stdout and stderr. A malformed suffix returned 2 with a diagnostic on stderr. | +| Documented examples | The packaged candidate Windows executable produced the documented README, Persian tutorial, and portfolio article NDJSON records. It reported inspection sizes of 24 and 29 bytes and passed the Persian repeated-suffix search across mixed LF and CRLF input. | + +The native integration tests build and run executables on their own runners. The separate package build produces the distribution archives. Linux and macOS archive payloads were checked for integrity and architecture during review. Direct execution of those extracted payloads was outside this verification. [Test history](EVIDENCE.md) · [CLI contract](SPEC.md) + +## Verified packages + +GitHub artifact `14528472864` is **8,982,978 bytes**. Its outer `dct-packages.zip` SHA-256 is `2261c04556de25eb3d793d1b1da5ebc716171ccf450ec944d841d20652ef7fa1`. GitHub listed expiration on November 26, 2026 at 13:27:23 CET (`2026-11-26T12:27:23Z`). [Private dct-packages artifact](https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44523796632/artifacts/14528472864) + +| ZIP | Bytes | Verified binary type | +| --- | ---: | --- | +| `dct-linux-amd64.zip` | 3,006,276 | ELF64 x86-64 | +| `dct-windows-amd64.zip` | 3,096,446 | PE32+ AMD64 | +| `dct-darwin-arm64.zip` | 2,888,079 | Mach-O 64-bit ARM64 | + +The verified outer ZIP, the three target ZIPs, and their original `SHA256SUMS.txt` are retained privately in `dist/hosted-44523796632/` in the original workspace. This copy remains available locally when the GitHub Actions download expires. The checked-in manifest records the three target ZIP digests for this artifact. [Pinned SHA-256 manifest](RELEASE_SHA256SUMS.txt) + +## Historical verification + +The implementation baseline is `482ebacf9d2dcc940c1e6931652b49610dee797a`. Its native matrix and package job passed on November 18, 2026 in run `44307143679`, resolving the Windows CRLF checkout blocker. The dependency and history scanners reported no vulnerabilities and no leaks in that run. [Private workflow run 44307143679](https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44307143679) + +Historical artifact `14428662773` is 8,982,494 bytes with outer SHA-256 `1630089350a96cc38169b634a7a5a5cf4ab8407c2b85f7cdf2c7df028b7c1d46`. Its listed expiration was November 25, 2026 at 13:49:02 CET. The corresponding local archives and manifest remain under `dist/hosted-44307143679/`. Each package set has its own ZIP digests. The three candidate executable payloads match the corresponding historical executable payloads byte for byte. [Historical private artifact](https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44307143679/artifacts/14428662773) + +## Reproduce the checks + +From the project directory with Go `1.27.4` and PowerShell 7 available, run the real verifier and packaging script as needed. + +```powershell +pwsh -NoProfile -File scripts/verify.ps1 +pwsh -NoProfile -File scripts/package.ps1 +``` + +To verify the candidate download or retained copy, check `dct-packages.zip` with `Get-FileHash -Algorithm SHA256` against the outer digest above. Extract the bundle and verify the three target ZIPs using the manifest for artifact `14528472864`. The packaging script creates a new archive set with its own manifest. [README verification and extraction steps](../README.md#install-the-010-candidate) + +## Release review items + +- Product scope is recursive, literal, case-sensitive UTF-8 search and regular-file inspection. Hidden entries follow normal selection. Regex, stdin input, ignore-file processing, and numeric performance targets are outside the candidate scope. +- The selected path list and a full search file affect memory use. Keep the live file tree stable for repeatable output. A read or write error can follow earlier results. Consumers should check the exit code before using all records as complete output. +- Unix JSON paths containing invalid UTF-8 use replacement characters. Linux and macOS archives may extract with mode `0644`; set the execute bit when needed. +- The packages are unsigned and include third-party notices and licenses. SHA-256 verifies package bytes against the pinned digests. Signing, public licensing and wider distribution remain separate review decisions. +- The project remains in `release_review` pending explicit user acceptance. Tagging `v0.1.0`, creating a private GitHub Release with the verified assets and checksums, and any PR merge require approval. [Draft pull request #1](https://github.com/soroushneyestani/developer-cli-toolkit/pull/1) +- The review includes the user documentation and release notes. [Persian tutorial](LEARNING_FA.md) · [English website article](WEBSITE_EN.md) · [English Instagram copy](INSTAGRAM_EN.md) · [Changelog](../CHANGELOG.md) diff --git a/docs/RELEASE_SHA256SUMS.txt b/docs/RELEASE_SHA256SUMS.txt new file mode 100644 index 0000000..78fe722 --- /dev/null +++ b/docs/RELEASE_SHA256SUMS.txt @@ -0,0 +1,3 @@ +f6a324433f7ab0e3c66f565e08fdb5c72b7933d13c2b2d05493cc31bbd131dc6 dct-linux-amd64.zip +87d0b52217a506bccce9647ecf5df7ffdf072a0714db4ec68427187172517de8 dct-windows-amd64.zip +a7a8a26fbfa557480396b9628f4c11c9446ad6584491d8565c1edf136333b84d dct-darwin-arm64.zip diff --git a/docs/SPEC.md b/docs/SPEC.md new file mode 100644 index 0000000..9086f0f --- /dev/null +++ b/docs/SPEC.md @@ -0,0 +1,36 @@ +# v0.1 contract and test plan + +Executable: `dct`, an original implementation inspired by ripgrep behavior, without source copying or compatibility promises. + +## Interface + +- `dct search [root]`: recursive, case-sensitive UTF-8 literal search. Root defaults to the current directory. Emit each matching line once. +- `dct inspect [root]`: recursively list regular files with relative paths and byte sizes. +- Both accept repeatable `--ext .go` (OR across exact case-sensitive suffixes) and `--json` (newline-delimited JSON). +- `--help` and `--version` succeed without traversing files. + +Use relative paths with `/` separators and lexicographic path ordering. Search line numbers start at 1. Support LF, CRLF, and unterminated final lines; exclude terminators from output. Reject empty literals, extra arguments, unknown flags, file roots, and extension filters lacking a leading dot or containing path separators. + +Include hidden files. Do not interpret ignore files or follow symlinks; reject symlink roots. Inspect only regular files. Search skips files containing NUL or invalid UTF-8. Process one file at a time. Traversal/read failures are errors, not silent nonmatches. + +## Output + +Search text: `path:line:text`. Inspect text: `pathbytes`. Text delimiters can be ambiguous in filenames; JSON is the machine interface. + +Search JSON fields: `path` (string), `line` (integer), `text` (string). Inspect JSON fields: `path` (string), `bytes` (integer). Emit diagnostics only to stderr. Empty results emit no records. + +Exit 0: search has matches, or inspection succeeds (including empty directories). Exit 1: completed search has no matches. Exit 2: usage, root, traversal, read, or output error. Partial results may precede errors; consumers must check exit status. An empty root argument is invalid. On Unix, NDJSON represents any invalid UTF-8 in filenames with replacement characters. + +## Integration proof + +Build and invoke the binary using Go os/exec and synthetic temporary fixtures, without shell-specific commands. Assert stdout, stderr, and exit status separately. + +1. Search: nested files, repeated matches on one line, case sensitivity, Unicode, CRLF, unterminated lines, no matches, deterministic order. +2. Filters and misuse: repeated extensions, excluded files, malformed filters, empty literals, unknown commands/flags, extra arguments, nonexistent and file roots. +3. Inspect: nested/empty directories, byte sizes, hidden files, spaces and delimiters in filenames, JSON escaping. +4. Safety: local symlinks, NUL files, invalid UTF-8, unreadable files. Explicitly skip permission/symlink tests with a reason when the host cannot enforce/create fixtures. Never test external targets. +5. Packaging: CGO-disabled Linux amd64, Windows amd64, macOS arm64 builds. Cross-compilation proves buildability only; run integration tests natively on all three OS families before release. + +## Implementation order + +Cobra skeleton and literal search with contract/misuse tests; extension filters; JSON; inspection; packaging and native CI. Performance benchmarking follows correctness; there is no numeric speed promise for v0.1. diff --git a/docs/TASKS.md b/docs/TASKS.md index ffb81b1..d6f8362 100644 --- a/docs/TASKS.md +++ b/docs/TASKS.md @@ -1,6 +1,17 @@ -# Tasks -- [ ] Design and implement: Build a fast file-search and workspace-inspection CLI with filters, JSON output and error codes. -- [ ] Prove: Cross-platform integration tests, binary packaging and sample workflows. -- [ ] Create real scripts/verify.ps1 and CI -- [ ] Document release candidate and limitations +# Tasks +- [x] Define original v0.1 contract, stack ADR, and integration test matrix. +- [x] Add verification script with explicit prerequisites and substantive Go checks. +- [x] Bootstrap Go/Cobra and literal search with contract and misuse tests. +- [x] Add extension filters and JSON with tests. +- [x] Add workspace inspection with tests. +- [x] Package binaries and add a native Windows/Linux/macOS CI matrix. +- [x] Document runnable sample workflows, release candidate, and limitations. +- [x] Run the native Linux and macOS jobs and record their results before release review. +- [x] Verify the fixed Windows checkout and the complete hosted packaging pipeline. +- [x] Check hosted package integrity and execute the packaged Windows smoke fixture. +- [x] Finish the README, changelog, Persian education, English website and Instagram copy, and release evidence. +- [x] Reconcile the release evidence with CI run `44523796632`, artifact `14528472864`, and the retained private archive and manifest. +- [ ] Obtain explicit user acceptance of the A02 release review. + +The corrected hosted Windows checkout and the entire native matrix and packaging pipeline passed. The project remains in `release_review`. Tagging `v0.1.0` and creating a private release require explicit user approval. [Release evidence](RELEASE_EVIDENCE.md) diff --git a/docs/TEST_SUMMARY.md b/docs/TEST_SUMMARY.md new file mode 100644 index 0000000..618e2c2 --- /dev/null +++ b/docs/TEST_SUMMARY.md @@ -0,0 +1,46 @@ +# A02 v0.1.0 test summary + +The binary candidate was built and verified at `1d41dcc0184a7fad5e09e1e7c9ee6cefc37dd930` on `codex/a02`. All three native verification jobs and the subsequent packaging job passed. The candidate is pinned to this run and artifact for release review. [Private candidate CI run 44523796632](https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44523796632) · [Private artifact 14528472864](https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44523796632/artifacts/14528472864) + +## Native verification + +| GitHub Actions runner | Result | Distribution package and binary type | +| --- | --- | --- | +| Windows `windows-2025` | Passed formatting, module integrity, vet, process-level integration tests, and native build. | Windows amd64, PE32+ AMD64 | +| Linux `ubuntu-24.04` | Passed the same native checks and the Linux-only dependency and Git history scans. | Linux amd64, ELF64 x86-64 | +| macOS `macos-15` | Passed formatting, module integrity, vet, process-level integration tests, and native build. | macOS arm64, Mach-O 64-bit ARM64 | + +The native tests compile and run the CLI against synthetic fixtures. They cover deterministic ordering, NDJSON, repeated suffix filters, Unicode and line endings, long lines, binary and invalid UTF-8 text handling, malformed arguments, symlinks, and read-error behavior. The candidate Windows log shows two fixture skips, `inspect_JSON_escapes_filename_delimiters` and `unreadable_file_is_an_error`, due to Windows filename restrictions and the permissions available to the test. The Windows sharing-violation test passed and exercises a read failure on Windows. The reviewed Linux and macOS verification logs showed no test skip lines. [Search tests](../search_test.go) · [Inspection and options tests](../options_test.go) · [Windows sharing-violation test](../search_windows_test.go) + +The candidate Linux scan steps finished successfully using `govulncheck v1.10.0` and `gitleaks v8.30.1`. These are scoped to the workflow's dependency and checked-out Git history checks. [CI workflow](../.github/workflows/ci.yml) + +## Verified candidate artifact + +The retained `dct-packages.zip` for artifact `14528472864` is 8,982,978 bytes. Its SHA-256 is `2261c04556de25eb3d793d1b1da5ebc716171ccf450ec944d841d20652ef7fa1`. The outer ZIP and all three inner ZIPs passed CRC checks. Every inner ZIP matched the bundled `SHA256SUMS.txt`, whose SHA-256 is `032ce1fe00289796f0f1b831b62c3c987e816e97d93b00589f918638daea0afa`. The archives include executables, release notes, and third-party notices and licenses. [Pinned checksum manifest](RELEASE_SHA256SUMS.txt) · [Release evidence](RELEASE_EVIDENCE.md) + +| Target ZIP | Bytes | SHA-256 | +| --- | ---: | --- | +| `dct-windows-amd64.zip` | 3,096,446 | `87d0b52217a506bccce9647ecf5df7ffdf072a0714db4ec68427187172517de8` | +| `dct-linux-amd64.zip` | 3,006,276 | `f6a324433f7ab0e3c66f565e08fdb5c72b7933d13c2b2d05493cc31bbd131dc6` | +| `dct-darwin-arm64.zip` | 2,888,079 | `a7a8a26fbfa557480396b9628f4c11c9446ad6584491d8565c1edf136333b84d` | + +Local review used the retained private copy in `dist/hosted-44523796632/`. The extracted review package carries the same artifact bytes in `artifacts/dct-packages.zip`. + +The Windows executable was extracted directly from the verified candidate archive. It reported `dct version 0.1.0`, reproduced the README's filtered search NDJSON and 24-byte inspection, matched the Persian guide's ordered search NDJSON and 29-byte inspection, and produced the portfolio article's search record. A no-match search returned exit 1 with empty stdout. A malformed suffix returned exit 2 with a diagnostic on stderr. [README examples](../README.md) · [Persian guide](LEARNING_FA.md) · [Portfolio article](WEBSITE_EN.md) + +The Linux and macOS distribution executables were checked for archive integrity and target architecture. Direct execution of those extracted distribution executables remains outside this review. Native CLI execution on both platforms was covered by the integration tests. + +## Historical verification + +Run `44307143679` at implementation checkpoint `482ebacf9d2dcc940c1e6931652b49610dee797a` passed the same runner matrix and packaging. The historical Windows archive's executable passed a separate smoke test. The executable payloads in the candidate and historical packages were compared byte for byte and matched for all three targets. [Historical CI run 44307143679](https://github.com/soroushneyestani/developer-cli-toolkit/actions/runs/44307143679) · [Verification history](EVIDENCE.md) + +Historical artifact `14428662773` had outer SHA-256 `1630089350a96cc38169b634a7a5a5cf4ab8407c2b85f7cdf2c7df028b7c1d46`. Its ZIP digests apply to that artifact only. + +## Outstanding limitations + +- Search is literal, case-sensitive, and operates on UTF-8 text. Hidden entries participate in selection. Regex, stdin input, and ignore-file processing are outside v0.1.0. +- Memory grows with the selected path list and the largest search file. Filesystem changes during execution can affect results. A read or write error can leave earlier records on stdout before exit 2. +- Unix paths containing invalid UTF-8 use replacement characters in JSON. Linux and macOS executables may require `chmod +x dct` after extraction. +- Evidence covers the listed runner and package targets. The review contains no measured performance targets or package signing. + +See the [CLI specification](SPEC.md) for the complete command and exit-status contract. diff --git a/docs/WEBSITE_EN.md b/docs/WEBSITE_EN.md new file mode 100644 index 0000000..420c21e --- /dev/null +++ b/docs/WEBSITE_EN.md @@ -0,0 +1,35 @@ +# Developer CLI Toolkit + +A workspace command should tell a script when to continue, when a search finished empty, and when to stop after an error. I built Developer CLI Toolkit around that requirement. Its command, `dct`, searches UTF-8 text and inventories regular files through a small Go and Cobra interface. + +## Using the toolkit + +`dct search` finds a case-sensitive literal recursively and emits each matching line once. `dct inspect` lists regular files and their sizes in bytes. Both commands default to the current directory, accept repeatable `--ext` suffix filters, and can emit newline-delimited JSON with `--json`. A file passes the filter if its name ends in any supplied suffix in a case-sensitive comparison. + +That makes the tool useful for finding `TODO` markers before a review, checking the contents of a handoff directory, or feeding a file inventory into a reporting script. For example, with `TODO: review the change` on the first line of `demo/notes.txt`, this command emits one record. + +```sh +dct search TODO demo --ext .txt --json +``` + +```json +{"path":"notes.txt","line":1,"text":"TODO: review the change"} +``` + +Search records contain `path`, `line`, and `text`. Inspection records contain `path` and `bytes`. Exit code `0` means a search found results or an inspection completed. Exit code `1` means a search completed without a match. Exit code `2` covers invalid input and runtime errors. Diagnostics go to standard error. A script should check the exit code before treating output as complete because a read error can occur after earlier results have been emitted. + +## Design decisions + +Cobra parses commands and flags in `main.go`, where text and JSON output are also formatted. The workspace layer in `workspace.go` opens the requested directory using Go's `os.OpenRoot`, enumerates matching regular files, and sorts their relative paths. Paths use forward slashes on each platform. Enumeration includes qualifying hidden files and files listed in ignore rules, skips symbolic-link entries, and applies the requested suffix filters. The command rejects a symbolic link supplied as the root. + +Search reads one file at a time and validates its whole contents before emitting matches from that file. This matters when a file appears to contain a valid match before an invalid UTF-8 sequence or a NUL byte. The file is skipped in either case. Search handles LF, CRLF, and an unterminated final line. Inspection reads metadata for byte sizes, with no need to open file contents. + +The selected paths remain in memory for sorting, and whole-file validation uses memory proportional to the largest file read during the search. A stable workspace gives reproducible results because the filesystem stays live during a scan. Newline-delimited JSON preserves record boundaries when names or matched text contain delimiters. On Unix, filenames containing invalid UTF-8 bytes are represented with replacement characters in JSON. + +## Verification and packaging + +The release candidate passed native CI on Windows, Linux, and macOS. Integration tests build and invoke the executable against synthetic workspaces, checking standard output, standard error, and exit status separately. The cases cover deterministic ordering, long lines, Unicode, malformed usage, and file handling. Some permission and filename fixtures depend on host capabilities. A Windows-specific test uses a sharing lock to exercise partial output followed by a read error. + +The first hosted Windows run exposed a Git checkout issue. CRLF conversion made the Go source files appear unformatted to `gofmt`. I set a repository attribute to keep Go source checkouts in LF, then verified the corrected native matrix. + +After the native jobs passed, a separate packaging job built ZIP archives for Windows amd64, Linux amd64, and macOS arm64. Each archive includes the executable and dependency notices. The job also generates a SHA-256 manifest for checking the ZIPs before extraction. The native results cover executables built for the tests, and the packaging job records which archives were produced. diff --git a/docs/adr/0001-cli-contract.md b/docs/adr/0001-cli-contract.md new file mode 100644 index 0000000..bd2afbd --- /dev/null +++ b/docs/adr/0001-cli-contract.md @@ -0,0 +1,9 @@ +# ADR 0001: Go/Cobra and deterministic literal search + +Status: accepted + +Retain the preferred Go/Cobra stack. Separate traversal/matching from command parsing to support unit tests and process-level contract tests. Pin Go and Cobra versions when bootstrapping go.mod, and commit go.sum with dependencies. + +Start with literal UTF-8 search and sequential processing, sorting paths for reproducible output. Sorting consumes memory proportional to discovered paths. Regex, ignore-file compatibility, and parallelism are deferred. No ripgrep performance parity is claimed. + +Use standard Go testing and synthetic temporary fixtures. The module requires Go 1.26.0 or newer and pins Cobra 1.10.2. Windows checks use Go 1.27.4. diff --git a/docs/adr/0002-workspace-io.md b/docs/adr/0002-workspace-io.md new file mode 100644 index 0000000..6b1656a --- /dev/null +++ b/docs/adr/0002-workspace-io.md @@ -0,0 +1,9 @@ +# ADR 0002: Scoped filesystem reads and complete-file validation + +Status: accepted + +`dct` checks that the supplied root is a directory and rejects a symbolic link at that path. It opens the directory with `os.OpenRoot` to constrain descendant operations to the opened tree. The filesystem walk skips symlink entries and sorts all selected, slash-separated paths because recursive directory order can differ from relative path order. + +Search reads and validates one complete file before emitting its matches. A file can contain a matching line before its first NUL or invalid UTF-8 byte. Emitting matches before validation would include records from files the contract requires the command to skip. Complete-file reads trade memory proportional to the largest file for a single read per path, complete binary-file detection, and no fixed line length. A two-pass design would lower memory use and require repeated I/O and consistency checks between passes. + +Inspection reads metadata and leaves file contents unopened. Enumeration and reading observe live filesystem state. A concurrent replacement can change which in-root file a path resolves to after enumeration. Keep the input tree stable for a consistent result. diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..f32694f --- /dev/null +++ b/go.mod @@ -0,0 +1,10 @@ +module example.com/engineering-mastery/developer-cli-toolkit + +go 1.26.0 + +require github.com/spf13/cobra v1.10.2 + +require ( + github.com/inconshreveable/mousetrap v1.1.0 // indirect + github.com/spf13/pflag v1.0.9 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..a6ee3e0 --- /dev/null +++ b/go.sum @@ -0,0 +1,10 @@ +github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= +github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= +github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY= +github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/licenses/cobra.txt b/licenses/cobra.txt new file mode 100644 index 0000000..298f0e2 --- /dev/null +++ b/licenses/cobra.txt @@ -0,0 +1,174 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. diff --git a/licenses/go.txt b/licenses/go.txt new file mode 100644 index 0000000..2a7cf70 --- /dev/null +++ b/licenses/go.txt @@ -0,0 +1,27 @@ +Copyright 2009 The Go Authors. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google LLC nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/licenses/mousetrap.txt b/licenses/mousetrap.txt new file mode 100644 index 0000000..5f920e9 --- /dev/null +++ b/licenses/mousetrap.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2022 Alan Shreve (@inconshreveable) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/licenses/pflag.txt b/licenses/pflag.txt new file mode 100644 index 0000000..63ed1cf --- /dev/null +++ b/licenses/pflag.txt @@ -0,0 +1,28 @@ +Copyright (c) 2012 Alex Ogier. All rights reserved. +Copyright (c) 2012 The Go Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/main.go b/main.go new file mode 100644 index 0000000..dc655f7 --- /dev/null +++ b/main.go @@ -0,0 +1,122 @@ +package main + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "os" + "strings" + "unicode/utf8" + + "github.com/spf13/cobra" +) + +const version = "0.1.0" + +func main() { + os.Exit(run(os.Args[1:], os.Stdout, os.Stderr)) +} + +func run(args []string, stdout, stderr io.Writer) int { + exitCode := 0 + var extensions []string + var asJSON bool + root := &cobra.Command{ + Use: "dct", + Short: "Search text and inspect workspace files", + Version: version, + Args: cobra.NoArgs, + SilenceErrors: true, + SilenceUsage: true, + RunE: func(cmd *cobra.Command, _ []string) error { return cmd.Help() }, + } + root.CompletionOptions.DisableDefaultCmd = true + root.SetArgs(args) + root.SetOut(stdout) + root.SetErr(stderr) + + search := &cobra.Command{ + Use: "search [root]", + Short: "Find a case-sensitive literal in UTF-8 text files", + Args: cobra.RangeArgs(1, 2), + RunE: func(_ *cobra.Command, args []string) error { + if args[0] == "" || !utf8.ValidString(args[0]) { + return errors.New("search requires a nonempty UTF-8 literal") + } + workspace, err := openWorkspace(args[1:], extensions) + if err != nil { + return err + } + defer workspace.Close() + files, err := listFiles(workspace, extensions) + if err != nil { + return err + } + encoder := json.NewEncoder(stdout) + found, err := searchFiles(workspace, files, []byte(args[0]), func(match searchMatch) error { + if asJSON { + return encoder.Encode(match) + } + _, err := fmt.Fprintf(stdout, "%s:%d:%s\n", match.Path, match.Line, match.Text) + return err + }) + if !found { + exitCode = 1 + } + return err + }, + } + + inspect := &cobra.Command{ + Use: "inspect [root]", + Short: "List regular workspace files and their byte sizes", + Args: cobra.MaximumNArgs(1), + RunE: func(_ *cobra.Command, args []string) error { + workspace, err := openWorkspace(args, extensions) + if err != nil { + return err + } + defer workspace.Close() + files, err := listFiles(workspace, extensions) + if err != nil { + return err + } + encoder := json.NewEncoder(stdout) + return inspectFiles(workspace, files, func(file fileSize) error { + if asJSON { + return encoder.Encode(file) + } + _, err := fmt.Fprintf(stdout, "%s\t%d\n", file.Path, file.Bytes) + return err + }) + }, + } + + for _, command := range []*cobra.Command{search, inspect} { + command.Flags().StringArrayVar(&extensions, "ext", nil, "include files ending with this suffix (repeatable)") + command.Flags().BoolVar(&asJSON, "json", false, "emit newline-delimited JSON") + root.AddCommand(command) + } + if err := root.Execute(); err != nil { + fmt.Fprintf(stderr, "dct: %v\n", err) + return 2 + } + return exitCode +} + +func openWorkspace(roots, extensions []string) (*os.Root, error) { + for _, extension := range extensions { + if !strings.HasPrefix(extension, ".") || strings.ContainsAny(extension, `/\`) { + return nil, fmt.Errorf("invalid extension %q: expected a dot-prefixed suffix without path separators", extension) + } + } + root := "." + if len(roots) > 0 { + root = roots[0] + if root == "" { + return nil, errors.New("root must be a directory path") + } + } + return openDirectory(root) +} diff --git a/options_test.go b/options_test.go new file mode 100644 index 0000000..a642e2f --- /dev/null +++ b/options_test.go @@ -0,0 +1,140 @@ +package main + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "reflect" + "runtime" + "strings" + "testing" +) + +func TestInspectAndOptionsCLI(t *testing.T) { + binary := buildCLI(t) + + t.Run("search extension filters and JSON", func(t *testing.T) { + root := t.TempDir() + writeFixture(t, root, ".hidden.go", "needle \"quoted\"\t\n") + writeFixture(t, root, "dir name/file.txt", "first\r\nneedle café\r\n") + writeFixture(t, root, "uppercase.GO", "needle excluded\n") + writeFixture(t, root, "suffix.go.bak", "needle excluded\n") + writeFixture(t, root, "archive.tar.gz", "needle compound suffix\n") + + result := runCLI(t, binary, root, "search", "needle", root, + "--ext", ".go", "--ext", ".txt", "--ext", ".go", "--json") + assertCLIJSON(t, result, + map[string]any{"path": ".hidden.go", "line": float64(1), "text": "needle \"quoted\"\t"}, + map[string]any{"path": "dir name/file.txt", "line": float64(2), "text": "needle café"}, + ) + + result = runCLI(t, binary, root, "search", "needle", "--ext", ".tar.gz") + assertCLI(t, result, 0, "archive.tar.gz:1:needle compound suffix\n", false) + result = runCLI(t, binary, root, "search", "needle", "--ext", ".md", "--json") + assertCLI(t, result, 1, "", false) + }) + + t.Run("malformed options on either command", func(t *testing.T) { + root := t.TempDir() + for _, filter := range []string{"go", "", ".go/sub", `.go\sub`} { + t.Run(fmt.Sprintf("extension %q", filter), func(t *testing.T) { + result := runCLI(t, binary, root, "search", "needle", "--ext", filter) + assertCLI(t, result, 2, "", true) + result = runCLI(t, binary, root, "inspect", "--ext", filter) + assertCLI(t, result, 2, "", true) + }) + } + result := runCLI(t, binary, root, "inspect", "--ext") + assertCLI(t, result, 2, "", true) + }) + + t.Run("inspect relative names and byte sizes", func(t *testing.T) { + root := t.TempDir() + const hidden = "\x00\xff" + const nested = "café\r\n" + writeFixture(t, root, ".hidden.dat", hidden) + writeFixture(t, root, "dir name/nested.txt", nested) + writeFixture(t, root, "dir name/zero.txt", "") + if err := os.Mkdir(filepath.Join(root, "empty"), 0o700); err != nil { + t.Fatalf("create empty directory: %v", err) + } + + result := runCLI(t, binary, root, "inspect") + assertCLI(t, result, 0, fmt.Sprintf(".hidden.dat\t%d\ndir name/nested.txt\t%d\ndir name/zero.txt\t0\n", len(hidden), len(nested)), false) + + result = runCLI(t, binary, root, "inspect", root, "--ext", ".txt", "--json") + assertCLIJSON(t, result, + map[string]any{"path": "dir name/nested.txt", "bytes": float64(len(nested))}, + map[string]any{"path": "dir name/zero.txt", "bytes": float64(0)}, + ) + result = runCLI(t, binary, root, "inspect", filepath.Join(root, "empty"), "--json") + assertCLI(t, result, 0, "", false) + }) + + t.Run("inspect JSON escapes filename delimiters", func(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("Windows filenames cannot contain colons or tabs") + } + root := t.TempDir() + const name = "colon:tab\t.txt" + writeFixture(t, root, name, "x") + result := runCLI(t, binary, root, "inspect", "--json") + assertCLIJSON(t, result, map[string]any{"path": name, "bytes": float64(1)}) + }) + + t.Run("inspect excludes links", func(t *testing.T) { + root := t.TempDir() + file := writeFixture(t, root, "real.txt", "abc") + if err := os.Symlink(file, filepath.Join(root, "linked.txt")); err != nil { + t.Skipf("cannot create file symlink on this host: %v", err) + } + result := runCLI(t, binary, root, "inspect") + assertCLI(t, result, 0, "real.txt\t3\n", false) + }) + + t.Run("inspect misuse", func(t *testing.T) { + root := t.TempDir() + file := writeFixture(t, root, "file.txt", "x") + cases := []struct { + name string + args []string + }{ + {"unknown flag", []string{"inspect", "--unrecognized"}}, + {"extra argument", []string{"inspect", root, "extra"}}, + {"missing root", []string{"inspect", filepath.Join(root, "missing")}}, + {"file root", []string{"inspect", file}}, + } + for _, test := range cases { + t.Run(test.name, func(t *testing.T) { + result := runCLI(t, binary, root, test.args...) + assertCLI(t, result, 2, "", true) + }) + } + }) +} + +func assertCLIJSON(t *testing.T, result cliResult, want ...map[string]any) { + t.Helper() + if result.exit != 0 || result.stderr != "" { + t.Errorf("exit %d, stderr %q; want exit 0 and empty stderr", result.exit, result.stderr) + } + output, terminated := strings.CutSuffix(result.stdout, "\n") + if !terminated { + t.Fatalf("JSON output lacks its final newline: %q", result.stdout) + } + lines := strings.Split(output, "\n") + if len(lines) != len(want) { + t.Fatalf("got %d JSON records, want %d (stdout %q)", len(lines), len(want), result.stdout) + } + for i, line := range lines { + var got map[string]any + if err := json.Unmarshal([]byte(line), &got); err != nil { + t.Errorf("JSON record %d: %v", i+1, err) + continue + } + if !reflect.DeepEqual(got, want[i]) { + t.Errorf("JSON record %d: got %#v, want %#v", i+1, got, want[i]) + } + } +} diff --git a/scripts/package.ps1 b/scripts/package.ps1 new file mode 100644 index 0000000..ca5a57a --- /dev/null +++ b/scripts/package.ps1 @@ -0,0 +1,79 @@ +[CmdletBinding()] +param() + +$ErrorActionPreference = 'Stop' +Set-StrictMode -Version Latest + +if (-not (Get-Command go -CommandType Application -ErrorAction SilentlyContinue)) { + throw 'Go is required on PATH to build the packages.' +} + +$projectRoot = Split-Path -Parent $PSScriptRoot +$dist = Join-Path $projectRoot 'dist' +if (Test-Path -LiteralPath $dist) { + $distItem = Get-Item -LiteralPath $dist -Force + if (-not $distItem.PSIsContainer -or ($distItem.Attributes -band [IO.FileAttributes]::ReparsePoint)) { + throw 'dist must be a local directory.' + } +} + +$targets = @( + @{ OS = 'linux'; Arch = 'amd64'; Binary = 'dct'; Archive = 'dct-linux-amd64.zip' } + @{ OS = 'windows'; Arch = 'amd64'; Binary = 'dct.exe'; Archive = 'dct-windows-amd64.zip' } + @{ OS = 'darwin'; Arch = 'arm64'; Binary = 'dct'; Archive = 'dct-darwin-arm64.zip' } +) +$runId = '{0}-{1}' -f [DateTime]::UtcNow.ToString('yyyyMMddTHHmmssZ'), [Guid]::NewGuid().ToString('N') +$staging = Join-Path $dist ".staging-$runId" +$destination = Join-Path $dist "dct-$runId" +$checksumsName = 'SHA256SUMS.txt' + +$requiredNotices = @('THIRD_PARTY_NOTICES.md', 'licenses') +$notices = @($requiredNotices | ForEach-Object { + $source = Join-Path $projectRoot $_ + if (-not (Test-Path -LiteralPath $source)) { throw "Required package content is missing: $_" } + $source +}) +$notices += @('CHANGELOG.md', 'LICENSE' | ForEach-Object { + $source = Join-Path $projectRoot $_ + if (Test-Path -LiteralPath $source -PathType Leaf) { $source } +}) + +$savedEnvironment = @{} +foreach ($name in 'GOOS', 'GOARCH', 'CGO_ENABLED') { + $savedEnvironment[$name] = [Environment]::GetEnvironmentVariable($name, 'Process') +} + +Push-Location $projectRoot +try { + [void][IO.Directory]::CreateDirectory($staging) + $env:CGO_ENABLED = '0' + $checksums = foreach ($target in $targets) { + $archivePath = Join-Path $staging $target.Archive + $binaryPath = Join-Path $staging $target.Binary + $env:GOOS = $target.OS + $env:GOARCH = $target.Arch + + & go build -mod=readonly -trimpath -buildvcs=false -o $binaryPath . + if ($LASTEXITCODE -ne 0) { throw "Build failed for $($target.OS)/$($target.Arch)." } + Compress-Archive -LiteralPath (@($binaryPath) + $notices) -DestinationPath $archivePath + [IO.File]::Delete($binaryPath) + + $hash = (Get-FileHash -LiteralPath $archivePath -Algorithm SHA256).Hash.ToLowerInvariant() + "$hash $($target.Archive)" + } + [IO.File]::WriteAllText((Join-Path $staging $checksumsName), (($checksums -join "`n") + "`n")) + [IO.Directory]::Move($staging, $destination) + Write-Output "Packages and SHA-256 checksums: $destination" +} finally { + foreach ($name in $savedEnvironment.Keys) { + [Environment]::SetEnvironmentVariable($name, $savedEnvironment[$name], 'Process') + } + Pop-Location + if ([IO.Directory]::Exists($staging)) { + $stagedNames = @($targets | ForEach-Object { $_.Archive }) + @('dct', 'dct.exe', $checksumsName) + foreach ($name in $stagedNames) { + [IO.File]::Delete((Join-Path $staging $name)) + } + [IO.Directory]::Delete($staging) + } +} diff --git a/scripts/verify.ps1 b/scripts/verify.ps1 new file mode 100644 index 0000000..1e7c9df --- /dev/null +++ b/scripts/verify.ps1 @@ -0,0 +1,36 @@ +[CmdletBinding()] +param() +$ErrorActionPreference = 'Stop' +Set-StrictMode -Version Latest +$projectRoot = Split-Path -Parent $PSScriptRoot +Push-Location $projectRoot +try { + if (-not (Get-Command go -CommandType Application -ErrorAction SilentlyContinue) -or + -not (Get-Command gofmt -CommandType Application -ErrorAction SilentlyContinue)) { + throw 'Go and gofmt are required on PATH. Install the Go toolchain and rerun scripts/verify.ps1.' + } + if (-not (Test-Path -LiteralPath 'go.mod')) { throw 'Implementation is not bootstrapped: go.mod is missing.' } + $packageDirectories = & go list -mod=readonly -buildvcs=false -f '{{.Dir}}' ./... + if ($LASTEXITCODE -ne 0) { throw 'go list failed.' } + $sources = @($packageDirectories | ForEach-Object { + Get-ChildItem -LiteralPath $_ -Filter '*.go' -File + }) + if ($sources.Count -eq 0) { throw 'No Go source files exist.' } + if (@($sources | Where-Object { $_.Name -like '*_test.go' }).Count -eq 0) { throw 'Real Go tests are required.' } + $unformatted = & gofmt -l @($sources.FullName) + if ($LASTEXITCODE -ne 0) { throw 'gofmt failed.' } + if ($unformatted) { throw "Unformatted Go files: $($unformatted -join ', ')" } + & go mod verify + if ($LASTEXITCODE -ne 0) { throw 'Module integrity check failed.' } + & go vet -mod=readonly -buildvcs=false ./... + if ($LASTEXITCODE -ne 0) { throw 'go vet failed.' } + & go test -mod=readonly -buildvcs=false -count=1 -v ./... + if ($LASTEXITCODE -ne 0) { throw 'Go tests failed.' } + $executableSuffix = & go env GOEXE + if ($LASTEXITCODE -ne 0) { throw 'Could not determine the native executable suffix.' } + & go build -mod=readonly -trimpath -buildvcs=false -o "bin/dct$executableSuffix" . + if ($LASTEXITCODE -ne 0) { throw 'Go build failed.' } + Write-Output 'Formatting, module integrity, vet, tests, and native build passed.' +} finally { + Pop-Location +} diff --git a/search_test.go b/search_test.go new file mode 100644 index 0000000..76b39fb --- /dev/null +++ b/search_test.go @@ -0,0 +1,219 @@ +package main + +import ( + "bytes" + "context" + "errors" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" + "time" +) + +func TestSearchCLI(t *testing.T) { + binary := buildCLI(t) + + t.Run("literal records in path order", func(t *testing.T) { + root := t.TempDir() + writeFixture(t, root, "a.txt", "a+b and a+b\r\nA+B\ncafé a+b\r\r\nunterminated a+b") + writeFixture(t, root, "folder/inside.txt", "a+b inside\n") + writeFixture(t, root, "folder-other.txt", "a+b outside\n") + writeFixture(t, root, ".hidden", "a+b hidden\n") + writeFixture(t, root, "regex.txt", "aaab\n") + writeFixture(t, root, ".gitignore", "folder/\n") + + result := runCLI(t, binary, root, "search", "a+b") + assertCLI(t, result, 0, ".hidden:1:a+b hidden\n"+ + "a.txt:1:a+b and a+b\n"+ + "a.txt:3:café a+b\r\n"+ + "a.txt:4:unterminated a+b\n"+ + "folder-other.txt:1:a+b outside\n"+ + "folder/inside.txt:1:a+b inside\n", false) + + result = runCLI(t, binary, root, "search", "café") + assertCLI(t, result, 0, "a.txt:3:café a+b\r\n", false) + }) + + t.Run("invalid files emit no prior matches", func(t *testing.T) { + root := t.TempDir() + writeFixture(t, root, "a-nul.txt", "needle before NUL\n\x00\n") + writeFixture(t, root, "b-utf8.txt", "needle before invalid UTF-8\n\xff\n") + writeFixture(t, root, "c-valid.txt", "needle in valid file") + + result := runCLI(t, binary, root, "search", "needle", root) + assertCLI(t, result, 0, "c-valid.txt:1:needle in valid file\n", false) + }) + + t.Run("long lines", func(t *testing.T) { + root := t.TempDir() + line := strings.Repeat("x", 70*1024) + "a needle" + writeFixture(t, root, "long.txt", line+"\n") + + result := runCLI(t, binary, root, "search", "needle") + assertCLI(t, result, 0, "long.txt:1:"+line+"\n", false) + }) + + t.Run("unmatched search", func(t *testing.T) { + root := t.TempDir() + writeFixture(t, root, "file.txt", "unrelated\n") + + result := runCLI(t, binary, root, "search", "needle", root) + assertCLI(t, result, 1, "", false) + }) + + t.Run("misuse", func(t *testing.T) { + root := t.TempDir() + file := writeFixture(t, root, "root.txt", "needle\n") + cases := []struct { + name string + args []string + }{ + {"missing literal", []string{"search"}}, + {"empty literal", []string{"search", ""}}, + {"extra argument", []string{"search", "needle", root, "extra"}}, + {"unknown command", []string{"unknown-command"}}, + {"unknown flag", []string{"search", "needle", "--unrecognized"}}, + {"missing root", []string{"search", "needle", filepath.Join(root, "missing")}}, + {"file root", []string{"search", "needle", file}}, + } + for _, test := range cases { + t.Run(test.name, func(t *testing.T) { + result := runCLI(t, binary, root, test.args...) + assertCLI(t, result, 2, "", true) + }) + } + }) + + t.Run("help and version", func(t *testing.T) { + root := t.TempDir() + for _, args := range [][]string{ + {"--help"}, + {"search", "needle", filepath.Join(root, "missing"), "--help"}, + {"--version"}, + } { + result := runCLI(t, binary, root, args...) + if result.exit != 0 || strings.TrimSpace(result.stdout) == "" || result.stderr != "" { + t.Errorf("%q: exit %d, stdout %q, stderr %q; want success with output only on stdout", args, result.exit, result.stdout, result.stderr) + } + } + }) + + t.Run("symlink traversal and root rejection", func(t *testing.T) { + root := t.TempDir() + targetRoot := t.TempDir() + targetFile := writeFixture(t, targetRoot, "target.txt", "needle outside root\n") + if err := os.Symlink(targetFile, filepath.Join(root, "file-link.txt")); err != nil { + t.Skipf("cannot create file symlink on this host: %v", err) + } + dirLink := filepath.Join(root, "dir-link") + if err := os.Symlink(targetRoot, dirLink); err != nil { + t.Skipf("cannot create directory symlink on this host: %v", err) + } + + result := runCLI(t, binary, root, "search", "needle") + assertCLI(t, result, 1, "", false) + + result = runCLI(t, binary, root, "search", "needle", dirLink) + assertCLI(t, result, 2, "", true) + }) + + t.Run("unreadable file is an error", func(t *testing.T) { + root := t.TempDir() + file := writeFixture(t, root, "unreadable.txt", "needle\n") + if err := os.Chmod(file, 0); err != nil { + t.Skipf("cannot change file permissions on this host: %v", err) + } + t.Cleanup(func() { + if err := os.Chmod(file, 0o600); err != nil { + t.Errorf("restore fixture permissions: %v", err) + } + }) + probe, err := os.Open(file) + if err == nil { + if closeErr := probe.Close(); closeErr != nil { + t.Fatalf("close permission probe: %v", closeErr) + } + t.Skip("this host still permits reading the file after chmod 000") + } + if !errors.Is(err, os.ErrPermission) { + t.Fatalf("probing unreadable file: %v", err) + } + + result := runCLI(t, binary, root, "search", "needle") + assertCLI(t, result, 2, "", true) + }) +} + +type cliResult struct { + exit int + stdout string + stderr string +} + +func buildCLI(t *testing.T) string { + t.Helper() + name := "dct" + if runtime.GOOS == "windows" { + name += ".exe" + } + binary := filepath.Join(t.TempDir(), name) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + cmd := exec.CommandContext(ctx, "go", "build", "-mod=readonly", "-buildvcs=false", "-o", binary, ".") + if output, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("build CLI: %v\n%s", err, output) + } + return binary +} + +func runCLI(t *testing.T, binary, workingDirectory string, args ...string) cliResult { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, binary, args...) + cmd.Dir = workingDirectory + var stdout, stderr bytes.Buffer + cmd.Stdout, cmd.Stderr = &stdout, &stderr + result := cliResult{} + if err := cmd.Run(); err != nil { + var exitErr *exec.ExitError + if ctx.Err() != nil || !errors.As(err, &exitErr) { + t.Fatalf("run CLI %q: %v", args, err) + } + result.exit = exitErr.ExitCode() + } + result.stdout = stdout.String() + result.stderr = stderr.String() + return result +} + +func writeFixture(t *testing.T, root, relativePath, content string) string { + t.Helper() + path := filepath.Join(root, filepath.FromSlash(relativePath)) + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatalf("create fixture directory: %v", err) + } + if err := os.WriteFile(path, []byte(content), 0o600); err != nil { + t.Fatalf("write fixture %q: %v", relativePath, err) + } + return path +} + +func assertCLI(t *testing.T, result cliResult, wantExit int, wantStdout string, wantDiagnostic bool) { + t.Helper() + if result.exit != wantExit { + t.Errorf("exit %d, want %d (stderr %q)", result.exit, wantExit, result.stderr) + } + if result.stdout != wantStdout { + t.Errorf("stdout (%d bytes) %.200q, want (%d bytes) %.200q", len(result.stdout), result.stdout, len(wantStdout), wantStdout) + } + if wantDiagnostic && strings.TrimSpace(result.stderr) == "" { + t.Error("expected a diagnostic on stderr") + } + if !wantDiagnostic && result.stderr != "" { + t.Errorf("stderr %q, want empty", result.stderr) + } +} diff --git a/search_windows_test.go b/search_windows_test.go new file mode 100644 index 0000000..f67dd3b --- /dev/null +++ b/search_windows_test.go @@ -0,0 +1,33 @@ +package main + +import ( + "strings" + "syscall" + "testing" +) + +func TestSearchReportsWindowsSharingViolation(t *testing.T) { + binary := buildCLI(t) + root := t.TempDir() + writeFixture(t, root, "a.txt", "needle in a readable file\n") + locked := writeFixture(t, root, "b.txt", "needle in a locked file\n") + name, err := syscall.UTF16PtrFromString(locked) + if err != nil { + t.Fatal(err) + } + handle, err := syscall.CreateFile(name, syscall.GENERIC_READ, 0, nil, syscall.OPEN_EXISTING, syscall.FILE_ATTRIBUTE_NORMAL, 0) + if err != nil { + t.Fatalf("lock fixture file: %v", err) + } + t.Cleanup(func() { + if err := syscall.CloseHandle(handle); err != nil { + t.Errorf("close fixture handle: %v", err) + } + }) + + result := runCLI(t, binary, root, "search", "needle") + assertCLI(t, result, 2, "a.txt:1:needle in a readable file\n", true) + if !strings.Contains(result.stderr, "b.txt") { + t.Errorf("diagnostic %q does not identify b.txt", result.stderr) + } +} diff --git a/workspace.go b/workspace.go new file mode 100644 index 0000000..1b05f51 --- /dev/null +++ b/workspace.go @@ -0,0 +1,117 @@ +package main + +import ( + "bytes" + "fmt" + "io/fs" + "os" + "path/filepath" + "slices" + "strings" + "unicode/utf8" +) + +func openDirectory(path string) (*os.Root, error) { + path = filepath.Clean(path) + info, err := os.Lstat(path) + if err != nil { + return nil, err + } + if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { + return nil, fmt.Errorf("root %q must be a directory and cannot be a symbolic link", path) + } + root, err := os.OpenRoot(path) + if err != nil { + return nil, err + } + opened, err := root.Stat(".") + if err != nil { + root.Close() + return nil, err + } + if !os.SameFile(info, opened) { + root.Close() + return nil, fmt.Errorf("root %q changed while being opened", path) + } + return root, nil +} + +func listFiles(root *os.Root, extensions []string) ([]string, error) { + var files []string + err := fs.WalkDir(root.FS(), ".", func(path string, entry fs.DirEntry, walkErr error) error { + if walkErr != nil { + return walkErr + } + if !entry.Type().IsRegular() { + return nil + } + if len(extensions) > 0 && !slices.ContainsFunc(extensions, func(extension string) bool { + return strings.HasSuffix(entry.Name(), extension) + }) { + return nil + } + files = append(files, path) + return nil + }) + if err != nil { + return nil, err + } + // Traversal order can differ from the order of complete slash-separated paths. + slices.Sort(files) + return files, nil +} + +type searchMatch struct { + Path string `json:"path"` + Line int `json:"line"` + Text string `json:"text"` +} + +func searchFiles(root *os.Root, files []string, literal []byte, emit func(searchMatch) error) (bool, error) { + found := false + for _, file := range files { + contents, err := root.ReadFile(file) + if err != nil { + return found, err + } + // Validate the whole file before emitting any matches from it. + if bytes.IndexByte(contents, 0) >= 0 || !utf8.Valid(contents) { + continue + } + for lineNumber := 1; len(contents) > 0; lineNumber++ { + line, rest, terminated := bytes.Cut(contents, []byte{'\n'}) + contents = rest + if terminated { + line = bytes.TrimSuffix(line, []byte{'\r'}) + } + if bytes.Contains(line, literal) { + if err := emit(searchMatch{Path: file, Line: lineNumber, Text: string(line)}); err != nil { + return found, fmt.Errorf("write search result: %w", err) + } + found = true + } + } + } + return found, nil +} + +type fileSize struct { + Path string `json:"path"` + Bytes int64 `json:"bytes"` +} + +func inspectFiles(root *os.Root, files []string, emit func(fileSize) error) error { + for _, file := range files { + info, err := root.Lstat(file) + if err != nil { + return err + } + if !info.Mode().IsRegular() { + continue + } + if err := emit(fileSize{Path: file, Bytes: info.Size()}); err != nil { + return fmt.Errorf("write inspection result: %w", err) + } + } + return nil +}