Debian Codegraph @

tasklog/log.go

raw symbols SCIP
1 package tasklog
2
3 import (
4 "fmt"
5 "io"
6 "os"
7 "strings"
8 "sync"
9 "time"
10
11 isatty "github.com/mattn/go-isatty"
12 "github.com/olekukonko/ts"
13 )
14
15 const (
16 DefaultLoggingThrottle = 200 * time.Millisecond
17 )
18
19 // Logger logs a series of tasks to an io.Writer, processing each task in order
20 // until completion .
21 type Logger struct {
22 // sink is the writer to write to.
23 sink io.Writer
24
25 // widthFn is a function that returns the width of the terminal that
26 // this logger is running within.
27 widthFn func() int
28
29 // tty is true if sink is connected to a terminal
30 tty bool
31
32 // forceProgress forces progress status even when stdout is not a tty
33 forceProgress bool
34
35 // throttle is the minimum amount of time that must pass between each
36 // instant data is logged.
37 throttle time.Duration
38
39 // queue is the incoming, unbuffered queue of tasks to enqueue.
40 queue chan Task
41 // tasks is the set of tasks to process.
42 tasks chan Task
43 // wg is a WaitGroup that is incremented when new tasks are enqueued,
44 // and decremented when tasks finish.
45 wg *sync.WaitGroup
46 }
47
48 // Option is the type for
49 type Option func(*Logger)
50
51 // ForceProgress returns an options function that configures forced progress status
52 // on the logger.
53 func ForceProgress(v bool) Option {
54 return func(l *Logger) {
55 l.forceProgress = v
56 }
57 }
58
59 // NewLogger returns a new *Logger instance that logs to "sink" and uses the
60 // current terminal width as the width of the line. Will log progress status if
61 // stdout is a terminal or if forceProgress is true
62 func NewLogger(sink io.Writer, options ...Option) *Logger {
63 if sink == nil {
64 sink = io.Discard
65 }
66
67 l := &Logger{
68 sink: sink,
69 throttle: DefaultLoggingThrottle,
70 widthFn: func() int {
71 size, err := ts.GetSize()
72 if err != nil {
73 return 80
74 }
75 return size.Col()
76 },
77 queue: make(chan Task),
78 tasks: make(chan Task),
79 wg: new(sync.WaitGroup),
80 }
81
82 for _, option := range options {
83 option(l)
84 }
85
86 l.tty = tty(sink)
87
88 go l.consume()
89
90 return l
91 }
92
93 type hasFd interface {
94 Fd() uintptr
95 }
96
97 // tty returns true if the writer is connected to a tty
98 func tty(writer io.Writer) bool {
99 if v, ok := writer.(hasFd); ok {
100 return isatty.IsTerminal(v.Fd()) || isatty.IsCygwinTerminal(v.Fd())
101 }
102 return false
103 }
104
105 // Close closes the queue and does not allow new Tasks to be `enqueue()`'d. It
106 // waits until the currently running Task has completed.
107 func (l *Logger) Close() {
108 if l == nil {
109 return
110 }
111
112 close(l.queue)
113
114 l.wg.Wait()
115 }
116
117 // Waiter creates and enqueues a new *WaitingTask.
118 func (l *Logger) Waiter(msg string) *WaitingTask {
119 t := NewWaitingTask(msg)
120 l.Enqueue(t)
121
122 return t
123 }
124
125 // Percentage creates and enqueues a new *PercentageTask.
126 func (l *Logger) Percentage(msg string, total uint64) *PercentageTask {
127 t := NewPercentageTask(msg, total)
128 l.Enqueue(t)
129
130 return t
131 }
132
133 // List creates and enqueues a new *ListTask.
134 func (l *Logger) List(msg string) *ListTask {
135 t := NewListTask(msg)
136 l.Enqueue(t)
137
138 return t
139 }
140
141 // Simple creates and enqueues a new *SimpleTask.
142 func (l *Logger) Simple() *SimpleTask {
143 t := NewSimpleTask()
144 l.Enqueue(t)
145
146 return t
147 }
148
149 // Enqueue enqueues the given Tasks "ts".
150 func (l *Logger) Enqueue(ts ...Task) {
151 if l == nil {
152 for _, t := range ts {
153 if t == nil {
154 // NOTE: Do not allow nil tasks which are unable
155 // to be completed.
156 continue
157 }
158 go func(t Task) {
159 for range t.Updates() {
160 // Discard all updates.
161 }
162 }(t)
163 }
164 return
165 }
166
167 l.wg.Add(len(ts))
168 for _, t := range ts {
169 if t == nil {
170 // NOTE: See above.
171 continue
172 }
173 l.queue <- t
174 }
175 }
176
177 // consume creates a pseudo-infinte buffer between the incoming set of tasks and
178 // the queue of tasks to work on.
179 func (l *Logger) consume() {
180 go func() {
181 // Process the single next task in sequence until completion,
182 // then consume the next task.
183 for task := range l.tasks {
184 l.logTask(task)
185 }
186 }()
187
188 defer close(l.tasks)
189
190 for {
191 // Wait for either a) l.queue to close, or b) a new task
192 // to be submitted.
193 task, ok := <-l.queue
194 if !ok {
195 // If the queue is closed, no more new tasks may
196 // be added.
197 return
198 }
199
200 // Otherwise, add a new task to the set of tasks to
201 // process immediately.
202 l.tasks <- task
203 }
204 }
205
206 // logTask logs the set of updates from a given task to the sink, then logs a
207 // "done." message, and then marks the task as done.
208 //
209 // By default, the *Logger throttles log entry updates to once per the duration
210 // of time specified by `l.throttle time.Duration`.
211 //
212 // If the duration if 0, or the task is "durable" (by implementing
213 // github.com/git-lfs/git-lfs/tasklog#DurableTask), then all entries will be
214 // logged.
215 func (l *Logger) logTask(task Task) {
216 defer l.wg.Done()
217
218 logAll := !task.Throttled()
219 var last time.Time
220
221 var update *Update
222 for update = range task.Updates() {
223 if !tty(os.Stdout) && !l.forceProgress {
224 continue
225 }
226 if logAll || l.throttle == 0 || !update.Throttled(last.Add(l.throttle)) {
227 l.logLine(update.S)
228 last = update.At
229 }
230 }
231
232 if update != nil {
233 // If a task sent no updates, the last recorded update will be
234 // nil. Given this, only log a message when there was at least
235 // (1) update.
236 l.log(fmt.Sprintf("%s, done.\n", update.S))
237 }
238
239 if v, ok := task.(interface {
240 // OnComplete is called after the Task "task" is closed, but
241 // before new tasks are accepted.
242 OnComplete()
243 }); ok {
244 // If the Task implements this interface, call it and block
245 // before accepting new tasks.
246 v.OnComplete()
247 }
248 }
249
250 // logLine writes a complete line and moves the cursor to the beginning of the
251 // line.
252 //
253 // It returns the number of bytes "n" written to the sink and the error "err",
254 // if one was encountered.
255 func (l *Logger) logLine(str string) (n int, err error) {
256 padding := strings.Repeat(" ", max(0, l.widthFn()-len(str)))
257
258 return l.log(str + padding + "\r")
259 }
260
261 // log writes a string verbatim to the sink.
262 //
263 // It returns the number of bytes "n" written to the sink and the error "err",
264 // if one was encountered.
265 func (l *Logger) log(str string) (n int, err error) {
266 return fmt.Fprint(l.sink, str)
267 }