Skip to content

refactor(tools/cli): execlude *.mock.compact contracts from builder#68

Open
0xisk wants to merge 5 commits intomainfrom
refactor/builder-ignore-mock
Open

refactor(tools/cli): execlude *.mock.compact contracts from builder#68
0xisk wants to merge 5 commits intomainfrom
refactor/builder-ignore-mock

Conversation

@0xisk
Copy link
Member

@0xisk 0xisk commented Feb 24, 2026

Types of changes

What types of changes does your code introduce to OpenZeppelin Midnight Contracts?
Put an x in the boxes that apply

  • Bugfix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation Update (if none of the other choices apply)

Fixes #66

Motivation: for large projects like Lunarswap, it is very time confusing to wait for the builder to compile with ZK all the mock contracts, because they are only meant for testing.

  • Compiler: Added --exclude (glob patterns to skip files, e.g. mocks/tests) and --dry-run (list files that would be compiled, no compile). Exported matchGlob and globToRegExp for pattern checks.
  • Builder: Dropped the hardcoded rm dist/Mock*.compact step; exclusion is handled via --exclude on the compiler.
  • Package: No exports; CLI-only, no library import surface. README documents --exclude and --dry-run, and the Programmatic API section was removed.
  • Tests: New/updated tests for exclusion, root-level patterns, --dry-run parsing/behavior, and showDryRun output.

PR Checklist

  • I have read the Contributing Guide
  • I have added tests that prove my fix is effective or that my feature works
  • I have added documentation of new methods and any new behavior or changes to existing behavior
  • CI Workflows Are Passing

Further comments

If this is a relatively large or complex change, kick off the discussion by explaining why you chose the solution you did and what alternatives you considered, etc...

Summary by CodeRabbit

Release Notes

  • New Features

    • Added --exclude CLI flag to filter files by glob patterns (repeatable option)
    • Added --dry-run CLI flag to preview compilation output without executing
  • Documentation

    • Updated README with examples, supported glob patterns, and guidance for exclusion and dry-run features

@0xisk 0xisk requested review from a team as code owners February 24, 2026 12:14
@0xisk 0xisk self-assigned this Feb 24, 2026
@0xisk 0xisk added the enhancement New feature or request label Feb 24, 2026
@coderabbitai
Copy link

coderabbitai bot commented Feb 24, 2026

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b1490e7e-b3a4-40ea-b1f2-b98f1e03542c

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

Walkthrough

This PR introduces file exclusion and dry-run capabilities to the CLI compiler. It adds glob pattern matching for excluding files, extends CLI options with --exclude and --dry-run flags, updates file discovery to filter excluded files, adds a dry-run preview mode in the UI service, and removes post-copy cleanup behavior for mock compact files from the build process.

Changes

Cohort / File(s) Summary
Documentation
packages/cli/README.md
Added user-facing documentation for --exclude and --dry-run CLI options with glob pattern examples, usage guidance, and sample outputs; removed Programmatic API section from Builder/CLI docs.
Configuration
packages/cli/package.json
Removed the exports field, eliminating the public entry point export map.
Build Process
packages/cli/src/Builder.ts
Shortened build step message and removed cleanup logic for Mock*.compact files; copy step now only transfers *.compact files without post-copy removal.
Core Compiler Logic
packages/cli/src/Compiler.ts
Added glob matching utilities (matchGlob, globToRegExp); extended CompilerOptions with exclude and dryRun fields; enhanced FileDiscovery to filter excluded files; added UIService.showDryRun() for preview mode; updated CompactCompiler to parse --exclude and --dry-run flags and skip compilation in dry-run mode.
Test Suite
packages/cli/test/Compiler.test.ts
Added comprehensive tests for exclude pattern matching, dry-run output formatting, and integration flows; verified that exclude patterns affect file discovery and compilation paths.

Sequence Diagram

