Skip to content

Snag a directory#67

Merged
MusicalNinjaDad merged 7 commits into
mainfrom
directory
Oct 27, 2025
Merged

Snag a directory#67
MusicalNinjaDad merged 7 commits into
mainfrom
directory

Conversation

@MusicalNinjaDad

@MusicalNinjaDad MusicalNinjaDad commented Oct 27, 2025

Copy link
Copy Markdown
Owner

Summary by Sourcery

Extend Snaggle to handle directories by iterating over contained files and apply the existing file processing logic via a new helper function

New Features:

  • Allow Snaggle to accept a directory path and process all contained non-directory files

Enhancements:

  • Extract single-file processing logic into a helper function

Tests:

  • Add TestDirectory to verify directory-based processing

@sourcery-ai

sourcery-ai Bot commented Oct 27, 2025

Copy link
Copy Markdown

Reviewer's Guide

Refactored the Snaggle entry point to support directory inputs by extracting the file-handling logic into a private helper and added corresponding tests while cleaning up obsolete test data.

Class diagram for refactored Snaggle entry point and helper

classDiagram
    class Snaggle {
        +Snaggle(path string, root string, opts ...option) error
    }
    class snaggle {
        +snaggle(path string, binDir string, libDir string, options options) error
    }
    Snaggle --> snaggle : calls
    class options {
        <<struct>>
    }
    class option {
        <<type>>
    }
    class elf {
        +New(path string) (*elf, error)
    }
    snaggle --> elf : uses
    Snaggle --> options : uses
    Snaggle --> option : uses
    snaggle --> options : uses
Loading

Flow diagram for directory handling in Snaggle

flowchart TD
    A["Snaggle(path, root, opts...)"] --> B["os.Stat(path)"]
    B --> C{IsDir?}
    C -- Yes --> D["os.ReadDir(path)"]
    D --> E["for each file in directory"]
    E --> F{file.IsDir?}
    F -- No --> G["snaggle(filePath, binDir, libDir, options)"]
    G --> H{error}
    H -- nil or FormatError --> E
    H -- other error --> I["return error"]
    F -- Yes --> E
    C -- No --> J["snaggle(path, binDir, libDir, options)"]
    J --> K["return"]
Loading

File-Level Changes

Change Details Files
Refactor Snaggle and add directory processing
  • Removed direct elf.New initialization from the public Snaggle function
  • Added os.Stat and ReadDir to detect and iterate over directory entries
  • Loop over non-directory files, invoking a new private handler and skipping non-ELF files
  • Introduced private snaggle() to encapsulate single-file ELF processing
snaggle.go
Expand test coverage with directory-based tests
  • Implemented TestDirectory to verify handling of entire directories
  • Set up a temporary workspace, derived expected outputs, and asserted file contents and logs
snaggle_test.go
Remove unused test data
  • Deleted internal/testdata/which2 as it’s no longer needed
internal/testdata/which2

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@MusicalNinjaDad MusicalNinjaDad linked an issue Oct 27, 2025 that may be closed by this pull request
@codecov

codecov Bot commented Oct 27, 2025

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 76.92308% with 6 lines in your changes missing coverage. Please review.
✅ Project coverage is 75.42%. Comparing base (355fef9) to head (65ae5be).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
snaggle.go 76.92% 4 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main      #67      +/-   ##
==========================================
+ Coverage   75.05%   75.42%   +0.36%     
==========================================
  Files           8        8              
  Lines         449      472      +23     
==========================================
+ Hits          337      356      +19     
- Misses         80       83       +3     
- Partials       32       33       +1     

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

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey there - I've reviewed your changes - here's some feedback:

  • In the loop over directory entries, the local variable path shadows the outer parameter—consider renaming it (e.g. entryPath) to avoid confusion.
  • The implementation only scans the immediate directory and skips nested directories—if you need to support deeper hierarchies, consider recursing into subfolders or using filepath.WalkDir for a more robust traversal.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In the loop over directory entries, the local variable `path` shadows the outer parameter—consider renaming it (e.g. `entryPath`) to avoid confusion.
- The implementation only scans the immediate directory and skips nested directories—if you need to support deeper hierarchies, consider recursing into subfolders or using filepath.WalkDir for a more robust traversal.

## Individual Comments

### Comment 1
<location> `snaggle_test.go:99` </location>
<code_context>
 	}
 }
