Skip to content

feat: enhance repository name validation and expose validation function#280

Merged
yamadashy merged 1 commit intomainfrom
fix/remote-url
Jan 10, 2025
Merged

feat: enhance repository name validation and expose validation function#280
yamadashy merged 1 commit intomainfrom
fix/remote-url

Conversation

@yamadashy
Copy link
Owner

@yamadashy yamadashy commented Jan 10, 2025

Improve repository URL validation logic and expose it for website use. Update validation patterns to strictly follow GitHub's repository name rules.

related: #278

Checklist

  • Run npm run test
  • Run npm run lint

@bolt-new-by-stackblitz
Copy link

Review PR in StackBlitz Codeflow Run & review this pull request in StackBlitz Codeflow.

@cloudflare-workers-and-pages
Copy link

cloudflare-workers-and-pages bot commented Jan 10, 2025

Deploying repomix with  Cloudflare Pages  Cloudflare Pages

Latest commit: 76d625e
Status: ✅  Deploy successful!
Preview URL: https://59ea84ba.repomix.pages.dev
Branch Preview URL: https://fix-remote-url.repomix.pages.dev

View logs

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 10, 2025

📝 Walkthrough

Walkthrough

The pull request introduces a new validation mechanism for repository URLs in the remote action functionality. A new function isValidRemoteValue is added to validate repository URLs in two formats: shorthand (e.g., owner/repo) and full GitHub URL. The validation logic is moved from the gitCommand.ts file to remoteAction.ts, enhancing error handling by throwing a RepomixError for invalid URLs. The src/index.ts file is also reorganized to improve export statement clarity and structure.

Changes

File Change Summary
src/cli/actions/remoteAction.ts Added isValidRemoteValue function to validate repository URLs with comprehensive checks for shorthand and full URL formats
src/core/file/gitCommand.ts Removed isValidRemoteUrl function, integrating URL validation directly into execGitShallowClone
src/index.ts Reorganized export statements, added new exports for CLI actions and validation function
tests/cli/actions/remoteAction.test.ts Added comprehensive test suite for isValidRemoteValue function, covering various valid and invalid URL formats

Sequence Diagram

sequenceDiagram
    participant User
    participant RemoteAction
    participant URLValidator
    participant GitClone

    User->>RemoteAction: Provide repository URL
    RemoteAction->>URLValidator: Validate URL
    alt URL is valid
        URLValidator-->>RemoteAction: Validation successful
        RemoteAction->>GitClone: Proceed with cloning
    else URL is invalid
        URLValidator-->>RemoteAction: Throw RepomixError
        RemoteAction-->>User: Display error message
    end
Loading

Possibly related PRs

Finishing Touches

  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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.
    • Generate unit testing code for this file.
    • 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. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

Documentation and Community

  • 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
Contributor

@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: 1

🧹 Nitpick comments (4)
src/core/file/gitCommand.ts (1)

32-36: Consider removing redundant URL validation.

This URL validation is redundant since isValidRemoteValue is already called in runRemoteAction before reaching this point. Consider removing this try-catch block to avoid duplicate validation.

-  // Check if the URL is valid
-  try {
-    new URL(url);
-  } catch (error) {
-    throw new RepomixError(`Invalid repository URL. Please provide a valid URL. url: ${url}`);
-  }
tests/cli/actions/remoteAction.test.ts (1)

133-139: Enhance URL test coverage.

