fork/gdu
git clone https://git.julia.blue/fork/gdu
1eaa266
ignore
1package report 2 3import ( 4"bytes" 5"errors" 6"fmt" 7"io" 8"math" 9"os" 10"strconv" 11"sync" 12"time" 13 14"github.com/dundee/gdu/v5/build" 15"github.com/dundee/gdu/v5/internal/common" 16"github.com/dundee/gdu/v5/pkg/analyze" 17"github.com/dundee/gdu/v5/pkg/device" 18"github.com/dundee/gdu/v5/pkg/fs" 19"github.com/fatih/color" 20) 21 22// UI struct 23type UI struct { 24* common.UI 25output io.Writer 26exportOutput io.Writer 27red * color.Color 28orange * color.Color 29writtenChan chan struct {} 30outputAttributes fs.JSONAttributes 31top int 32depth int 33summarize bool 34} 35 36// CreateExportUI creates UI for stdout 37func CreateExportUI ( 38output io.Writer , 39exportOutput io.Writer , 40useColors bool , 41showProgress bool , 42useSIPrefix bool , 43top int , 44depth int , 45summarize bool , 46outputAttributes fs.JSONAttributes , 47)* UI { 48ui := & UI { 49UI :& common.UI { 50ShowProgress :showProgress , 51Analyzer :analyze .CreateAnalyzer (), 52UseSIPrefix :useSIPrefix , 53 }, 54output :output , 55exportOutput :exportOutput , 56writtenChan :make (chan struct {}), 57outputAttributes :outputAttributes , 58top :top , 59depth :depth , 60summarize :summarize , 61 } 62if ! useSIPrefix { 63ui .SetBlockSizeFromEnvironment () 64 } 65ui .red = color .New (color .FgRed ).Add (color .Bold ) 66ui .orange = color .New (color .FgYellow ).Add (color .Bold ) 67 68if ! useColors { 69color .NoColor = true 70 } 71 72return ui 73} 74 75// StartUILoop stub 76func (ui * UI )StartUILoop ()error { 77return nil 78} 79 80// SetCollapsePath sets the flag to collapse paths 81func (ui * UI )SetCollapsePath (value bool ) { 82} 83 84// SetShowSymlinkTarget is a no-op for the export UI (no rendered file list) 85func (ui * UI )SetShowSymlinkTarget (value bool ) { 86} 87 88// ListDevices lists mounted devices and shows their disk usage 89func (ui * UI )ListDevices (getter device.DevicesInfoGetter )error { 90return errors .New ("exporting devices list is not supported" ) 91} 92 93// ReadAnalysis reads analysis report from JSON file 94func (ui * UI )ReadAnalysis (input io.Reader )error { 95return errors .New ("reading analysis is not possible while exporting" ) 96} 97 98// ReadFromStorage reads analysis data from persistent key-value storage 99func (ui * UI )ReadFromStorage (storagePath ,path string )error { 100storage := analyze .NewStorage (storagePath ,path ) 101closeFn := storage .Open () 102defer closeFn () 103 104dir ,err := storage .GetDirForPath (path ) 105if err != nil { 106return err 107 } 108 109var waitWritten sync.WaitGroup 110if ui .ShowProgress { 111waitWritten .Add (1 ) 112go func () { 113defer waitWritten .Done () 114ui .updateProgress () 115 }() 116 } 117 118return ui .exportDir (dir ,& waitWritten ) 119} 120 121// AnalyzePath analyzes recursively disk usage in given path 122func (ui * UI )AnalyzePath (path string ,_ fs.Item )error { 123var ( 124dir fs.Item 125wait sync.WaitGroup 126waitWritten sync.WaitGroup 127 ) 128 129if ui .ShowProgress { 130waitWritten .Add (1 ) 131go func () { 132defer waitWritten .Done () 133ui .updateProgress () 134 }() 135 } 136 137wait .Add (1 ) 138go func () { 139defer wait .Done () 140dir = ui .Analyzer .AnalyzeDir (path ,ui .CreateIgnoreFunc (),ui .CreateFileTypeFilter ()) 141if ui .IsFilteringFiles () { 142dir .UpdateStatsWithFileFiltering (make (fs.HardLinkedItems ,10 )) 143 }else { 144dir .UpdateStats (make (fs.HardLinkedItems ,10 )) 145 } 146 }() 147 148wait .Wait () 149 150return ui .exportDir (dir ,& waitWritten ) 151} 152 153func (ui * UI )topDir (dir fs.Item ) fs.Item { 154files := analyze .CollectTopFiles (dir ,ui .top ) 155 156topDir := & analyze.Dir { 157File :& analyze.File { 158Name :dir .GetName (), 159Mtime :dir .GetMtime (), 160 }, 161 } 162if d ,ok := dir .(* analyze.Dir );ok { 163topDir .BasePath = d .BasePath 164 } 165for _ ,f := range files { 166file := * f .(* analyze.File ) 167file .Parent = topDir 168topDir .AddFile (& file ) 169 } 170topDir .UpdateStats (make (fs.HardLinkedItems ,10 )) 171return topDir 172} 173 174func (ui * UI )limitDirByDepth (dir fs.Item ,currentDepth int ) fs.Item { 175if d ,ok := dir .(* analyze.Dir );ok { 176limited := & analyze.Dir { 177File :& analyze.File { 178Name :d .GetName (), 179Mtime :d .GetMtime (), 180Parent :d .GetParent (), 181Size :d .GetSize (), 182Usage :d .GetUsage (), 183 }, 184BasePath :d .BasePath , 185ItemCount :d .ItemCount , 186 } 187if currentDepth == ui .depth { 188return limited 189 } 190for f := range d .GetFiles (fs .SortBySize ,fs .SortDesc ) { 191if f .IsDir () { 192child := ui .limitDirByDepth (f ,currentDepth + 1 ) 193if child != nil { 194child .SetParent (limited ) 195limited .AddFile (child ) 196 } 197 }else if currentDepth + 1 <= ui .depth { 198file := * f .(* analyze.File ) 199file .Parent = limited 200limited .AddFile (& file ) 201 } 202 } 203return limited 204 } 205 206return dir 207} 208 209func (ui * UI )summarizeDir (dir fs.Item ) fs.Item { 210summary := & analyze.Dir { 211File :& analyze.File { 212Name :dir .GetName (), 213Mtime :dir .GetMtime (), 214 }, 215 } 216if d ,ok := dir .(* analyze.Dir );ok { 217summary .BasePath = d .BasePath 218summary .ItemCount = d .ItemCount 219summary .Size = d .GetSize () 220summary .Usage = d .GetUsage () 221 } 222return summary 223} 224 225func (ui * UI )exportDir (dir fs.Item ,waitWritten * sync.WaitGroup )error { 226// Sorting is now handled by GetFiles with sort parameters 227 228var ( 229buff bytes.Buffer 230err error 231 ) 232 233buff .Write ([]byte (`[1,2,{"progname":"gdu","progver":"` )) 234buff .Write ([]byte (build .Version )) 235buff .Write ([]byte (`","timestamp":` )) 236buff .Write ([]byte (strconv .FormatInt (time .Now ().Unix (),10 ))) 237buff .Write ([]byte ("},\n" )) 238 239switch { 240case ui .summarize : 241dir = ui .summarizeDir (dir ) 242case ui .top > 0 : 243dir = ui .topDir (dir ) 244case ui .depth > 0 : 245dir = ui .limitDirByDepth (dir ,0 ) 246 } 247 248if err := dir .EncodeJSON (& buff ,true ,ui .outputAttributes );err != nil { 249return err 250 } 251if _ ,err = buff .Write ([]byte ("]\n" ));err != nil { 252return err 253 } 254if _ ,err = buff .WriteTo (ui .exportOutput );err != nil { 255return err 256 } 257 258if f ,ok := ui .exportOutput .(* os.File );ok { 259err = f .Close () 260if err != nil { 261return err 262 } 263 } 264 265if ui .ShowProgress { 266ui .writtenChan <- struct {}{} 267waitWritten .Wait () 268 } 269 270return nil 271} 272 273func (ui * UI )updateProgress () { 274waitingForWrite := false 275 276emptyRow := "\r" 277for j := 0 ;j < 100 ;j ++ { 278emptyRow += " " 279 } 280 281progressRunes := []rune (`⠇⠏⠋⠙⠹⠸⠼⠴⠦⠧` ) 282 283doneChan := ui .Analyzer .GetDone () 284 285i := 0 286for { 287fmt .Fprint (ui .output ,emptyRow ) 288 289progress := ui .Analyzer .GetProgress () 290 291select { 292case <- doneChan : 293fmt .Fprint (ui .output ,"\r" ) 294waitingForWrite = true 295case <- ui .writtenChan : 296fmt .Fprint (ui .output ,"\r" ) 297return 298default : 299 } 300 301fmt .Fprintf (ui .output ,"\r %s " ,string (progressRunes [i ])) 302 303if waitingForWrite { 304fmt .Fprint (ui .output ,"Writing output file..." ) 305 }else { 306fmt .Fprint (ui .output ,"Scanning... Total items: " + 307ui .red .Sprint (common .FormatNumber (int64 (progress .ItemCount )))+ 308" size: " + 309ui .formatSize (progress .TotalUsage )) 310 } 311 312time .Sleep (100 * time .Millisecond ) 313i ++ 314i %= 10 315 } 316} 317 318func (ui * UI )formatSize (size int64 )string { 319if formatted ,ok := ui .FormatBlockSize (size );ok { 320return ui .orange .Sprint (formatted ) 321 } 322if ui .UseSIPrefix { 323return ui .formatWithDecPrefix (size ) 324 } 325return ui .formatWithBinPrefix (size ) 326} 327 328func (ui * UI )formatWithBinPrefix (size int64 )string { 329fsize := float64 (size ) 330asize := math .Abs (fsize ) 331 332switch { 333case asize >= common .Ei : 334return ui .orange .Sprintf ("%.1f" ,fsize / common .Ei )+ " EiB" 335case asize >= common .Pi : 336return ui .orange .Sprintf ("%.1f" ,fsize / common .Pi )+ " PiB" 337case asize >= common .Ti : 338return ui .orange .Sprintf ("%.1f" ,fsize / common .Ti )+ " TiB" 339case asize >= common .Gi : 340return ui .orange .Sprintf ("%.1f" ,fsize / common .Gi )+ " GiB" 341case asize >= common .Mi : 342return ui .orange .Sprintf ("%.1f" ,fsize / common .Mi )+ " MiB" 343case asize >= common .Ki : 344return ui .orange .Sprintf ("%.1f" ,fsize / common .Ki )+ " KiB" 345default : 346return ui .orange .Sprintf ("%d" ,size )+ " B" 347 } 348} 349 350func (ui * UI )formatWithDecPrefix (size int64 )string { 351fsize := float64 (size ) 352asize := math .Abs (fsize ) 353 354switch { 355case asize >= common .E : 356return ui .orange .Sprintf ("%.1f" ,fsize / common .E )+ " EB" 357case asize >= common .P : 358return ui .orange .Sprintf ("%.1f" ,fsize / common .P )+ " PB" 359case asize >= common .T : 360return ui .orange .Sprintf ("%.1f" ,fsize / common .T )+ " TB" 361case asize >= common .G : 362return ui .orange .Sprintf ("%.1f" ,fsize / common .G )+ " GB" 363case asize >= common .M : 364return ui .orange .Sprintf ("%.1f" ,fsize / common .M )+ " MB" 365case asize >= common .K : 366return ui .orange .Sprintf ("%.1f" ,fsize / common .K )+ " kB" 367default : 368return ui .orange .Sprintf ("%d" ,size )+ " B" 369 } 370}