-
Notifications
You must be signed in to change notification settings - Fork 516
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
Update license Component for Github SBOM #9755
base: develop
Are you sure you want to change the base?
Update license Component for Github SBOM #9755
Conversation
Important Review skippedReview was skipped as selected files did not have any reviewable changes. 💤 Files selected but had no reviewable changes (1)
You can disable this status message by setting the WalkthroughThe pull request introduces a comprehensive update to the Software Bill of Materials (SBOM) viewer component, focusing on dynamically fetching SBOM data from GitHub repositories. The changes include implementing a new script to fetch SBOM data, integrating react-query for data retrieval, adding internationalization support, and modifying the component to work with dynamically loaded JSON files. The Changes
Assessment against linked issues
Poem
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
✅ Deploy Preview for care-ohc ready!
To edit notification comments on pull requests, go to your Netlify site configuration. |
There was a problem hiding this 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 (7)
src/components/Licenses/SBOMViewer.tsx (7)
52-66
: Consider more robust error handling.
Currently, any fetch failure logs an error to the console and returnsnull
. Think about handling errors more gracefully in the UI, for instance by showing a user-facing alert or fallback message.
86-86
: Tab naming could be more descriptive.
Using "bom" vs "beBom" might be confusing. Renaming them to “frontendBom” / “backendBom” can improve clarity.
118-118
: Consider displaying additional SBOM metadata.
AlongsidespdxVersion
, you might also display thedataLicense
or other relevant metadata for a more comprehensive SBOM overview.
131-131
: Use stable keys when rendering lists.
Consider using a unique identifier from each package (e.g.,pkg.SPDXID
orpkg.name
) instead of the arrayindex
for improved React performance.
137-137
: Commented-out externalRefs link.
This might be leftover debug code or a temporary workaround. Consider removing or adding a rationale comment if intentionally disabled.
150-150
: Fallback anchor for unrecognized license IDs.
Navigating to "#" might not provide user feedback. Consider a placeholder page or tooltip to clarify no recognized license URL is available.
172-172
: Consider stable keys for external references.
Usingidx
as the key can lead to React diffing issues if references change order. Prefer a unique property from each reference, if available.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/components/Licenses/SBOMViewer.tsx
(3 hunks)
🔇 Additional comments (14)
src/components/Licenses/SBOMViewer.tsx (14)
2-2
: Imports look good.
The newly added import for React hooks is appropriate and aligns with best practices in functional components.
15-27
: Validate optional fields for GitHubPackage.
All fields in this interface appear to match the GitHub SBOM format. Consider verifying whether any additional fields from GitHub’s SBOM API may need to be included or marked optional for better type safety.
30-41
: Interface structure aligns with GitHub SBOM data.
It’s good that each property is optional, preventing runtime errors when the SBOM might be missing certain fields.
49-51
: Separate state variables for frontend and backend SBOM.
Assigning each SBOM to its own state variable is clear and logical.
68-85
: Concise async loading for both FE/BE.
Fetching FE and BE SBOM data in parallel is efficient. If partial fetch success is acceptable (only one resource might load), confirm thatnull
states are handled correctly in the UI.
93-93
: Array fallback for safe rendering.
The usage of|| []
ensures no errors whenbomData
orsbom
isnull
. Nice defensive coding.
122-123
: Date formatting is handled gracefully.
Falling back to "N/A" if a date is missing ensures the UI won’t break.
129-129
: Package header is clear.
Labeling this section is helpful in guiding the user to the package list.
143-143
: Package name and version.
Displaying both name and version in the same heading is user-friendly and concise.
146-146
: Conditional rendering of the license.
Filtering out packages without alicenseConcluded
field reduces UI clutter. Implementation is clear.
155-155
: License fallback "N/A."
Good to maintain a sensible default text if the license field is somehow empty.
175-175
: External reference link fallback.
IfreferenceLocator
is missing, a fallback of "#" prevents errors. This maintains a functioning UI.
178-178
: Optional reference locator text.
Gracefully handles missing locator content by providing "N/A."
180-182
: Category display is optional.
The checks forref.referenceCategory
andref.referenceLocator
align with the optional nature of external references.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
🧹 Nitpick comments (2)
scripts/fetchSbomData.js (1)
49-49
: Add proper error handling for unhandled rejections.The script should handle unhandled promise rejections properly.
Add this error handling:
+process.on('unhandledRejection', (error) => { + console.error('Unhandled promise rejection:', error); + process.exit(1); +}); + fetchData();src/components/Licenses/SBOMViewer.tsx (1)
Line range hint
134-157
: Add error handling for clipboard operations.The clipboard functionality should handle potential errors.
- const handleCopy = () => { + const handleCopy = (text: string, result: boolean) => { + if (!result) { + console.error('Failed to copy to clipboard'); + return; + } setCopyStatus(true); setTimeout(() => setCopyStatus(false), 2000); };
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
.gitignore
(1 hunks)package.json
(1 hunks)scripts/fetchSbomData.js
(1 hunks)src/components/Licenses/SBOMViewer.tsx
(4 hunks)
🧰 Additional context used
🪛 GitHub Actions: Lint Code Base
package.json
[warning] Node.js version incompatibility - Required: >=22.8.0, Current: v20.18.1
[warning] Multiple deprecated package dependencies: sourcemap-codec, rimraf, npmlog, inflight, gauge, are-we-there-yet, boolean, @humanwhocodes/config-array, @humanwhocodes/object-schema, glob, eslint
scripts/fetchSbomData.js
[error] 1-1: Cannot use import statement outside a module. Need to set "type": "module" in package.json or use .mjs extension
🔇 Additional comments (5)
.gitignore (1)
68-70
: LGTM! Appropriate entries added to .gitignore.The new entries correctly exclude the generated SBOM data files from version control.
src/components/Licenses/SBOMViewer.tsx (2)
1-13
: LGTM! Good implementation of i18n and SBOM data imports.The changes properly implement internationalization and correctly update the SBOM data imports to use the new GitHub SBOM format.
Line range hint
34-133
: LGTM! Well-structured UI with proper i18n implementation.The UI components are well-organized with proper internationalization of all strings and good TypeScript/React patterns.
package.json (2)
38-38
: LGTM! Appropriate addition to postinstall script.The script is correctly added to run after platform dependencies are installed.
🧰 Tools
🪛 GitHub Actions: Lint Code Base
[warning] Node.js version incompatibility - Required: >=22.8.0, Current: v20.18.1
[warning] Multiple deprecated package dependencies: sourcemap-codec, rimraf, npmlog, inflight, gauge, are-we-there-yet, boolean, @humanwhocodes/config-array, @humanwhocodes/object-schema, glob, eslint
Line range hint
1-1
: Update Node.js version and deprecated dependencies.The pipeline shows several issues that need attention:
- Node.js version incompatibility (required >=22.8.0, current v20.18.1)
- Multiple deprecated package dependencies
Please update the Node.js version in your CI environment and update the following deprecated packages:
- sourcemap-codec
- rimraf
- npmlog
- inflight
- gauge
- are-we-there-yet
- boolean
- @humanwhocodes/config-array
- @humanwhocodes/object-schema
- glob
- eslint
Run this script to check for the latest versions:
🧰 Tools
🪛 GitHub Actions: Lint Code Base
[warning] Node.js version incompatibility - Required: >=22.8.0, Current: v20.18.1
[warning] Multiple deprecated package dependencies: sourcemap-codec, rimraf, npmlog, inflight, gauge, are-we-there-yet, boolean, @humanwhocodes/config-array, @humanwhocodes/object-schema, glob, eslint
scripts/fetchSbomData.js
Outdated
import fs from "fs"; | ||
import fetch from "node-fetch"; | ||
|
||
const fetchSBOMData = async (url) => { | ||
const response = await fetch(url, { | ||
headers: { | ||
Accept: "application/vnd.github+json", | ||
"X-GitHub-Api-Version": "2022-11-28", | ||
}, | ||
}); | ||
if (!response.ok) { | ||
throw new Error(`Error fetching SBOM data from ${url}`); | ||
} | ||
return await response.json(); | ||
}; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fix ESM compatibility and add GitHub authentication.
The code has several issues that need to be addressed:
- ES modules syntax requires "type": "module" in package.json
- GitHub API calls should use authentication to avoid rate limiting
- API version should be configurable for future compatibility
Apply these changes:
+// Add to package.json
+{
+ "type": "module"
+}
import fs from "fs";
import fetch from "node-fetch";
+import dotenv from "dotenv";
+
+dotenv.config();
+
+const GITHUB_TOKEN = process.env.GITHUB_TOKEN;
const fetchSBOMData = async (url) => {
const response = await fetch(url, {
headers: {
Accept: "application/vnd.github+json",
+ Authorization: `Bearer ${GITHUB_TOKEN}`,
"X-GitHub-Api-Version": "2022-11-28",
},
});
Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 GitHub Actions: Lint Code Base
[error] 1-1: Cannot use import statement outside a module. Need to set "type": "module" in package.json or use .mjs extension
const bomData = activeTab === "bom" ? feBomData : beBomData; | ||
|
||
const handleCopy = () => { | ||
setCopyStatus(true); | ||
setTimeout(() => setCopyStatus(false), 2000); | ||
}; | ||
|
||
const bomData = (activeTab === "bom" ? feBomData : beBomData) as CycloneDXBOM; | ||
const packages = bomData?.sbom?.packages || []; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Add TypeScript interfaces for the GitHub SBOM format.
The code lacks type definitions for the new GitHub SBOM format, which could lead to runtime errors.
Add these type definitions:
interface GitHubSBOM {
sbom: {
spdxVersion: string;
creationInfo: {
created: string;
};
packages: Array<{
name: string;
versionInfo?: string;
licenseConcluded?: string;
externalRefs?: Array<{
referenceLocator?: string;
referenceCategory?: string;
}>;
}>;
};
}
const bomData = (activeTab === "bom" ? feBomData : beBomData) as GitHubSBOM;
const packages = bomData?.sbom?.packages || [];
scripts/fetchSbomData.js
Outdated
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
let's keep the script in typescript similar to the other postinstall script
@@ -187,12 +144,12 @@ const BOMDisplay: React.FC = () => { | |||
onCopy={handleCopy} | |||
> | |||
<button className="text-md hover:bg-primary-dark w-full rounded-md bg-primary px-4 py-2 text-white transition-all duration-300 focus:outline-none md:w-auto"> | |||
Copy BOM JSON | |||
{t("Copy BOM JSON")} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this is not the way to add translations. see how other translations are done
.gitignore
Outdated
src/components/Licenses/feBomData.json |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
let's keep this inside the public
dir. instead.
(we'd also be able to access it by care.ohc.network/licenses/backend|frontend.json
)
…o issues/9534/update-license-sbom
There was a problem hiding this 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
🔭 Outside diff range comments (1)
src/components/Licenses/SBOMViewer.tsx (1)
Line range hint
102-153
: Add TypeScript interfaces for the GitHub SBOM format.Define proper TypeScript interfaces to improve type safety and code maintainability.
interface ExternalRef { referenceLocator?: string; referenceCategory?: string; } interface Package { name?: string; versionInfo?: string; licenseConcluded?: string; externalRefs?: ExternalRef[]; } interface GitHubSBOM { sbom: { spdxVersion: string; creationInfo: { created: string; }; packages: Package[]; }; }Extract package card into a separate component.
Consider extracting the package display logic into a reusable component to improve code organization and maintainability.
interface PackageCardProps { pkg: Package; index: number; showExternalRefs: number | null; onToggleRefs: (index: number) => void; } const PackageCard: React.FC<PackageCardProps> = ({ pkg, index, showExternalRefs, onToggleRefs, }) => { const { t } = useTranslation(); return ( <div className="block rounded-md border p-2 transition-all duration-300 hover:shadow-lg"> {/* ... existing package card JSX ... */} </div> ); };
🧹 Nitpick comments (6)
src/components/Licenses/SBOMViewer.tsx (3)
17-21
: Enhance error handling in fetchJsonData function.The error handling could be more informative by including the HTTP status code and response details.
const fetchJsonData = async (url: string) => { const response = await fetch(url); - if (!response.ok) throw new Error("Failed to fetch data"); + if (!response.ok) { + throw new Error( + `Failed to fetch data: ${response.status} ${response.statusText}` + ); + } return response.json(); };
29-45
: Add retry and caching configuration to useQuery hooks.Consider adding retry and caching configurations to improve the data fetching reliability and performance.
const { data: feBomData, isLoading: feBomLoading, error: feBomError, } = useQuery({ queryKey: ["feBomData"], queryFn: () => fetchJsonData("/licenses/feBomData.json"), + retry: 2, + staleTime: 5 * 60 * 1000, // 5 minutes + cacheTime: 30 * 60 * 1000, // 30 minutes });
58-60
: Enhance error state display.Consider providing more detailed error information to help users understand and report issues.
- return <div>{t("error_404")}</div>; + return ( + <div className="text-red-600"> + <div>{t("error_404")}</div> + <div className="text-sm mt-2"> + {feBomError?.message || beBomError?.message} + </div> + </div> + );scripts/fetchSbomData.ts (3)
1-2
: Consider using native fetch API instead of node-fetchThe native fetch API is now available in Node.js versions >= 18.0.0. Consider using it instead of the node-fetch package to reduce dependencies.
-import fetch from "node-fetch";
4-7
: Strengthen the SBOMData interface typingThe current interface is too permissive with
Record<string, unknown>
. Consider defining more specific types based on the actual SBOM data structure from GitHub's API.interface SBOMData { sbom: { metadata: { version: string; tools: Array<{ name: string; version: string; }>; }; components: Array<{ name: string; version: string; licenses?: Array<{ license: { id: string; }; }>; }>; }; }
62-62
: Improve script execution with proper error handlingAdd proper process handling and success/failure indication.
-fetchData(); +fetchData() + .then(() => { + console.log('Successfully fetched and saved SBOM data'); + process.exit(0); + }) + .catch((error) => { + console.error('Failed to fetch SBOM data:', error); + process.exit(1); + }); + +// Handle unexpected errors +process.on('unhandledRejection', (error) => { + console.error('Unhandled rejection:', error); + process.exit(1); +});
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
.gitignore
(1 hunks)package.json
(1 hunks)public/locale/en.json
(6 hunks)scripts/fetchSbomData.ts
(1 hunks)src/components/Licenses/SBOMViewer.tsx
(4 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- .gitignore
- package.json
🔇 Additional comments (2)
public/locale/en.json (1)
473-474
: LGTM! All required translations are present.The translations for the SBOM viewer component have been properly added and are consistent with the component's usage.
Also applies to: 1090-1090, 1185-1185, 1297-1297, 1662-1662
scripts/fetchSbomData.ts (1)
13-28
:⚠️ Potential issueAdd GitHub authentication and improve error handling
- GitHub API has rate limits for unauthenticated requests. Add authentication using a GitHub token.
- Implement retry logic for transient failures.
- Add more specific error handling based on HTTP status codes.
Apply these improvements:
const fetchSBOMData = async (url: string): Promise<SBOMData> => { + const MAX_RETRIES = 3; + const GITHUB_TOKEN = process.env.GITHUB_TOKEN; + + if (!GITHUB_TOKEN) { + throw new Error('GITHUB_TOKEN environment variable is required'); + } + + for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) { const response = await fetch(url, { headers: { Accept: "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28", + Authorization: `Bearer ${GITHUB_TOKEN}`, }, }); if (!response.ok) { + if (response.status === 429) { + const retryAfter = response.headers.get('Retry-After'); + await new Promise(resolve => + setTimeout(resolve, (retryAfter ? parseInt(retryAfter) : 60) * 1000) + ); + continue; + } + + if (attempt === MAX_RETRIES) { const error: FetchError = new Error(`Error fetching SBOM data from ${url}`); error.response = response; throw error; + } + + await new Promise(resolve => setTimeout(resolve, 1000 * attempt)); + continue; } return (await response.json()) as SBOMData; + } + + throw new Error(`Failed to fetch SBOM data after ${MAX_RETRIES} attempts`); };
scripts/fetchSbomData.ts
Outdated
const fetchData = async (): Promise<void> => { | ||
const feUrl = | ||
"https://api.github.com/repos/ohcnetwork/care_fe/dependency-graph/sbom"; | ||
const beUrl = | ||
"https://api.github.com/repos/ohcnetwork/care/dependency-graph/sbom"; | ||
|
||
try { | ||
const [frontendData, backendData] = await Promise.all([ | ||
fetchSBOMData(feUrl), | ||
fetchSBOMData(beUrl), | ||
]); | ||
|
||
// Write frontend SBOM data | ||
fs.writeFileSync( | ||
"./public/licenses/feBomData.json", | ||
JSON.stringify(frontendData, null, 2), | ||
); | ||
|
||
// Write backend SBOM data | ||
fs.writeFileSync( | ||
"./public/licenses/beBomData.json", | ||
JSON.stringify(backendData, null, 2), | ||
); | ||
} catch (error) { | ||
if (error instanceof Error) { | ||
console.error("Error fetching SBOM data:", error.message); | ||
} else { | ||
console.error("Unknown error occurred while fetching SBOM data"); | ||
} | ||
} | ||
}; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Improve robustness of file operations and error handling
- Ensure target directory exists before writing files
- Validate received data before writing
- Add more informative error logging
const fetchData = async (): Promise<void> => {
const feUrl =
"https://api.github.com/repos/ohcnetwork/care_fe/dependency-graph/sbom";
const beUrl =
"https://api.github.com/repos/ohcnetwork/care/dependency-graph/sbom";
+ const outputDir = "./public/licenses";
+
+ // Ensure directory exists
+ if (!fs.existsSync(outputDir)) {
+ fs.mkdirSync(outputDir, { recursive: true });
+ }
+
try {
const [frontendData, backendData] = await Promise.all([
fetchSBOMData(feUrl),
fetchSBOMData(beUrl),
]);
+ // Validate received data
+ if (!frontendData?.dependencies || !backendData?.dependencies) {
+ throw new Error('Invalid SBOM data received');
+ }
+
// Write frontend SBOM data
fs.writeFileSync(
- "./public/licenses/feBomData.json",
+ `${outputDir}/feBomData.json`,
JSON.stringify(frontendData, null, 2),
);
// Write backend SBOM data
fs.writeFileSync(
- "./public/licenses/beBomData.json",
+ `${outputDir}/beBomData.json`,
JSON.stringify(backendData, null, 2),
);
} catch (error) {
if (error instanceof Error) {
- console.error("Error fetching SBOM data:", error.message);
+ console.error("Error processing SBOM data:", {
+ message: error.message,
+ stack: error.stack,
+ ...(error as FetchError).response && {
+ status: (error as FetchError).response?.status,
+ statusText: (error as FetchError).response?.statusText,
+ },
+ });
} else {
console.error("Unknown error occurred while fetching SBOM data");
}
+ process.exit(1);
}
};
Committable suggestion skipped: line range outside the PR's diff.
@@ -1273,7 +1278,7 @@ | |||
"moving_camera": "Moving Camera", | |||
"my_doctors": "My Doctors", | |||
"my_profile": "My Profile", | |||
"my_schedules": "My Schedules", |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
why was this translation deleted?
scripts/fetchSbomData.ts
Outdated
interface SBOMData { | ||
dependencies?: Record<string, unknown>; | ||
[key: string]: unknown; // Add more specific fields if known | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
are you sure the type is right? I don't see any dependencies
keyword in the API's response.
You can use tools like JSON to TypeScript to easily generate types from JSON.
https://transform.tools/json-to-typescript
interface SBOMData { | |
dependencies?: Record<string, unknown>; | |
[key: string]: unknown; // Add more specific fields if known | |
} | |
interface GitHubSbomApiResponse { | |
sbom: { | |
spdxVersion: string | |
dataLicense: string | |
SPDXID: string | |
name: string | |
documentNamespace: string | |
creationInfo: { | |
creators: string[] | |
created: string | |
} | |
packages: { | |
name: string | |
SPDXID: string | |
versionInfo: string | |
downloadLocation: string | |
filesAnalyzed: boolean | |
licenseConcluded?: string | |
copyrightText?: string | |
externalRefs: { | |
referenceCategory: string | |
referenceType: string | |
referenceLocator: string | |
}[] | |
licenseDeclared?: string | |
}[] | |
relationships: { | |
spdxElementId: string | |
relatedSpdxElement: string | |
relationshipType: string | |
}[] | |
} | |
} |
scripts/fetchSbomData.ts
Outdated
const feUrl = | ||
"https://api.github.com/repos/ohcnetwork/care_fe/dependency-graph/sbom"; | ||
const beUrl = | ||
"https://api.github.com/repos/ohcnetwork/care/dependency-graph/sbom"; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nitpick: let's store this globally as constants instead of keeping it inside the function.
scripts/fetchSbomData.ts
Outdated
response?: Response; | ||
} | ||
|
||
const fetchSBOMData = async (url: string): Promise<SBOMData> => { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
we've decided to follow this naming convention for abbrevs. in new code
const fetchSBOMData = async (url: string): Promise<SBOMData> => { | |
const fetchSbomData = async (url: string): Promise< GitHubSbomApiResponse > => { |
scripts/fetchSbomData.ts
Outdated
} catch (error) { | ||
if (error instanceof Error) { | ||
console.error("Error fetching SBOM data:", error.message); | ||
} else { | ||
console.error("Unknown error occurred while fetching SBOM data"); | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
let's not try catch. let the build fail instead
There was a problem hiding this 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
♻️ Duplicate comments (1)
scripts/fetchSbomData.ts (1)
60-75
:⚠️ Potential issueAddress pipeline failures by ensuring directory exists.
The pipeline is failing because the target directory doesn't exist. This was addressed in a previous review but the changes weren't applied.
const fetchData = async (): Promise<void> => { + const outputDir = "./public/licenses"; + + // Ensure directory exists + if (!fs.existsSync(outputDir)) { + fs.mkdirSync(outputDir, { recursive: true }); + } + const [frontendData, backendData] = await Promise.all([ - fetchSBOMData(FE_SBOM_URL), - fetchSBOMData(BE_SBOM_URL), + fetchSbomData(FE_SBOM_URL), + fetchSbomData(BE_SBOM_URL), ]); fs.writeFileSync( - "./public/licenses/feBomData.json", + `${outputDir}/feBomData.json`, JSON.stringify(frontendData, null, 2), ); fs.writeFileSync( - "./public/licenses/beBomData.json", + `${outputDir}/beBomData.json`, JSON.stringify(backendData, null, 2), ); };🧰 Tools
🪛 GitHub Actions: Lint Code Base
[error] 66-66: Failed to write to feBomData.json during postinstall script execution
🪛 GitHub Actions: Cypress Tests
[error] 66-66: Failed to write to './public/licenses/feBomData.json' - directory does not exist (ENOENT error)
🪛 GitHub Actions: Deploy Care Fe
[error] 66-66: Failed to write to './public/licenses/feBomData.json': directory does not exist
🧹 Nitpick comments (2)
public/locale/en.json (1)
651-653
: Consider using sentence case for consistency.While the changes are functionally correct, consider using sentence case for "BOM JSON" to match the style of other UI elements (e.g., "Bom Json").
- "copy_bom_json": "Copy BOM JSON", + "copy_bom_json": "Copy Bom Json",scripts/fetchSbomData.ts (1)
46-47
: Consider making API version configurable.The GitHub API version is hardcoded. Consider moving it to a configuration file or environment variable for easier updates.
+const GITHUB_API_VERSION = "2022-11-28"; + const fetchSbomData = async (url: string): Promise<GitHubSbomApiResponse> => { const response = await fetch(url, { headers: { Accept: "application/vnd.github+json", - "X-GitHub-Api-Version": "2022-11-28", + "X-GitHub-Api-Version": GITHUB_API_VERSION, }, });
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
public/locale/en.json
(6 hunks)scripts/fetchSbomData.ts
(1 hunks)
🧰 Additional context used
🪛 GitHub Actions: Lint Code Base
scripts/fetchSbomData.ts
[error] 66-66: Failed to write to feBomData.json during postinstall script execution
🪛 GitHub Actions: Cypress Tests
scripts/fetchSbomData.ts
[error] 66-66: Failed to write to './public/licenses/feBomData.json' - directory does not exist (ENOENT error)
🪛 GitHub Actions: Deploy Care Fe
scripts/fetchSbomData.ts
[error] 66-66: Failed to write to './public/licenses/feBomData.json': directory does not exist
🔇 Additional comments (6)
public/locale/en.json (2)
507-508
: LGTM! Clear and consistent naming for backend/frontend components.The added translations maintain consistency with the application's naming conventions.
1180-1180
: LGTM! Appropriate translations for SBOM-related terms.The added translations for license, N/A, packages, and SPDX SBOM version are clear and appropriate for the context.
Also applies to: 1282-1282, 1415-1415, 1835-1835
scripts/fetchSbomData.ts (4)
1-7
: LGTM! Well-structured imports and constants.Good job moving the URLs to top-level constants as suggested in the previous review.
9-41
: LGTM! Well-defined type interface.The
GitHubSbomApiResponse
interface accurately reflects the GitHub SBOM API structure as discussed in the previous review.
43-58
: Follow the agreed naming convention for abbreviations.As discussed in the previous review, we should use "Sbom" instead of "SBOM" in the function name.
-const fetchSBOMData = async (url: string): Promise<GitHubSbomApiResponse> => { +const fetchSbomData = async (url: string): Promise<GitHubSbomApiResponse> => {
1-77
: Verify the implementation in the CI environment.Let's ensure the script works correctly in the CI environment by checking:
- Directory creation
- File permissions
- API rate limits
✅ Verification successful
Implementation verified successfully
The script should work correctly in the CI environment:
- Directory permissions and structure are properly set up
- GitHub API endpoints are accessible
- Rate limits (60 requests/hour) are sufficient for the required API calls (2 requests)
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify the implementation in CI environment # Check if the script has write permissions in the target directory echo "Checking directory permissions..." mkdir -p ./public/licenses if [ ! -w "./public/licenses" ]; then echo "Error: No write permissions in ./public/licenses" exit 1 fi # Check GitHub API rate limits echo "Checking GitHub API rate limits..." curl -s -I -H "Accept: application/vnd.github+json" \ -H "X-GitHub-Api-Version: 2022-11-28" \ "https://api.github.com/rate_limit"Length of output: 465
Script:
#!/bin/bash # Description: Verify GitHub API access with correct methods echo "Checking GitHub API rate limits..." curl -s \ -H "Accept: application/vnd.github+json" \ -H "X-GitHub-Api-Version: 2022-11-28" \ "https://api.github.com/rate_limit" echo -e "\nChecking SBOM API endpoints..." curl -s -o /dev/null -w "FE SBOM Status: %{http_code}\n" \ -H "Accept: application/vnd.github+json" \ -H "X-GitHub-Api-Version: 2022-11-28" \ "https://api.github.com/repos/ohcnetwork/care_fe/dependency-graph/sbom" curl -s -o /dev/null -w "BE SBOM Status: %{http_code}\n" \ -H "Accept: application/vnd.github+json" \ -H "X-GitHub-Api-Version: 2022-11-28" \ "https://api.github.com/repos/ohcnetwork/care/dependency-graph/sbom"Length of output: 1445
🧰 Tools
🪛 GitHub Actions: Lint Code Base
[error] 66-66: Failed to write to feBomData.json during postinstall script execution
🪛 GitHub Actions: Cypress Tests
[error] 66-66: Failed to write to './public/licenses/feBomData.json' - directory does not exist (ENOENT error)
🪛 GitHub Actions: Deploy Care Fe
[error] 66-66: Failed to write to './public/licenses/feBomData.json': directory does not exist
…o issues/9534/update-license-sbom
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
instead of this, we can do in the fetch sbom data script.
await mkdir(path, { recursive: true })
</h3> | ||
{bomData.components?.map((component, index) => ( | ||
{packages.map((pkg: any, index: number) => ( |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
now that we have strong types defined, let's not use any.
{packages.map((pkg: any, index: number) => ( | |
{packages.map((package, index) => ( |
Proposed Changes
@ohcnetwork/care-fe-code-reviewers
Merge Checklist
Summary by CodeRabbit
New Features
Chores
Documentation