Consider adding more test cases for URLs with:

  • Query parameters (e.g., https://example.com/repo?ref=main)
  • URL fragments (e.g., https://example.com/repo#readme)
  • Port numbers (e.g., https://localhost:8080/repo)
  • Special characters in path (e.g., https://example.com/org/repo%20name)
 const validUrls = [
   'https://example.com',
   'http://localhost',
   'https://github.com/user/repo',
   'https://gitlab.com/user/repo',
   'https://domain.com/path/to/something',
+  'https://example.com/repo?ref=main',
+  'https://example.com/repo#readme',
+  'https://localhost:8080/repo',
+  'https://example.com/org/repo%20name',
 ];
src/cli/actions/remoteAction.ts (2)

24-26: Enhance error message with validation rules.

The error message could be more helpful by including the expected format rules.

-    throw new RepomixError('Invalid repository URL or user/repo format');
+    throw new RepomixError(
+      'Invalid repository URL or user/repo format. Expected format: ' +
+      'owner/repo (e.g., user/project) or a valid Git repository URL'
+    );

121-122: Consider more restrictive repository name validation.

The current regex pattern allows some characters that GitHub might not support. Consider using GitHub's official repository name restrictions.

-  const namePattern = '[a-zA-Z0-9](?:[a-zA-Z0-9._-]*[a-zA-Z0-9])?';
+  // GitHub username: 1-39 characters, alphanumeric or single hyphens, cannot begin/end with hyphen
+  const usernamePattern = '[a-zA-Z0-9](?:[a-zA-Z0-9]|-(?=[a-zA-Z0-9])){0,38}';
+  // GitHub repository: similar rules but allows dots
+  const repoPattern = '[a-zA-Z0-9](?:[a-zA-Z0-9]|-(?=[a-zA-Z0-9])|[._](?=[a-zA-Z0-9])){0,99}';
+  const shortFormRegex = new RegExp(`^${usernamePattern}/${repoPattern}$`);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 001e3f7 and e7e5064.

📒 Files selected for processing (5)
  • src/cli/actions/remoteAction.ts (2 hunks)
  • src/core/file/gitCommand.ts (2 hunks)
  • src/index.ts (1 hunks)
  • tests/cli/actions/remoteAction.test.ts (2 hunks)
  • tests/core/file/gitCommand.test.ts (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • tests/core/file/gitCommand.test.ts
  • src/index.ts
⏰ Context from checks skipped due to timeout of 90000ms (15)
  • GitHub Check: Test (macos-latest, 23.x)
  • GitHub Check: Test (macos-latest, 21.x)
  • GitHub Check: Test (macos-latest, 19.x)
  • GitHub Check: Test (windows-latest, 23.x)
  • GitHub Check: Test (windows-latest, 22.x)
  • GitHub Check: Test (windows-latest, 21.x)
  • GitHub Check: Test (windows-latest, 20.x)
  • GitHub Check: Test (windows-latest, 18.x)
  • GitHub Check: Test (ubuntu-latest, 23.x)
  • GitHub Check: Test (ubuntu-latest, 22.x)
  • GitHub Check: Test (ubuntu-latest, 21.x)
  • GitHub Check: Test (ubuntu-latest, 20.x)
  • GitHub Check: Test (ubuntu-latest, 19.x)
  • GitHub Check: Lint Renovate config
  • GitHub Check: Cloudflare Pages

Comment on lines +127 to +133
// Check the direct form of the GitHub URL. e.g. https://github.com/yamadashy/repomix or https://gist.github.com/yamadashy/1234567890abcdef
try {
new URL(remoteValue);
return true;
} catch (error) {
return false;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve URL validation for Git repositories.

The current URL validation accepts any valid URL. Consider adding specific checks for Git repository URLs.

-  // Check the direct form of the GitHub URL. e.g.  https://github.com/yamadashy/repomix or https://gist.github.com/yamadashy/1234567890abcdef
   try {
-    new URL(remoteValue);
-    return true;
+    const url = new URL(remoteValue);
+    // Check if the URL is a valid Git repository URL
+    const isGitUrl = /^https?:\/\/([^/]+\/){2}/.test(url.toString()) || // Has at least two path segments
+                     /^git@[^:]+:.+\/.+$/.test(remoteValue);           // SSH format
+    return isGitUrl;
   } catch (error) {
     return false;
   }
📝 Committable suggestion

‼️ 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.

Suggested change
// Check the direct form of the GitHub URL. e.g. https://github.com/yamadashy/repomix or https://gist.github.com/yamadashy/1234567890abcdef
try {
new URL(remoteValue);
return true;
} catch (error) {
return false;
}
try {
const url = new URL(remoteValue);
// Check if the URL is a valid Git repository URL
const isGitUrl = /^https?:\/\/([^/]+\/){2}/.test(url.toString()) || // Has at least two path segments
/^git@[^:]+:.+\/.+$/.test(remoteValue); // SSH format
return isGitUrl;
} catch (error) {
return false;
}

Copy link
Contributor

@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: 1

♻️ Duplicate comments (1)
src/cli/actions/remoteAction.ts (1)

127-133: 🛠️ Refactor suggestion

Improve URL validation for Git repositories.

The current URL validation accepts any valid URL. Consider adding specific checks for Git repository URLs.

-  // Check the direct form of the GitHub URL. e.g.  https://github.com/yamadashy/repomix or https://gist.github.com/yamadashy/1234567890abcdef
   try {
-    new URL(remoteValue);
-    return true;
+    const url = new URL(remoteValue);
+    // Check if the URL is a valid Git repository URL
+    return /^https?:\/\/(?:github\.com|gitlab\.com|bitbucket\.org)\/[^/]+\/[^/]+(?:\.git)?$/.test(url.toString()) ||
+           /^git@(?:github\.com|gitlab\.com|bitbucket\.org):.+\/.+(?:\.git)?$/.test(remoteValue);
   } catch (error) {
     return false;
   }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e7e5064 and 76d625e.

📒 Files selected for processing (4)
  • src/cli/actions/remoteAction.ts (2 hunks)
  • src/core/file/gitCommand.ts (2 hunks)
  • src/index.ts (1 hunks)
  • tests/cli/actions/remoteAction.test.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/core/file/gitCommand.ts
  • src/index.ts
⏰ Context from checks skipped due to timeout of 90000ms (12)
  • GitHub Check: Test (windows-latest, 23.x)
  • GitHub Check: Build and run (windows-latest, 23.x)
  • GitHub Check: Test (windows-latest, 22.x)
  • GitHub Check: Build and run (windows-latest, 22.x)
  • GitHub Check: Test (windows-latest, 21.x)
  • GitHub Check: Build and run (windows-latest, 21.x)
  • GitHub Check: Test (windows-latest, 20.x)
  • GitHub Check: Test (windows-latest, 19.x)
  • GitHub Check: Test (windows-latest, 18.x)
  • GitHub Check: Test (windows-latest, 18.0.0)
  • GitHub Check: Lint Renovate config
  • GitHub Check: Cloudflare Pages
🔇 Additional comments (3)
src/cli/actions/remoteAction.ts (2)

24-26: LGTM! Early validation is well implemented.

Good placement of validation before any operations, with a clear error message using the appropriate error type.


120-125: LGTM! Robust shorthand format validation.

The regex pattern correctly implements GitHub's repository naming rules, ensuring names:

  • Start and end with alphanumeric characters
  • Can contain dots, hyphens, and underscores in between
tests/cli/actions/remoteAction.test.ts (1)

86-128: LGTM! Comprehensive test coverage for shorthand format.

Excellent test coverage with thorough validation of:

  • Various valid patterns including edge cases
  • Invalid patterns and disallowed characters
  • Clear test descriptions and helpful error messages

@yamadashy yamadashy merged commit 3a3b0cf into main Jan 10, 2025
@codecov
Copy link

codecov bot commented Jan 10, 2025

Codecov Report

Attention: Patch coverage is 85.00000% with 3 lines in your changes missing coverage. Please review.

Project coverage is 92.12%. Comparing base (001e3f7) to head (76d625e).
Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
src/cli/actions/remoteAction.ts 87.50% 2 Missing ⚠️
src/core/file/gitCommand.ts 75.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #280      +/-   ##
==========================================
+ Coverage   92.00%   92.12%   +0.11%     
==========================================
  Files          44       44              
  Lines        2140     2146       +6     
  Branches      467      469       +2     
==========================================
+ Hits         1969     1977       +8     
+ Misses        171      169       -2     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

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.

1 participant