Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generate link to the package manager in SBOM page using PURL #10625

Open
wants to merge 15 commits into
base: develop
Choose a base branch
from

Conversation

rajku-dev
Copy link
Contributor

@rajku-dev rajku-dev commented Feb 15, 2025

Proposed Changes

  • Fixes Cleanup Licenses Page #10607
  • Create a utility function to generate a URL
  • Handles redirection to the package manager page with the appropriate version.
    @ohcnetwork/care-fe-code-reviewers

Merge Checklist

  • Add specs that demonstrate bug / test a new feature.
  • Update product documentation.
  • Ensure that UI text is kept in I18n files.
  • Prep screenshot or demo video for changelog entry, and attach it to issue.
  • Request for Peer Reviews
  • Completion of QA

Summary by CodeRabbit

  • New Features

    • Introduced a function to generate URLs for various package types, enhancing navigation to external resources.
  • Refactor

    • Streamlined the package information display by removing extraneous external reference elements, focusing solely on key details such as name, version, and license.
  • New Types

    • Added a new type for package categorization, supporting various package types including PyPI, npm, GitHub, and GitHub Actions.

@rajku-dev rajku-dev requested a review from a team as a code owner February 15, 2025 12:04
Copy link

netlify bot commented Feb 15, 2025

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 91df922
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/67b5a5c92953f30008accc2d
😎 Deploy Preview https://deploy-preview-10625.preview.ohc.network
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link
Contributor

coderabbitai bot commented Feb 15, 2025

Walkthrough

A new function getPackageUrl has been added to generate URLs for various package types (PyPI, npm, GitHub, and GitHub Actions) using the package name and reference locator. The SbomPackage component now uses this function to construct the href attribute, replacing previous URL logic. Additionally, state management and UI elements related to external references have been removed, simplifying the component to focus on package name, version, and license information only.

Changes

File Path Summary of Changes
src/pages/Licenses/Licenses.tsx - Added getPackageUrl to generate URLs based on package type.
- Updated SbomPackage to use getPackageUrl for anchor href.
- Removed state/UI for external references.
src/types/license.ts - Introduced new type PackageType as a union of string literals: "pypi", "npm", "github", and "githubactions".
src/pages/Licenses/utils.ts - Added new utility function getPackageUrl to generate URLs based on package name and reference locator.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant SbomPackage
    participant getPackageUrl
    participant AnchorElement
    
    Client->>SbomPackage: Provide package data
    SbomPackage->>getPackageUrl: getPackageUrl(pkgName, purl)
    getPackageUrl-->>SbomPackage: Return generated URL
    SbomPackage->>AnchorElement: Render anchor with URL
    AnchorElement-->>Client: Display anchor link
Loading

Poem

I'm a bunny in the code field, hopping with glee,
Crafting URLs like carrots, perfectly free.
External clutter hopped away, leaving clear space,
With getPackageUrl shining in its rightful place.
Enjoy our tidy code, a carrot-filled embrace!
🥕🐇

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

🧹 Nitpick comments (2)
src/pages/Licenses/Licenses.tsx (2)

22-38: Improve the getPackageUrl function implementation.

The function can be enhanced for better maintainability and type safety:

Consider this alternative implementation:

-function getPackageUrl(pkgName: string, purl: string) {
+type PackageType = 'pypi' | 'npm' | 'github' | 'githubactions';
+
+function getPackageUrl(pkgName: string, purl: string | undefined): string {
+  if (!purl || !pkgName) return '';
+
+  const urlMap: Record<PackageType, string> = {
+    pypi: `https://pypi.org/project/${pkgName}`,
+    npm: `https://www.npmjs.com/package/${pkgName}`,
+    github: `https://github.com/${pkgName}`,
+    githubactions: `https://github.com/actions/${pkgName}`,
+  };
+
+  const type = Object.keys(urlMap).find(key => purl.startsWith(`pkg:${key}/`));
+  return type ? urlMap[type as PackageType] : purl;
+}
-  if (purl) {
-    switch (true) {
-      case purl.startsWith("pkg:pypi/"):
-        return `https://pypi.org/project/${pkgName}`;
-      case purl.startsWith("pkg:npm/"):
-        return `https://www.npmjs.com/package/${pkgName}`;
-      case purl.startsWith("pkg:github/"):
-        return `https://github.com/${pkgName}`;
-      case purl.startsWith("pkg:githubactions/"):
-        return `https://github.com/actions/${pkgName}`;
-      default:
-        return purl;
-    }
-  }
-  return purl;
-}

