From 10b82c8211010c8f420f3d3f355a2fb417abd9ed Mon Sep 17 00:00:00 2001 From: alpha912 Date: Wed, 11 Nov 2026 21:25:36 +0000 Subject: [PATCH 1/2] docs: rewrite documentation and raise repository quality standards - README rewritten with a real example, architecture overview, limitations and layout - New: docs/architecture.md, SECURITY.md, SUPPORT.md, AGENTS.md - CONTRIBUTING rewritten; changelog moved to CHANGELOG.md - Issue templates, pull request template and CODEOWNERS - REUSE licensing metadata (SPDX headers, REUSE.toml, LICENSES/) checked in CI - Stricter TypeScript checks; purpose headers on every source file - 11 new unit tests; dead test helper and stale tsconfig files removed - Fix stray '*' in Micro descriptions taken from /** */ comments - VSIX slimmed from 4.7 MB to 92 KB (256 px icon; docs and banners no longer bundled) - CI: concurrency control and a REUSE job; .gitattributes and .editorconfig --- .editorconfig | 12 + .gitattributes | 8 + .github/CODEOWNERS | 18 ++ .github/ISSUE_TEMPLATE/bug_report.yml | 77 +++++ .github/ISSUE_TEMPLATE/config.yml | 15 + .github/ISSUE_TEMPLATE/docs_issue.yml | 27 ++ .github/ISSUE_TEMPLATE/feature_request.yml | 35 +++ .github/pull_request_template.md | 27 ++ .github/workflows/ci.yml | 18 +- .vscodeignore | 30 +- AGENTS.md | 121 ++++++++ docs/changelog.md => CHANGELOG.md | 19 +- CONTRIBUTING.md | 210 +++++++------ LICENSES/CC-BY-4.0.txt | 156 ++++++++++ LICENSES/MIT.txt | 21 ++ README.md | 337 ++++++++++++++++----- REUSE.toml | 23 ++ SECURITY.md | 81 +++++ SUPPORT.md | 17 ++ assets/icon.png | Bin 0 -> 14102 bytes docs/README.md | 45 +-- docs/api-reference.md | 4 +- docs/architecture.md | 159 ++++++++++ docs/configuration.md | 2 +- docs/contributing.md | 8 +- docs/installation.md | 64 ++-- docs/troubleshooting.md | 2 +- docs/usage.md | 2 +- package.json | 6 +- scripts/publish-release.cjs | 9 + src/analyzer.ts | 11 +- src/config.ts | 9 + src/exporter.ts | 9 + src/extension.ts | 9 + src/formatters.ts | 9 + src/fsUtils.ts | 9 + src/git.ts | 9 + src/secrets.ts | 9 + src/skeleton.ts | 9 + src/test/runTest.ts | 9 + src/test/suite/extension.test.ts | 9 + src/test/suite/fileProcessing.test.ts | 9 + src/test/suite/index.ts | 9 + src/test/suite/markdownGeneration.test.ts | 9 + src/test/suite/mockFileSystem.ts | 64 ---- src/test/tsconfig.json | 14 - src/test/unit/exporter.test.ts | 9 + src/test/unit/helpers.test.ts | 113 +++++++ src/tokens.ts | 9 + src/tsconfig.json | 7 - src/types.ts | 9 + tsconfig.json | 11 +- 52 files changed, 1597 insertions(+), 320 deletions(-) create mode 100644 .editorconfig create mode 100644 .gitattributes create mode 100644 .github/CODEOWNERS create mode 100644 .github/ISSUE_TEMPLATE/bug_report.yml create mode 100644 .github/ISSUE_TEMPLATE/config.yml create mode 100644 .github/ISSUE_TEMPLATE/docs_issue.yml create mode 100644 .github/ISSUE_TEMPLATE/feature_request.yml create mode 100644 .github/pull_request_template.md create mode 100644 AGENTS.md rename docs/changelog.md => CHANGELOG.md (76%) create mode 100644 LICENSES/CC-BY-4.0.txt create mode 100644 LICENSES/MIT.txt create mode 100644 REUSE.toml create mode 100644 SECURITY.md create mode 100644 SUPPORT.md create mode 100644 assets/icon.png create mode 100644 docs/architecture.md delete mode 100644 src/test/suite/mockFileSystem.ts delete mode 100644 src/test/tsconfig.json create mode 100644 src/test/unit/helpers.test.ts delete mode 100644 src/tsconfig.json diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..f15441a --- /dev/null +++ b/.editorconfig @@ -0,0 +1,12 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true +indent_style = space +indent_size = 2 + +[*.md] +trim_trailing_whitespace = false diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..3868511 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,8 @@ +* text=auto eol=lf +*.bat text eol=crlf +*.png binary +*.jpg binary +*.jpeg binary +*.gif binary +*.ico binary +*.vsix binary diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..d530307 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,18 @@ +# SPDX-FileCopyrightText: 2024-2026 Alphin Tom +# +# SPDX-License-Identifier: MIT + +# Code owners: review is requested from these people on pull requests that +# touch the matching paths. + +* @alpha912 + +/src/ @alpha912 +/scripts/ @alpha912 +/.github/ @alpha912 +/package.json @alpha912 +/bun.lock @alpha912 +/LICENSE.md @alpha912 +/LICENSES/ @alpha912 +/REUSE.toml @alpha912 +/SECURITY.md @alpha912 diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..c61a071 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,77 @@ +# SPDX-FileCopyrightText: 2024-2026 Alphin Tom +# +# SPDX-License-Identifier: MIT + +name: Bug report +description: An export is wrong, incomplete or fails +title: "[Bug]: " +labels: ["bug", "triage"] +body: + - type: markdown + attributes: + value: | + Thanks for reporting. A minimal, sanitized example is the most useful thing you can include. + Never paste private code or real credentials. Security issues go through SECURITY.md, not here. + - type: dropdown + id: area + attributes: + label: Area + options: + - Export Wizard + - Export Git Changes + - Copy Current File + - Original Markdown / Micro commands + - File selection and ignore rules + - Secret redaction + - Output format (Markdown, XML, text) + - Micro or skeleton mode + - Token estimate or budget warning + - Installation or activation + - Documentation + validations: + required: true + - type: input + id: version + attributes: + label: Extension version + description: Shown on the extension's page in VS Code. + placeholder: "3.0.0" + validations: + required: true + - type: input + id: environment + attributes: + label: Environment + description: VS Code version (Help → About) and operating system. + placeholder: "VS Code 1.146.0, Windows 11" + validations: + required: true + - type: textarea + id: steps + attributes: + label: Steps to reproduce + description: The command you ran, the options you chose and any relevant settings or ignore files. + placeholder: | + 1. Open a folder containing … + 2. Run "CodebaseMD: Export Wizard" → Workspace → Full → Markdown → Clipboard + validations: + required: true + - type: textarea + id: example + attributes: + label: Minimal example + description: The smallest file or folder layout that shows the problem, with any secrets replaced by fake values. + render: text + - type: textarea + id: expected + attributes: + label: What you expected + validations: + required: true + - type: textarea + id: actual + attributes: + label: What happened instead + description: Include the text of any notification. Screenshots help. + validations: + required: true diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..c4a89b3 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,15 @@ +# SPDX-FileCopyrightText: 2024-2026 Alphin Tom +# +# SPDX-License-Identifier: MIT + +blank_issues_enabled: false +contact_links: + - name: Security vulnerability + url: https://github.com/alpha912/codebase-md/security/advisories/new + about: Do not open an issue. Report privately as described in SECURITY.md. + - name: Questions and ideas + url: https://github.com/alpha912/codebase-md/discussions + about: Ask how to do something or share how you use CodebaseMD. + - name: Troubleshooting guide + url: https://github.com/alpha912/codebase-md/blob/main/docs/troubleshooting.md + about: Common problems and their fixes. diff --git a/.github/ISSUE_TEMPLATE/docs_issue.yml b/.github/ISSUE_TEMPLATE/docs_issue.yml new file mode 100644 index 0000000..62e1d76 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/docs_issue.yml @@ -0,0 +1,27 @@ +# SPDX-FileCopyrightText: 2024-2026 Alphin Tom +# +# SPDX-License-Identifier: MIT + +name: Documentation issue +description: Something in the README or docs is wrong, unclear or missing +title: "[Docs]: " +labels: ["documentation", "triage"] +body: + - type: input + id: page + attributes: + label: Page + description: File path or link to the page. + placeholder: docs/configuration.md + validations: + required: true + - type: textarea + id: problem + attributes: + label: What is wrong or missing + validations: + required: true + - type: textarea + id: suggestion + attributes: + label: Suggested wording diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000..4aa63e0 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,35 @@ +# SPDX-FileCopyrightText: 2024-2026 Alphin Tom +# +# SPDX-License-Identifier: MIT + +name: Feature request +description: Suggest a new capability or a change in behaviour +title: "[Feature]: " +labels: ["enhancement", "triage"] +body: + - type: textarea + id: problem + attributes: + label: The problem + description: What are you trying to do, and what gets in the way today? + validations: + required: true + - type: textarea + id: proposal + attributes: + label: What you would like + description: Describe the behaviour you want. A sketch of the command, setting or output is welcome. + validations: + required: true + - type: textarea + id: alternatives + attributes: + label: Alternatives you considered + - type: checkboxes + id: constraints + attributes: + label: Fit with the project + description: CodebaseMD runs locally and makes no network requests. + options: + - label: This works without sending code to a service + - label: I am willing to help implement or test it diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..d254232 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,27 @@ +## What and why + + + +## Areas touched + +- [ ] Export pipeline (`exporter`, `fsUtils`, `git`, `secrets`) +- [ ] Output (`formatters`, Micro, skeleton, token estimate) +- [ ] VS Code integration (`extension`, `config`, `package.json` contributions) +- [ ] Documentation +- [ ] Repository (CI, dependencies, licensing) + +## How it was tested + + + +## Checklist + +- [ ] Tests added or updated for behaviour changes +- [ ] `bun run check` passes; `bun run test:integration` passes if VS Code integration changed +- [ ] `CHANGELOG.md` updated under `[Unreleased]` +- [ ] Documentation updated for user-visible changes +- [ ] Breaking changes are marked **BREAKING** with migration notes +- [ ] Safety properties are unchanged (workspace containment, no symlink following, redaction before transformation), or the change is explained above +- [ ] New files have SPDX headers or are covered by `REUSE.toml` +- [ ] The title does not start with `release:` +- [ ] I agree my contribution is licensed under the MIT License (see CONTRIBUTING.md) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 736d0da..ac55de5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,6 +9,12 @@ on: permissions: contents: read +# A newer push to the same branch or pull request replaces the running check. +# Runs on main are never cancelled, so a release is not interrupted. +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + jobs: test: name: Test (${{ matrix.os }}) @@ -46,9 +52,19 @@ jobs: path: '*.vsix' if-no-files-found: error + reuse: + name: REUSE licensing + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false + - run: pipx run reuse==6.3.0 lint + release: name: Publish GitHub release - needs: test + needs: [test, reuse] if: github.event_name == 'push' && startsWith(github.event.head_commit.message, 'release:') runs-on: ubuntu-latest timeout-minutes: 10 diff --git a/.vscodeignore b/.vscodeignore index ba09703..1ab5bfc 100644 --- a/.vscodeignore +++ b/.vscodeignore @@ -1,15 +1,31 @@ +# Only the compiled extension, its runtime dependency, the icon, README, +# CHANGELOG and LICENSE ship in the VSIX. +.github/** +.vscode/** +.vscode-test/** src/** out/test/** **/*.map +scripts/** +docs/** +releases/** CodebaseMD-Web/** -.vscode-test/** +LICENSES/** +assets/banner.png +assets/logo.png +assets/logo-with-text.png +.editorconfig +.gitattributes .gitignore +AGENTS.md +CODE_OF_CONDUCT.md +CONTRIBUTING.md +REUSE.toml +SECURITY.md +SUPPORT.md +biome.json +bun.lock tsconfig.json -docs/v3-plan.md -*.vsix integration-test.log -.github/** -scripts/** +*.vsix *.sha256 -biome.json -bun.lock diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..8b52dc6 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,121 @@ +# AGENTS.md - AI Agent Instructions + +## Repository Purpose + +CodebaseMD is a VS Code extension that exports a workspace folder, a selection +of files or Git changes as one Markdown, XML or plain-text document, with a +folder tree, token estimates and secret redaction. It runs locally and makes +no network requests. The repository holds the extension source, its tests, +the documentation and the release notes. + +## Quick Start for AI Agents + +1. Read `docs/architecture.md` (the pipeline and its safety properties) and + `docs/api-reference.md` (modules and command IDs). +2. Read `src/exporter.ts` for the core flow, then the module you will change. +3. Run the checks for what you touch (see **Before Making Changes**). + +## Building + +```sh +bun install --frozen-lockfile +bun run check # Biome, then compile and unit tests +bun run test:integration # extension host; on headless Linux: xvfb-run -a … +bun run package # VSIX +``` + +Use Bun for installs and scripts. Node.js 22.12+ must also be installed. Do +not add `package-lock.json`; `bun.lock` is the lockfile. + +## Layout + +| Path | Contents | +| --- | --- | +| `src/extension.ts` | Commands, wizard, progress, budget warning, output destinations | +| `src/config.ts` | Reads and validates `codebaseMD.*` settings | +| `src/exporter.ts` | Pipeline: collect, read, redact, transform, render | +| `src/fsUtils.ts` | Ignore rules, containment, directory walk | +| `src/git.ts` | Changed files and filtered diffs | +| `src/secrets.ts` | Heuristic redaction (text and count only) | +| `src/analyzer.ts` | Micro representation and language mapping | +| `src/skeleton.ts` | Declaration outlines | +| `src/tokens.ts` | `ceil(characters / 4)` estimate | +| `src/formatters.ts` | Markdown, XML, text, folder tree | +| `src/types.ts` | Options, document types, defaults, cancellation | +| `src/test/unit/` | Unit tests, run with Mocha on Node | +| `src/test/suite/` | Tests that run inside a VS Code extension host | +| `docs/` | User and developer documentation | +| `releases/` | Release notes per version; VSIX files of releases before 3.0 | +| `scripts/publish-release.cjs` | Used by CI to publish a GitHub release | + +## Code Conventions + +- **Licensing headers:** every source file starts with + `SPDX-FileCopyrightText` and `SPDX-License-Identifier` (REUSE). Files that + cannot carry a header are covered by `REUSE.toml`. +- **Header comments:** source files continue with + `// File: … / What: … / Why: … / Related: …`. Keep the pattern. +- **TypeScript:** strict, with unused locals and parameters as errors. + Biome formats and lints (`bun run lint:fix`). No non-null assertions. +- **Module boundary:** only `extension.ts` and `config.ts` import `vscode`. + Everything else is plain Node code so the unit tests can run it. +- **Tests** import the production module they cover; do not re-implement + logic in a test. + +## Do's and Don'ts + +### DO + +- Add a test with every behaviour change, and run `bun run check`. +- Keep user-facing claims accurate: token counts, redaction, Micro and + skeleton modes are heuristics and are described that way everywhere. +- Update `CHANGELOG.md` under `[Unreleased]` and the affected pages in + `docs/` and `README.md`. +- Keep `engines.vscode` and `@types/vscode` in step; `vsce` refuses to package + when the types are newer than the engine. + +### DON'T + +- Don't start a commit or pull request title with `release:`. On `main` that + prefix publishes a GitHub release. +- Don't weaken the safety properties: no files outside the workspace folder, + no following symbolic links, redaction before transformation, Git without a + shell and without external diff or textconv programs. +- Don't log or return matched secret values; redaction reports counts only. +- Don't add runtime dependencies without a strong reason; `ignore` is the only + one and it ships to every user. +- Don't commit `out/`, `*.vsix` or `node_modules/`. +- Don't change the Micro output format casually; it is documented in + `docs/micro-export-format.md` and users depend on it. + +## Before Making Changes + +| You changed | Run | +| --- | --- | +| Anything in `src/` | `bun run check` | +| `extension.ts`, `config.ts`, `package.json` contributions | also `bun run test:integration` | +| Dependencies | also `bun audit` and `bun run package` | +| New files | also `uvx reuse lint` | +| Documentation only | check that relative links resolve | + +## Common Tasks + +### Adding a setting + +1. Add it to `contributes.configuration` in `package.json`. +2. Add the field and default to `ExportOptions` and `defaults` in + `src/types.ts`, and validate it in `src/config.ts`. +3. Use it in the pipeline, add a unit test, and document it in the settings + table in `README.md` and in `docs/configuration.md`. + +### Adding a secret pattern + +1. Add the pattern to `src/secrets.ts`. +2. Add a positive case and a near-miss case to the redaction test in + `src/test/unit/exporter.test.ts`, using synthetic values only. + +### Supporting a file type + +1. Add the extension or special name in `src/exporter.ts` + (`isSupportedFile`) and the language in `src/analyzer.ts`. +2. Add cases to the language-mapping and support tests. diff --git a/docs/changelog.md b/CHANGELOG.md similarity index 76% rename from docs/changelog.md rename to CHANGELOG.md index dd154aa..fad89d4 100644 --- a/docs/changelog.md +++ b/CHANGELOG.md @@ -2,15 +2,26 @@ All notable changes to this project will be documented in this file. -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +Longer notes for each release are in [`releases/`](releases/). ## [Unreleased] ### Changed -- Minimum supported VS Code is now 1.146 (previously 1.70). -- Development tooling: TypeScript 7, Bun for installs and scripts (`bun.lock` replaces `package-lock.json`), and Biome for linting and formatting. +- **BREAKING:** the minimum supported VS Code is now 1.146 (previously 1.70). Stay on 3.0.0 if you use an older VS Code or a fork based on one. +- The VSIX is smaller: it ships a 256 px icon and no longer bundles the documentation, release notes, banner and full-size logos. +- Development tooling: TypeScript 7 with stricter compiler checks, Bun for installs and scripts (`bun.lock` replaces `package-lock.json`), and Biome for linting and formatting. - Dependency updates, including `ignore` 7. +- The changelog moved from `docs/changelog.md` to `CHANGELOG.md`. + +### Fixed +- Micro summaries no longer keep a stray `*` in the description taken from a `/** … */` comment. + +### Added +- Documentation: rewritten README, an architecture guide, a security policy, support and agent guides, and issue and pull request templates. +- REUSE licensing metadata: SPDX headers on source files, `REUSE.toml` and `LICENSES/`, checked in CI. +- More unit tests for language mapping, the Micro representation, path containment and formatting helpers. ## [3.0.0] - 2026-09-18 @@ -24,7 +35,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Modular production code and tests that import it, with extension-host command checks. - Existing commands retain Markdown-to-file behavior and the established Micro format. -See [release notes](../releases/RELEASE-NOTES-3.0.0.md) for compatibility and limitations. +See [release notes](releases/RELEASE-NOTES-3.0.0.md) for compatibility and limitations. ## [2.0.3] - 2025-05-22 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2c728e7..79ab9e1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,102 +1,130 @@ # Contributing to CodebaseMD -We welcome contributions to **CodebaseMD**! Whether you’re fixing bugs, adding new features, improving documentation, or suggesting ideas, we appreciate your involvement. Before getting started, please review the following guidelines. +Thank you for helping. CodebaseMD is a small VS Code extension with one +maintainer, so the most useful contributions are focused: a bug report with a +minimal example, a fix with a test, or a documentation correction. -## How to Contribute +## Before You Start -### 1. Fork the Repository +- **Bugs and ideas:** open an issue with the + [templates](https://github.com/alpha912/codebase-md/issues/new/choose). For + anything larger than a small fix, open an issue first so the approach can be + agreed before you write code. +- **Security problems:** do not open an issue. Follow [SECURITY.md](SECURITY.md). +- **Questions:** see [SUPPORT.md](SUPPORT.md). +- Everyone taking part is expected to follow the + [Code of Conduct](CODE_OF_CONDUCT.md). -- Go to the [CodebaseMD GitHub repository](https://github.com/alpha912/codebase-md). -- Click on the **Fork** button in the top-right corner to create a copy of the repository under your GitHub account. +## Setting Up -### 2. Clone the Fork +You need [Bun](https://bun.sh) 1.4+, Node.js 22.12+ (24 recommended) and Git. +Bun installs dependencies and runs scripts; Node is still required because VS +Code runs extensions on Node and `vsce` calls npm when packaging. -Once you have forked the repository, clone it to your local machine: - -``` -git clone https://github.com/your-username/codebase-md.git +```sh +git clone https://github.com//codebase-md.git cd codebase-md -``` - -### 3. Create a Branch - -Create a new branch for your work. This makes it easier to isolate your changes and submit them as a pull request. - -``` -git checkout -b feature/my-new-feature -``` - -### 4. Make Your Changes - -- For new features, be sure to update/add relevant tests. -- For bug fixes, provide steps in your pull request for testing the fix. - -### 5. Compile and Test Your Changes - -Use [Bun](https://bun.sh) 1.4+, Node.js 22.12+ (Node 24 recommended) and Git. Bun installs dependencies and runs scripts; Node is still needed for packaging and the extension-host tests. Install dependencies and compile the TypeScript sources: - -``` bun install --frozen-lockfile -bun run compile -``` - -If you made significant changes, also run the linter and tests to ensure everything works correctly: - -``` -bun run lint -bun run test -``` - -Unit tests exercise production modules and use temporary Git repositories (Git must be installed). Run `bun run test:integration` for VS Code extension-host tests and `bun run package` to build a VSIX. Formatting and linting use Biome (`bun run lint:fix` applies fixes). Compiled output lives in `out/`; do not add generated JavaScript under `src/`. - -### Release maintainers - -Update `package.json`, `bun.lock`, changelog, README and `releases/RELEASE-NOTES-.md`. A commit on `main` whose message starts with `release:` triggers publication **only after both Windows and Linux CI jobs pass**. The release job packages the verified commit, creates a draft with the VSIX and SHA-256 checksum, and publishes it as the latest GitHub release. Ordinary commits and pull requests cannot publish. Existing release tags are not overwritten. Marketplace publication remains a separate explicit action. - -### 6. Commit Your Changes - -Write meaningful commit messages, following these guidelines: -- Start with a lowercase verb, such as `fix:`, `feat:`, or `docs:`. -- Keep the commit message short but descriptive. - -Example commit message: - -``` -git add . -git commit -m "fix: resolve export error for unsupported file types" -``` - -### 7. Push the Branch - -Push your changes to your forked repository: - -``` -git push origin feature/my-new-feature +bun run check ``` -### 8. Submit a Pull Request - -Go to your fork on GitHub, and you should see a prompt to submit a pull request. Provide a meaningful description of the changes in the pull request, referencing any issues that are related. - -We will review your pull request as soon as possible and provide feedback if needed. - -## Guidelines - -- **Respect existing code standards**: Follow the coding style and conventions used in the project. -- **Test thoroughly**: Ensure your changes don’t break existing functionality. -- **Stay focused**: Stick to the purpose of your pull request, and try not to include unrelated changes. - -## Reporting Bugs - -If you encounter a bug, please submit an issue in the [issue tracker](https://github.com/alpha912/codebase-md/issues) and include: -- Steps to reproduce the bug. -- Expected and actual results. -- Any additional information, such as screenshots or error logs. - -## Feature Requests - -Feel free to open a new issue in the [issue tracker](https://github.com/alpha912/codebase-md/issues) for feature requests. Make sure to provide as much context as possible to help us understand the need for the new feature. - ---- - -Thank you for your contributions! 🎉 +To try the extension, open the folder in VS Code and press `F5` to start an +Extension Development Host, or build a VSIX with `bun run package` and install +it with **Extensions → … → Install from VSIX…**. + +| Command | What it does | +| --- | --- | +| `bun run lint` | Biome lint and format check | +| `bun run lint:fix` | Apply Biome formatting and safe fixes | +| `bun run typecheck` | Type-check without writing output | +| `bun run test` | Compile, then run the unit tests | +| `bun run check` | `lint` followed by `test` | +| `bun run test:integration` | Run the tests inside a VS Code extension host | +| `bun run package` | Build `codebase-md-.vsix` | +| `bun audit` | Check dependencies for known advisories | + +On headless Linux, run the integration tests with +`xvfb-run -a bun run test:integration`. The first run downloads a VS Code +build into `.vscode-test/`. + +## Making a Change + +1. Create a branch from `main` (`fix/…`, `feat/…`, `docs/…`). +2. Make the change. Keep to the module boundaries in + [docs/architecture.md](docs/architecture.md): only `extension.ts` and + `config.ts` may import `vscode`; the export pipeline stays plain Node code + so it can be unit tested. +3. Add or update tests. Tests import the production module they cover; + unit tests go in `src/test/unit/`, tests that need VS Code in + `src/test/suite/`. +4. Update the documentation the change affects, and add a line under + `[Unreleased]` in [CHANGELOG.md](CHANGELOG.md). +5. Run `bun run check`, and `bun run test:integration` if you touched + `extension.ts`, `config.ts` or `package.json` contributions. + +Conventions: + +- **TypeScript:** strict mode with unused-code checks; Biome formats and + lints. Do not commit generated JavaScript; compiled output lives in `out/`. +- **File headers:** every source file starts with SPDX lines and a + `File / What / Why / Related` comment. Keep the pattern in new files. +- **Honest output:** token counts, redaction and the condensed modes are + heuristics. Describe them as such in code comments, UI text and docs. +- **Safety properties:** exports never include files outside the workspace + folder, never follow symbolic links, and redact before any transformation. + A change that weakens one of these needs a test and a clear reason. +- **Dependencies:** the extension ships one runtime dependency (`ignore`). + Adding another needs a strong case, since it ships to every user. + +## Pull Requests + +- Keep each pull request to one topic and fill in the template. +- Use [Conventional Commits](https://www.conventionalcommits.org/) prefixes + for the title: `fix:`, `feat:`, `docs:`, `chore:`, `test:`, `refactor:`. + Do not start a title with `release:`; that prefix publishes a release (see + below). +- CI must pass on Linux and Windows: lint, unit tests, extension-host tests, + dependency audit, packaging and the REUSE check. +- Pull requests are squash-merged. + +## Licensing of Contributions + +CodebaseMD is MIT licensed. By submitting a contribution you agree that it is +licensed under the [MIT License](LICENSE.md), and you confirm that you have +the right to submit it. No separate contributor agreement is required. + +The repository follows the [REUSE](https://reuse.software/) specification. +New source files need the SPDX header used elsewhere in `src/`; files that +cannot carry a header are covered by [`REUSE.toml`](REUSE.toml). Run +`uvx reuse lint` (or `pipx run reuse lint`) after adding files. + +## Releases + +Releases are cut by the maintainer and published by CI. + +1. Update `version` in `package.json`, move the `[Unreleased]` entries in + `CHANGELOG.md` under the new version and date, and write + `releases/RELEASE-NOTES-.md`. +2. Update version-specific text in `README.md` and `docs/`. +3. Merge to `main` with a commit message that starts with `release:`. + +A `release:` commit on `main` triggers publication only after the Linux and +Windows jobs pass. The release job packages that exact commit, creates a draft +GitHub release with the VSIX and its SHA-256 checksum, and then publishes it +as the latest release. Existing tags are never overwritten. Ordinary commits +and pull requests cannot publish. Publishing to the Visual Studio Marketplace +is a separate, manual step (`bun run publish`). + +### Release checklist + +- [ ] `bun run check` and `bun run test:integration` pass locally +- [ ] `bun audit` reports no advisories +- [ ] `CHANGELOG.md` and `releases/RELEASE-NOTES-.md` describe every + user-visible change, including breaking ones +- [ ] `engines.vscode` matches the minimum version stated in the docs +- [ ] The packaged VSIX installs and the Export Wizard runs + +## Questions + +Open a [discussion](https://github.com/alpha912/codebase-md/discussions) or +see [SUPPORT.md](SUPPORT.md). diff --git a/LICENSES/CC-BY-4.0.txt b/LICENSES/CC-BY-4.0.txt new file mode 100644 index 0000000..13ca539 --- /dev/null +++ b/LICENSES/CC-BY-4.0.txt @@ -0,0 +1,156 @@ +Creative Commons Attribution 4.0 International + + Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. + +Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. More considerations for licensors. + +Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public. + +Creative Commons Attribution 4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. + +Section 1 – Definitions. + + a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. + + c. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. + + d. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. + + e. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. + + f. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License. + + g. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. + + h. Licensor means the individual(s) or entity(ies) granting rights under this Public License. + + i. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. + + j. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. + + k. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. + +Section 2 – Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: + + A. reproduce and Share the Licensed Material, in whole or in part; and + + B. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. + + 3. Term. The term of this Public License is specified in Section 6(a). + + 4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. + + 5. Downstream recipients. + + A. Offer from the Licensor – Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. + + B. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. + + 6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). + +b. Other rights. + + 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this Public License. + + 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties. + +Section 3 – License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified form), You must: + + A. retain the following if it is supplied by the Licensor with the Licensed Material: + + i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of warranties; + + v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; + + B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and + + C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. + + 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. + + 4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License. + +Section 4 – Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database; + + b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and + + c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. +For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. + +Section 5 – Disclaimer of Warranties and Limitation of Liability. + + a. Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You. + + b. To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You. + + c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. + +Section 6 – Term and Termination. + + a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or + + 2. upon express reinstatement by the Licensor. + + c. For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. + + d. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. + + e. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. + +Section 7 – Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. + +Section 8 – Interpretation. + + a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. + + c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. + + d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. + +Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. + +Creative Commons may be contacted at creativecommons.org. diff --git a/LICENSES/MIT.txt b/LICENSES/MIT.txt new file mode 100644 index 0000000..71e1ee8 --- /dev/null +++ b/LICENSES/MIT.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Alphin Tom + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index d71d409..50d7f28 100644 --- a/README.md +++ b/README.md @@ -1,113 +1,302 @@ -# CodebaseMD +

