vendor/github.com/ysmood/fetchup/utils.go

201 lines · 3741 bytes

  1package fetchup
  2
  3import (
  4	"context"
  5	"crypto/rand"
  6	"fmt"
  7	"io"
  8	"net/http"
  9	"os"
 10	"path/filepath"
 11	"runtime"
 12	"strings"
 13	"time"
 14)
 15
 16// Logger interface
 17type Logger interface {
 18	// Same as fmt.Printf
 19	Println(...interface{})
 20}
 21
 22// Log type for Println
 23type Log func(msg ...interface{})
 24
 25// Println interface
 26func (l Log) Println(msg ...interface{}) {
 27	l(msg...)
 28}
 29
 30// LoggerQuiet does nothing
 31var LoggerQuiet Logger = Log(func(_ ...interface{}) {})
 32
 33// MultiLogger is similar to https://golang.org/pkg/io/#MultiWriter
 34func MultiLogger(list ...Logger) Log {
 35	return Log(func(msg ...interface{}) {
 36		for _, lg := range list {
 37			lg.Println(msg...)
 38		}
 39	})
 40}
 41
 42type progress struct {
 43	ctx     context.Context
 44	s       io.Reader
 45	total   int
 46	count   int
 47	logger  Logger
 48	last    time.Time
 49	minSpan time.Duration
 50}
 51
 52var _ io.ReadWriter = &progress{}
 53
 54// newProgress returns a new progress reader.
 55func newProgress(ctx context.Context, s io.Reader, total int, minSpan time.Duration, logger Logger) *progress {
 56	return &progress{
 57		ctx:     ctx,
 58		s:       s,
 59		total:   total,
 60		logger:  logger,
 61		minSpan: minSpan,
 62	}
 63}
 64
 65func (p *progress) Read(b []byte) (n int, err error) {
 66	if p.ctx.Err() != nil {
 67		return 0, p.ctx.Err()
 68	}
 69
 70	n, err = p.s.Read(b)
 71
 72	p.count += n
 73
 74	if err != nil {
 75		return
 76	}
 77
 78	if time.Since(p.last) < p.minSpan {
 79		return
 80	}
 81
 82	p.last = time.Now()
 83	p.report()
 84
 85	return
 86}
 87
 88func (p *progress) Write(b []byte) (n int, err error) {
 89	if p.ctx.Err() != nil {
 90		return len(b), p.ctx.Err()
 91	}
 92
 93	n = len(b)
 94
 95	p.count += n
 96
 97	if time.Since(p.last) < p.minSpan {
 98		return
 99	}
100
101	p.last = time.Now()
102	p.report()
103
104	return
105}
106
107func (p *progress) report() {
108	out := ""
109	if p.total > 0 {
110		out = fmt.Sprintf("%02d%%", p.count*100/p.total)
111	} else {
112		out = fmt.Sprintf("%.3fMB", float64(p.count)/1024/1024)
113	}
114	p.logger.Println(EventProgress, out)
115}
116
117func CacheDir() string {
118	return filepath.Join(map[string]string{
119		"windows": filepath.Join(os.Getenv("APPDATA")),
120		"darwin":  filepath.Join(os.Getenv("HOME"), ".cache"),
121		"linux":   filepath.Join(os.Getenv("HOME"), ".cache"),
122	}[runtime.GOOS])
123}
124
125// StripFirstDir removes the first dir but keep all its children.
126func StripFirstDir(dir string) error {
127	list, err := readDir(dir)
128	if err != nil {
129		return err
130	}
131
132	name := ""
133	for _, f := range list {
134		if f.IsDir() {
135			if name != "" {
136				return fmt.Errorf("expected only one dir in %s", dir)
137			}
138
139			name = f.Name()
140			continue
141		}
142	}
143
144	if name == "" {
145		return fmt.Errorf("no dir found under %s", dir)
146	}
147
148	root := filepath.Join(dir, name)
149	up := filepath.Join(filepath.Dir(dir))
150	toName := filepath.Base(dir)
151
152	b := make([]byte, 8)
153	_, err = rand.Read(b)
154	if err != nil {
155		return err
156	}
157	tmp := filepath.Join(up, fmt.Sprintf("%x", b))
158
159	err = os.Rename(root, tmp)
160	if err != nil {
161		return err
162	}
163	err = os.RemoveAll(dir)
164	if err != nil {
165		return err
166	}
167	return os.Rename(tmp, filepath.Join(up, toName))
168}
169
170func readDir(dir string) ([]os.FileInfo, error) {
171	dirFile, err := os.Open(dir)
172	if err != nil {
173		return nil, err
174	}
175	defer func() { _ = dirFile.Close() }()
176
177	list, err := dirFile.Readdir(0)
178	if err != nil {
179		return nil, err
180	}
181
182	return list, nil
183}
184
185func normalizePath(p string) string {
186	p = strings.ReplaceAll(p, "\\", string(filepath.Separator))
187	return strings.ReplaceAll(p, "/", string(filepath.Separator))
188}
189
190// DefaultTransport is the default http transport for fetchup, it auto handles the gzip and user-agent.
191type DefaultTransport struct {
192	UA string
193}
194
195var _ http.RoundTripper = (*DefaultTransport)(nil)
196
197func (t *DefaultTransport) RoundTrip(req *http.Request) (*http.Response, error) {
198	req.Header.Set("User-Agent", t.UA)
199	req.Header.Set("Accept-Encoding", "gzip")
200	return http.DefaultTransport.RoundTrip(req)
201}