/
main.go
266 lines (207 loc) · 5.15 KB
/
main.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
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
package main
import (
"archive/zip"
"errors"
"flag"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"runtime"
"time"
"howett.net/ranger"
"github.com/dustin/go-humanize"
"golang.org/x/crypto/ssh/terminal"
)
var (
sourceURL string // download URL
remoteFile string // remote file name
localFile string // local file name
timeout int // timeout
verbose bool // verbose mode shows a progress bar
showFiles bool // list the files in the zip then exit
limitBytes uint64 // limit the download to this many bytes
)
const defaultBufferSize = 128 * 1024
func init() {
flag.StringVar(&sourceURL, "u", "", "the url you wish to download from")
flag.StringVar(&remoteFile, "r", "", "the remote filename to download")
flag.StringVar(&localFile, "o", "", "the output filename")
flag.IntVar(&timeout, "t", 5, "timeout, in seconds")
flag.BoolVar(&verbose, "v", false, "verbose")
flag.BoolVar(&showFiles, "l", false, "list files in zip")
flag.Uint64Var(&limitBytes, "b", 0, "limit filesize downloaded (in bytes)")
flag.Parse()
if sourceURL == "" {
fmt.Println("You must specify a URL")
flag.PrintDefaults()
os.Exit(1)
}
if !showFiles {
if remoteFile == "" {
fmt.Println("You must specify a remote filename")
flag.PrintDefaults()
os.Exit(1)
}
if localFile == "" {
_, localFile = filepath.Split(remoteFile)
}
}
}
// returns a progress bar fitting the terminal width given a progress percentage
func progressBar(progress int) (progressBar string) {
var width int
if runtime.GOOS == "windows" {
// we'll just assume it's standard terminal width
width = 80
} else {
width, _, _ = terminal.GetSize(0)
}
// take off 40 for extra info (e.g. percentage)
width = width - 40
// get the current progress
currentProgress := (progress * width) / 100
progressBar = "["
// fill up progress
for i := 0; i < currentProgress; i++ {
progressBar = progressBar + "="
}
progressBar = progressBar + ">"
// fill the rest with spaces
for i := width; i > currentProgress; i-- {
progressBar = progressBar + " "
}
// end the progressbar
progressBar = progressBar + "] " + fmt.Sprintf("%3d%%", progress)
return progressBar
}
func getBufferSize(lim uint64) uint64 {
if lim < defaultBufferSize {
return lim
}
return defaultBufferSize
}
func downloadFile(file *zip.File, writer *os.File) error {
rc, err := file.Open()
if err != nil {
return err
}
defer rc.Close()
downloaded := uint64(0)
var filesize uint64
var buf []byte
if limitBytes != 0 {
filesize = limitBytes
buf = make([]byte, getBufferSize(limitBytes))
} else {
filesize = file.UncompressedSize64
buf = make([]byte, defaultBufferSize)
}
humanizedFilesize := humanize.Bytes(filesize)
for {
// adjust the size of the buffer to get the exact
// number of bytes we want to download
if downloaded+defaultBufferSize > filesize {
buf = make([]byte, filesize-downloaded)
}
if n, err := io.ReadFull(rc, buf); n > 0 && err == nil || err == io.EOF {
writer.Write(buf[:n])
downloaded += uint64(n)
if verbose {
fmt.Printf(
"\r%s %10s/%-10s",
progressBar(int(downloaded*100/filesize)),
humanize.Bytes(downloaded),
humanizedFilesize,
)
}
if limitBytes != 0 && downloaded >= limitBytes {
break
}
} else if err != nil {
return err
} else {
break
}
}
if verbose {
fmt.Println()
}
return err
}
func findFile(reader *zip.Reader, filename string) (*zip.File, error) {
if reader.File == nil {
return nil, errors.New("file read error")
}
for _, f := range reader.File {
if f.Name == filename {
return f, nil
}
}
return nil, errors.New("unable to find file")
}
func listFiles(reader *zip.Reader) error {
if reader.File == nil {
return errors.New("file read error")
}
var total uint64
for _, f := range reader.File {
total += f.UncompressedSize64
fmt.Printf("%6s \t %s\n", humanize.Bytes(f.UncompressedSize64), f.Name)
}
fmt.Println("------")
fmt.Printf("%6s\n", humanize.Bytes(total))
return nil
}
func main() {
downloadURL, err := url.Parse(sourceURL)
reader, err := ranger.NewReader(
&ranger.HTTPRanger{
URL: downloadURL,
Client: &http.Client{
Timeout: time.Duration(timeout) * time.Second,
},
},
)
if err != nil {
fmt.Printf("Unable to create reader for url: %s\n", downloadURL)
os.Exit(1)
}
readerLen, err := reader.Length()
if err != nil {
fmt.Println("Unable to get reader length")
os.Exit(1)
}
zipReader, err := zip.NewReader(reader, readerLen)
if err != nil {
fmt.Printf("Unable to create zip reader for url: %s\n", downloadURL)
os.Exit(1)
}
if showFiles {
listFiles(zipReader)
return
}
var localFileHandle *os.File
if localFile != "-" {
localFileHandle, err = os.Create(localFile)
} else {
localFileHandle = os.Stdout
}
defer localFileHandle.Close()
if err != nil {
fmt.Printf("Unable to create local file: %s", localFile)
os.Exit(1)
}
foundFile, err := findFile(zipReader, remoteFile)
if err != nil {
fmt.Printf("Unable find file: %s in zip.", remoteFile)
os.Exit(1)
}
err = downloadFile(foundFile, localFileHandle)
if err != nil {
fmt.Printf("Unable read file %s from zip.", remoteFile)
os.Exit(1)
}
}