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

Add functionality to inspect nodes #104

Merged
merged 1 commit into from
Oct 26, 2024
Merged

Conversation

neilnaveen
Copy link
Member

@neilnaveen neilnaveen commented Oct 26, 2024

  • Updated the README to reflect changes
  • Removed the output dir from query custom, and moved it to its own command
  • We can either see the node in stdout or write it to a file

Summary by CodeRabbit

Release Notes

  • Documentation

    • Updated example commands and descriptions in the README for clarity.
    • Standardized terminology from "PACKAGE" to "library" in command examples.
    • Improved formatting consistency for shell command examples.
  • New Features

    • Introduced a new command for querying node information with options for outputting results to a file or console.
    • Enhanced querying functionality to visualize dependencies without file generation.
    • Added a glob search command for improved querying capabilities.
  • Bug Fixes

    • Streamlined file handling in the SBOM processing function for improved efficiency.

Copy link
Contributor

coderabbitai bot commented Oct 26, 2024

Walkthrough

The changes encompass updates to the README.md file for improved command examples and terminology, particularly replacing "PACKAGE" with "library." The cmd/query/custom/custom.go file has had the outputdir field removed, simplifying output handling to console display only. A new file, cmd/query/output/output.go, introduces functionality for querying node information and optionally outputting results to a file. The command structure in cmd/query/query.go has been updated to integrate the new output command, while modifications in pkg/tools/ingest/sbom.go streamline file handling and node processing.

Changes

File Path Change Summary
README.md Updated command examples and descriptions; replaced "PACKAGE" with "library"; standardized formatting.
cmd/query/custom/custom.go Removed outputdir field and associated flag; eliminated output directory handling in Run method.
cmd/query/output/output.go Introduced new functionality for querying and outputting node information; added options struct and methods.
cmd/query/query.go Added new command for output handling by integrating output.New(storage) into the command structure.
pkg/tools/ingest/sbom.go Modified file handling in processSBOMFile; changed parameters in graph.AddNode function call.

Possibly related PRs

  • Updated README to include offline capabilities #100: The changes in this PR also involve updates to the README.md file, specifically refining command examples and descriptions, which aligns with the main PR's focus on enhancing clarity and accuracy in documentation.
  • Updated README #101: Similar to the main PR, this PR modifies the README.md file to improve clarity and structure, including updates to command descriptions, making it relevant to the changes made in the main PR.

🐰 In the garden where commands grow,
A rabbit hops with knowledge to show.
"Library" now sings in the README bright,
With paths that guide us, oh what a sight!
Output flows freely, no files to confine,
Just tables of data, all neatly aligned.
Let's celebrate changes with a joyful cheer,
For clarity blooms in the code we hold dear! 🌼


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

codecov bot commented Oct 26, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Files with missing lines Coverage Δ
pkg/tools/ingest/sbom.go 59.25% <100.00%> (+1.61%) ⬆️

... and 2 files with indirect coverage changes

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

🧹 Outside diff range and nitpick comments (4)
cmd/query/output/output.go (1)

22-25: Improve flag documentation and remove empty line.

The flag description should provide more details about the expected format and behavior.

 func (o *options) AddFlags(cmd *cobra.Command) {
-    
-    cmd.Flags().StringVar(&o.outputFile, "output-file", "", "output file")
+    cmd.Flags().StringVar(&o.outputFile, "output-file", "", "path to write JSON output (if not specified, writes to stdout)")
 }
pkg/tools/ingest/sbom.go (1)

Line range hint 1-134: Consider these improvements for better maintainability and performance.

  1. Use golang.org/x/sync/errgroup for concurrent processing and proper error handling
  2. Rename nameToId to something more descriptive like nodeIdentifierMapping
  3. Consider batching edge operations for better performance

Here's an example of using errgroup for concurrent processing:

import "golang.org/x/sync/errgroup"

func SBOM(sbomPath string, storage graph.Storage, progress func(count int, path string)) (int, error) {
    // ... existing code ...
    
    if info.IsDir() {
        g := new(errgroup.Group)
        for _, entry := range entries {
            entry := entry // https://golang.org/doc/faq#closures_and_goroutines
            g.Go(func() error {
                entryPath := filepath.Join(sbomPath, entry.Name())
                subCount, err := SBOM(entryPath, storage, progress)
                if err != nil {
                    return fmt.Errorf("failed to ingest SBOM from path %s: %w", entryPath, err)
                }
                atomic.AddInt32(&count, int32(subCount))
                if progress != nil {
                    progress(int(atomic.LoadInt32(&count)), entryPath)
                }
                return nil
            })
        }
        if err := g.Wait(); err != nil {
            return count, err
        }
    }
    // ... rest of the code ...
}
README.md (2)

62-91: Add examples for the new node inspection functionality.

While the example commands are clear and well-documented, consider adding examples demonstrating the new node inspection functionality, including:

  • Viewing node information in stdout
  • Writing node information to a file using the new output command

Example addition:

 minefield query custom "dependents library pkg:dep2@1.0.0" --visualize
