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