Repository navigation
Expand file tree
/
Copy patharchives.go
More file actions
283 lines (255 loc) · 8.54 KB
/
Copy patharchives.go
File metadata and controls
283 lines (255 loc) · 8.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
// Package archives provides in-memory archive reading and browsing capabilities.
//
// It supports multiple archive formats including:
// - ZIP (.zip, .jar, .whl, .nupkg, .egg, .vsix)
// - TAR (.tar, .tar.gz, .tgz, .crate, .tar.bz2, .tar.xz, .tar.zst)
// - GEM (.gem - Ruby gems with nested tar structure)
// - Hex (.tar - Hex packages with nested contents.tar.gz)
// - CONDA (.conda - v2 conda packages, zip of zstd tarballs)
//
// The .apk extension is routed by content since Android packages are ZIP
// and Alpine packages are gzipped tar. Filenames without a recognised
// extension are opened by inspecting the first bytes.
//
// The package is designed to work entirely in memory without writing to disk,
// making it suitable for browsing cached artifacts on-demand.
package archives
import (
"bufio"
"bytes"
"fmt"
"io"
"path"
"strings"
"time"
"github.com/git-pkgs/magic"
)
const (
formatZIP = "zip"
formatTAR = "tar"
formatTarGzip = "tar.gz"
formatTGZ = "tgz"
formatTarBzip2 = "tar.bz2"
formatTarXZ = "tar.xz"
formatTarZstd = "tar.zst"
formatGem = "gem"
formatConda = "conda"
contentSniffSize = 512
compressionGzip = "gzip"
compressionBzip2 = "bzip2"
compressionXZ = "xz"
compressionZstd = "zstd"
)
// FileInfo represents metadata about a file in an archive.
type FileInfo struct {
Path string // Full path within archive
Name string // Base name
Size int64 // Uncompressed bytes; -1 for an unknown streaming size
ModTime time.Time // Modification time
IsDir bool // Whether this is a directory
Mode uint32 // fs.FileMode value: permission bits plus fs.ModeType bits
HasMode bool // Whether Mode was recorded by the archive
CompressedSize int64 // Compressed size (if available)
}
// Reader provides methods to browse and extract files from archives.
type Reader interface {
// List returns all files in the archive.
List() ([]FileInfo, error)
// ListDir returns files in a specific directory path.
// Use "" or "/" for root directory.
ListDir(dirPath string) ([]FileInfo, error)
// Extract reads a specific file from the archive.
// Returns io.ReadCloser for the file content.
Extract(filePath string) (io.ReadCloser, error)
// Hash returns the hex-encoded digest of the raw archive bytes using
// the named algorithm. Supported algorithms are SHA256, SHA512, SHA1
// and MD5. The hash is computed over the original archive as passed
// to Open, not the decompressed contents.
Hash(algo string) (string, error)
// Close releases resources associated with the reader.
Close() error
}
// Open creates an archive reader for the given content.
// The filename is used first to detect the archive format. If it has no
// supported extension, the content is checked for a supported physical format.
// Recognised archives are read entirely into memory. An unrecognised stream
// with no supported extension is rejected after reading at most 512 bytes.
//
//nolint:ireturn // factory function returning interface by design
func Open(filename string, content io.Reader) (Reader, error) {
format := detectFormat(filename)
if format == "" {
buffered := bufio.NewReaderSize(content, contentSniffSize)
prefix, err := buffered.Peek(contentSniffSize)
if err != nil && err != io.EOF {
return nil, fmt.Errorf("reading archive content: %w", err)
}
format = detectContentPrefixFormat(prefix)
if format == "" {
return nil, fmt.Errorf("unsupported archive format: %s", filename)
}
content = buffered
}
raw, err := io.ReadAll(content)
if err != nil {
return nil, fmt.Errorf("reading archive content: %w", err)
}
return openRaw(format, raw)
}
// OpenBytes is like Open but accepts the archive content as a byte slice.
// The slice is retained (not copied) for the lifetime of the Reader and
// must not be modified by the caller after this call.
//
//nolint:ireturn // factory function returning interface by design
func OpenBytes(filename string, content []byte) (Reader, error) {
format := detectFormat(filename)
if format == "" {
format = detectContentFormat(content)
}
if format == "" {
return nil, fmt.Errorf("unsupported archive format: %s", filename)
}
return openRaw(format, content)
}
//nolint:ireturn
func openRaw(format string, raw []byte) (Reader, error) {
switch format {
case formatZIP:
return openZip(raw)
case formatTAR:
hexPackage, err := isHex(bytes.NewReader(raw), StreamOptions{MaxInputBytes: maxDecompressedSize, MaxEntries: maxArchiveEntries})
if err != nil {
return nil, err
}
if hexPackage {
return openNestedTar(raw, hexContents, "Hex")
}
return openTar(raw, "")
case formatTarGzip, formatTGZ:
return openTar(raw, compressionGzip)
case formatTarBzip2:
return openTar(raw, compressionBzip2)
case formatTarXZ:
return openTar(raw, compressionXZ)
case formatTarZstd:
return openTar(raw, compressionZstd)
case formatGem:
return openGem(raw)
case formatConda:
return openConda(raw)
case compressionGzip, compressionBzip2, compressionXZ, compressionZstd:
return openCompressed(raw)
default:
return nil, fmt.Errorf("unsupported format: %s", format)
}
}
func detectContentFormat(content []byte) string {
return archiveFormat(magic.Detect(content).Format)
}
func detectContentPrefixFormat(content []byte) string {
return archiveFormat(magic.DetectPrefix(content).Format)
}
func archiveFormat(detected string) string {
switch detected {
case "zip":
return formatZIP
case "tar":
return formatTAR
case compressionGzip, compressionBzip2, compressionXZ, compressionZstd:
return detected
default:
return ""
}
}
// OpenWithPrefix opens an archive and strips the given prefix from all paths.
// This is useful for npm packages which wrap content in a "package/" directory.
//
//nolint:ireturn // factory function returning interface by design
func OpenWithPrefix(filename string, content io.Reader, stripPrefix string) (Reader, error) {
reader, err := Open(filename, content)
if err != nil {
return nil, err
}
return wrapPrefix(reader, stripPrefix), nil
}
// OpenBytesWithPrefix is like OpenWithPrefix but accepts the archive content as
// a byte slice. The slice is retained (not copied) for the lifetime of the
// Reader and must not be modified by the caller after this call.
//
//nolint:ireturn // factory function returning interface by design
func OpenBytesWithPrefix(filename string, content []byte, stripPrefix string) (Reader, error) {
reader, err := OpenBytes(filename, content)
if err != nil {
return nil, err
}
return wrapPrefix(reader, stripPrefix), nil
}
//nolint:ireturn
func wrapPrefix(reader Reader, stripPrefix string) Reader {
if stripPrefix == "" {
return reader
}
return &prefixStripper{reader: reader, prefix: stripPrefix}
}
// detectFormat determines archive format from filename extension.
func detectFormat(filename string) string {
filename = strings.ToLower(filename)
// Check for compound extensions first
if strings.HasSuffix(filename, ".tar.gz") {
return formatTarGzip
}
if strings.HasSuffix(filename, ".tar.bz2") {
return formatTarBzip2
}
if strings.HasSuffix(filename, ".tar.xz") {
return formatTarXZ
}
if strings.HasSuffix(filename, ".tar.zst") {
return formatTarZstd
}
// Check simple extensions. .apk is deliberately absent: Alpine packages
// are gzipped tarballs and Android packages are zips, so it falls
// through to content sniffing.
ext := path.Ext(filename)
switch ext {
case ".zip", ".jar", ".whl", ".nupkg", ".egg", ".vsix":
return formatZIP
case ".tar":
return formatTAR
case ".tgz", ".crate":
return formatTGZ
case ".gem":
return formatGem
case ".conda":
return formatConda
default:
return ""
}
}
// normalizeDir normalizes directory path for consistent comparison.
func normalizeDir(dirPath string) string {
dirPath = strings.TrimSpace(dirPath)
dirPath = strings.Trim(dirPath, "/")
if dirPath == "" {
return ""
}
return dirPath + "/"
}
// isInDir reports whether filePath is directly in dirPath (not in a
// subdirectory). dirPath must already be normalized via normalizeDir;
// callers do this once outside the per-entry loop.
func isInDir(filePath, dirPath string) bool {
filePath = strings.TrimSuffix(filePath, "/")
if dirPath == "" {
return strings.IndexByte(filePath, '/') < 0
}
// dirPath ends in "/"; an entry naming the directory itself counts as
// inside it so explicit dir entries in the archive are listed.
if filePath == dirPath[:len(dirPath)-1] {
return true
}
if !strings.HasPrefix(filePath, dirPath) {
return false
}
return strings.IndexByte(filePath[len(dirPath):], '/') < 0
}