+
+# Inspect node information in stdout
+minefield query output pkg:dep2@1.0.0
+
+# Write node information to a file
+minefield query output pkg:dep2@1.0.0 --output-file=node_info.txt
🧰 Tools
🪛 Markdownlint

75-75: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


80-80: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


85-85: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


75-85: Maintain consistent list style throughout the document.

The unordered lists use a mix of dashes (-) and asterisks (). For better maintainability, use asterisks () consistently throughout the document.

Apply this change:

-   - This command generates a ranked list of packages, ordered by the number of other packages that depend on them.
+   * This command generates a ranked list of packages, ordered by the number of other packages that depend on them.

-   - This command queries the dependents for a specific package, in this case `dep2`.
+   * This command queries the dependents for a specific package, in this case `dep2`.

-   - These queries output the intersection of two queries, finding package dependencies shared between each pair.
+   * These queries output the intersection of two queries, finding package dependencies shared between each pair.
🧰 Tools
🪛 Markdownlint

75-75: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


80-80: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


85-85: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 8ea49f4 and 5ec00ea.

📒 Files selected for processing (5)
  • README.md (1 hunks)
  • cmd/query/custom/custom.go (0 hunks)
  • cmd/query/output/output.go (1 hunks)
  • cmd/query/query.go (2 hunks)
  • pkg/tools/ingest/sbom.go (2 hunks)
💤 Files with no reviewable changes (1)
  • cmd/query/custom/custom.go
🧰 Additional context used
🪛 Markdownlint
README.md

75-75: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


80-80: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


85-85: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)

🔇 Additional comments (3)
cmd/query/query.go (1)

6-6: LGTM! Clean integration of the new output command.

The changes follow the existing command structure pattern and maintain consistency with the codebase. The new output functionality is properly integrated into the command hierarchy.

Also applies to: 20-20

cmd/query/output/output.go (2)

72-77: Make file permissions configurable and more secure.

The file permissions are hard-coded to 0644. Consider making this configurable or using a more restrictive default.
[security]