sequenceDiagram
    actor User
    participant CLI as CLI / CompactCompiler
    participant Parser as Argument Parser
    participant Discovery as FileDiscovery
    participant UIService as UIService
    participant Compiler as Compilation Engine

    User->>CLI: Invoke with --exclude and --dry-run flags
    CLI->>Parser: parseArgs(args)
    Parser->>Parser: Extract exclude patterns and dryRun flag
    CLI->>Discovery: new FileDiscovery(srcDir, exclude patterns)
    Discovery->>Discovery: Filter .compact files via isExcluded()
    alt Dry-run mode active
        CLI->>UIService: showDryRun(filtered files, targetDir)
        UIService->>User: Display preview of files to compile
    else Dry-run mode inactive
        CLI->>Compiler: compile()
        Compiler->>Compiler: Process filtered files
        Compiler->>User: Generate output
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • emnul
  • andrew-fleming

Poem

🐰 With patterns to match and files to exclude,
We hop through the globs in a careful mood,
A dry-run preview before we compile,
Clean buildpaths ahead, every last mile! ✨
Ready to skip the Mock contracts with style! 🎉

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Title check ⚠️ Warning The PR title contains a typo ('execlude' instead of 'exclude') and is misleading about the primary change—it emphasizes builder changes but the main feature adds compiler CLI flags for exclusion and dry-run. Correct the typo and clarify the title to reflect the primary changes: 'refactor(cli): add --exclude and --dry-run flags for compiler' or similar.
Out of Scope Changes check ⚠️ Warning The removal of the 'exports' field from package.json and the Programmatic API section from README appear to be out of scope; issue #66 only requires excluding mock contracts from the builder. Clarify whether removing exports and the Programmatic API section are intentional scope changes, or revert these changes to keep the PR focused on the exclusion feature.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The PR successfully addresses issue #66 by excluding *.mock.compact contracts from the builder through the new --exclude CLI flag mechanism.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/builder-ignore-mock

Comment @coderabbitai help to get the list of available commands and usage tips.

@0xisk 0xisk modified the milestone: compact `0.29.0` Feb 24, 2026
@0xisk 0xisk moved this from Backlog to In progress in OZ Development for Midnight Feb 24, 2026
@0xisk 0xisk moved this from In progress to Needs Review in OZ Development for Midnight Feb 24, 2026
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
packages/cli/README.md (1)

183-185: ⚠️ Potential issue | 🟡 Minor

Stale "Copy and clean" step description

Line 184 still reads "Copy and clean .compact files to dist/" but the cleanup (removal of Mock*.compact) was removed in this PR. The step now only copies.

📝 Proposed fix
-4. Copy and clean `.compact` files to `dist/`
+4. Copy `.compact` files to `dist/`
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/cli/README.md` around lines 183 - 185, Update the README step that
currently reads "Copy and clean `.compact` files to `dist/`" to reflect the new
behavior: change the wording to "Copy `.compact` files to `dist/`" (or similar
phrasing) to remove mention of cleanup/removal of Mock*.compact, referencing the
entry in the CLI README where the artifact copy steps are listed so the
documentation matches the PR changes.
packages/cli/src/Builder.ts (1)

116-125: ⚠️ Potential issue | 🟠 Major

--dry-run flag is silently ignored for all build steps

compile() returns early when dryRun is true, but build() unconditionally proceeds to run all three shell steps (tsc, artifact copy, .compact copy). A user passing --dry-run to compact-builder will see the dry-run preview from the compiler, then immediately trigger a real TypeScript compilation and file copy — the opposite of what the flag promises.

The README states the builder "Accepts all compiler options except --skip-zk", which explicitly advertises --dry-run support.

🐛 Proposed fix
  public async build(): Promise<void> {
    const compiler = new CompactCompiler(this.options);
    await compiler.compile();

+   if (this.options.dryRun) {
+     return; // dry-run: compiler already showed the preview; skip build steps
+   }
+
    for (const [index, step] of this.steps.entries()) {
      await this.executeStep(step, index, this.steps.length);
    }
  }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/cli/src/Builder.ts` around lines 116 - 125, The build method
currently always runs executeStep over this.steps even when the
CompactCompiler.compile() returned early for a dry run; update build to check
the dry-run flag and skip executing real build steps when dryRun is true: after
creating the CompactCompiler and awaiting compiler.compile(), inspect the same
dry-run option (this.options.dryRun or compiler.dryRun if available) and return
early (or skip the for loop) so executeStep(...) is not invoked during a dry
run; reference the build method, CompactCompiler.compile, and executeStep to
locate and change the logic.
packages/cli/src/Compiler.ts (1)

922-930: ⚠️ Potential issue | 🟡 Minor

[COMPILE] prefix shown in dry-run mode when no files are found

When dryRun is true and compactFiles.length === 0 (either because the directory is truly empty, or because every file matched an --exclude pattern), showNoFiles is called before the dry-run branch is reached. This emits:

⚠ [COMPILE] No .compact files found in .

The [COMPILE] prefix implies compilation was attempted, which is misleading during a dry-run. When all files are excluded the message is also indistinguishable from "no files exist", making it impossible to verify that --exclude patterns are correct via --dry-run.

🐛 Proposed fix – move the dry-run gate before showNoFiles
-    if (compactFiles.length === 0) {
-      UIService.showNoFiles(this.options.targetDir);
-      return;
-    }
-
     if (this.options.dryRun) {
       UIService.showDryRun(compactFiles, this.options.targetDir);
       return;
     }

+    if (compactFiles.length === 0) {
+      UIService.showNoFiles(this.options.targetDir);
+      return;
+    }
+
     UIService.showCompilationStart(compactFiles.length, this.options.targetDir);

showDryRun already handles the zero-file case gracefully ("Would compile 0 file(s)") and keeps the [DRY-RUN] prefix throughout.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/cli/src/Compiler.ts` around lines 922 - 930, The dry-run branch must
be evaluated before the "no files" check so UIService.showDryRun handles the
zero-file case and uses the correct "[DRY-RUN]" prefix; in the method where
compactFiles is checked (in Compiler.ts near the block referencing compactFiles,
this.options.dryRun, UIService.showNoFiles and UIService.showDryRun) move the if
(this.options.dryRun) { UIService.showDryRun(compactFiles,
this.options.targetDir); return; } check to occur before the if
(compactFiles.length === 0) { UIService.showNoFiles(...); return; } so dry-run
always takes precedence and short-circuits before showing the "no files" compile
message.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/cli/README.md`:
- Around line 130-135: The fenced code block showing the example output (the
block containing "ℹ [DRY-RUN] Would compile 2 file(s):" and the two file lines)
lacks a language specifier which triggers markdownlint MD040; update that fenced
block to include a language tag such as text or console (e.g., replace ``` with
```text) so the linter is satisfied while keeping the existing contents
unchanged.

In `@packages/cli/src/Builder.ts`:
- Around line 78-82: The current shell task in Builder that runs 'find src -name
"*.compact" -exec cp {} dist/' ignores this.options.exclude and flattens files;
replace that shell task with a TypeScript copy that uses the already-filtered
list from FileDiscovery (the same list CompactCompiler uses) so excluded
patterns are respected, create target subdirectories under dist preserving each
file's relative path (avoid name collisions), and ensure directories are created
before writing; update the Builder task definition to call this new copy routine
instead of the shell command.

---

Outside diff comments:
In `@packages/cli/README.md`:
- Around line 183-185: Update the README step that currently reads "Copy and
clean `.compact` files to `dist/`" to reflect the new behavior: change the
wording to "Copy `.compact` files to `dist/`" (or similar phrasing) to remove
mention of cleanup/removal of Mock*.compact, referencing the entry in the CLI
README where the artifact copy steps are listed so the documentation matches the
PR changes.

In `@packages/cli/src/Builder.ts`:
- Around line 116-125: The build method currently always runs executeStep over
this.steps even when the CompactCompiler.compile() returned early for a dry run;
update build to check the dry-run flag and skip executing real build steps when
dryRun is true: after creating the CompactCompiler and awaiting
compiler.compile(), inspect the same dry-run option (this.options.dryRun or
compiler.dryRun if available) and return early (or skip the for loop) so
executeStep(...) is not invoked during a dry run; reference the build method,
CompactCompiler.compile, and executeStep to locate and change the logic.

