-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecompress.go
122 lines (99 loc) · 2.31 KB
/
decompress.go
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
// @author: Brian Wojtczak
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bufio"
"github.com/dustin/go-humanize"
"github.com/google/renameio"
"github.com/klauspost/compress/gzip"
"github.com/pkg/errors"
"io"
"log"
"os"
"path/filepath"
"strings"
"time"
)
// DecompressFile takes a filename and decompresses it to a new file of the
// same name without the .gz suffix. If keep is false, the original file is
// deleted if decompression is successful.
func DecompressFile(filename, suffix string, keep, force, verbose bool) (err error) {
var (
inputInfo os.FileInfo
outputInfo os.FileInfo
inputFile *os.File
outputFile *renameio.PendingFile
zr *gzip.Reader
outputFilename string
)
started := time.Now().UTC()
if verbose {
log.Printf(
"Decompressing %s",
filename,
)
}
inputInfo, err = os.Stat(filename)
if err != nil {
return err
}
inputFile, err = os.Open(filename)
if err != nil {
return err
}
//goland:noinspection GoUnhandledErrorResult
defer inputFile.Close()
outputFilename = strings.TrimSuffix(filename, suffix)
if !force {
if _, err := os.Stat(outputFilename); err == nil {
return errors.New("output file already exists")
}
}
outputFile, err = renameio.TempFile(filepath.Dir(outputFilename), outputFilename)
if err != nil {
return err
}
//goland:noinspection GoUnhandledErrorResult
defer outputFile.Cleanup()
outputBuffer := bufio.NewWriter(outputFile)
zr, err = gzip.NewReader(bufio.NewReader(inputFile))
if err != nil {
return err
}
_, err = io.Copy(outputBuffer, zr)
if err != nil {
return err
}
if err := zr.Close(); err != nil {
return err
}
if err := inputFile.Close(); err != nil {
return err
}
if err := outputBuffer.Flush(); err != nil {
return errors.Wrap(err, "error flushing output buffer")
}
if err := outputFile.CloseAtomicallyReplace(); err != nil {
return err
}
outputInfo, err = os.Stat(outputFilename)
if err != nil {
return err
}
if !keep {
if err = os.Remove(filename); err != nil {
return err
}
}
if verbose {
log.Printf(
"Decompressed %s from %s to %s in %v",
outputFilename,
humanize.Bytes(uint64(inputInfo.Size())),
humanize.Bytes(uint64(outputInfo.Size())),
time.Since(started),
)
}
return nil
}