+const defaultFilePerms = 0600  // More restrictive default

     if o.outputFile != "" {
-        err = os.WriteFile(o.outputFile, jsonOutput, 0644)
+        err = os.WriteFile(o.outputFile, jsonOutput, defaultFilePerms)
         if err != nil {
             return fmt.Errorf("failed to write output file: %v", err)
         }

84-98: ⚠️ Potential issue

Remove unused storage parameter and improve command description.

The storage parameter is not used in the implementation, and the command description could be more informative.

-func New(storage graph.Storage) *cobra.Command {
+func New() *cobra.Command {
     o := &options{
-        storage: storage,
     }
     cmd := &cobra.Command{
         Use:               "output [node name]",
-        Short:             "Output the node, with its metadata",
+        Short:             "Display or save node information",
+        Long:              `Query and output detailed information about a node, including its metadata.
+                           The output can be displayed in the terminal or saved to a file.`,
+        Example:           "  minefield query output mynode --output-file=node-info.json",
         Args:              cobra.ExactArgs(1),
         RunE:              o.Run,
         DisableAutoGenTag: true,
     }

Likely invalid or redundant comment.

cmd/query/output/output.go Show resolved Hide resolved
cmd/query/output/output.go Outdated Show resolved Hide resolved
cmd/query/output/output.go Show resolved Hide resolved
cmd/query/output/output.go Outdated Show resolved Hide resolved
cmd/query/output/output.go Show resolved Hide resolved
pkg/tools/ingest/sbom.go Outdated Show resolved Hide resolved
pkg/tools/ingest/sbom.go Show resolved Hide resolved
- Updated the README to reflect changes
- Removed the output dir from query custom, and moved it to its own
  command
- We can either see the node in stdout or write it to a file

Signed-off-by: neilnaveen <42328488+neilnaveen@users.noreply.github.com>
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

🧹 Outside diff range and nitpick comments (4)
cmd/query/globsearch/globsearch.go (3)

Line range hint 15-21: Consider enhancing the max-output flag configuration.

While the current implementation works, consider these improvements:

  1. Add validation to prevent negative values for max-output
  2. Consider making the default limit configurable or higher for better usability
 func (o *options) AddFlags(cmd *cobra.Command) {
-	cmd.Flags().IntVar(&o.maxOutput, "max-output", 10, "max output length")
+	cmd.Flags().IntVar(&o.maxOutput, "max-output", 10, "maximum number of results to display (must be positive)")
+	cmd.MarkFlagRequired("max-output")
+	cmd.PreRunE = func(cmd *cobra.Command, args []string) error {
+		if o.maxOutput <= 0 {
+			return fmt.Errorf("max-output must be positive, got %d", o.maxOutput)
+		}
+		return nil
+	}
 }

Line range hint 23-63: Several improvements needed in the Run implementation.

The implementation has multiple areas that could be enhanced for better reliability and maintainability:

  1. Add timeout to HTTP client:
-	httpClient := &http.Client{}
+	httpClient := &http.Client{
+		Timeout: 30 * time.Second,
+	}
  1. Fix the off-by-one error in output limiting:
-	if count > o.maxOutput {
+	if count >= o.maxOutput {
  1. Move the default address to a constant:
+const defaultServiceAddr = "http://localhost:8089"
+
 func (o *options) Run(cmd *cobra.Command, args []string) error {
 	pattern := args[0]
 	httpClient := &http.Client{}
 	addr := os.Getenv("BITBOMDEV_ADDR")
 	if addr == "" {
-		addr = "http://localhost:8089"
+		addr = defaultServiceAddr
 	}

Line range hint 65-81: Enhance command usage documentation.

While the command configuration is correct, the usage description could be more helpful to users.

 	cmd := &cobra.Command{
-		Use:               "globsearch [pattern]",
-		Short:             "Search for nodes by glob pattern",
+		Use:               "globsearch [glob-pattern]",
+		Short:             "Search for nodes by glob pattern (e.g., '*.jar' or 'com.example.*')",
+		Example:           "  minefield globsearch '*.jar'\n  minefield globsearch 'org.apache.*' --max-output 20",
 		Args:              cobra.ExactArgs(1),
 		RunE:              o.Run,
 		DisableAutoGenTag: true,
 	}
README.md (1)

75-75: Maintain consistent list style in markdown.

For consistency with the rest of the document, consider using asterisks (*) instead of dashes (-) for unordered lists.

-   - This command generates a ranked list of packages, ordered by the number of other packages that depend on them.
+   * This command generates a ranked list of packages, ordered by the number of other packages that depend on them.

-   - This command queries the dependents for a specific package, in this case `dep2`.
+   * This command queries the dependents for a specific package, in this case `dep2`.

-   - These queries output the intersection of two queries, finding package dependencies shared between each pair.
+   * These queries output the intersection of two queries, finding package dependencies shared between each pair.

Also applies to: 80-80, 85-85

🧰 Tools
🪛 Markdownlint

75-75: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 5ec00ea and 95259a4.

📒 Files selected for processing (6)
  • README.md (1 hunks)
  • cmd/query/custom/custom.go (1 hunks)
  • cmd/query/globsearch/globsearch.go (1 hunks)
  • cmd/query/output/output.go (1 hunks)
  • cmd/query/query.go (2 hunks)
  • pkg/tools/ingest/sbom.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • cmd/query/custom/custom.go
  • cmd/query/query.go
  • pkg/tools/ingest/sbom.go
🧰 Additional context used
🪛 Markdownlint
README.md

75-75: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


80-80: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


85-85: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)

🔇 Additional comments (4)
cmd/query/globsearch/globsearch.go (2)

Line range hint 1-13: LGTM! Package structure and imports are well-organized.

The package rename from query to globsearch better reflects its specific functionality, improving code organization.


Line range hint 23-63: Verify the service address configuration across the codebase.

The hardcoded service address and environment variable name should be consistent across the codebase.

✅ Verification successful

Service address configuration is consistent across the codebase

The verification shows that both the environment variable BITBOMDEV_ADDR and the default address localhost:8089 (or http://localhost:8089) are consistently used across all client components:

  • Cache service client
  • Graph service client
  • Query service client
  • Leaderboard service client
  • Service startup configuration
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other occurrences of the service address and environment variable
echo "Searching for service address usage:"
rg -A 2 "localhost:8089"

echo "Searching for environment variable usage:"
rg -A 2 "BITBOMDEV_ADDR"

Length of output: 2840

README.md (2)

74-91: LGTM! Clear and accurate command examples.

The command examples are well-structured and accurately reflect the new functionality for:

  • Viewing node information (leaderboard and query commands)
  • Consistent terminology using "library" instead of "PACKAGE"
  • Visualization options
🧰 Tools
🪛 Markdownlint

75-75: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


80-80: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


85-85: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


66-68: Verify the example path exists.

The example uses testdata/small directory. Let's verify this path exists in the repository.

✅ Verification successful

Path testdata/small exists with valid SBOM files

The directory testdata/small exists and contains three SBOM files (dep1.json, libA.json, libB.json), making the example command in the README accurate and functional.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if the testdata/small directory exists and contains SBOM files
if fd -t d "small$" testdata/; then
    echo "Directory exists. Checking contents:"
    fd . testdata/small/
else
    echo "Warning: testdata/small directory not found"
fi

Length of output: 225

cmd/query/output/output.go Show resolved Hide resolved
cmd/query/output/output.go Show resolved Hide resolved
@naveensrinivasan naveensrinivasan merged commit 3a2c3fb into main Oct 26, 2024
7 checks passed
@naveensrinivasan naveensrinivasan deleted the neil/outputNodes branch October 26, 2024 16:24
@coderabbitai coderabbitai bot mentioned this pull request Oct 27, 2024
@neilnaveen neilnaveen restored the neil/outputNodes branch October 31, 2024 15:54
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.

2 participants