+
+func TestDirectory(t *testing.T) {
+	var stdout strings.Builder
+	log.SetOutput(&stdout)
</code_context>

<issue_to_address>
**suggestion (testing):** Missing test for error conditions when processing a directory.

Please add tests for cases like os.ReadDir failure, unreadable files, and snaggle errors to cover error handling in directory processing.

Suggested implementation:

```golang
func TestDirectory(t *testing.T) {
	var stdout strings.Builder
	log.SetOutput(&stdout)
	t.Cleanup(func() { log.SetOutput(os.Stdout) })

	Assert := assert.New(t)
	tmp := WorkspaceTempDir(t)

	contents := CommonBinaries(t)
	dir := TestdataPath(".")
	inplace := false

	var expectedOut []string

	// Test: os.ReadDir failure
	t.Run("ReadDirError", func(t *testing.T) {
		// Simulate ReadDir error by passing a non-existent directory
		_, err := os.ReadDir("/nonexistent-directory-should-fail")
		Assert.Error(err, "expected error when reading non-existent directory")
	})

	// Test: unreadable file in directory
	t.Run("UnreadableFile", func(t *testing.T) {
		unreadableFile := filepath.Join(tmp, "unreadable.txt")
		err := os.WriteFile(unreadableFile, []byte("data"), 0000)
		Assert.NoError(err)
		defer os.Remove(unreadableFile)

		f, err := os.Open(unreadableFile)
		if f != nil {
			f.Close()
		}
		Assert.Error(err, "expected error when opening unreadable file")
	})

	// Test: snaggle error simulation
	t.Run("SnaggleError", func(t *testing.T) {
		// Simulate a snaggle error by calling a function that returns an error
		err := errors.New("snaggle error")
		Assert.Error(err, "expected snaggle error")
	})
}

```

- If your directory processing logic is encapsulated in a function (e.g., `ProcessDirectory`), you should call that function in the error tests and mock its dependencies to trigger the errors.
- You may need to adjust the error simulation to match your actual error handling and logging mechanisms.
- Ensure that the error cases are covered in your main directory processing function, not just in the test scaffolding.
</issue_to_address>

### Comment 2
<location> `snaggle.go:158` </location>
<code_context>
 	binDir := filepath.Join(root, "bin")
 	libDir := filepath.Join(root, "lib64")

+	stat, err := os.Stat(path)
+	if err != nil {
+		return err
</code_context>

<issue_to_address>
**issue (complexity):** Consider replacing manual directory traversal and recursion with filepath.WalkDir to simplify file iteration and error handling.

Consider replacing the custom recursion in Snaggle + snaggle with Go’s filepath.WalkDir. This flattens the logic, kills the helper, and handles directories/files in one place:

```go
import (
    "debug/elf"
    "errors"
    "io/fs"
    "path/filepath"
    "golang.org/x/sync/errgroup"
)

// Snaggle walks src (file or dir), parses each ELF, skips non-ELF,
// and links executables into bin/ or libs into lib64/ under root.
func Snaggle(src, root string, opts ...option) error {
    // 1. apply options as before
    var options options
    for _, o := range opts {
        o(&options)
    }

    binDir := filepath.Join(root, "bin")
    libDir := filepath.Join(root, "lib64")
    g := new(errgroup.Group)

    // 2. walk everything under src
    err := filepath.WalkDir(src, func(path string, d fs.DirEntry, err error) error {
        if err != nil {
            return err
        }
        if d.IsDir() {
            return nil
        }

        // 3. open ELF, skip non-ELF
        f, err := elf.New(path)
        if err != nil {
            var fe *elf.FormatError
            if errors.As(err, &fe) {
                return nil
            }
            return err
        }

        // 4. no-op for inplace
        if options.inplace {
            return nil
        }

        // 5. enqueue link
        dst := libDir
        if f.IsExe() {
            dst = binDir
        }
        p := path // capture
        g.Go(func() error { return link(p, dst) })
        return nil
    })
    if err != nil {
        return err
    }

    // 6. wait for all links
    return g.Wait()
}
```

Steps:
- Remove `os.Stat`/`os.ReadDir` and the separate `snaggle` helper.
- Use `filepath.WalkDir` to iterate files.
- Inline ELF-open + skip-FormatError logic.
- Use one errgroup for parallel links.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@MusicalNinjaDad MusicalNinjaDad enabled auto-merge (squash) October 27, 2025 14:54
@MusicalNinjaDad MusicalNinjaDad merged commit e456836 into main Oct 27, 2025
12 checks passed
@MusicalNinjaDad MusicalNinjaDad deleted the directory branch October 27, 2025 14:55
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.

snaggle all Elfs

1 participant