-
Notifications
You must be signed in to change notification settings - Fork 0
/
distro.go
107 lines (96 loc) · 2.44 KB
/
distro.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package lxrunoffline
import (
"fmt"
"log"
"os"
"strings"
)
type Distro struct {
DistroId string
DistroName string
WslVersion uint64
FileSystemVersion uint64
InstallationDirectory string
}
/* lx.GetDistroSummary(distro_uid string)
Return a distro with the info it has. This function read Windows Registry
*/
func (lx *LxRunOffline) GetDistroSummary(distro_uid string) (*Distro, error) {
ds, _, err := lx.GetRegistryValue(addPathPrefix(distro_uid), registry_distro_name)
if err != nil {
return &Distro{}, err
}
fi, _, err := lx.GetRegistryValueInt(addPathPrefix(distro_uid), registry_version)
if err != nil {
return &Distro{}, err
}
wv, _, err := lx.GetRegistryValueInt(addPathPrefix(distro_uid), registry_flags)
if err != nil {
return &Distro{}, err
}
wsl_version := func() uint64 {
if lx.IsWSL2(wv) {
return 2
} else {
return 1
}
}()
dir, _, err := lx.GetRegistryValue(addPathPrefix(distro_uid), registry_dir)
if err != nil {
return &Distro{}, err
}
d := &Distro{
DistroId: distro_uid,
DistroName: ds,
FileSystemVersion: fi,
WslVersion: wsl_version,
InstallationDirectory: dir,
}
return d, err
}
/* *Distro.DirSize()
Return a prettier string of size of distro installation folder on disk
*/
func (ds *Distro) DirSize() string {
var stringSize string
size := diskUsage(ds.InstallationDirectory)
switch {
case size > 1024*1024*1024:
stringSize = fmt.Sprintf("%.1fG", float64(size)/(1024*1024*1024))
case size > 1024*1024:
stringSize = fmt.Sprintf("%.1fM", float64(size)/(1024*1024))
case size > 1024:
stringSize = fmt.Sprintf("%.1fK", float64(size)/1024)
default:
stringSize = fmt.Sprintf("%d", size)
}
return stringSize
}
/* diskUsage(path string)
Return int64 of disk usage of current distro. This function used by *Distro.DirSize().
*/
func diskUsage(path string) int64 {
var size int64
pathString := strings.TrimLeft(path, `\?`)
dir, err := os.Open(pathString)
if err != nil {
return size
}
defer dir.Close()
filesOnDir, err := dir.Readdir(-1)
if err != nil {
log.Fatal(err)
os.Exit(1)
}
for _, file := range filesOnDir {
if !file.IsDir() {
size += file.Size()
}
if file.IsDir() {
size += diskUsage(fmt.Sprintf("%s/%s", pathString, file.Name()))
} else {
size += file.Size()
}
}
return size
}