85 lines
2.2 KiB
Go
85 lines
2.2 KiB
Go
//go:build linux || freebsd
|
|||
|
|
// +build linux freebsd
|
||
|
|
|
||
|
|
package archive
|
||
|
|
|
||
|
|
import (
|
||
|
|
"io"
|
||
|
|
"strings"
|
||
|
|
)
|
||
|
|
|
||
|
|
// Extractor is the interface for archive extraction
|
||
|
|
type Extractor interface {
|
||
|
|
Name() string
|
||
|
|
Extensions() []string
|
||
|
|
Extract(r io.Reader, destDir string) error
|
||
|
|
CanHandle(filename string) bool
|
||
|
|
}
|
||
|
|
|
||
|
|
// BaseExtractor provides a basic implementation
|
||
|
|
type BaseExtractor struct {
|
||
|
|
name string
|
||
|
|
extensions []string
|
||
|
|
}
|
||
|
|
|
||
|
|
func NewBaseExtractor(name string, extensions []string) *BaseExtractor {
|
||
|
|
return &BaseExtractor{name: name, extensions: extensions}
|
||
|
|
}
|
||
|
|
|
||
|
|
func (b *BaseExtractor) Name() string { return b.name }
|
||
|
|
func (b *BaseExtractor) Extensions() []string { return b.extensions }
|
||
|
|
func (b *BaseExtractor) CanHandle(filename string) bool {
|
||
|
|
filename = strings.ToLower(filename)
|
||
|
|
for _, ext := range b.extensions {
|
||
|
|
if strings.HasSuffix(filename, ext) {
|
||
|
|
return true
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return false
|
||
|
|
}
|
||
|
|
|
||
|
|
// DetectArchiveFormat detects the archive format by file extension
|
||
|
|
func DetectArchiveFormat(filename string) string {
|
||
|
|
filename = strings.ToLower(filename)
|
||
|
|
if strings.HasSuffix(filename, ".tar.gz") || strings.HasSuffix(filename, ".tgz") {
|
||
|
|
return "tar.gz"
|
||
|
|
}
|
||
|
|
if strings.HasSuffix(filename, ".tar.bz2") || strings.HasSuffix(filename, ".tbz2") {
|
||
|
|
return "tar.bz2"
|
||
|
|
}
|
||
|
|
if strings.HasSuffix(filename, ".zip") {
|
||
|
|
return "zip"
|
||
|
|
}
|
||
|
|
if strings.HasSuffix(filename, ".tar") {
|
||
|
|
return "tar"
|
||
|
|
}
|
||
|
|
return ""
|
||
|
|
}
|
||
|
|
|
||
|
|
// IsArchiveFormat checks whether the filename looks like an archive
|
||
|
|
func IsArchiveFormat(filename string) bool { return DetectArchiveFormat(filename) != "" }
|
||
|
|
|
||
|
|
// GetArchiveAndCompression splits filename into archive + compression parts
|
||
|
|
func GetArchiveAndCompression(filename string) (archive, compression string) {
|
||
|
|
filename = strings.ToLower(filename)
|
||
|
|
if strings.HasSuffix(filename, ".tar.gz") || strings.HasSuffix(filename, ".tgz") {
|
||
|
|
return "tar", "gzip"
|
||
|
|
}
|
||
|
|
if strings.HasSuffix(filename, ".tar.bz2") || strings.HasSuffix(filename, ".tbz2") {
|
||
|
|
return "tar", "bzip2"
|
||
|
|
}
|
||
|
|
if strings.HasSuffix(filename, ".zip") {
|
||
|
|
return "zip", ""
|
||
|
|
}
|
||
|
|
if strings.HasSuffix(filename, ".tar") {
|
||
|
|
return "tar", ""
|
||
|
|
}
|
||
|
|
if strings.HasSuffix(filename, ".gz") {
|
||
|
|
return "", "gzip"
|
||
|
|
}
|
||
|
|
if strings.HasSuffix(filename, ".bz2") {
|
||
|
|
return "", "bzip2"
|
||
|
|
}
|
||
|
|
return "", ""
|
||
|
|
}
|