+ CodebaseMD +

+ +

+ CodebaseMD is a VS Code extension that exports a workspace, a selection or your Git changes as one Markdown, XML or plain-text document, ready to paste into an AI assistant or a review. +

+ +

+ Download · + Documentation · + Changelog · + Contributing · + Security · + Support +

+ +

+ Latest release + CI + Visual Studio Marketplace + License: MIT + REUSE compliant +

+ +> **Status:** 3.0.0 is the current release. `main` has unreleased changes: the +> next release requires VS Code 1.146 or later (3.0.0 runs on 1.70 and later). +> See the [changelog](CHANGELOG.md) and the [limitations](#limitations). + +## Contents + +- [What CodebaseMD is](#what-codebasemd-is) +- [A short example](#a-short-example) +- [Install](#install) +- [Commands](#commands) +- [Settings](#settings) +- [Choosing what is shared](#choosing-what-is-shared) +- [How it works](#how-it-works) +- [Limitations](#limitations) +- [Repository layout](#repository-layout) +- [Development](#development) +- [Documentation](#documentation) +- [Contributing](#contributing) +- [License](#license) + +## What CodebaseMD is + +Giving an assistant or a reviewer the right code usually means copying files +one at a time. CodebaseMD does it in one step: pick a scope, and it writes a +single document with a folder tree, per-language statistics, a token estimate +and the contents of each file. + +- **Scopes:** the workspace, selected files and folders, changes against + `HEAD`, or the current file (including unsaved edits). +- **Formats:** Markdown with a linked contents list, escaped XML, or plain + text. +- **Destinations:** a file, the clipboard, or a new editor tab. +- **Content modes:** full source, a compact Micro summary, or a declaration + skeleton, for fitting more files into a context budget. +- **Guard rails:** recognizable secrets are redacted by default, ignore rules + are respected, symbolic links are not followed, and a warning appears before + an export exceeds your token budget. + +CodebaseMD runs entirely on your machine. It does not upload source code, call +an AI provider or collect telemetry. + +## A short example + + + + + + +
+ +A workspace with three files: + +```text +├── .env +├── README.md +└── src/ + └── greet.ts +``` -![CodebaseMD banner](assets/banner.png) +`.env` holds a token: -[![GitHub release](https://img.shields.io/github/v/release/alpha912/codebase-md)](https://github.com/alpha912/codebase-md/releases/latest) -[![CI](https://github.com/alpha912/codebase-md/actions/workflows/ci.yml/badge.svg)](https://github.com/alpha912/codebase-md/actions/workflows/ci.yml) -[![Marketplace](https://img.shields.io/visual-studio-marketplace/v/alpha912.codebase-md)](https://marketplace.visualstudio.com/items?itemName=alpha912.codebase-md) -[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE.md) +```dotenv +API_TOKEN="sk_live_abc…" +``` -**Prepare code context without leaving VS Code.** Export a workspace, selected files, or Git changes as Markdown, XML, or plain text. Save it, copy it, or open it in an editor. +Run **CodebaseMD: Export Wizard**, choose +*Workspace → Full → Markdown → Clipboard*, +and paste. -CodebaseMD runs locally. It does not upload your source code or call an AI provider. +The token is replaced before the export +leaves the editor, and the summary line +reports one redaction. -[Install from GitHub Releases](https://github.com/alpha912/codebase-md/releases/latest) · [Documentation](docs/README.md) · [Changelog](docs/changelog.md) · [Report an issue](https://github.com/alpha912/codebase-md/issues) + -## Start in a minute +````markdown +# Project Export -1. Download the `.vsix` from [GitHub Releases](https://github.com/alpha912/codebase-md/releases/latest). -2. In VS Code, open **Extensions → … → Install from VSIX…**, then select the file. -3. Open a local workspace and run **CodebaseMD: Export Wizard** from the Command Palette. -4. Choose your scope, content mode, output format, and destination. +3 files | 28 estimated content tokens (characters / 4) | 1 redactions | full mode -The Marketplace has its own publication schedule; use the GitHub VSIX for this release. VS Code 1.146 or later is required. Git is needed only for Git exports. +## Languages -## What's new in version 3.0.0 +| Language | Files | Estimated tokens | +| --- | ---: | ---: | +| dotenv | 1 | 7 | +| markdown | 1 | 2 | +| typescript | 1 | 19 | -| Capability | What you can do | -| --- | --- | -| Export Wizard | Choose workspace, selected files/folders, Git changes, or current file | -| Output formats | Generate Markdown with a contents list, escaped XML, or plain text | -| Destinations | Save a file, copy to clipboard, or open an editable document | -| Content modes | Include full source, existing Micro summaries, or best-effort skeletons | -| Context budgets | See approximate tokens per file and language; warn before exceeding a budget | -| Git context | Export changes against HEAD, untracked files, and optional filtered diffs | -| Secret redaction | Replace recognizable credentials before exporting; report counts | -| File handling | Respect nested ignore rules, skip symlinks, bound file sizes, and cancel exports | +## Contents -The four existing commands still save Markdown. Micro retains its established summary format. Read the [v3 release notes](releases/RELEASE-NOTES-3.0.0.md) for migration details. +- [\.env](#file-1) — dotenv, ~7 tokens +- [README\.md](#file-2) — markdown, ~2 tokens +- [src/greet\.ts](#file-3) — typescript, ~19 tokens -## Commands +### \.env -| Command Palette title | Behavior | -| --- | --- | -| **CodebaseMD: Export Wizard** | Four-step export flow | -| **CodebaseMD: Export Git Changes** | Changed files using configured output options | -| **CodebaseMD: Copy Current File** | Copy the active saved file, including unsaved edits | -| **Export Codebase as Markdown** | Full workspace to a Markdown file | -| **Export Selected as Markdown** | Selected files/folders to Markdown | -| **Export Micro Codebase** | Workspace Micro summary to Markdown | -| **Export Selected as Micro Codebase** | Selected Micro summary to Markdown | +```dotenv +API_TOKEN="***REDACTED***" +``` -The two selected-export commands also appear in the Explorer context menu. From the Command Palette, they open a file/folder picker. Multi-root workspaces prompt for one folder per export. +### src/greet\.ts -## Settings +```typescript +export function greet(name: string): string { + return `Hello, ${name}`; +} +``` +```` -Search for **CodebaseMD** in Settings. All keys below use the `codebaseMD.` prefix and can be configured per workspace folder. +
-| Setting | Default | Meaning | -| --- | --- | --- | -| `format` | `markdown` | `markdown`, `xml`, or `text` | -| `contentMode` | `full` | `full`, `micro`, or `skeleton` | -| `target` | `file` | `file`, `clipboard`, or `editor` | -| `tokenBudget` | `32000` | Warning threshold; `0` disables warnings | -| `redactSecrets` | `true` | Heuristic redaction of recognizable secrets | -| `maxFileSizeKB` | `1024` | Maximum content/diff size per file in KiB | -| `exclude` | `[]` | Additional gitignore-style exclusions | -| `respectGitignore` | `true` | Apply root and nested `.gitignore` rules | -| `includeDiff` | `false` | Add tracked-file diffs to Git exports | -| `lineNumbers` | `false` | Number lines in the exported representation | -| `customHeader` | empty | Add your task or instructions | +The output above is abridged: a real export also lists the largest files and +the folder tree. XML and plain-text exports carry the same information. + +## Install -The wizard starts from these defaults. Original commands retain their full/Micro and Markdown-to-file behavior; Copy Current File always uses the clipboard. +1. Download the `.vsix` from + [GitHub Releases](https://github.com/alpha912/codebase-md/releases/latest). + A SHA-256 checksum is published next to it. +2. In VS Code, open **Extensions → … → Install from VSIX…** and select the + file. +3. Open a local folder and run **CodebaseMD: Export Wizard** from the Command + Palette. -## Choose what is shared +The extension is also on the +[Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=alpha912.codebase-md). +Marketplace publication is a separate step and can lag behind GitHub Releases. +Git is needed only for Git exports. See [installation](docs/installation.md) +for details. -- **`.gitignore` and `exclude`** remove matching files entirely, including their paths. -- **`.codebaseignore`** in the workspace root hides matching contents but retains paths in the tree. -- **Default exclusions** skip dependency/build directories, lockfiles, archives, and default `codebase-export.*` output names. -- **Size and binary checks** replace unavailable content with an omission notice. Symbolic links and junctions are skipped. +## Commands + +| Command Palette title | What it does | +| --- | --- | +| **CodebaseMD: Export Wizard** | Four steps: scope, content mode, format, destination | +| **CodebaseMD: Export Git Changes** | Files changed against `HEAD` plus untracked files, using your settings | +| **CodebaseMD: Copy Current File** | Copies the active saved file, including unsaved edits | +| **Export Codebase as Markdown** | Whole workspace folder to a Markdown file | +| **Export Selected as Markdown** | Selected files and folders to a Markdown file | +| **Export Micro Codebase** | Whole workspace folder as a Micro summary | +| **Export Selected as Micro Codebase** | Selected files and folders as a Micro summary | + +The two selected-export commands also appear in the Explorer context menu. +Multi-root workspaces prompt for one folder per export. [Usage](docs/usage.md) +walks through each command. -These rules also apply to explicit selections. See [configuration examples](docs/configuration.md). +## Settings -## Accuracy and scope +Search for **CodebaseMD** in Settings. Every key has the `codebaseMD.` prefix +and can be set per workspace folder. -**Token estimates** use `ceil(characters / 4)`, not a model tokenizer. File statistics cover transformed content. The budget warning covers the entire formatted output, including headers and diffs. Actual model usage can differ substantially. +| Setting | Default | Meaning | +| --- | --- | --- | +| `format` | `markdown` | `markdown`, `xml` or `text` | +| `contentMode` | `full` | `full`, `micro` or `skeleton` | +| `target` | `file` | `file`, `clipboard` or `editor` | +| `tokenBudget` | `32000` | Warn above this estimate; `0` disables the warning | +| `redactSecrets` | `true` | Replace recognizable secrets before exporting | +| `maxFileSizeKB` | `1024` | Largest file content or diff to include, in KiB | +| `exclude` | `[]` | Extra gitignore-style patterns to leave out entirely | +| `respectGitignore` | `true` | Apply root and nested `.gitignore` files | +| `includeDiff` | `false` | Add tracked-file diffs to Git exports | +| `lineNumbers` | `false` | Number the lines of the exported representation | +| `customHeader` | empty | Text added to the top of each export, such as your task | -**Micro and skeleton modes** use heuristics, not complete language parsers. Skeletons may miss multiline declarations or misidentify signatures; files without recognized declarations retain full content. Line numbers in condensed modes refer to the exported representation. +The wizard starts from these values. The four original commands always save +Markdown in their full or Micro mode, and Copy Current File always uses the +clipboard. [Configuration](docs/configuration.md) has examples. -**Secret redaction** recognizes common provider tokens, JWTs, private keys, and password/token assignments. It can miss secrets or redact ordinary values. Review exports before sharing them. Paths remain visible unless excluded; redaction reports contain counts, not matched values. +## Choosing what is shared -**Git exports** use disk/index changes against HEAD to select files. Buffer-only edits do not add files to this scope, although selected open files use editor content. Diffs reflect disk/index state, omit deleted/excluded/unavailable contents, and do not include untracked-file patches. Deleted paths remain listed. Repositories without commits are supported. Git exports require workspace trust. +| Rule | Effect | +| --- | --- | +| `.gitignore` (root and nested) and `codebaseMD.exclude` | Matching files are left out entirely, including their paths | +| `.codebaseignore` in the workspace root | Matching files keep their path in the tree; their content is omitted | +| Built-in exclusions | Dependency and build directories, lockfiles, archives and `codebase-export.*` are skipped | +| Size and binary checks | Oversized and binary files get an omission notice instead of content | +| Symbolic links and junctions | Never followed, even when selected explicitly | + +The same rules apply to explicit selections and to Git exports. + +## How it works + +```text +VS Code command ──► config.ts ──► exporter.ts ──► formatters.ts ──► file / clipboard / editor + (extension.ts) validated │ + settings ├─ fsUtils.ts ignore rules, containment, directory walk + ├─ git.ts changed files and filtered diffs + ├─ secrets.ts redaction, before any transformation + ├─ analyzer.ts Micro summaries, language mapping + ├─ skeleton.ts declaration outlines + └─ tokens.ts characters / 4 estimate +``` -**Local workspaces** are supported, one folder per export. Virtual filesystem workspaces and untitled files are not supported. +Only `extension.ts` and `config.ts` touch VS Code APIs. The export pipeline is +plain Node code, which is why the unit tests can run it against temporary +directories and Git repositories without an editor. Nothing is written until +the export has been prepared and the budget check has passed. +[Architecture](docs/architecture.md) describes each stage and the safety +properties it keeps. + +## Limitations + +- **Token estimates** are `ceil(characters / 4)`, not a model tokenizer. Real + usage can differ substantially. +- **Secret redaction** is heuristic. It recognizes common provider tokens, + JWTs, private keys and password or token assignments; it can miss secrets + and can redact ordinary values. Review exports before sharing them. Paths + stay visible unless excluded. +- **Micro and skeleton modes** use regular expressions, not language parsers. + They can miss multiline declarations or misread signatures. Use full mode + when exact source matters. +- **Git exports** reflect the disk and index against `HEAD`. Unsaved buffers do + not select a file, diffs do not include untracked files, and Git exports + require a trusted workspace. +- **Workspaces** must be local folders, one folder per export. Virtual + filesystems and untitled files are not supported. +- **Platforms:** CI covers Linux and Windows. macOS is expected to work but is + not tested in CI. + +## Repository layout + +| Path | Contents | +| --- | --- | +| `src/` | Extension source; one module per pipeline stage | +| `src/test/unit/` | Unit tests for the pipeline and helpers (no VS Code needed) | +| `src/test/suite/` | Tests that run inside a VS Code extension host | +| `docs/` | User and developer documentation | +| `releases/` | Release notes per version, and VSIX files of releases before 3.0 | +| `scripts/` | Release publishing script used by CI | +| `assets/` | Icon, logo and banner | +| `.github/` | CI workflow, Dependabot, issue and pull request templates | +| `CodebaseMD-Web/` | Placeholder for a separate web prototype; not part of the extension | ## Development -Use [Bun](https://bun.sh) 1.4+, Node.js 22.12+ (Node 24 recommended) and Git: +You need [Bun](https://bun.sh) 1.4+, Node.js 22.12+ (24 recommended) and Git. ```sh bun install --frozen-lockfile -bun run lint -bun run test -bun run test:integration -bun run package +bun run check # Biome lint and format check, then unit tests +bun run test:integration # extension-host tests (Linux: prefix with xvfb-run -a) +bun run package # build the VSIX ``` -Unit tests import production modules and create temporary Git repositories. Integration tests launch a VS Code host and verify commands, clipboard output, and unsaved content. Linux integration tests require a display (`xvfb-run -a bun run test:integration` in CI). The CI workflow tests Windows and Linux and retains the built VSIX as an artifact. +CI runs the same steps on Linux and Windows, audits dependencies, checks REUSE +licensing metadata and keeps the built VSIX as an artifact. See +[CONTRIBUTING.md](CONTRIBUTING.md) for the workflow and +[AGENTS.md](AGENTS.md) for a short guide aimed at coding agents. + +## Documentation -See [contributing](CONTRIBUTING.md), the [developer module reference](docs/api-reference.md), and the [research and implementation plan](docs/v3-plan.md). The separate [web prototype](CodebaseMD-Web/README.md) is not part of this extension release. +| Document | For | +| --- | --- | +| [Installation](docs/installation.md) | Installing and verifying the extension | +| [Usage](docs/usage.md) | Each command, step by step | +| [Configuration](docs/configuration.md) | Settings, ignore files and limits | +| [Micro export format](docs/micro-export-format.md) | The compact summary notation | +| [Troubleshooting](docs/troubleshooting.md) | Common problems and fixes | +| [Architecture](docs/architecture.md) | Pipeline stages and safety properties | +| [Developer reference](docs/api-reference.md) | Modules, command IDs and the `exportCodebase` contract | +| [Changelog](CHANGELOG.md) and [release notes](releases/) | What changed in each version | + +## Contributing + +Bug reports, fixes and documentation improvements are welcome. Start with +[CONTRIBUTING.md](CONTRIBUTING.md); use the +[issue templates](https://github.com/alpha912/codebase-md/issues/new/choose) for +bugs and ideas, and [SECURITY.md](SECURITY.md) for vulnerabilities. Everyone +taking part is expected to follow the [Code of Conduct](CODE_OF_CONDUCT.md). ## License -[MIT](LICENSE.md) · Created by [Alphin Tom](https://github.com/alpha912). +[MIT](LICENSE.md) © Alphin Tom. The repository follows the +[REUSE](https://reuse.software/) specification: source files carry SPDX +headers and [`REUSE.toml`](REUSE.toml) covers the rest. The Code of Conduct is +adapted from the Contributor Covenant under CC BY 4.0. diff --git a/REUSE.toml b/REUSE.toml new file mode 100644 index 0000000..edfc0b2 --- /dev/null +++ b/REUSE.toml @@ -0,0 +1,23 @@ +# SPDX-FileCopyrightText: 2024-2026 Alphin Tom +# +# SPDX-License-Identifier: MIT +# +# Licensing for files that cannot carry an SPDX header (JSON, Markdown, images, +# lockfiles, packaged VSIX files). Source files carry their own headers. +# See https://reuse.software/spec/. + +version = 1 + +# Default: everything not otherwise annotated is MIT, held by Alphin Tom. +[[annotations]] +path = "**" +precedence = "aggregate" +SPDX-FileCopyrightText = "2024-2026 Alphin Tom" +SPDX-License-Identifier = "MIT" + +# Contributor Covenant text, adapted. Upstream attribution is kept in the file. +[[annotations]] +path = "CODE_OF_CONDUCT.md" +precedence = "override" +SPDX-FileCopyrightText = ["Contributor Covenant authors", "2024-2026 Alphin Tom"] +SPDX-License-Identifier = "CC-BY-4.0" diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..7d3f16d --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,81 @@ +# Security Policy + +## Reporting a Vulnerability + +Report suspected vulnerabilities privately through GitHub's +**Report a vulnerability** button on the repository's +[Security tab](https://github.com/alpha912/codebase-md/security). If you cannot +use GitHub's form, write to the contact address in the +[Code of Conduct](CODE_OF_CONDUCT.md#enforcement) with "SECURITY" in the +subject. + +Include the extension version (or commit), your VS Code version and platform, +what an attacker can do, and the smallest workspace layout or file that +reproduces it. Please do not open public issues or pull requests for +undisclosed vulnerabilities, and do not attach private code or real +credentials. + +The project has one maintainer and reports are handled on a best-effort basis. +You can normally expect a first reply within a week, and a disclosure date +agreed with you once a fix is ready. Reporters are credited in the release +notes unless they ask not to be. + +## Supported Versions + +Security fixes go into the next release; only the latest release is supported. + +| Version | Supported | +| --- | --- | +| Latest 3.x release | Yes | +| 2.x and earlier | No; upgrade to the latest release | + +## Scope + +CodebaseMD reads files from a workspace folder and writes one document to a +file, the clipboard or an editor. It makes no network requests. The following +are in scope: + +- **Leaving the workspace:** any way to make an export include a file outside + the chosen workspace folder, including through symbolic links, junctions, + `..` segments or crafted selections. +- **Bypassing exclusions:** content or paths that appear in an export although + `.gitignore`, `.codebaseignore`, `codebaseMD.exclude`, the size limit or the + binary check should have removed them. +- **Output injection:** source text that breaks out of a Markdown code fence + or produces malformed or misleading XML. +- **Git handling:** a repository or Git configuration that makes the extension + run an external program (diff drivers, textconv filters, pagers, prompts) or + that exposes excluded content through a diff. +- **Untrusted workspaces:** any Git operation that runs before the workspace + is trusted. +- **Resource exhaustion:** a workspace that makes an export hang or exhaust + memory in a way the size limits and cancellation should prevent. +- **Release integrity:** problems in the CI and release workflow. + +Out of scope: + +- **Secrets that redaction misses.** Redaction is a documented heuristic, not + a guarantee. Missed patterns are welcome as ordinary bug reports with a + synthetic example; reports that redaction leaks or logs the *matched values* + are in scope. +- Vulnerabilities in dependencies that the extension does not reach. Report + those upstream, and tell us if CodebaseMD exposes them. +- What happens to an export after it leaves the editor, for example the + handling of pasted text by another tool or service. + +## Assurance + +What has been done: file collection resolves every path, checks that it stays +inside the workspace folder and rejects symbolic links in every path +component; redaction runs before any transformation and reports only counts; +Markdown fences are sized so embedded backticks cannot close them, and XML +output is escaped, including control characters; Git is invoked without a +shell, with literal pathspecs, with terminal prompts disabled and with +external diff and textconv programs turned off, and only in trusted +workspaces. These behaviours are covered by unit tests. Workflow actions are +pinned to commit hashes, the workflow token is read-only except in the release +job, dependencies are audited in CI, and each release ships with a SHA-256 +checksum. + +What has not been done: no independent security audit and no fuzzing. Treat +an export as something to review before you share it. diff --git a/SUPPORT.md b/SUPPORT.md new file mode 100644 index 0000000..88d0005 --- /dev/null +++ b/SUPPORT.md @@ -0,0 +1,17 @@ +# Getting Help + +| You want to | Go to | +| --- | --- | +| Fix a problem yourself | [Troubleshooting](docs/troubleshooting.md), then [usage](docs/usage.md) and [configuration](docs/configuration.md) | +| Ask a question or share how you use CodebaseMD | [GitHub Discussions](https://github.com/alpha912/codebase-md/discussions) | +| Report a bug | [Bug report](https://github.com/alpha912/codebase-md/issues/new?template=bug_report.yml) | +| Suggest a feature | [Feature request](https://github.com/alpha912/codebase-md/issues/new?template=feature_request.yml) | +| Report a documentation problem | [Documentation issue](https://github.com/alpha912/codebase-md/issues/new?template=docs_issue.yml) | +| Report a vulnerability | [SECURITY.md](SECURITY.md); do not open a public issue | + +When you report a bug, include the extension version, your VS Code version and +platform, the command you ran and a minimal, sanitized example. Never attach +private code or real credentials. + +CodebaseMD is maintained by one person in their spare time. Issues are read, +but there is no guaranteed response time and no paid support. diff --git a/assets/icon.png b/assets/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..47f14b4b940ad2cdf35861c3df9118dba27f668b GIT binary patch literal 14102 zcmd6uRZty4x3)JB+%32U4Fq?0cMb0D?ry;$SaA2??y`~K?yehm*f@u;{=0K7|BG{~ zx@xAnX69mg$+Onm9jT-siHv}c0001xrKQAF004;3TL=Ig%;!bdxy&2@;MkBB6ISzF zJ)e;#{G>2tV#z_xPVL1vcm2@-nmy@Ya0J zLjRAa|L6PvmuEsr9FC+kx4Q?XJ{Ip=4;gcUCEsTS%SHF((&P+PgN2ik*<@h;;F-b8 z4N=lfB%2|Of2j&AFin^>gv26Xa&cQnYa|DJslprYZ3O_JkptmqVuOrGmjFu#36N}9 zLcQK2Oq3=G==Cvy7=h%DS_OvT5QS_oZRC@`JfllynQoW1u3Nut{O$MqBhLsRzCO(C z-BYhh^WcNidY3A`Q-tJ7kL8X^S5Jw`a5rY^y_bYsp(;A`bxS=JwTJ4+?b79Il|Rlh zs-EM-Sw6!Z{qoS`l(W_ zWJ~=Sj&<=M|-{K(VDh zn|LHX*?(}g`Ff;qDZJ@<`4h0(X`v*D(ExM#R~!|`F=uH z)$j>fJPj&?N@c9f*Pgy*uU*R7X`-IL%=0^d@0@uVrBX0|zWw7jt8q&j#0<4hw?CC6 zB~KW2Kk|Kq<-P2=O+TTf-kovizLxv|!bxVe;Q-=aH!_`e=i)=~kqq)!?y)}TgO)FI z$FC%h7%WABEaZE7jx>`$YT=fnm;opgk#k`}GK@+x=d)h#i)Sud{4Q&v3PZpx8WF<= zW-w&0si^Pi>Y73cy$>;Z`M=t)cTvYKGvrGU$nJ|Cr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vc31uIt z@;gZUr?Vl3CUN)-s5R4C4@l&KM=cJnx6gTLwQE6eq}Mq?+kEXEm71O)oBob!83HQ5 z+k7Hy+Vqf2*<8&@9BBXahx^0sw)vj#^~Y_JD~Xvza}+4f;L9ojRYln->8I|Qlan#G zk|lxr`g64JhuToJF_+zlz=OVxl0ThsvbUEhcHfund5%~&H?Q;Kx3nu&`PbRSl%I7y zD-7!LLdojmFUnwAfGj-qe|ZaR(!M#n!D@~)UyKMPI}rteifd#k^1OdUY`G60S@$;) z7P!Y>mOFGfF?}vhyD{JUhAmUVBuOppm)?5^KKN5uu#weED#7S%XD8cX2~`|yH#$!} zX+#je9#Ew$n*{?%2(*XCR}frXKSA6eU!RaD+Y`RzS=8NQyn;Amqd^Oe4PvW@X~mXV zFJqMBJ{#Q3j6hQi;n8idlL&}+I|O$_=}hj0o<#CZt(eLA~If~QLUK>nQUekG0L zv4(#ESMe(!gtVAy^Y=ack~qlTjZzThKUN)W^l4Pr;#PUUp-%{_m`S$S2nH^h3Fzyn%`t!QTzQ=Mi8ewL|vi|=8jNd>BZEa@QH?Xs8iz6!<>4Evonmm - CodebaseMD Logo -

+CodebaseMD exports a workspace, a selection or your Git changes as one +Markdown, XML or plain-text document. Start with the +[project README](../README.md) for an overview and a short example. -Welcome to CodebaseMD 3.0: export code context as Markdown, XML or text to a file, clipboard or editor. Start with the [Export Wizard and settings](../README.md#whats-new-in-version-300), or read the [v3 release notes](../releases/RELEASE-NOTES-3.0.0.md). +## Using the extension -## Table of Contents +| Page | Contents | +| --- | --- | +| [Installation](installation.md) | Installing from GitHub Releases or the Marketplace, and verifying it works | +| [Usage](usage.md) | The Export Wizard, Git Changes, Copy Current File and the original commands | +| [Configuration](configuration.md) | Settings, `.codebaseignore`, exclusions and limits | +| [Micro export format](micro-export-format.md) | The compact summary notation and how to read it | +| [Troubleshooting](troubleshooting.md) | Common problems and their fixes | -1. [Installation](./installation.md) -2. [Usage](./usage.md) -3. [Configuration](./configuration.md) -4. [API Reference](./api-reference.md) -5. [Contributing](./contributing.md) -6. [Changelog](./changelog.md) -7. [Troubleshooting](./troubleshooting.md) -8. [Micro Export Format](https://github.com/alpha912/codebase-md/blob/main/docs/micro-export-format.md) -9. [v3 Plan and Research](https://github.com/alpha912/codebase-md/blob/main/docs/v3-plan.md) +## Working on the extension -For the main project README, please refer to the [README.md](../README.md) in the root directory. +| Page | Contents | +| --- | --- | +| [Architecture](architecture.md) | The export pipeline, module boundaries and safety properties | +| [Developer reference](api-reference.md) | Modules, command IDs and the `exportCodebase` contract | +| [Contributing](../CONTRIBUTING.md) | Setup, checks, pull requests and releases | +| [Agent instructions](../AGENTS.md) | A short guide for coding agents | +| [v3 plan and research](v3-plan.md) | The research and plan behind version 3.0 (historical) | ---- +## Project -

- CodebaseMD -

+| Page | Contents | +| --- | --- | +| [Changelog](../CHANGELOG.md) | Changes in each version | +| [Release notes](../releases/) | Longer notes per release | +| [Security policy](../SECURITY.md) | Reporting vulnerabilities; what is in scope | +| [Support](../SUPPORT.md) | Where to ask questions and report problems | diff --git a/docs/api-reference.md b/docs/api-reference.md index fdcbcc7..5cccce6 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -1,6 +1,6 @@ -# Developer API Reference +# Developer Reference -CodebaseMD does not expose a stable external programmatic API. Its production modules are independently testable: +CodebaseMD does not expose a stable external programmatic API. Its production modules are independently testable; [architecture](architecture.md) describes how they fit together: | Module | Responsibility | | --- | --- | diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..ec2ab99 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,159 @@ +# Architecture + +CodebaseMD is a single VS Code extension with one runtime dependency +(`ignore`). An export is a pipeline: settings are validated, files are +selected, each file is read, redacted and transformed, and the result is +rendered as one document. Nothing is written until the whole document exists +and the token-budget check has passed. + +```text +VS Code command ──► config.ts ──► exporter.ts ──► formatters.ts ──► file / clipboard / editor + (extension.ts) validated │ + settings ├─ fsUtils.ts ignore rules, containment, directory walk + ├─ git.ts changed files and filtered diffs + ├─ secrets.ts redaction, before any transformation + ├─ analyzer.ts Micro summaries, language mapping + ├─ skeleton.ts declaration outlines + └─ tokens.ts characters / 4 estimate +``` + +## Module boundary + +Only `extension.ts` and `config.ts` import `vscode`. Everything else is plain +Node code. `exportCodebase(root, options, request, hooks)` receives what it +needs through its arguments: + +- `options`: an `ExportOptions` value, already validated; +- `request`: either a list of selected absolute paths or `{ git: true }`; +- `hooks`: `cancelled()`, `progress(message)` and `readText(path)`, which lets + the command layer supply unsaved editor contents. + +It returns the structured document, the formatted text and a token estimate +for the whole output. It does not write files, touch the clipboard or show +notifications. This is what lets the unit tests exercise filtering, redaction +and Git behaviour against temporary directories without an editor. + +## Stages + +### 1. Settings (`config.ts`) + +Reads `codebaseMD.*` for the workspace folder being exported. Every value is +checked; anything of the wrong type or out of range falls back to its default, +so the pipeline never sees invalid options. + +### 2. File selection (`fsUtils.ts`, `git.ts`) + +`createFilters` builds three rule sets: the built-in exclusions plus +`codebaseMD.exclude`; `.codebaseignore` from the workspace root (content +only); and, when `respectGitignore` is on, each directory's `.gitignore`, +evaluated ancestor by ancestor so a nested negation cannot re-include an +ignored directory. + +`collectFiles` walks the workspace folder, or the selected paths, or the paths +Git reports as changed. For every path it: + +- resolves it and rejects anything outside the workspace folder; +- checks each path component with `lstat` and stops at a symbolic link or + junction, including when a child of a link was selected explicitly; +- applies the exclusion rules; +- deduplicates, so overlapping selections produce one entry. + +For Git scope, `getGitChanges` lists files changed against `HEAD` (staged and +unstaged), untracked files that are not ignored, and deleted files. A +repository without commits is handled by listing the index instead. + +### 3. Reading and transforming (`exporter.ts`) + +Each selected file becomes an entry with a path, a language and either content +or an omission notice. Content is omitted when the file is matched by +`.codebaseignore`, is not a supported type, is not a regular file, exceeds +`maxFileSizeKB`, contains a NUL byte (binary) or cannot be read. The path +stays in the export so the reader can see that something was left out. + +For files that are read, the order is fixed: + +1. **Read** the editor buffer if the hook supplies one, otherwise the file. +2. **Redact** (`secrets.ts`), unless `redactSecrets` is off. +3. **Transform** according to the content mode: unchanged, Micro + (`analyzer.ts`) or skeleton (`skeleton.ts`). +4. **Number lines**, if requested. +5. **Estimate tokens** (`tokens.ts`) on the result. + +Redaction comes before transformation so a condensed mode can never surface a +value that redaction would have removed. The custom header and any diffs are +redacted too. + +### 4. Diffs (`git.ts`) + +With `includeDiff`, a diff is produced for each tracked file whose content was +included. Files that were omitted for any reason contribute no diff, so a diff +cannot reveal content the filters removed. Diffs are size-limited like file +contents. + +### 5. Rendering (`formatters.ts`) + +`formatDocument` renders the document as Markdown, XML or plain text. All +three carry the summary line, the custom header, the folder tree, per-language +statistics, each file and any diffs. Markdown adds a linked contents list. + +- Markdown code fences are made longer than any run of backticks in the + content, so source text cannot close a fence early. +- XML text and attributes are escaped, and characters that XML 1.0 forbids are + replaced. + +### 6. Output (`extension.ts`) + +The command layer estimates tokens for the complete output, warns if the +estimate exceeds `tokenBudget`, and only then writes to the chosen +destination. Saving refuses to overwrite a file that is part of the export. + +## Safety properties + +These are the behaviours a change must not weaken. Each is covered by unit +tests in `src/test/unit/`. + +| Property | Where it is enforced | +| --- | --- | +| No file outside the workspace folder is exported | `isWithin`, `collectFiles` | +| Symbolic links and junctions are never followed | `collectFiles`, `exportCodebase` | +| Excluded paths never appear; `.codebaseignore` content never appears | `createFilters`, `exportCodebase` | +| Redaction runs before transformation and reports counts only | `exportCodebase`, `redactSecrets` | +| Diffs never include content the filters removed | `exportCodebase` | +| Git runs without a shell, prompts, pagers, external diff or textconv programs | `git.ts` | +| Git operations require a trusted workspace | `extension.ts` | +| A cancelled export returns nothing | `checkCancelled` throughout | +| Output stays well-formed for any source text | `codeFence`, `xmlEscape` | + +## Heuristics + +Three parts of the pipeline are deliberately approximate, and the UI and +documentation say so: + +- **Token estimate:** `ceil(characters / 4)`. It is model-independent and + cheap; it is not a tokenizer. +- **Secret redaction:** regular expressions for common provider tokens, JWTs, + private keys and password or token assignments. It can miss secrets and can + redact ordinary values. +- **Micro and skeleton modes:** regular expressions, not parsers. When + skeleton mode recognises no declarations in a file, it returns the file + unchanged rather than an empty outline. + +## Tests + +| Suite | Location | Runs in | Covers | +| --- | --- | --- | --- | +| Unit | `src/test/unit/` | Node (Mocha) | The pipeline against temporary directories and Git repositories; pure helpers | +| Extension host | `src/test/suite/` | A downloaded VS Code build | Activation, commands, clipboard output, unsaved buffers | + +`bun run test` runs the unit suite. `bun run test:integration` runs every +compiled test, unit tests included, inside the extension host. + +## Build and release + +TypeScript compiles `src/` to CommonJS in `out/`. `vsce package` bundles +`out/` (without tests and source maps), the `ignore` package, the icon, the +README, the changelog and the license into the VSIX; `.vscodeignore` lists +what is left out. CI runs lint, tests, the dependency audit and packaging on +Linux and Windows, and a commit on `main` whose message starts with `release:` +publishes a GitHub release from that commit. See +[CONTRIBUTING.md](../CONTRIBUTING.md#releases). diff --git a/docs/configuration.md b/docs/configuration.md index 6248172..5e00050 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -33,4 +33,4 @@ Use `codebaseMD.exclude` or `.gitignore` when paths should also be omitted. Root ## Limits -Files above `maxFileSizeKB`, binary files and unsupported types receive omission notices. Symbolic links and junctions are skipped. Token estimates, redaction and skeleton extraction are heuristic; see [accuracy and scope](../README.md#accuracy-and-scope). No source edits or rebuilds are needed to change settings. +Files above `maxFileSizeKB`, binary files and unsupported types receive omission notices. Symbolic links and junctions are skipped. Token estimates, redaction and skeleton extraction are heuristic; see [limitations](../README.md#limitations). No source edits or rebuilds are needed to change settings. diff --git a/docs/contributing.md b/docs/contributing.md index 4cbe0f5..66814e5 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -1,7 +1,5 @@ # Contributing -See the [repository contribution guide](../CONTRIBUTING.md) for setup, testing, and pull request guidance. - -Development requires Bun 1.4+, Node.js 22.12+ (Node 24 recommended) and Git. Run `bun install --frozen-lockfile`, `bun run lint`, `bun run test`, `bun run test:integration`, and `bun run package`. `bun run lint:fix` applies Biome formatting and safe lint fixes. On headless Linux, run integration tests with `xvfb-run -a`. - -Production modules are described in the [developer reference](api-reference.md). Add regression tests that import the actual module being changed. Keep generated JavaScript in `out/` and do not commit VSIX files. +The contribution guide is [CONTRIBUTING.md](../CONTRIBUTING.md) in the +repository root: setup, checks, conventions, pull requests and releases. +[Architecture](architecture.md) explains how the code is organised. diff --git a/docs/installation.md b/docs/installation.md index d9218ef..c76b2c1 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -1,34 +1,54 @@ # Installation -There are two ways to install the CodebaseMD extension for Visual Studio Code: +CodebaseMD needs VS Code and a local folder to export. Git is needed only for +Git exports. -For v3.0.0, install the VSIX from GitHub Releases. Marketplace publishing is separate and its version may differ. The extension supports VS Code 1.146+ and local filesystem workspaces. +| Release | Requires | +| --- | --- | +| 3.0.0 (current) | VS Code 1.70 or later | +| Next release (unreleased, on `main`) | VS Code 1.146 or later | -## 1. From Visual Studio Marketplace +## From GitHub Releases -1. Open Visual Studio Code -2. Go to the Extensions view by clicking on the square icon in the left sidebar or pressing `Ctrl+Shift+X` (Windows/Linux) or `Cmd+Shift+X` (macOS) -3. Search for "CodebaseMD" -4. Click on the "Install" button next to the CodebaseMD extension +This is the recommended way to get the newest version. -## 2. Manual Installation via VSIX +1. Download `codebase-md-.vsix` from the + [latest release](https://github.com/alpha912/codebase-md/releases/latest). +2. Optionally verify it against the `.sha256` file published next to it: -1. Download the latest `.vsix` file from the [releases section](https://github.com/alpha912/codebase-md/releases) of the GitHub repository -2. Open Visual Studio Code -3. Go to the Extensions view -4. Click on the "..." (More Actions) button in the top-right corner of the Extensions view -5. Select "Install from VSIX..." -6. Navigate to the downloaded `.vsix` file and select it -7. Click "Install" + ```sh + sha256sum -c codebase-md-.vsix.sha256 + ``` -After installation, you may need to reload Visual Studio Code for the extension to activate. +3. In VS Code, open the Extensions view (`Ctrl+Shift+X`, or `Cmd+Shift+X` on + macOS), choose **… → Install from VSIX…** and select the file. -## Verifying Installation +You can also install from a terminal: -To verify that CodebaseMD has been installed correctly: +```sh +code --install-extension codebase-md-.vsix +``` -1. Open the Command Palette (`Ctrl+Shift+P` or `Cmd+Shift+P`) -2. Type "CodebaseMD" -3. Run **CodebaseMD: Export Wizard**. The original Markdown and Micro commands are also available. +## From the Visual Studio Marketplace -If you encounter any issues during installation, please refer to the [Troubleshooting](./troubleshooting.md) guide or [open an issue](https://github.com/alpha912/codebase-md/issues) on GitHub. +Search for **CodebaseMD** in the Extensions view and choose **Install**, or +open the +[Marketplace page](https://marketplace.visualstudio.com/items?itemName=alpha912.codebase-md). +Marketplace publication is a separate step from a GitHub release, so the +version there can be older. + +## Verifying the installation + +1. Open a local folder. +2. Open the Command Palette (`Ctrl+Shift+P`, or `Cmd+Shift+P` on macOS) and + type "CodebaseMD". +3. Run **CodebaseMD: Export Wizard** and choose *Workspace → Full → Markdown → + Editor*. A new tab opens with the export. + +If the commands are missing, see [troubleshooting](troubleshooting.md). + +## Updating and removing + +Install a newer VSIX over the existing one to update. To remove the extension, +choose **Uninstall** on its page in the Extensions view. CodebaseMD stores no +data outside your VS Code settings. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 76d31e9..780a471 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -2,7 +2,7 @@ ## Commands are missing -Confirm the extension is enabled, reload VS Code, and search for **CodebaseMD: Export Wizard**. The v3 GitHub VSIX may be newer than the Marketplace version. VS Code 1.146 or later is required. +Confirm the extension is enabled, reload VS Code, and search for **CodebaseMD: Export Wizard**. The GitHub VSIX may be newer than the Marketplace version. Check that your VS Code meets the [minimum version](installation.md) for the release you installed. ## No files to export diff --git a/docs/usage.md b/docs/usage.md index c1d34c7..01961dd 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -33,7 +33,7 @@ Open a saved file in your workspace and run **CodebaseMD: Copy Current File**. I Exports contain file paths, a folder tree, language statistics, estimated content tokens, and the requested representation. Markdown also has a linked contents list. The completion notification and budget check use an estimate of the whole document, including formatting and diffs. -Token counts, secret detection and condensed representations are heuristic. Consult [accuracy and scope](../README.md#accuracy-and-scope) and [Micro format details](micro-export-format.md). There is no fixed compression ratio. +Token counts, secret detection and condensed representations are heuristic. Consult [limitations](../README.md#limitations) and [Micro format details](micro-export-format.md). There is no fixed compression ratio. ## Filtering and settings diff --git a/package.json b/package.json index 1939102..e4f280d 100644 --- a/package.json +++ b/package.json @@ -26,7 +26,7 @@ "url": "https://github.com/alpha912/codebase-md.git" }, "license": "MIT", - "icon": "assets/logo.png", + "icon": "assets/icon.png", "contributes": { "commands": [ { @@ -168,6 +168,7 @@ "scripts": { "vscode:prepublish": "tsc -p ./", "compile": "tsc -p ./", + "typecheck": "tsc -p ./ --noEmit", "watch": "tsc -watch -p ./", "test-compile": "tsc -p ./", "pretest": "bun run test-compile", @@ -176,7 +177,8 @@ "publish": "vsce publish", "test:integration": "bun run compile && node ./out/test/runTest.js", "lint": "biome check .", - "lint:fix": "biome check --write ." + "lint:fix": "biome check --write .", + "check": "bun run lint && bun run test" }, "devDependencies": { "@biomejs/biome": "^2.6.6", diff --git a/scripts/publish-release.cjs b/scripts/publish-release.cjs index 98e981d..2a856bc 100644 --- a/scripts/publish-release.cjs +++ b/scripts/publish-release.cjs @@ -1,3 +1,12 @@ +// SPDX-FileCopyrightText: 2024-2026 Alphin Tom +// +// SPDX-License-Identifier: MIT + +// File: scripts/publish-release.cjs +// What: Creates the GitHub release for the version in package.json and attaches the VSIX and its SHA-256 checksum. +// Why: Releases are published by CI from a verified commit, never by hand, and never overwrite an existing tag. +// Related: .github/workflows/ci.yml, releases/RELEASE-NOTES-.md + // Run after successful checks and packaging. Never overwrite a published release. const fs = require('node:fs'); const crypto = require('node:crypto'); diff --git a/src/analyzer.ts b/src/analyzer.ts index 0845083..a4afa8d 100644 --- a/src/analyzer.ts +++ b/src/analyzer.ts @@ -1,3 +1,12 @@ +// SPDX-FileCopyrightText: 2024-2026 Alphin Tom +// +// SPDX-License-Identifier: MIT + +// File: src/analyzer.ts +// What: Language mapping and the Micro representation: a regex-based summary of a file's path, dependencies, exports and members. +// Why: Micro is the established compact format from 2.x; it is heuristic and intentionally not a language parser. +// Related: exporter.ts, docs/micro-export-format.md + import * as path from 'node:path'; export function condenseMicroCode(code: string, fileName: string, filePath: string): string { @@ -190,7 +199,7 @@ function extractFileMetadata(code: string, language: string, _filePath: string): for (let i = 0; i < Math.min(10, lines.length); i++) { const line = lines[i].trim(); if (line.startsWith('//') || line.startsWith('/*') || line.startsWith('*')) { - const comment = line.replace(/^\/\/|^\/\*|\*\/$|\*$/g, '').trim(); + const comment = line.replace(/^\/\/+|^\/\*+|^\*+(?!\/)|\*+\/$/g, '').trim(); if (comment && !comment.startsWith('@') && description.length < 100) { description += (description ? ' ' : '') + comment; } diff --git a/src/config.ts b/src/config.ts index d8e1e01..a2ce227 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1,3 +1,12 @@ +// SPDX-FileCopyrightText: 2024-2026 Alphin Tom +// +// SPDX-License-Identifier: MIT + +// File: src/config.ts +// What: Reads the `codebaseMD.*` settings for a workspace folder and replaces invalid values with defaults. +// Why: Settings are user input; the exporter must never see an out-of-range or mistyped option. +// Related: types.ts, extension.ts + import * as vscode from 'vscode'; import { defaults, type ExportOptions } from './types'; diff --git a/src/exporter.ts b/src/exporter.ts index 2a351a7..6c918d9 100644 --- a/src/exporter.ts +++ b/src/exporter.ts @@ -1,3 +1,12 @@ +// SPDX-FileCopyrightText: 2024-2026 Alphin Tom +// +// SPDX-License-Identifier: MIT + +// File: src/exporter.ts +// What: The export pipeline: collect files, read them, redact, transform (full, Micro or skeleton), and render one document. +// Why: Keeps the whole export pure of VS Code APIs so unit tests can run it against temporary directories. +// Related: fsUtils.ts, git.ts, secrets.ts, formatters.ts + import * as fs from 'node:fs'; import * as path from 'node:path'; import { condenseMicroCode, getLanguageForSpecialFile, getLanguageFromExtension } from './analyzer'; diff --git a/src/extension.ts b/src/extension.ts index b02ce05..1c9c7d2 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -1,3 +1,12 @@ +// SPDX-FileCopyrightText: 2024-2026 Alphin Tom +// +// SPDX-License-Identifier: MIT + +// File: src/extension.ts +// What: VS Code entry point: registers the commands, runs the Export Wizard, shows progress and the token-budget warning, and writes the result to a file, the clipboard or an editor. +// Why: The only module that performs side effects in VS Code; everything it calls is testable without an extension host. +// Related: exporter.ts, config.ts + import * as vscode from 'vscode'; import { readConfig } from './config'; import { exportCodebase } from './exporter'; diff --git a/src/formatters.ts b/src/formatters.ts index dba5c51..f291290 100644 --- a/src/formatters.ts +++ b/src/formatters.ts @@ -1,3 +1,12 @@ +// SPDX-FileCopyrightText: 2024-2026 Alphin Tom +// +// SPDX-License-Identifier: MIT + +// File: src/formatters.ts +// What: Renders an export document as Markdown, XML or plain text, including the folder tree and statistics. +// Why: Output must stay well-formed whatever the source contains: fences cannot be closed early and XML is always escaped. +// Related: exporter.ts, types.ts + import type { ExportDocument, OutputFormat } from './types'; export function xmlEscape(text: string): string { diff --git a/src/fsUtils.ts b/src/fsUtils.ts index 988f20b..703559e 100644 --- a/src/fsUtils.ts +++ b/src/fsUtils.ts @@ -1,3 +1,12 @@ +// SPDX-FileCopyrightText: 2024-2026 Alphin Tom +// +// SPDX-License-Identifier: MIT + +// File: src/fsUtils.ts +// What: Ignore rules, workspace containment checks and the directory walk that selects files for an export. +// Why: Decides what leaves the workspace: nothing outside the root, nothing excluded, no symbolic links or junctions followed. +// Related: exporter.ts + import * as fs from 'node:fs'; import * as path from 'node:path'; import ignore, { type Ignore } from 'ignore'; diff --git a/src/git.ts b/src/git.ts index 5796f79..42e530e 100644 --- a/src/git.ts +++ b/src/git.ts @@ -1,3 +1,12 @@ +// SPDX-FileCopyrightText: 2024-2026 Alphin Tom +// +// SPDX-License-Identifier: MIT + +// File: src/git.ts +// What: Finds files changed against HEAD (staged, unstaged, untracked, renamed, deleted) and produces filtered diffs. +// Why: Git scope and diffs must work without external diff or textconv tools and in repositories without commits. +// Related: exporter.ts + import { execFile } from 'node:child_process'; import * as path from 'node:path'; import { checkCancelled, type ExportHooks } from './types'; diff --git a/src/secrets.ts b/src/secrets.ts index ea31d62..b9c912c 100644 --- a/src/secrets.ts +++ b/src/secrets.ts @@ -1,3 +1,12 @@ +// SPDX-FileCopyrightText: 2024-2026 Alphin Tom +// +// SPDX-License-Identifier: MIT + +// File: src/secrets.ts +// What: Heuristic secret redaction that returns sanitized text and a count, never the matched values. +// Why: Exports are meant to be pasted into other tools; recognizable credentials should not travel with them. +// Related: exporter.ts + export interface RedactionResult { text: string; count: number; diff --git a/src/skeleton.ts b/src/skeleton.ts index 214b77c..17e8b27 100644 --- a/src/skeleton.ts +++ b/src/skeleton.ts @@ -1,3 +1,12 @@ +// SPDX-FileCopyrightText: 2024-2026 Alphin Tom +// +// SPDX-License-Identifier: MIT + +// File: src/skeleton.ts +// What: Skeleton mode: keeps import and declaration lines and drops bodies. +// Why: A cheaper, language-agnostic alternative to Micro for fitting more files into a context budget. +// Related: exporter.ts + /** Best-effort outline. This deliberately does not claim to be a language parser. */ export function skeleton(code: string, language: string): string { const lines = code.split(/\r?\n/); diff --git a/src/test/runTest.ts b/src/test/runTest.ts index b0fbbc1..09d6686 100644 --- a/src/test/runTest.ts +++ b/src/test/runTest.ts @@ -1,3 +1,12 @@ +// SPDX-FileCopyrightText: 2024-2026 Alphin Tom +// +// SPDX-License-Identifier: MIT + +// File: src/test/runTest.ts +// What: Launches a VS Code extension host and runs the integration suite inside it. +// Why: Commands, clipboard output and unsaved-buffer handling can only be verified in a real host. +// Related: suite/index.ts + import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; diff --git a/src/test/suite/extension.test.ts b/src/test/suite/extension.test.ts index d3fc56e..a73ff6b 100644 --- a/src/test/suite/extension.test.ts +++ b/src/test/suite/extension.test.ts @@ -1,3 +1,12 @@ +// SPDX-FileCopyrightText: 2024-2026 Alphin Tom +// +// SPDX-License-Identifier: MIT + +// File: src/test/suite/extension.test.ts +// What: Extension-host tests for activation and the current-file command. +// Why: Covers behaviour that depends on VS Code itself. +// Related: ../../extension.ts + import * as assert from 'node:assert'; import * as vscode from 'vscode'; diff --git a/src/test/suite/fileProcessing.test.ts b/src/test/suite/fileProcessing.test.ts index cacb01e..564b97f 100644 --- a/src/test/suite/fileProcessing.test.ts +++ b/src/test/suite/fileProcessing.test.ts @@ -1,3 +1,12 @@ +// SPDX-FileCopyrightText: 2024-2026 Alphin Tom +// +// SPDX-License-Identifier: MIT + +// File: src/test/suite/fileProcessing.test.ts +// What: Checks file-support rules inside the extension host. +// Why: Guards the production rules against drifting from what the host loads. +// Related: ../../exporter.ts + import * as assert from 'node:assert'; import { isSupportedFile } from '../../exporter'; diff --git a/src/test/suite/index.ts b/src/test/suite/index.ts index ed21c3d..ea82a52 100644 --- a/src/test/suite/index.ts +++ b/src/test/suite/index.ts @@ -1,3 +1,12 @@ +// SPDX-FileCopyrightText: 2024-2026 Alphin Tom +// +// SPDX-License-Identifier: MIT + +// File: src/test/suite/index.ts +// What: Mocha entry point loaded by the extension host; discovers every compiled `*.test.js`. +// Why: The host needs a single module that runs the tests and reports failures. +// Related: ../runTest.ts + import * as fs from 'node:fs'; import * as path from 'node:path'; diff --git a/src/test/suite/markdownGeneration.test.ts b/src/test/suite/markdownGeneration.test.ts index 37c0604..dbadae6 100644 --- a/src/test/suite/markdownGeneration.test.ts +++ b/src/test/suite/markdownGeneration.test.ts @@ -1,3 +1,12 @@ +// SPDX-FileCopyrightText: 2024-2026 Alphin Tom +// +// SPDX-License-Identifier: MIT + +// File: src/test/suite/markdownGeneration.test.ts +// What: Checks fence and tree generation inside the extension host. +// Why: Guards the production formatters against drifting from what the host loads. +// Related: ../../formatters.ts + import * as assert from 'node:assert'; import { codeFence, folderTree } from '../../formatters'; diff --git a/src/test/suite/mockFileSystem.ts b/src/test/suite/mockFileSystem.ts deleted file mode 100644 index 36139bf..0000000 --- a/src/test/suite/mockFileSystem.ts +++ /dev/null @@ -1,64 +0,0 @@ -import * as path from 'node:path'; - -export interface MockFileSystem { - rootPath: string; - files: string[]; - mockFileContents: Record; - readFile: (filePath: string) => string; - isDirectory: (filePath: string) => boolean; - isFile: (filePath: string) => boolean; - getRelativePath: (filePath: string) => string; -} - -/** - * Creates a mock file system structure for testing - */ -export function createMockFileSystem(): MockFileSystem { - const rootPath = `${path.sep}mock-project`; - - const files = [ - path.join(rootPath, 'src', 'index.ts'), - path.join(rootPath, 'src', 'utils', 'helper.ts'), - path.join(rootPath, 'src', 'components', 'App.tsx'), - path.join(rootPath, 'src', 'components', 'Button.tsx'), - path.join(rootPath, 'package.json'), - path.join(rootPath, 'tsconfig.json'), - path.join(rootPath, 'README.md'), - path.join(rootPath, '.gitignore'), - path.join(rootPath, 'node_modules', 'react', 'package.json'), - path.join(rootPath, 'node_modules', 'typescript', 'package.json'), - path.join(rootPath, 'build', 'index.js'), - path.join(rootPath, 'public', 'index.html'), - path.join(rootPath, 'public', 'styles.css'), - path.join(rootPath, 'Dockerfile'), - ]; - - const mockFileContents: Record = { - [path.join(rootPath, 'src', 'index.ts')]: - '// Main entry point\nimport React from "react";\nimport ReactDOM from "react-dom";\nimport App from "./components/App";\n\nReactDOM.render(, document.getElementById("root"));', - [path.join(rootPath, 'src', 'components', 'App.tsx')]: - '// App component\nimport React from "react";\nimport Button from "./Button";\n\nexport default function App() {\n return (\n
\n

Hello World

\n
\n );\n}', - [path.join(rootPath, 'package.json')]: - '{\n "name": "mock-project",\n "version": "1.0.0",\n "dependencies": {\n "react": "^17.0.2",\n "react-dom": "^17.0.2"\n }\n}', - [path.join(rootPath, 'README.md')]: '# Mock Project\n\nThis is a mock project for testing.', - }; - - return { - rootPath, - files, - mockFileContents, - readFile: (filePath: string): string => { - return mockFileContents[filePath] || ''; - }, - isDirectory: (filePath: string): boolean => { - // Check if any file starts with this path - return files.some((f) => f.startsWith(filePath) && f !== filePath); - }, - isFile: (filePath: string): boolean => { - return files.includes(filePath); - }, - getRelativePath: (filePath: string): string => { - return path.relative(rootPath, filePath); - }, - }; -} diff --git a/src/test/tsconfig.json b/src/test/tsconfig.json deleted file mode 100644 index 1b21353..0000000 --- a/src/test/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "extends": "../tsconfig.json", - "compilerOptions": { - "module": "commonjs", - "target": "es2015", - "outDir": "../../out", - "rootDir": "..", - "sourceMap": true, - "strict": true, - "esModuleInterop": true, - "skipLibCheck": true - }, - "include": ["."] -} diff --git a/src/test/unit/exporter.test.ts b/src/test/unit/exporter.test.ts index 3255189..5ac4c4f 100644 --- a/src/test/unit/exporter.test.ts +++ b/src/test/unit/exporter.test.ts @@ -1,3 +1,12 @@ +// SPDX-FileCopyrightText: 2024-2026 Alphin Tom +// +// SPDX-License-Identifier: MIT + +// File: src/test/unit/exporter.test.ts +// What: Unit tests for the export pipeline against temporary directories and Git repositories. +// Why: The pipeline's filtering, redaction and Git behaviour are the product; they are tested without VS Code. +// Related: ../../exporter.ts + import * as assert from 'node:assert'; import { execFileSync } from 'node:child_process'; import * as fs from 'node:fs'; diff --git a/src/test/unit/helpers.test.ts b/src/test/unit/helpers.test.ts new file mode 100644 index 0000000..9d1dcd4 --- /dev/null +++ b/src/test/unit/helpers.test.ts @@ -0,0 +1,113 @@ +// SPDX-FileCopyrightText: 2024-2026 Alphin Tom +// +// SPDX-License-Identifier: MIT + +// File: src/test/unit/helpers.test.ts +// What: Unit tests for language mapping, the Micro representation, path containment and formatting helpers. +// Why: Pins the small pure functions the pipeline is built from. +// Related: ../../analyzer.ts, ../../fsUtils.ts, ../../formatters.ts + +import * as assert from 'node:assert'; +import * as path from 'node:path'; +import { condenseMicroCode, getLanguageForSpecialFile, getLanguageFromExtension } from '../../analyzer'; +import { codeFence, folderTree, formatDocument, xmlEscape } from '../../formatters'; +import { isWithin, relativePath } from '../../fsUtils'; +import type { ExportDocument } from '../../types'; + +suite('Language mapping', () => { + test('maps known extensions and falls back to unknown', () => { + assert.strictEqual(getLanguageFromExtension('.ts'), 'typescript'); + assert.strictEqual(getLanguageFromExtension('.py'), 'python'); + assert.strictEqual(getLanguageFromExtension('.zzz'), 'unknown'); + }); + + test('maps extensionless files and falls back to plaintext', () => { + assert.strictEqual(getLanguageForSpecialFile('Dockerfile'), 'dockerfile'); + assert.strictEqual(getLanguageForSpecialFile('Makefile'), 'makefile'); + assert.strictEqual(getLanguageForSpecialFile('nope'), 'plaintext'); + }); +}); + +suite('Micro representation', () => { + const source = [ + 'import { x } from "./x";', + 'export class Greeter {', + ' private name: string;', + ' public greet(who: string): string {', + ' return who;', + ' }', + '}', + 'export function hi(): void {}', + '', + ].join('\n'); + + test('summarises path, dependencies, exports and members', () => { + const micro = condenseMicroCode(source, 'greeter.ts', 'src/greeter.ts'); + assert.ok(micro.startsWith('// PATH: src/greeter.ts [TYPESCRIPT]\n')); + assert.ok(micro.includes('// DEPS: ./x')); + assert.ok(micro.includes('EXPORT [C:1, F:1]')); + assert.ok(micro.includes('C+ Greeter {')); + assert.ok(micro.includes('V- name:string')); + assert.ok(micro.includes('F+ greet(who:string):string')); + assert.ok(micro.includes('F+ hi')); + }); + + test('description comes from the leading comment without comment markers', () => { + const micro = condenseMicroCode(`/** Greets people. */\n${source}`, 'greeter.ts', 'src/greeter.ts'); + assert.ok(micro.includes('// DESC: Greets people.\n')); + }); + + test('drops method bodies', () => { + const micro = condenseMicroCode(source, 'greeter.ts', 'src/greeter.ts'); + assert.ok(!micro.includes('return who;')); + }); +}); + +suite('Path containment', () => { + const root = path.resolve('workspace', 'project'); + + test('accepts the root and its descendants only', () => { + assert.ok(isWithin(root, root)); + assert.ok(isWithin(root, path.join(root, 'src', 'a.ts'))); + assert.ok(!isWithin(root, path.dirname(root))); + assert.ok(!isWithin(root, `${root}-sibling`)); + assert.ok(!isWithin(root, path.join(root, '..', 'other', 'a.ts'))); + }); + + test('relative paths always use forward slashes', () => { + assert.strictEqual(relativePath(root, path.join(root, 'src', 'nested', 'a.ts')), 'src/nested/a.ts'); + }); +}); + +suite('Formatting helpers', () => { + const doc: ExportDocument = { + files: [{ path: 'a.ts', language: 'typescript', content: 'x', tokens: 1, redactions: 0 }], + mode: 'full', + header: 'Task', + diff: '', + redactions: 0, + }; + + test('XML escaping replaces control characters and markup', () => { + assert.strictEqual(xmlEscape('a\u0001&"q"'), 'a�<b>&"q"'); + }); + + test('code fences carry the language', () => { + assert.strictEqual(codeFence('x', 'ts'), '```ts\nx\n```'); + }); + + test('folder tree lists directories before files, sorted', () => { + assert.strictEqual( + folderTree(['b.ts', 'a/c.ts', 'a/b/d.ts']), + ['├── a/', '│ ├── b/', '│ │ └── d.ts', '│ └── c.ts', '└── b.ts'].join('\n'), + ); + }); + + test('plain text output carries the summary, header, tree and file content', () => { + const text = formatDocument(doc, 'text'); + assert.ok(text.startsWith('CodebaseMD Export\n1 files | 1 estimated content tokens')); + assert.ok(text.includes('\nTask\n')); + assert.ok(text.includes('└── a.ts')); + assert.ok(text.includes('=== a.ts (~1 tokens) ===\nx')); + }); +}); diff --git a/src/tokens.ts b/src/tokens.ts index 2ce2f9b..2dd71a6 100644 --- a/src/tokens.ts +++ b/src/tokens.ts @@ -1,3 +1,12 @@ +// SPDX-FileCopyrightText: 2024-2026 Alphin Tom +// +// SPDX-License-Identifier: MIT + +// File: src/tokens.ts +// What: Character-based token estimate. +// Why: Gives a model-independent size signal for budgets without bundling a tokenizer. +// Related: exporter.ts, formatters.ts + /** A model-independent heuristic, not a tokenizer or a context-limit guarantee. */ export function estimateTokens(text: string): number { return Math.ceil(text.length / 4); diff --git a/src/tsconfig.json b/src/tsconfig.json deleted file mode 100644 index 7eca4fe..0000000 --- a/src/tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "../tsconfig.json", - "compilerOptions": { - "outDir": "../out", - "rootDir": "." - } -} diff --git a/src/types.ts b/src/types.ts index 4a1be72..dabcc41 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,3 +1,12 @@ +// SPDX-FileCopyrightText: 2024-2026 Alphin Tom +// +// SPDX-License-Identifier: MIT + +// File: src/types.ts +// What: Shared option, document and hook types, the default options and the cancellation contract. +// Why: One definition of the export contract for the pipeline, the command layer and the tests. +// Related: exporter.ts, config.ts + export type OutputFormat = 'markdown' | 'xml' | 'text'; export type ContentMode = 'full' | 'micro' | 'skeleton'; export type ExportTarget = 'file' | 'clipboard' | 'editor'; diff --git a/tsconfig.json b/tsconfig.json index f806084..80edf13 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -7,13 +7,16 @@ "sourceMap": true, "rootDir": "src", "strict": true, - "noImplicitAny": true, "types": ["node", "vscode", "mocha"], "moduleResolution": "node16", "esModuleInterop": true, - "allowSyntheticDefaultImports": true, "skipLibCheck": true, - "forceConsistentCasingInFileNames": true + "forceConsistentCasingInFileNames": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noImplicitReturns": true, + "noImplicitOverride": true, + "noFallthroughCasesInSwitch": true }, - "exclude": ["node_modules", ".vscode-test", "test-file.ts", "test-*.js", "*.test.ts"] + "include": ["src"] } From e42558605fe2e06dd77e2a0ecbe2eb034266943f Mon Sep 17 00:00:00 2001 From: alpha912 Date: Wed, 11 Nov 2026 21:26:44 +0000 Subject: [PATCH 2/2] chore: use LF line endings in Biome now that .gitattributes enforces them --- biome.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/biome.json b/biome.json index 3ff82f4..b82c6d0 100644 --- a/biome.json +++ b/biome.json @@ -14,7 +14,7 @@ "indentStyle": "space", "indentWidth": 2, "lineWidth": 120, - "lineEnding": "auto" + "lineEnding": "lf" }, "linter": { "enabled": true,