]>
Commit | Line | Data |
---|---|---|
bae9f6d2 JC |
1 | package getter |
2 | ||
3 | import ( | |
4 | "archive/tar" | |
5 | "compress/bzip2" | |
6 | "fmt" | |
7 | "io" | |
8 | "os" | |
9 | "path/filepath" | |
10 | ) | |
11 | ||
12 | // TarBzip2Decompressor is an implementation of Decompressor that can | |
13 | // decompress tar.bz2 files. | |
14 | type TarBzip2Decompressor struct{} | |
15 | ||
16 | func (d *TarBzip2Decompressor) Decompress(dst, src string, dir bool) error { | |
17 | // If we're going into a directory we should make that first | |
18 | mkdir := dst | |
19 | if !dir { | |
20 | mkdir = filepath.Dir(dst) | |
21 | } | |
22 | if err := os.MkdirAll(mkdir, 0755); err != nil { | |
23 | return err | |
24 | } | |
25 | ||
26 | // File first | |
27 | f, err := os.Open(src) | |
28 | if err != nil { | |
29 | return err | |
30 | } | |
31 | defer f.Close() | |
32 | ||
33 | // Bzip2 compression is second | |
34 | bzipR := bzip2.NewReader(f) | |
35 | ||
36 | // Once bzip decompressed we have a tar format | |
37 | tarR := tar.NewReader(bzipR) | |
38 | done := false | |
39 | for { | |
40 | hdr, err := tarR.Next() | |
41 | if err == io.EOF { | |
42 | if !done { | |
43 | // Empty archive | |
44 | return fmt.Errorf("empty archive: %s", src) | |
45 | } | |
46 | ||
47 | return nil | |
48 | } | |
49 | if err != nil { | |
50 | return err | |
51 | } | |
52 | ||
53 | path := dst | |
54 | if dir { | |
55 | path = filepath.Join(path, hdr.Name) | |
56 | } | |
57 | ||
58 | if hdr.FileInfo().IsDir() { | |
59 | if dir { | |
60 | return fmt.Errorf("expected a single file: %s", src) | |
61 | } | |
62 | ||
63 | // A directory, just make the directory and continue unarchiving... | |
64 | if err := os.MkdirAll(path, 0755); err != nil { | |
65 | return err | |
66 | } | |
67 | ||
68 | continue | |
69 | } | |
70 | ||
71 | // We have a file. If we already decoded, then it is an error | |
72 | if !dir && done { | |
73 | return fmt.Errorf("expected a single file, got multiple: %s", src) | |
74 | } | |
75 | ||
76 | // Mark that we're done so future in single file mode errors | |
77 | done = true | |
78 | ||
79 | // Open the file for writing | |
80 | dstF, err := os.Create(path) | |
81 | if err != nil { | |
82 | return err | |
83 | } | |
84 | _, err = io.Copy(dstF, tarR) | |
85 | dstF.Close() | |
86 | if err != nil { | |
87 | return err | |
88 | } | |
89 | ||
90 | // Chmod the file | |
91 | if err := os.Chmod(path, hdr.FileInfo().Mode()); err != nil { | |
92 | return err | |
93 | } | |
94 | } | |
95 | } |