Skip to content

Conversation

@marchuk-vlad
Copy link
Contributor

@marchuk-vlad marchuk-vlad commented Aug 15, 2025

Summary by CodeRabbit

  • New Features
    • Added a CLI subcommand to calculate the hash of a file or all files in a folder. Accepts a local path, validates it, and outputs the algorithm and hash in JSON. Provides clear errors for invalid or missing paths.
  • Chores
    • Bumped package version to 0.12.3.
    • Updated dependency @super-protocol/sp-files-addon to ^0.12.1.

marchuk-vlad and others added 2 commits August 15, 2025 14:46
* feat: Add calculate-hash command

* fix(calculate-hash): Comment fixes
@marchuk-vlad marchuk-vlad requested a review from serega-k August 15, 2025 12:10
@marchuk-vlad marchuk-vlad self-assigned this Aug 15, 2025
@coderabbitai
Copy link

coderabbitai bot commented Aug 15, 2025

Walkthrough

Adds a new CLI subcommand "files calculate-hash" for hashing a file or directory, implemented in a new module. Updates package version and a dependency. Wires the new command into the CLI entrypoint to accept a localPath argument and output algo/hash JSON.

Changes

Cohort / File(s) Summary of Changes
Release metadata
package.json
Bumped version 0.12.1 → 0.12.3; updated dependency @super-protocol/sp-files-addon ^0.11.0 → ^0.12.1.
New hashing command module
src/commands/filesCalculateHash.ts
Added new command implementation: validates path, computes resource hash, builds root hash via cryptoUtils.getDirHashFileContents, parses algo/hash, outputs JSON. Exports FilesCalculateHashParams and default async handler.
CLI wiring
src/index.ts
Imported filesCalculateHash and added "files calculate-hash" subcommand accepting localPath; invokes handler.

Sequence Diagram(s)

sequenceDiagram
  participant U as User
  participant CLI as CLI (files calculate-hash)
  participant H as filesCalculateHash
  participant CRH as calculateResourceHash
  participant CU as cryptoUtils.getDirHashFileContents

  U->>CLI: run files calculate-hash <localPath>
  CLI->>H: filesCalculateHash({ localPath })
  H->>H: validate & resolve path
  H->>CRH: compute resource hash
  CRH-->>H: hash data
  H->>CU: build root hash from contents
  CU-->>H: algo:hash string
  H-->>CLI: { algo, hash } JSON
  CLI-->>U: print JSON
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~18 minutes

Poem

A hoppity hop through paths I dash,
I sniff a file, a folder’s stash—
Crunching bytes with whiskered flair,
Algo found, the hash laid bare.
Thump-thump keys, results in sight,
0x dreams by moonlit byte.
🐇✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch release/0.12.3

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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: 0

🧹 Nitpick comments (8)
package.json (1)

40-40: Dependency upgrade to @super-protocol/sp-files-addon ^0.12.1 — check packaged binary

The new command relies on calculateResourceHash from this package. Since you bundle with pkg, please verify the packaged binary (dist/spctl) can run files calculate-hash successfully. If sp-files-addon has any dynamic requires, pkg may need explicit asset hints.

If a runtime include is needed, consider adding it to pkg.assets, e.g.:

   "pkg": {
     "assets": [
       "config.example.json",
       "node_modules/@super-protocol/uplink-nodejs/build/Release/*",
       "node_modules/axios/**/*"
+      // "node_modules/@super-protocol/sp-files-addon/**/*"
     ]
   }
src/commands/filesCalculateHash.ts (6)

12-16: Nit: message says “Filename” but the command accepts files or folders

Minor wording tweak for clarity.

