git-lfs/vendor/github.com/cheggaaa/pb/example/copy/copy.go

82 lines
1.5 KiB
Go
Raw Normal View History

2014-04-16 21:11:52 +00:00
package main
import (
"fmt"
"github.com/cheggaaa/pb"
2014-04-16 21:11:52 +00:00
"io"
"net/http"
2015-04-24 17:48:49 +00:00
"os"
2014-04-16 21:11:52 +00:00
"strconv"
2015-04-24 17:48:49 +00:00
"strings"
"time"
2014-04-16 21:11:52 +00:00
)
func main() {
// check args
if len(os.Args) < 3 {
printUsage()
return
}
sourceName, destName := os.Args[1], os.Args[2]
2015-04-24 17:48:49 +00:00
2014-04-16 21:11:52 +00:00
// check source
var source io.Reader
var sourceSize int64
if strings.HasPrefix(sourceName, "http://") {
2015-04-24 17:48:49 +00:00
// open as url
2014-04-16 21:11:52 +00:00
resp, err := http.Get(sourceName)
if err != nil {
fmt.Printf("Can't get %s: %v\n", sourceName, err)
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
fmt.Printf("Server return non-200 status: %v\n", resp.Status)
return
}
i, _ := strconv.Atoi(resp.Header.Get("Content-Length"))
sourceSize = int64(i)
source = resp.Body
} else {
// open as file
s, err := os.Open(sourceName)
if err != nil {
fmt.Printf("Can't open %s: %v\n", sourceName, err)
return
}
defer s.Close()
// get source size
sourceStat, err := s.Stat()
if err != nil {
fmt.Printf("Can't stat %s: %v\n", sourceName, err)
return
}
sourceSize = sourceStat.Size()
source = s
}
2015-04-24 17:48:49 +00:00
2014-04-16 21:11:52 +00:00
// create dest
dest, err := os.Create(destName)
if err != nil {
fmt.Printf("Can't create %s: %v\n", destName, err)
return
}
defer dest.Close()
2015-04-24 17:48:49 +00:00
// create bar
2014-04-16 21:11:52 +00:00
bar := pb.New(int(sourceSize)).SetUnits(pb.U_BYTES).SetRefreshRate(time.Millisecond * 10)
bar.ShowSpeed = true
bar.Start()
2015-04-24 17:48:49 +00:00
2014-04-16 21:11:52 +00:00
// create multi writer
writer := io.MultiWriter(dest, bar)
2015-04-24 17:48:49 +00:00
2014-04-16 21:11:52 +00:00
// and copy
io.Copy(writer, source)
bar.Finish()
}
func printUsage() {
fmt.Println("copy [source file or url] [dest file]")
2015-04-24 17:48:49 +00:00
}