github.com/hasnat/dolt/go@v0.0.0-20210628190320-9eb5d843fbb7/store/util/status/status.go (about) 1 // Copyright 2019 Dolthub, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 // 15 // This file incorporates work covered by the following copyright and 16 // permission notice: 17 // 18 // Copyright 2016 Attic Labs, Inc. All rights reserved. 19 // Licensed under the Apache License, version 2.0: 20 // http://www.apache.org/licenses/LICENSE-2.0 21 22 // Package status prints status messages to a console, overwriting previous values. 23 package status 24 25 import ( 26 "fmt" 27 "sync" 28 "time" 29 ) 30 31 const ( 32 clearLine = "\x1b[2K\r" 33 Rate = 100 * time.Millisecond 34 ) 35 36 var ( 37 lastTime time.Time 38 lastFormat string 39 lastArgs []interface{} 40 ) 41 42 var mu = &sync.Mutex{} 43 44 func Clear() { 45 mu.Lock() 46 defer mu.Unlock() 47 48 fmt.Print(clearLine) 49 reset(time.Time{}) 50 } 51 52 func WillPrint() bool { 53 mu.Lock() 54 defer mu.Unlock() 55 56 return time.Since(lastTime) >= Rate 57 } 58 59 func Printf(format string, args ...interface{}) { 60 mu.Lock() 61 defer mu.Unlock() 62 63 now := time.Now() 64 if now.Sub(lastTime) < Rate { 65 lastFormat, lastArgs = format, args 66 } else { 67 fmt.Printf(clearLine+format, args...) 68 reset(now) 69 } 70 } 71 72 func Done() { 73 mu.Lock() 74 defer mu.Unlock() 75 76 if lastArgs != nil { 77 fmt.Printf(clearLine+lastFormat, lastArgs...) 78 } 79 fmt.Println() 80 reset(time.Time{}) 81 } 82 83 func reset(time time.Time) { 84 lastTime = time 85 lastFormat, lastArgs = "", nil 86 }