In `@packages/cli/src/Compiler.ts`:
- Around line 922-930: The dry-run branch must be evaluated before the "no
files" check so UIService.showDryRun handles the zero-file case and uses the
correct "[DRY-RUN]" prefix; in the method where compactFiles is checked (in
Compiler.ts near the block referencing compactFiles, this.options.dryRun,
UIService.showNoFiles and UIService.showDryRun) move the if
(this.options.dryRun) { UIService.showDryRun(compactFiles,
this.options.targetDir); return; } check to occur before the if
(compactFiles.length === 0) { UIService.showNoFiles(...); return; } so dry-run
always takes precedence and short-circuits before showing the "no files" compile
message.

ℹ️ Review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dd729af and 77754af.

📒 Files selected for processing (5)
  • packages/cli/README.md
  • packages/cli/package.json
  • packages/cli/src/Builder.ts
  • packages/cli/src/Compiler.ts
  • packages/cli/test/Compiler.test.ts
💤 Files with no reviewable changes (1)
  • packages/cli/package.json

Comment on lines +130 to +135
**Example output:**
```
ℹ [DRY-RUN] Would compile 2 file(s):
Token.compact
AccessControl.compact
```
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Fenced code block missing language specifier

The markdownlint MD040 warning here is valid — the example output block has no language tag. Use text (or console) to satisfy the linter.

📝 Proposed fix
-```
+```text
 ℹ [DRY-RUN] Would compile 2 file(s):
     Token.compact
     AccessControl.compact
</details>

<!-- suggestion_start -->

<details>
<summary>📝 Committable suggestion</summary>

> ‼️ **IMPORTANT**
> Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

```suggestion
**Example output:**
🧰 Tools
🪛 markdownlint-cli2 (0.21.0)

[warning] 131-131: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/cli/README.md` around lines 130 - 135, The fenced code block showing
the example output (the block containing "ℹ [DRY-RUN] Would compile 2 file(s):"
and the two file lines) lacks a language specifier which triggers markdownlint
MD040; update that fenced block to include a language tag such as text or
console (e.g., replace ``` with ```text) so the linter is satisfied while
keeping the existing contents unchanged.

Comment on lines 78 to 82
{
cmd: 'mkdir -p dist && find src -type f -name "*.compact" -exec cp {} dist/ \\; 2>/dev/null && rm dist/Mock*.compact 2>/dev/null || true',
msg: 'Copying and cleaning .compact files',
cmd: 'mkdir -p dist && find src -type f -name "*.compact" -exec cp {} dist/ \\; 2>/dev/null || true',
msg: 'Copying .compact files',
shell: '/bin/bash',
},
Copy link

@coderabbitai coderabbitai bot Feb 24, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

--exclude patterns are not honoured by the .compact copy step

