Skip to content

Commit

Permalink
Merge pull request #403 from another-rex:add-seek
Browse files Browse the repository at this point in the history
PiperOrigin-RevId: 718146993
  • Loading branch information
copybara-github committed Jan 22, 2025
2 parents 8748276 + 052f941 commit 56d881c
Show file tree
Hide file tree
Showing 2 changed files with 85 additions and 0 deletions.
13 changes: 13 additions & 0 deletions artifact/image/layerscanning/image/file_node.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,19 @@ func (f *fileNode) ReadAt(b []byte, off int64) (n int, err error) {
return f.file.ReadAt(b, off)
}

func (f *fileNode) Seek(offset int64, whence int) (n int64, err error) {
if f.isWhiteout {
return 0, fs.ErrNotExist
}
if f.file == nil {
f.file, err = os.Open(f.RealFilePath())
}
if err != nil {
return 0, err
}
return f.file.Seek(offset, whence)
}

// Close closes the real file referred to by the fileNode and resets the file field.
func (f *fileNode) Close() error {
if f.file != nil {
Expand Down
72 changes: 72 additions & 0 deletions artifact/image/layerscanning/image/file_node_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -400,6 +400,78 @@ func TestReadAt(t *testing.T) {
}
}

// Test for the Seek method
func TestSeek(t *testing.T) {
tempDir := t.TempDir()
os.WriteFile(path.Join(tempDir, "bar"), []byte("bar"), 0600)

// Test seeking to different positions
tests := []struct {
name string
offset int64
whence int
want int64
}{
{
name: "seek to beginning",
offset: 0,
whence: io.SeekStart,
want: 0,
},
{
name: "seek to current position",
offset: 0,
whence: io.SeekCurrent,
want: 0,
},
{
name: "seek to end",
offset: 0,
whence: io.SeekEnd,
want: 3,
},
{
name: "seek to 10 bytes from beginning",
offset: 10,
whence: io.SeekStart,
want: 10,
},
{
name: "seek to 10 bytes from current position (at 0)",
offset: 10,
whence: io.SeekCurrent,
want: 10,
},
{
name: "seek to 2 bytes from end",
offset: -2,
whence: io.SeekEnd,
want: 1,
},
}

for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
// Create a fileNode for the opened file
fileNode := &fileNode{
extractDir: tempDir,
originLayerID: "",
virtualPath: "/bar",
isWhiteout: false,
mode: filePermission,
}
gotPos, err := fileNode.Seek(tc.offset, tc.whence)
fileNode.Close()
if err != nil {
t.Fatalf("Seek failed: %v", err)
}
if gotPos != tc.want {
t.Errorf("Seek returned incorrect position: got %d, want %d", gotPos, tc.want)
}
})
}
}

func TestClose(t *testing.T) {
tempDir := t.TempDir()
os.WriteFile(path.Join(tempDir, "bar"), []byte("bar"), 0600)
Expand Down

0 comments on commit 56d881c

Please sign in to comment.