This repository has been archived by the owner on Feb 24, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 887
/
remote.go
91 lines (76 loc) · 1.73 KB
/
remote.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
package cas
import (
"encoding/json"
"fmt"
"net/http"
"os"
"time"
"github.com/appc/spec/schema/types"
"github.com/coreos/rocket/Godeps/_workspace/src/github.com/mitchellh/ioprogress"
)
func NewRemote(name string, mirrors []string) *Remote {
// TODO: don't assume the name is a mirror?
r := &Remote{}
r.Name = name
r.Mirrors = []string{name}
return r
}
type Remote struct {
Name string
Mirrors []string
ETag string
Blob string
}
func (r Remote) Marshal() []byte {
m, _ := json.Marshal(r)
return m
}
func (r *Remote) Unmarshal(data []byte) {
err := json.Unmarshal(data, r)
if err != nil {
panic(err)
}
}
func (r Remote) Hash() string {
return types.NewHashSHA256([]byte(r.Name)).String()
}
func (r Remote) Type() int64 {
return remoteType
}
// TODO: add locking
func (r Remote) Download(ds Store) (*Remote, error) {
res, err := http.Get(r.Name)
if err != nil {
return nil, err
}
defer res.Body.Close()
prefix := "Downloading aci"
fmtBytesSize := 18
barSize := int64(80 - len(prefix) - fmtBytesSize)
bar := ioprogress.DrawTextFormatBar(barSize)
fmtfunc := func(progress, total int64) string {
return fmt.Sprintf(
"%s: %s %s",
prefix,
bar(progress, total),
ioprogress.DrawTextFormatBytes(progress, total),
)
}
reader := &ioprogress.Reader{
Reader: res.Body,
Size: res.ContentLength,
DrawFunc: ioprogress.DrawTerminalf(os.Stdout, fmtfunc),
DrawInterval: time.Second,
}
// TODO(jonboulle): handle http more robustly (redirects?)
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf("bad HTTP status code: %d", res.StatusCode)
}
key, err := ds.WriteACI(r.Hash(), reader)
if err != nil {
return nil, err
}
r.Blob = key
ds.WriteIndex(&r)
return &r, nil
}