-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathfileutil.go
More file actions
82 lines (71 loc) · 1.77 KB
/
Copy pathfileutil.go
File metadata and controls
82 lines (71 loc) · 1.77 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
package metha
import (
"fmt"
"io"
"math/rand"
"os"
"path/filepath"
"strings"
"github.com/adrg/xdg"
"github.com/klauspost/compress/zstd"
gzip "github.com/klauspost/pgzip"
)
// MustGlob is like filepath.Glob, but panics on bad pattern.
func MustGlob(pattern string) []string {
m, err := filepath.Glob(pattern)
if err != nil {
panic(err)
}
return m
}
// MoveCompressFile with compression type support
func MoveCompressFile(src, dst string, compressionType CompressionType, level int) (err error) {
tmp := fmt.Sprintf("%s-tmp-%d", dst, rand.Intn(999999999))
f, err := os.Create(tmp)
if err != nil {
return err
}
defer f.Close()
var writer io.WriteCloser
switch compressionType {
case CompZstd:
// Create zstd encoder with level
zstdOpts := zstd.WithEncoderLevel(zstd.EncoderLevelFromZstd(level))
writer, err = zstd.NewWriter(f, zstdOpts)
default: // CompGzip
writer = gzip.NewWriter(f)
}
if err != nil {
return err
}
defer writer.Close()
ff, err := os.Open(src)
if err != nil {
return err
}
defer ff.Close()
if _, err := io.Copy(writer, ff); err != nil {
return err
}
if err := os.Rename(tmp, dst); err != nil {
return err
}
return os.Remove(src)
}
// GetBaseDir returns the base directory for the cache.
func GetBaseDir() string {
if dir := os.Getenv("METHA_DIR"); dir != "" {
return dir
}
return filepath.Join(xdg.CacheHome, "metha")
}
// Add a function to detect compression type from file extension or content
func DetectCompression(filename string, firstBytes []byte) CompressionType {
if strings.HasSuffix(filename, ".zst") {
return CompZstd
}
if strings.HasSuffix(filename, ".gz") || (len(firstBytes) > 2 && firstBytes[0] == 0x1f && firstBytes[1] == 0x8b) {
return CompGzip
}
return CompGzip // Default for backward compatibility
}