]> Sergey Matveev's repositories - syncer.git/blob - printer.go
97e00287a16df46105b59ec9b0f5207ab0dcda06
[syncer.git] / printer.go
1 /*
2 syncer -- stateful file/device data syncer.
3 Copyright (C) 2015-2019 Sergey Matveev <stargrave@stargrave.org>
4
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, version 3 of the License.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program.  If not, see <http://www.gnu.org/licenses/>.
16 */
17
18 package main
19
20 import (
21         "fmt"
22         "strconv"
23 )
24
25 const (
26         BufLine       = 80
27         CharChanged   = byte('%')
28         CharUnchanged = byte('.')
29 )
30
31 type Printer struct {
32         i       int64
33         total   int64
34         changed int64
35         frmt    string
36         bufSize int
37         outBuf  []byte
38 }
39
40 func NewPrinter(total int64) *Printer {
41         p := Printer{total: total}
42         maxLen := len(fmt.Sprintf("%d", total))
43         p.frmt = "%" + strconv.Itoa(maxLen) + "d/%d %02d%% %s\n"
44         p.bufSize = BufLine - (2*maxLen + 6)
45         p.outBuf = make([]byte, 0, p.bufSize)
46         return &p
47 }
48
49 func (p *Printer) Changed() {
50         p.i++
51         p.changed++
52         p.outBuf = append(p.outBuf, CharChanged)
53         p.Output()
54 }
55
56 func (p *Printer) Unchanged() {
57         p.i++
58         p.outBuf = append(p.outBuf, CharUnchanged)
59         p.Output()
60 }
61
62 func (p *Printer) Output() {
63         if !(len(p.outBuf) == p.bufSize || p.i == p.total) {
64                 return
65         }
66         fmt.Printf(p.frmt, p.i, p.total, 100*p.changed/p.i, string(p.outBuf))
67         p.outBuf = p.outBuf[:0]
68 }