-  if (!inputPath) {
-    Printer.print('Filename should be defined');
+  if (!inputPath) {
+    Printer.print('Path should be defined');

20-30: Avoid extra I/O before hashing or gate it behind verbosity

Listing directory entries is only used for an informational log and performs an additional readdir pass. Consider:

  • Dropping the readdir completely, or
  • Printing a simpler “Found folder …” message without counting entries, or
  • Emitting these lines only in a verbose mode (and keeping stdout clean for JSON).
-    if (stat.isDirectory()) {
-      const files = await fs.readdir(localPath);
-
-      Printer.print(`Found folder "${localPath}" with ${files.length} top-level entries`);
-    } else if (stat.isFile()) {
+    if (stat.isDirectory()) {
+      Printer.print(`Found folder "${localPath}"`);
+    } else if (stat.isFile()) {
       Printer.print(`Found file "${localPath}"`);
     } else {
       Printer.print(`Found path "${localPath}" (not a regular file or directory)`);
     }

31-35: Nit: remove the leading newline in the error message

Keeps stderr formatting consistent with the rest of the CLI.

-    if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
-      Printer.error(`\nFile or folder is missing on path ${localPath}`);
+    if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
+      Printer.error(`File or folder is missing on path ${localPath}`);
       return;
     }

47-54: Consider including encoding for consistency with other hash objects

Other parts of the CLI use { algo, encoding, hash }. If consumers expect that structure, add encoding: 'hex' (or whatever rootHash.hash uses).

-    const hash = {
-      algo: colonIndex > 0 ? raw.slice(0, colonIndex).toLowerCase() : '',
-      hash: colonIndex > 0 ? raw.slice(colonIndex + 1) : raw,
-    };
+    const hash = {
+      algo: colonIndex > 0 ? raw.slice(0, colonIndex).toLowerCase() : '',
+      hash: colonIndex > 0 ? raw.slice(colonIndex + 1) : raw,
+      encoding: 'hex',
+    };

42-55: Keep stdout JSON-only; route progress logs elsewhere or add a quiet flag

Right now the command prints human-readable lines (“Found …”, “Calculating hash…”) before the JSON. If the intent is machine consumption, this breaks piping (e.g., to jq). Options:

  • Emit progress messages to stderr instead (keep JSON on stdout), or
  • Add a --quiet/--json-only flag and suppress progress logs when set.

If you want a quick minimal change without new flags, send progress to stderr:

-    Printer.print('Calculating hash...');
+    Printer.error('Calculating hash...');

And similarly for the “Found …” lines above.


55-57: Preserve original error details when wrapping

Re-throwing a new Error drops the original stack/details. Use cause to preserve context (Node.js supports it), or follow your top-level pattern with hasCustomMessage.

-  } catch (error) {
-    throw new Error(`Failed to calculate hash: ${(error as Error).message}`);
-  }
+  } catch (error) {
+    throw Object.assign(new Error('Failed to calculate hash'), { cause: error });
+  }

Alternatively, if you want the top-level handler to display a custom message and log the original error:

throw { hasCustomMessage: true, message: 'Failed to calculate hash', error };
src/index.ts (1)

1598-1605: Consider a --quiet/--json-only option for machine-friendly output

The hashing routine prints informational lines before the final JSON. Adding a flag here would let callers get pure JSON on stdout.

   filesCommand
     .command('calculate-hash')
     .description('Calculate the hash of a file or all files in a folder')
-    .argument('localPath', 'Path to the file or folder')
-    .action(async (localPath: string) => {
-      await filesCalculateHash({ localPath });
+    .argument('localPath', 'Path to the file or folder')
+    .option('--quiet', 'Suppress non-JSON logs', false)
+    .action(async (localPath: string, options: any) => {
+      await filesCalculateHash({ localPath /*, quiet: options.quiet */ });
     });

If you adopt this, update FilesCalculateHashParams and guard prints accordingly.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 115324a and fb91d16.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (3)
  • package.json (2 hunks)
  • src/commands/filesCalculateHash.ts (1 hunks)
  • src/index.ts (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/commands/filesCalculateHash.ts (1)
src/printer.ts (1)
  • error (25-27)
🔇 Additional comments (3)
package.json (1)

3-3: Version bump to 0.12.3 — LGTM

Release metadata aligns with the new CLI feature.

src/commands/filesCalculateHash.ts (1)

44-46: Confirm shape alignment between external utilities
calculateResourceHash is imported from @super-protocol/sp-files-addon and getDirHashFileContents from @super-protocol/sdk-js. Since there are no other calls to getDirHashFileContents in this repo, please verify in their TypeScript definitions or official docs that the value returned by calculateResourceHash(localPath) matches the input shape expected by getDirHashFileContents({ … }). If they differ, this call could throw or produce an incorrect root hash.

src/index.ts (1)

16-16: New import — LGTM

Cleanly wires the new command into the CLI.

@Idris0v Idris0v merged commit 0572b39 into main Sep 3, 2025
11 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants