Skip to content

Add a ReadFile method, to read a file inside a resource pack #315

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions minecraft/resource/pack.go
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,38 @@ func (pack *Pack) ReadAt(b []byte, off int64) (n int, err error) {
return pack.content.ReadAt(b, off)
}

// ReadFile reads a specific file from the Pack's content and returns its content as a byte slice.
func (p *Pack) ReadFile(filePath string) ([]byte, error) {
// Create a new zip reader from the content of the bytes.Reader
zipReader, err := zip.NewReader(p.content, int64(p.content.Size()))
if err != nil {
return nil, fmt.Errorf("failed to create zip reader: %w", err)
}

// Iterate over the files in the archive to find the file
for _, file := range zipReader.File {
// Check if the current file is the one we're looking for
if strings.EqualFold(file.Name, filePath) {
// Open the file
rc, err := file.Open()
if err != nil {
return nil, fmt.Errorf("failed to open file %s: %w", filePath, err)
}
defer rc.Close()

// Read the file content
content, err := io.ReadAll(rc)
if err != nil {
return nil, fmt.Errorf("failed to read file content: %w", err)
}

return content, nil
}
}

return nil, fmt.Errorf("file %s not found in the resource pack", filePath)
}

// WithContentKey creates a copy of the pack and sets the encryption key to the key provided, after which the
// new Pack is returned.
func (pack Pack) WithContentKey(key string) *Pack {
Expand Down