github.com/sealerio/sealer@v0.11.1-0.20240507115618-f4f89c5853ae/utils/progressbar/progressbar.go (about) 1 // Copyright © 2023 Alibaba Group Holding Ltd. 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 package progressbar 16 17 import ( 18 "github.com/schollz/progressbar/v3" 19 "github.com/sirupsen/logrus" 20 ) 21 22 type EasyProgressUtil struct { 23 progressbar.ProgressBar 24 } 25 26 var ( 27 width = 50 28 optionEnableColorCodes = progressbar.OptionEnableColorCodes(true) 29 optionSetWidth = progressbar.OptionSetWidth(width) 30 optionShowCount = progressbar.OptionShowCount() 31 OptionShowIts = progressbar.OptionShowIts() 32 optionSetTheme = progressbar.OptionSetTheme(progressbar.Theme{ 33 Saucer: "=", 34 SaucerHead: ">", 35 SaucerPadding: " ", 36 BarStart: "[", 37 BarEnd: "]", 38 }) 39 ) 40 41 // NewEasyProgressUtil create a new progress bar like this: 42 // [copying files to 1.1.1.1] 94% [==============================================> ] (18/19, 6 it/s) [3s:0s] 43 func NewEasyProgressUtil(total int, describe string) *EasyProgressUtil { 44 return &EasyProgressUtil{ 45 *progressbar.NewOptions(total, 46 optionEnableColorCodes, 47 optionSetWidth, 48 optionSetTheme, 49 optionShowCount, 50 OptionShowIts, 51 progressbar.OptionSetDescription(describe), 52 ), 53 } 54 } 55 56 // Increment add 1 to progress bar 57 func (epu *EasyProgressUtil) Increment() { 58 if err := epu.Add(1); err != nil { 59 logrus.Errorf("failed to increment progress bar, err: %s", err) 60 } 61 } 62 63 // Fail print error message 64 func (epu *EasyProgressUtil) Fail(err error) { 65 if err != nil { 66 epu.Describe(err.Error()) 67 } 68 } 69 70 // Refresh make progress bar refresh 71 // NB: We have to do this when progress bar is finished, but we want to reuse it 72 func (epu *EasyProgressUtil) Refresh() { 73 // save current 74 current := epu.ProgressBar.State().CurrentBytes 75 epu.Reset() 76 if err := epu.Set(int(current)); err != nil { 77 logrus.Errorf("failed to refresh progress bar, err: %s", err) 78 } 79 } 80 81 // SetTotal set total num of progress bar 82 func (epu *EasyProgressUtil) SetTotal(num int) { 83 if num > epu.GetMax() { 84 epu.ChangeMax(num) 85 epu.Refresh() 86 } 87 }