The shell command at line 79 copies every .compact file found under src/ regardless of this.options.exclude. Exclude patterns are propagated to CompactCompiler (so mock files aren't compiled), but they never reach this step, so the excluded source files are still written to dist/. The old rm dist/Mock*.compact cleanup that kept them out of dist/ was removed without an equivalent filter here, leaving dist/ populated with the very mock contracts issue #66 aimed to exclude.

Additionally, because find ... -exec cp {} dist/ flattens all .compact files into a single directory, same-named files from different subdirectories (e.g., src/access/Token.compact and src/token/Token.compact) would silently overwrite each other.

The cleanest fix is to perform the copy in TypeScript, reusing the already-filtered file list from FileDiscovery, rather than relying on a raw shell command.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/cli/src/Builder.ts` around lines 78 - 82, The current shell task in
Builder that runs 'find src -name "*.compact" -exec cp {} dist/' ignores
this.options.exclude and flattens files; replace that shell task with a
TypeScript copy that uses the already-filtered list from FileDiscovery (the same
list CompactCompiler uses) so excluded patterns are respected, create target
subdirectories under dist preserving each file's relative path (avoid name
collisions), and ensure directories are created before writing; update the
Builder task definition to call this new copy routine instead of the shell
command.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧩 Analysis chain

@emnul, agreed — the copy step needs to be fixed. I'll plan the TypeScript-based replacement now.

Task: Fix .compact copy step to respect exclude patterns and preserve directory structure

  • Add copyCompactFiles() private method to CompactBuilder using FileDiscovery
  • Replace the raw shell copy step with a call to this new method
  • Preserve relative paths under dist/ to avoid name collisions

🏁 Script executed:

#!/bin/bash
# Check current imports and FileDiscovery.getCompactFiles signature
rg -n "getCompactFiles\|DEFAULT_SRC_DIR" packages/cli/src/Compiler.ts | head -40
rg -n "^import" packages/cli/src/Builder.ts

Length of output: 296


🏁 Script executed:

#!/bin/bash
rg -n "getCompactFiles\|DEFAULT_SRC_DIR\|class FileDiscovery" packages/cli/src/Compiler.ts | head -40
rg -n "^import" packages/cli/src/Builder.ts

Length of output: 296


🏁 Script executed:

#!/bin/bash
# Get FileDiscovery class, getCompactFiles, and DEFAULT_SRC_DIR from Compiler.ts
ast-grep --pattern 'class FileDiscovery {
  $$$
}' packages/cli/src/Compiler.ts

rg -n "DEFAULT_SRC_DIR|getCompactFiles|srcDir" packages/cli/src/Compiler.ts | head -30

Length of output: 7098


@emnul, here's the concrete fix. The plan replaces the raw shell copy step with a TypeScript method that reuses FileDiscovery (honoring exclude patterns) and preserves each file's relative path under dist/ to prevent name collisions.

Task: Fix .compact copy step in Builder.ts

  • Import FileDiscovery + Node.js fs/path utilities
  • Extend step type to support an async fn callback alongside cmd
  • Replace 3rd shell step with a fn pointing to a new copyCompactFiles() method
  • Update executeStep to dispatch correctly on fn vs cmd
  • Add private copyCompactFiles() using FileDiscovery with exclude patterns

Failed to handle agent chat message. Please try again.

```

Accepts all compiler options except `--skip-zk` (builds always include ZK proofs).
Accepts all compiler options except `--skip-zk` (builds always include ZK proofs). Use `--exclude` to skip mock contracts or test files during the build.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct me if I'm wrong here, but I'm not seeing any logic that filters --skip-zk for the Builder CLI. The docs should be updated or that logic should be added if we want to enforce this requirement

Comment on lines 78 to 82
{
cmd: 'mkdir -p dist && find src -type f -name "*.compact" -exec cp {} dist/ \\; 2>/dev/null && rm dist/Mock*.compact 2>/dev/null || true',
msg: 'Copying and cleaning .compact files',
cmd: 'mkdir -p dist && find src -type f -name "*.compact" -exec cp {} dist/ \\; 2>/dev/null || true',
msg: 'Copying .compact files',
shell: '/bin/bash',
},
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1

Comment on lines +809 to +828
} else if (args[i] === '--exclude') {
const valueExists =
i + 1 < args.length && !args[i + 1].startsWith('--');
if (valueExists) {
options.exclude = options.exclude ?? [];
options.exclude.push(args[i + 1]);
i++;
} else {
throw new Error('--exclude flag requires a glob pattern');
}
} else if (args[i] === '--include') {
const valueExists =
i + 1 < args.length && !args[i + 1].startsWith('--');
if (valueExists) {
options.include = options.include ?? [];
options.include.push(args[i + 1]);
i++;
} else {
throw new Error('--include flag requires a glob pattern');
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe it's about time we use a cli parser package like yargs instead of hand rolling it with this logic monster

Comment on lines +22 to +80
/**
* Returns true if path matches the glob pattern.
* Supports ** (match zero or more path segments) and * (match within segment).
*
* @param path - The file path to test (use forward slashes)
* @param pattern - Glob pattern to match against
* @returns true if the path matches the pattern
* @example
* ```typescript
* // Pattern string: two asterisks, slash, asterisk, .mock.compact (backslash in code escapes slash for JSDoc)
* matchGlob('foo/bar.mock.compact', '**\/*.mock.compact'); // true
* matchGlob('bar.mock.compact', '*.mock.compact'); // true
* matchGlob('test/unit/foo.compact', '**\/test/**'); // true
* ```
*/
export function matchGlob(path: string, pattern: string): boolean {
const re = globToRegExp(pattern);
return re.test(path);
}

/**
* Converts a glob pattern to a RegExp.
* Supports:
* - `**` matches zero or more path segments
* - `*` matches any characters except `/`
*
* Does NOT support:
* - `?` (single character wildcard)
* - Brace expansion `{a,b}`
* - Negation `!pattern`
*
* @param pattern - Glob pattern to convert
* @returns RegExp that matches paths according to the glob pattern
* @example
* ```typescript
* // Pattern string: two asterisks, slash, asterisk, .mock.compact (backslash in code escapes slash for JSDoc)
* const re = globToRegExp('**\/*.mock.compact');
* re.test('foo/bar.mock.compact'); // true
* re.test('bar.mock.compact'); // true (** matches zero segments)
* ```
*/
// Placeholders for glob-to-regex (private-use Unicode, not in patterns)
const GLOB_STAR_STAR = '\uE001';
const GLOB_STAR = '\uE002';
const GLOB_STAR_STAR_END = '\uE003';

export function globToRegExp(pattern: string): RegExp {
const escaped = pattern
.replace(/[.+^${}()|[\]\\]/g, '\\$&')
.replace(/\*\*\//g, GLOB_STAR_STAR)
.replace(/\/\*\*$/g, `/${GLOB_STAR_STAR_END}`)
.replace(/\*\*/g, GLOB_STAR_STAR)
.replace(/\*/g, GLOB_STAR);
const reStr = escaped
.replace(new RegExp(GLOB_STAR_STAR, 'g'), '(?:[^/]*/)*')
.replace(new RegExp(GLOB_STAR, 'g'), '[^/]*')
.replace(new RegExp(GLOB_STAR_STAR_END, 'g'), '.*');
return new RegExp(`^${reStr}$`);
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This feels like an overly complex solution when we could instead use node's built-in import { matchesGlob } from 'node:path'; in isIncluded

Comment on lines +622 to +635
/**
* Displays dry-run output showing which files would be compiled.
*
* @param files - Array of file paths that would be compiled
* @param targetDir - Optional target directory being compiled
* @example
* ```typescript
* UIService.showDryRun(['Token.compact', 'AccessControl.compact']);
* // Output:
* // [DRY-RUN] Would compile 2 file(s):
* // Token.compact
* // AccessControl.compact
* ```
*/
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It should be noted that --dry-run skips environment validation

Comment on lines 796 to +806
it('should create instance with all parameters', () => {
compiler = new CompactCompiler(
{
flags: '--skip-zk',
targetDir: 'security',
version: '0.26.0',
hierarchical: true,
srcDir: 'contracts',
outDir: 'build',
exclude: ['**/*.mock.compact'],
include: ['**/test/**'],
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't we also have dryRun and verbose here?

Comment on lines +818 to +819
expect(compiler.testOptions.exclude).toEqual(['**/*.mock.compact']);
expect(compiler.testOptions.include).toEqual(['**/test/**']);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same with above

);
});

it('should parse --exclude flag', () => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What should the behavior be if the include and exclude globs are the same?

});
});

describe('CompactCompiler', () => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No E2E tests for the --include flag in CompactCompiler. It's a minor concern, but would surface any internal wiring issues

);

showDryRunSpy.mockRestore();
});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
});
});
it('should pass targetDir to showDryRun', async () => {
mockReaddir.mockResolvedValue([
{ name: 'MyToken.compact', isFile: () => true, isDirectory: () => false },
] as any);
const showDryRunSpy = vi
.spyOn(UIService, 'showDryRun')
.mockImplementation(() => {});
compiler = new CompactCompiler(
{ dryRun: true, targetDir: 'security' },
mockExec,
);
await compiler.compile();
expect(showDryRunSpy).toHaveBeenCalledWith(['MyToken.compact'], 'security');
showDryRunSpy.mockRestore();
});

we don't validate that this.options.targetDir flows through to showDryRun

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

Status: Needs Review

Development

Successfully merging this pull request may close these issues.

Builder should ignore *.mock.compact contracts

2 participants