Benefits:

  • Type safety with TypeScript types
  • More maintainable with a lookup object
  • Input validation for both parameters
  • Eliminates the switch-true anti-pattern
  • Removes redundant return statement

128-128: Simplify the href attribute and improve error handling.

The current implementation can be enhanced:

-href={`${getPackageUrl(pkg.name, pkg.externalRefs?.[0].referenceLocator)}`}
+href={getPackageUrl(pkg.name, pkg.externalRefs?.[0]?.referenceLocator)}

Consider adding error handling for missing package data:

if (!pkg.name || !pkg.versionInfo) {
  return null; // or a fallback UI
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 21ecdf5 and 7433b24.

📒 Files selected for processing (1)
  • src/pages/Licenses/Licenses.tsx (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: cypress-run (1)

Copy link
Member

@rithviknishad rithviknishad left a comment

Choose a reason for hiding this comment

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

can we cleanup the implementation? code doesn't look clean.

@rajku-dev rajku-dev changed the title Generate clickable link to the package manager in SBOM page Generate link to the package manager in SBOM page using PURL Feb 15, 2025
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 (1)
src/pages/Licenses/Licenses.tsx (1)

22-37: Enhance type safety and URL handling in getPackageUrl.

The function works but could be improved in several ways:

  1. Add explicit parameter types
  2. Handle version information from purl
  3. Use constants for URL prefixes
  4. Add validation for external reference type

Consider this improved implementation:

-function getPackageUrl(pkgName: string, purl: string): string {
+const PACKAGE_URL_PREFIXES = {
+  pypi: "https://pypi.org/project/",
+  npm: "https://www.npmjs.com/package/",
+  github: "https://github.com/",
+  githubactions: "https://github.com/actions/",
+} as const;
+
+function getPackageUrl(pkgName: string, purl: string | undefined): string {
   if (!purl || !pkgName) return "";

-  const urlMap: Record<PackageType, string> = {
-    pypi: `https://pypi.org/project/${pkgName}`,
-    npm: `https://www.npmjs.com/package/${pkgName}`,
-    github: `https://github.com/${pkgName}`,
-    githubactions: `https://github.com/actions/${pkgName}`,
-  };
+  const urlMap: Record<PackageType, string> = Object.fromEntries(
+    Object.entries(PACKAGE_URL_PREFIXES).map(([key, prefix]) => [
+      key,
+      `${prefix}${pkgName}`,
+    ])
+  ) as Record<PackageType, string>;

   const pkgtype = Object.keys(urlMap).find((key) =>
     purl.startsWith(`pkg:${key}/`),
   );

+  // Extract version from purl if available
+  const version = purl.match(/[@]([^?]+)/)?.[1];
+  const baseUrl = pkgtype ? urlMap[pkgtype as PackageType] : purl;
+  
+  return version ? `${baseUrl}/v${version}` : baseUrl;
-  return pkgtype ? urlMap[pkgtype as PackageType] : purl;
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7433b24 and 68a37b3.

📒 Files selected for processing (2)
  • src/pages/Licenses/Licenses.tsx (2 hunks)
  • src/types/license.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Test
  • GitHub Check: cypress-run (1)
🔇 Additional comments (2)
src/types/license.ts (1)

35-35: LGTM! Well-defined type for package managers.

The PackageType type is well-defined and includes all necessary package types for the SBOM page.

src/pages/Licenses/Licenses.tsx (1)

15-15: LGTM! Clean import statement.

The PackageType import is correctly added and used in the code.

src/pages/Licenses/Licenses.tsx Outdated Show resolved Hide resolved
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/pages/Licenses/Licenses.tsx (1)

127-127: ⚠️ Potential issue

Add validation for external references.

The current implementation assumes the first external reference is the correct package URL, which might not always be true. Consider adding validation for the reference type.

Apply this improvement:

-href={`${getPackageUrl(pkg.name, pkg.externalRefs[0].referenceLocator)}`}
+href={`${getPackageUrl(
+  pkg.name,
+  pkg.externalRefs?.find(ref => 
+    ref.referenceType === "purl" || 
+    ref.referenceType === "package-url"
+  )?.referenceLocator
+)}`}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 68a37b3 and 0e14300.

📒 Files selected for processing (1)
  • src/pages/Licenses/Licenses.tsx (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: cypress-run (1)
🔇 Additional comments (1)
src/pages/Licenses/Licenses.tsx (1)

15-15: LGTM!

The import of PackageType is correctly added and aligns with the new functionality.

src/pages/Licenses/Licenses.tsx Outdated Show resolved Hide resolved
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 (2)
src/pages/Licenses/utils.ts (1)

3-21: 🛠️ Refactor suggestion

Add input validation and JSDoc documentation.

The function needs better error handling and documentation.

Apply these improvements as suggested in the past review:

+/**
+ * Generates a package manager URL from a package name and PURL.
+ * @param pkgName - The name of the package
+ * @param purl - The Package URL (PURL) string
+ * @returns The package manager URL or empty string if inputs are invalid
+ */
 function getPackageUrl(pkgName: string, purl: string): string {
   if (!purl || !pkgName) return "";
 
+  // Validate PURL format
+  const purlRegex = /^pkg:[a-zA-Z]+\/.+/;
+  if (!purlRegex.test(purl)) return "";
+
+  // Extract version from PURL if present
+  const versionMatch = purl.match(/@([^/]+)/);
+  const version = versionMatch?.[1];
+
   const urlMap: Record<PackageType, string> = {
-    pypi: `https://pypi.org/project/${pkgName}`,
-    npm: `https://www.npmjs.com/package/${pkgName}`,
+    pypi: `https://pypi.org/project/${pkgName}${version ? `/${version}` : ''}`,
+    npm: `https://www.npmjs.com/package/${pkgName}${version ? `/v/${version}` : ''}`,
     github: `https://github.com/${pkgName}`,
     githubactions: `https://github.com/actions/${pkgName}`,
   };
src/pages/Licenses/Licenses.tsx (1)

111-111: 🛠️ Refactor suggestion

Add validation for external references.

The current implementation assumes the first external reference is the correct package URL, which might not always be true.

Apply this improvement as suggested in the past review:

-href={`${getPackageUrl(pkg.name, pkg.externalRefs?.[0].referenceLocator)}`}
+href={`${getPackageUrl(
+  pkg.name,
+  pkg.externalRefs?.find(ref => 
+    ref.referenceType === "purl" || 
+    ref.referenceType === "package-url"
+  )?.referenceLocator
+)}`}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0e14300 and f1317a6.

📒 Files selected for processing (2)
  • src/pages/Licenses/Licenses.tsx (2 hunks)
  • src/pages/Licenses/utils.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Test
  • GitHub Check: cypress-run (1)
  • GitHub Check: OSSAR-Scan

src/pages/Licenses/Licenses.tsx Outdated Show resolved Hide resolved
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: 2

🧹 Nitpick comments (2)
src/pages/Licenses/utils.ts (2)

7-12: Consider moving URLs to configuration.

The hardcoded URLs would be better maintained in a configuration file, allowing for easier updates and environment-specific changes.

+import { config } from '@/config';
+
 export const getPackageUrl = (
   pkgName: LicensesSbom["sbom"]["packages"][number]["name"],
   purl: LicensesSbom["sbom"]["packages"][number]["externalRefs"][number]["referenceLocator"],
 ): URL => {
-  const urlMap: Record<PackageType, string> = {
-    pypi: `https://pypi.org/project/${pkgName}`,
-    npm: `https://www.npmjs.com/package/${pkgName}`,
-    github: `https://github.com/${pkgName}`,
-    githubactions: `https://github.com/actions/${pkgName}`,
-  };
+  const urlMap: Record<PackageType, string> = config.packageUrls;

3-19: Add tests and documentation for the utility function.

To ensure reliability and maintainability:

  1. Add unit tests to verify URL generation for different package types
  2. Add JSDoc documentation explaining the function's purpose, parameters, and return value

Would you like me to help generate:

  1. Unit tests for various package types and edge cases?
  2. JSDoc documentation for the utility function?
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f1317a6 and 5e5c79b.

📒 Files selected for processing (1)
  • src/pages/Licenses/utils.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: Redirect rules - care-ohc
  • GitHub Check: Header rules - care-ohc
  • GitHub Check: Pages changed - care-ohc
  • GitHub Check: Test
  • GitHub Check: cypress-run (1)
  • GitHub Check: OSSAR-Scan
🔇 Additional comments (1)
src/pages/Licenses/utils.ts (1)

1-1: LGTM!

Types are properly imported using the project's path alias convention.

src/pages/Licenses/utils.ts Outdated Show resolved Hide resolved
src/pages/Licenses/utils.ts Show resolved Hide resolved
@rajku-dev
Copy link
Contributor Author

rajku-dev commented Feb 15, 2025

can we show the count of packages, as done for Users/Patients etc
this will give users a quick overview

@github-actions github-actions bot added needs-triage question Further information is requested labels Feb 15, 2025
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/pages/Licenses/Licenses.tsx (1)

111-111: ⚠️ Potential issue

Add validation for external references and error handling.

The current implementation assumes the first external reference exists and is the correct package URL, which might not always be true.

-        href={`${getPackageUrl(pkg.name, pkg.versionInfo, pkg.externalRefs[0].referenceLocator)}`}
+        href={pkg.externalRefs?.length > 0 
+          ? `${getPackageUrl(
+              pkg.name,
+              pkg.versionInfo,
+              pkg.externalRefs.find(ref => 
+                ref.referenceType === "purl" || 
+                ref.referenceType === "package-url"
+              )?.referenceLocator ?? ''
+            )}`
+          : "#"
+        }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5e5c79b and b6848d3.

📒 Files selected for processing (2)
  • src/pages/Licenses/Licenses.tsx (2 hunks)
  • src/pages/Licenses/utils.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Test
  • GitHub Check: cypress-run (1)
  • GitHub Check: OSSAR-Scan
🔇 Additional comments (3)
src/pages/Licenses/utils.ts (2)

1-7: Add input validation for parameters.

The function should validate input parameters to handle null/undefined values gracefully.

 export const getPackageUrl = (
   pkgName: LicensesSbom["sbom"]["packages"][number]["name"],
   version: LicensesSbom["sbom"]["packages"][number]["versionInfo"],
   purl: LicensesSbom["sbom"]["packages"][number]["externalRefs"][number]["referenceLocator"],
 ): URL => {
+  if (!pkgName || !version || !purl) {
+    throw new Error('Package name, version, and PURL are required');
+  }

15-19: Add PURL validation and error handling.

The URL construction should validate PURL format and handle invalid URLs gracefully.

+  const isPurlValid = (purl: string): boolean => {
+    return /^pkg:[a-zA-Z]+\/.+/.test(purl);
+  };
+
+  if (!isPurlValid(purl)) {
+    throw new Error('Invalid PURL format');
+  }
+
   const pkgType = Object.keys(urlMap).find((key) =>
     purl.startsWith(`pkg:${key}/`),
   );

-  return pkgType ? new URL(urlMap[pkgType as PackageType]) : new URL(purl);
+  try {
+    return pkgType ? new URL(urlMap[pkgType as PackageType]) : new URL(purl);
+  } catch (error) {
+    throw new Error(`Invalid URL: ${error.message}`);
+  }
src/pages/Licenses/Licenses.tsx (1)

15-15: LGTM!

The import statement is correctly placed and properly imports the utility function.

src/pages/Licenses/utils.ts Show resolved Hide resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
changes required needs-triage question Further information is requested
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Cleanup Licenses Page
2 participants