File: progress.go

package info (click to toggle)
dh-make-golang 0.0~git20180827.d94f0cb-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 160 kB
  • sloc: sh: 9; makefile: 7
file content (67 lines) | stat: -rw-r--r-- 1,293 bytes parent folder | download
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
package main

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"time"
)

// #include <unistd.h>
// #include <stdbool.h>
//
// bool stdoutisatty() {
//   return isatty(STDOUT_FILENO);
// }
import "C"

const (
	_ = 1 << (10 * iota)
	Kibi
	Mebi
	Gibi
	Tebi
	Pebi
	Exbi
)

func humanizeBytes(b int64) string {
	if b > Tebi {
		return fmt.Sprintf("%.2f TiB", float64(b)/float64(Tebi))
	} else if b > Gibi {
		return fmt.Sprintf("%.2f GiB", float64(b)/float64(Gibi))
	} else if b > Mebi {
		return fmt.Sprintf("%.2f MiB", float64(b)/float64(Mebi))
	} else {
		return fmt.Sprintf("%.2f KiB", float64(b)/float64(Kibi))
	}
}

func progressSize(prefix, path string, done chan struct{}) {
	// previous holds how many bytes the previous line contained, so that we
	// can clear it in its entirety.
	var previous int
	tty := C.stdoutisatty()
	for {
		if tty {
			var usage int64
			filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
				if err == nil && info.Mode().IsRegular() {
					usage += info.Size()
				}
				return nil
			})
			fmt.Printf("\r%s", strings.Repeat(" ", previous))
			previous, _ = fmt.Printf("\r%s: %s", prefix, humanizeBytes(usage))
		}

		select {
		case <-done:
			fmt.Printf("\r")
			return
		case <-time.After(250 * time.Millisecond):
			break
		}
	}
}