feat: toon map- en schijfverbruik op het opslagtabblad
De gekozen map wordt recursief gemeten, met een cache en een tijdslimiet. De schijf toont totaal, gebruikt en vrij, met een balk voor de bezetting. Co-authored-by: tim <tim@timfalken.com>
@@ -0,0 +1,36 @@
1
package i18n
2
3
func init() {
4
addCatalog(en, storageEN)
5
addCatalog(nl, storageNL)
6
addCatalog(de, storageDE)
7
addCatalog(fr, storageFR)
8
}
9
10
var storageEN = map[string]string{
11
"setup.usedDir": "BlueGit uses %s in this directory.",
12
"setup.usedDirPartial": "Count stopped early; the directory is larger.",
13
"setup.diskStat": "Disk: %s total, %s used, %s free.",
14
"setup.diskMeter": "Disk usage",
15
}
16
17
var storageNL = map[string]string{
18
"setup.usedDir": "BlueGit gebruikt %s in deze map.",
19
"setup.usedDirPartial": "De telling stopte voortijdig; de map is groter.",
20
"setup.diskStat": "Schijf: %s totaal, %s gebruikt, %s vrij.",
21
"setup.diskMeter": "Schijfbezetting",
22
}
23
24
var storageDE = map[string]string{
25
"setup.usedDir": "BlueGit belegt %s in diesem Verzeichnis.",
26
"setup.usedDirPartial": "Die Zählung endete vorzeitig; das Verzeichnis ist größer.",
27
"setup.diskStat": "Datenträger: %s gesamt, %s belegt, %s frei.",
28
"setup.diskMeter": "Belegung",
29
}
30
31
var storageFR = map[string]string{
32
"setup.usedDir": "BlueGit occupe %s dans ce dossier.",
33
"setup.usedDirPartial": "Le calcul s’est arrêté trop tôt ; le dossier est plus grand.",
34
"setup.diskStat": "Disque : %s au total, %s utilisés, %s libres.",
35
"setup.diskMeter": "Occupation du disque",
36
}
@@ -0,0 +1,36 @@1
package i18n2
3
func init() {4
addCatalog(en, storageEN)5
addCatalog(nl, storageNL)6
addCatalog(de, storageDE)7
addCatalog(fr, storageFR)8
}9
10
var storageEN = map[string]string{11
"setup.usedDir": "BlueGit uses %s in this directory.",12
"setup.usedDirPartial": "Count stopped early; the directory is larger.",13
"setup.diskStat": "Disk: %s total, %s used, %s free.",14
"setup.diskMeter": "Disk usage",15
}16
17
var storageNL = map[string]string{18
"setup.usedDir": "BlueGit gebruikt %s in deze map.",19
"setup.usedDirPartial": "De telling stopte voortijdig; de map is groter.",20
"setup.diskStat": "Schijf: %s totaal, %s gebruikt, %s vrij.",21
"setup.diskMeter": "Schijfbezetting",22
}23
24
var storageDE = map[string]string{25
"setup.usedDir": "BlueGit belegt %s in diesem Verzeichnis.",26
"setup.usedDirPartial": "Die Zählung endete vorzeitig; das Verzeichnis ist größer.",27
"setup.diskStat": "Datenträger: %s gesamt, %s belegt, %s frei.",28
"setup.diskMeter": "Belegung",29
}30
31
var storageFR = map[string]string{32
"setup.usedDir": "BlueGit occupe %s dans ce dossier.",33
"setup.usedDirPartial": "Le calcul s’est arrêté trop tôt ; le dossier est plus grand.",34
"setup.diskStat": "Disque : %s au total, %s utilisés, %s libres.",35
"setup.diskMeter": "Occupation du disque",36
}@@ -58,6 +58,8 @@ type Server struct {
58
58
storageMu sync.RWMutex
59
59
storage string
60
60
storageSet bool
61
usageMu sync.Mutex
62
usage dirUsage
61
63
cards *card.Cache
62
64
// mergingMR zijn merge requests die opMergeMR nu zelf afrondt.
63
65
// AfterPush mag hun bronbranch niet alvast verwijderen.
@@ -518,139 +520,143 @@ func randomState() (string, error) {
518
520
519
521
// View is de gegevensset voor elk scherm.
520
522
type View struct {
521
Title string
522
BaseURL string
523
RunnerName string
524
User *store.User
525
CSRF string
526
Notice string
527
Err string
528
Repos []store.Repo
529
Groups []store.Group
530
Repo *store.Repo
531
Role access.Role
532
CanWrite bool
533
CanAdmin bool
534
CanMerge bool
535
CanForce bool
536
CanComment bool
537
CanApply bool
538
Commits []CommitRow
539
CommitDays []CommitDay
540
CommitPrev string
541
CommitNext string
542
Commit *CommitRow
543
CommitDiff *CommitDiff
544
Entries []EntryRow
545
TreePath string
546
Blob string
547
BlobPath string
548
Binary bool
549
Branches []BranchRow
550
Branch *BranchBoard
551
MRs []store.MergeRequest
552
Flow *FlowBoard
553
MR *store.MergeRequest
554
Banner *MRBanner
555
MRPipe *PipeRow
556
MergeBlocks []string
557
Approval *ApprovalView
558
Reviews []ReviewRow
559
CanReview bool
560
CanApprove bool
561
CanDismiss bool
562
CanClose bool
563
CanReopen bool
564
IsOwner bool
565
Candidates []store.Member
566
Diff string
567
DiffFiles []DiffFileView
568
Pipes []store.Pipeline
569
PipeRows []PipeRow
570
Pipe *store.Pipeline
571
PipeSource string
572
PipeStatus string
573
PipeLabel string
574
PipeJobs []JobLink
575
PipeStages []StageView
576
PipeFailed bool
577
Live bool
578
LiveURL string
579
Jobs []store.Job
580
JobPage *JobPage
581
Editor *CIEditor
582
Releases []store.Release
583
Members []store.Member
584
Secrets []store.SecretMeta
585
HookSecrets []SecretChoice
586
Hooks []HookView
587
HookEdit HookDraft
588
Patterns []string
589
TagPatterns []string
590
Tags []TagRow
591
Tokens []store.TokenInfo
592
ShowExpiry bool
593
Keys []store.SSHKey
594
CloneHTTP string
595
CloneSSH string
596
Group *store.Group
597
Tab string
598
Rev string
599
NewToken string
600
StorageUnset bool
601
StoragePath string
602
StorageFree string
603
StorageTotal string
604
MinFree string
605
Wide bool
606
Info bool
607
ShowUpdate bool
608
Update *UpdateView
609
HookDoc string
610
Spec cispec.Doc
611
SpecJSON template.JS
612
APIJSON template.JS
613
Page string
614
Lang string
615
HTMLLang string
616
Cunei bool
617
Langs []LangChoice
618
Query string
619
SortDir string
620
FlipDir string
621
Cards []RepoCard
622
Head *CommitRow
623
Files []FileRow
624
Tree []FileRow
625
Readme template.HTML
626
ReadmeName string
627
LicensePath string
628
NCommits int
629
NBranches int
630
NTags int
631
NReleases int
632
Created string
633
Lines []CodeLine
634
BlobSize string
635
FileName string
636
RevProtected bool
637
Heat *activity.Calendar
638
Notes []NoteRow
639
Profile *store.User
640
Card *ProfileCard
641
DescHTML template.HTML
642
Timeline []TimelineItem
643
CompareFrom string
644
CompareTo string
645
FormTitle string
646
Labels []string
647
CanEditMR bool
648
Issues *IssueBoard
649
IssueDoc string
650
DescTpls []string
651
TplPick string
652
FormBody string
653
Social *card.Meta
523
Title string
524
BaseURL string
525
RunnerName string
526
User *store.User
527
CSRF string
528
Notice string
529
Err string
530
Repos []store.Repo
531
Groups []store.Group
532
Repo *store.Repo
533
Role access.Role
534
CanWrite bool
535
CanAdmin bool
536
CanMerge bool
537
CanForce bool
538
CanComment bool
539
CanApply bool
540
Commits []CommitRow
541
CommitDays []CommitDay
542
CommitPrev string
543
CommitNext string
544
Commit *CommitRow
545
CommitDiff *CommitDiff
546
Entries []EntryRow
547
TreePath string
548
Blob string
549
BlobPath string
550
Binary bool
551
Branches []BranchRow
552
Branch *BranchBoard
553
MRs []store.MergeRequest
554
Flow *FlowBoard
555
MR *store.MergeRequest
556
Banner *MRBanner
557
MRPipe *PipeRow
558
MergeBlocks []string
559
Approval *ApprovalView
560
Reviews []ReviewRow
561
CanReview bool
562
CanApprove bool
563
CanDismiss bool
564
CanClose bool
565
CanReopen bool
566
IsOwner bool
567
Candidates []store.Member
568
Diff string
569
DiffFiles []DiffFileView
570
Pipes []store.Pipeline
571
PipeRows []PipeRow
572
Pipe *store.Pipeline
573
PipeSource string
574
PipeStatus string
575
PipeLabel string
576
PipeJobs []JobLink
577
PipeStages []StageView
578
PipeFailed bool
579
Live bool
580
LiveURL string
581
Jobs []store.Job
582
JobPage *JobPage
583
Editor *CIEditor
584
Releases []store.Release
585
Members []store.Member
586
Secrets []store.SecretMeta
587
HookSecrets []SecretChoice
588
Hooks []HookView
589
HookEdit HookDraft
590
Patterns []string
591
TagPatterns []string
592
Tags []TagRow
593
Tokens []store.TokenInfo
594
ShowExpiry bool
595
Keys []store.SSHKey
596
CloneHTTP string
597
CloneSSH string
598
Group *store.Group
599
Tab string
600
Rev string
601
NewToken string
602
StorageUnset bool
603
StoragePath string
604
StorageFree string
605
StorageUsed string
606
StorageTotal string
607
StoragePercent int
608
StorageBlueGit string
609
StoragePartial bool
610
MinFree string
611
Wide bool
612
Info bool
613
ShowUpdate bool
614
Update *UpdateView
615
HookDoc string
616
Spec cispec.Doc
617
SpecJSON template.JS
618
APIJSON template.JS
619
Page string
620
Lang string
621
HTMLLang string
622
Cunei bool
623
Langs []LangChoice
624
Query string
625
SortDir string
626
FlipDir string
627
Cards []RepoCard
628
Head *CommitRow
629
Files []FileRow
630
Tree []FileRow
631
Readme template.HTML
632
ReadmeName string
633
LicensePath string
634
NCommits int
635
NBranches int
636
NTags int
637
NReleases int
638
Created string
639
Lines []CodeLine
640
BlobSize string
641
FileName string
642
RevProtected bool
643
Heat *activity.Calendar
644
Notes []NoteRow
645
Profile *store.User
646
Card *ProfileCard
647
DescHTML template.HTML
648
Timeline []TimelineItem
649
CompareFrom string
650
CompareTo string
651
FormTitle string
652
Labels []string
653
CanEditMR bool
654
Issues *IssueBoard
655
IssueDoc string
656
DescTpls []string
657
TplPick string
658
FormBody string
659
Social *card.Meta
654
660
}
655
661
656
662
// LangChoice is één taal in de instellingen.
@@ -58,6 +58,8 @@ type Server struct {58
storageMu sync.RWMutex58
storageMu sync.RWMutex59
storage string59
storage string60
storageSet bool60
storageSet bool61
usageMu sync.Mutex62
usage dirUsage61
cards *card.Cache63
cards *card.Cache62
// mergingMR zijn merge requests die opMergeMR nu zelf afrondt.64
// mergingMR zijn merge requests die opMergeMR nu zelf afrondt.63
// AfterPush mag hun bronbranch niet alvast verwijderen.65
// AfterPush mag hun bronbranch niet alvast verwijderen.@@ -518,139 +520,143 @@ func randomState() (string, error) {518
520
519
// View is de gegevensset voor elk scherm.521
// View is de gegevensset voor elk scherm.520
type View struct {522
type View struct {521
Title string523
Title string522
BaseURL string524
BaseURL string523
RunnerName string525
RunnerName string524
User *store.User526
User *store.User525
CSRF string527
CSRF string526
Notice string528
Notice string527
Err string529
Err string528
Repos []store.Repo530
Repos []store.Repo529
Groups []store.Group531
Groups []store.Group530
Repo *store.Repo532
Repo *store.Repo531
Role access.Role533
Role access.Role532
CanWrite bool534
CanWrite bool533
CanAdmin bool535
CanAdmin bool534
CanMerge bool536
CanMerge bool535
CanForce bool537
CanForce bool536
CanComment bool538
CanComment bool537
CanApply bool539
CanApply bool538
Commits []CommitRow540
Commits []CommitRow539
CommitDays []CommitDay541
CommitDays []CommitDay540
CommitPrev string542
CommitPrev string541
CommitNext string543
CommitNext string542
Commit *CommitRow544
Commit *CommitRow543
CommitDiff *CommitDiff545
CommitDiff *CommitDiff544
Entries []EntryRow546
Entries []EntryRow545
TreePath string547
TreePath string546
Blob string548
Blob string547
BlobPath string549
BlobPath string548
Binary bool550
Binary bool549
Branches []BranchRow551
Branches []BranchRow550
Branch *BranchBoard552
Branch *BranchBoard551
MRs []store.MergeRequest553
MRs []store.MergeRequest552
Flow *FlowBoard554
Flow *FlowBoard553
MR *store.MergeRequest555
MR *store.MergeRequest554
Banner *MRBanner556
Banner *MRBanner555
MRPipe *PipeRow557
MRPipe *PipeRow556
MergeBlocks []string558
MergeBlocks []string557
Approval *ApprovalView559
Approval *ApprovalView558
Reviews []ReviewRow560
Reviews []ReviewRow559
CanReview bool561
CanReview bool560
CanApprove bool562
CanApprove bool561
CanDismiss bool563
CanDismiss bool562
CanClose bool564
CanClose bool563
CanReopen bool565
CanReopen bool564
IsOwner bool566
IsOwner bool565
Candidates []store.Member567
Candidates []store.Member566
Diff string568
Diff string567
DiffFiles []DiffFileView569
DiffFiles []DiffFileView568
Pipes []store.Pipeline570
Pipes []store.Pipeline569
PipeRows []PipeRow571
PipeRows []PipeRow570
Pipe *store.Pipeline572
Pipe *store.Pipeline571
PipeSource string573
PipeSource string572
PipeStatus string574
PipeStatus string573
PipeLabel string575
PipeLabel string574
PipeJobs []JobLink576
PipeJobs []JobLink575
PipeStages []StageView577
PipeStages []StageView576
PipeFailed bool578
PipeFailed bool577
Live bool579
Live bool578
LiveURL string580
LiveURL string579
Jobs []store.Job581
Jobs []store.Job580
JobPage *JobPage582
JobPage *JobPage581
Editor *CIEditor583
Editor *CIEditor582
Releases []store.Release584
Releases []store.Release583
Members []store.Member585
Members []store.Member584
Secrets []store.SecretMeta586
Secrets []store.SecretMeta585
HookSecrets []SecretChoice587
HookSecrets []SecretChoice586
Hooks []HookView588
Hooks []HookView587
HookEdit HookDraft589
HookEdit HookDraft588
Patterns []string590
Patterns []string589
TagPatterns []string591
TagPatterns []string590
Tags []TagRow592
Tags []TagRow591
Tokens []store.TokenInfo593
Tokens []store.TokenInfo592
ShowExpiry bool594
ShowExpiry bool593
Keys []store.SSHKey595
Keys []store.SSHKey594
CloneHTTP string596
CloneHTTP string595
CloneSSH string597
CloneSSH string596
Group *store.Group598
Group *store.Group597
Tab string599
Tab string598
Rev string600
Rev string599
NewToken string601
NewToken string600
StorageUnset bool602
StorageUnset bool601
StoragePath string603
StoragePath string602
StorageFree string604
StorageFree string603
StorageTotal string605
StorageUsed string604
MinFree string606
StorageTotal string605
Wide bool607
StoragePercent int606
Info bool608
StorageBlueGit string607
ShowUpdate bool609
StoragePartial bool608
Update *UpdateView610
MinFree string609
HookDoc string611
Wide bool610
Spec cispec.Doc612
Info bool611
SpecJSON template.JS613
ShowUpdate bool612
APIJSON template.JS614
Update *UpdateView613
Page string615
HookDoc string614
Lang string616
Spec cispec.Doc615
HTMLLang string617
SpecJSON template.JS616
Cunei bool618
APIJSON template.JS617
Langs []LangChoice619
Page string618
Query string620
Lang string619
SortDir string621
HTMLLang string620
FlipDir string622
Cunei bool621
Cards []RepoCard623
Langs []LangChoice622
Head *CommitRow624
Query string623
Files []FileRow625
SortDir string624
Tree []FileRow626
FlipDir string625
Readme template.HTML627
Cards []RepoCard626
ReadmeName string628
Head *CommitRow627
LicensePath string629
Files []FileRow628
NCommits int630
Tree []FileRow629
NBranches int631
Readme template.HTML630
NTags int632
ReadmeName string631
NReleases int633
LicensePath string632
Created string634
NCommits int633
Lines []CodeLine635
NBranches int634
BlobSize string636
NTags int635
FileName string637
NReleases int636
RevProtected bool638
Created string637
Heat *activity.Calendar639
Lines []CodeLine638
Notes []NoteRow640
BlobSize string639
Profile *store.User641
FileName string640
Card *ProfileCard642
RevProtected bool641
DescHTML template.HTML643
Heat *activity.Calendar642
Timeline []TimelineItem644
Notes []NoteRow643
CompareFrom string645
Profile *store.User644
CompareTo string646
Card *ProfileCard645
FormTitle string647
DescHTML template.HTML646
Labels []string648
Timeline []TimelineItem647
CanEditMR bool649
CompareFrom string648
Issues *IssueBoard650
CompareTo string649
IssueDoc string651
FormTitle string650
DescTpls []string652
Labels []string651
TplPick string653
CanEditMR bool652
FormBody string654
Issues *IssueBoard653
Social *card.Meta655
IssueDoc string656
DescTpls []string657
TplPick string658
FormBody string659
Social *card.Meta654
}660
}655
661
656
// LangChoice is één taal in de instellingen.662
// LangChoice is één taal in de instellingen.@@ -11,12 +11,14 @@ import (
11
11
"os"
12
12
"os/exec"
13
13
"path/filepath"
14
"strconv"
14
15
"strings"
15
16
"testing"
16
17
"time"
17
18
18
19
"gitlab.com/Timfa/bluegit/internal/auth"
19
20
"gitlab.com/Timfa/bluegit/internal/config"
21
"gitlab.com/Timfa/bluegit/internal/state"
20
22
"gitlab.com/Timfa/bluegit/internal/store"
21
23
)
22
24
@@ -268,8 +270,30 @@ func TestSetupChoosesStorage(t *testing.T) {
268
270
t.Fatal(err)
269
271
}
270
272
page = read(t, res)
271
if !strings.Contains(page, "does not move") || !strings.Contains(page, "Free space") {
272
t.Fatalf("wijzigen:\n%s", page)
273
info, err := state.Inspect(storage)
274
if err != nil {
275
t.Fatal(err)
276
}
277
n, err := state.DirSize(context.Background(), storage)
278
if err != nil {
279
t.Fatal(err)
280
}
281
pct := state.Percent(info.Used(), info.Total)
282
for _, want := range []string{
283
"does not move",
284
"BlueGit uses " + state.Format(n),
285
"Disk: " + state.Format(info.Total),
286
state.Format(info.Used()) + " used",
287
state.Format(info.Free) + " free.",
288
`<svg class="diskbar-svg"`,
289
`class="fill" width="` + strconv.Itoa(pct) + `"`,
290
} {
291
if !strings.Contains(page, want) {
292
t.Fatalf("mist %q\n%s", want, page)
293
}
294
}
295
if strings.Contains(page, "Count stopped early") {
296
t.Fatal("kleine map hoort volledig geteld")
273
297
}
274
298
res, err = http.Get(ts.URL + "/tim/demo.git/info/refs?service=git-upload-pack")
275
299
if err != nil {
@@ -11,12 +11,14 @@ import (11
"os"11
"os"12
"os/exec"12
"os/exec"13
"path/filepath"13
"path/filepath"14
"strconv"14
"strings"15
"strings"15
"testing"16
"testing"16
"time"17
"time"17
18
18
"gitlab.com/Timfa/bluegit/internal/auth"19
"gitlab.com/Timfa/bluegit/internal/auth"19
"gitlab.com/Timfa/bluegit/internal/config"20
"gitlab.com/Timfa/bluegit/internal/config"21
"gitlab.com/Timfa/bluegit/internal/state"20
"gitlab.com/Timfa/bluegit/internal/store"22
"gitlab.com/Timfa/bluegit/internal/store"21
)23
)22
24
@@ -268,8 +270,30 @@ func TestSetupChoosesStorage(t *testing.T) {268
t.Fatal(err)270
t.Fatal(err)269
}271
}270
page = read(t, res)272
page = read(t, res)271
if !strings.Contains(page, "does not move") || !strings.Contains(page, "Free space") {273
info, err := state.Inspect(storage)272
t.Fatalf("wijzigen:\n%s", page)274
if err != nil {275
t.Fatal(err)276
}277
n, err := state.DirSize(context.Background(), storage)278
if err != nil {279
t.Fatal(err)280
}281
pct := state.Percent(info.Used(), info.Total)282
for _, want := range []string{283
"does not move",284
"BlueGit uses " + state.Format(n),285
"Disk: " + state.Format(info.Total),286
state.Format(info.Used()) + " used",287
state.Format(info.Free) + " free.",288
`<svg class="diskbar-svg"`,289
`class="fill" width="` + strconv.Itoa(pct) + `"`,290
} {291
if !strings.Contains(page, want) {292
t.Fatalf("mist %q\n%s", want, page)293
}294
}295
if strings.Contains(page, "Count stopped early") {296
t.Fatal("kleine map hoort volledig geteld")273
}297
}274
res, err = http.Get(ts.URL + "/tim/demo.git/info/refs?service=git-upload-pack")298
res, err = http.Get(ts.URL + "/tim/demo.git/info/refs?service=git-upload-pack")275
if err != nil {299
if err != nil {@@ -2,14 +2,53 @@ package server
2
2
3
3
import (
4
4
"context"
5
"errors"
5
6
"net/http"
6
7
"os"
7
8
"strings"
9
"time"
8
10
9
11
"gitlab.com/Timfa/bluegit/internal/gitrepo"
10
12
"gitlab.com/Timfa/bluegit/internal/state"
11
13
)
12
14
15
// dirUsage is de laatst getelde grootte van de gekozen map.
16
type dirUsage struct {
17
path string
18
n uint64
19
partial bool
20
at time.Time
21
}
22
23
const (
24
usageTTL = time.Minute
25
usageBudget = 2 * time.Second
26
)
27
28
// bluegitUsage telt de map, met een cache en een tijdslimiet.
29
// Een grote repository houdt de pagina zo hooguit usageBudget tegen.
30
// partial betekent dat de telling voortijdig stopte.
31
func (s *Server) bluegitUsage(path string) (uint64, bool, bool) {
32
s.usageMu.Lock()
33
cached := s.usage
34
fresh := cached.path == path && !cached.at.IsZero() && time.Since(cached.at) < usageTTL
35
s.usageMu.Unlock()
36
if fresh {
37
return cached.n, cached.partial, true
38
}
39
ctx, cancel := context.WithTimeout(context.Background(), usageBudget)
40
defer cancel()
41
n, err := state.DirSize(ctx, path)
42
partial := errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled)
43
if err != nil && !partial {
44
return 0, false, false
45
}
46
s.usageMu.Lock()
47
s.usage = dirUsage{path: path, n: n, partial: partial, at: time.Now()}
48
s.usageMu.Unlock()
49
return n, partial, true
50
}
51
13
52
func (s *Server) noStorageText(r *http.Request) string {
14
53
return s.tr(r, "err.noStorage") + "\n"
15
54
}
@@ -136,7 +175,13 @@ func (s *Server) renderSetup(w http.ResponseWriter, r *http.Request, problem, pr
136
175
info, err := state.Inspect(v.StoragePath)
137
176
if info.Total > 0 {
138
177
v.StorageFree = state.Format(info.Free)
178
v.StorageUsed = state.Format(info.Used())
139
179
v.StorageTotal = state.Format(info.Total)
180
v.StoragePercent = state.Percent(info.Used(), info.Total)
181
if n, partial, ok := s.bluegitUsage(info.Path); ok {
182
v.StorageBlueGit = state.Format(n)
183
v.StoragePartial = partial
184
}
140
185
}
141
186
if err != nil && v.Err == "" {
142
187
v.Err = s.trErr(r, err)
@@ -2,14 +2,53 @@ package server2
2
3
import (3
import (4
"context"4
"context"5
"errors"5
"net/http"6
"net/http"6
"os"7
"os"7
"strings"8
"strings"9
"time"8
10
9
"gitlab.com/Timfa/bluegit/internal/gitrepo"11
"gitlab.com/Timfa/bluegit/internal/gitrepo"10
"gitlab.com/Timfa/bluegit/internal/state"12
"gitlab.com/Timfa/bluegit/internal/state"11
)13
)12
14
15
// dirUsage is de laatst getelde grootte van de gekozen map.16
type dirUsage struct {17
path string18
n uint6419
partial bool20
at time.Time21
}22
23
const (24
usageTTL = time.Minute25
usageBudget = 2 * time.Second26
)27
28
// bluegitUsage telt de map, met een cache en een tijdslimiet.29
// Een grote repository houdt de pagina zo hooguit usageBudget tegen.30
// partial betekent dat de telling voortijdig stopte.31
func (s *Server) bluegitUsage(path string) (uint64, bool, bool) {32
s.usageMu.Lock()33
cached := s.usage34
fresh := cached.path == path && !cached.at.IsZero() && time.Since(cached.at) < usageTTL35
s.usageMu.Unlock()36
if fresh {37
return cached.n, cached.partial, true38
}39
ctx, cancel := context.WithTimeout(context.Background(), usageBudget)40
defer cancel()41
n, err := state.DirSize(ctx, path)42
partial := errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled)43
if err != nil && !partial {44
return 0, false, false45
}46
s.usageMu.Lock()47
s.usage = dirUsage{path: path, n: n, partial: partial, at: time.Now()}48
s.usageMu.Unlock()49
return n, partial, true50
}51
13
func (s *Server) noStorageText(r *http.Request) string {52
func (s *Server) noStorageText(r *http.Request) string {14
return s.tr(r, "err.noStorage") + "\n"53
return s.tr(r, "err.noStorage") + "\n"15
}54
}@@ -136,7 +175,13 @@ func (s *Server) renderSetup(w http.ResponseWriter, r *http.Request, problem, pr136
info, err := state.Inspect(v.StoragePath)175
info, err := state.Inspect(v.StoragePath)137
if info.Total > 0 {176
if info.Total > 0 {138
v.StorageFree = state.Format(info.Free)177
v.StorageFree = state.Format(info.Free)178
v.StorageUsed = state.Format(info.Used())139
v.StorageTotal = state.Format(info.Total)179
v.StorageTotal = state.Format(info.Total)180
v.StoragePercent = state.Percent(info.Used(), info.Total)181
if n, partial, ok := s.bluegitUsage(info.Path); ok {182
v.StorageBlueGit = state.Format(n)183
v.StoragePartial = partial184
}140
}185
}141
if err != nil && v.Err == "" {186
if err != nil && v.Err == "" {142
v.Err = s.trErr(r, err)187
v.Err = s.trErr(r, err)@@ -1288,6 +1288,13 @@ a.flowpipe.passed .mark::after { left: 4px; top: 2px; width: 3px; height: 6px; }
1288
1288
.mrreviews li { display: flex; flex-wrap: wrap; gap: 0.35rem; align-items: center; padding: 0.15rem 0; }
1289
1289
.mrreviews form { margin: 0; }
1290
1290
.mergeacts { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; }
1291
.diskuse { display: grid; gap: var(--sp-2); margin: 0 0 var(--sp-4); }
1292
.diskuse p { margin: 0; }
1293
.diskbar { display: flex; align-items: center; gap: var(--sp-2); }
1294
.diskbar-svg { flex: 1; width: 100%; height: 16px; display: block; border-radius: 999px; }
1295
.diskbar-svg .track { fill: var(--line); }
1296
.diskbar-svg .fill { fill: var(--blue); }
1297
.diskbar span { min-width: 3rem; text-align: right; font-variant-numeric: tabular-nums; }
1291
1298
.mergedby { margin: 0; }
1292
1299
.mergedby .branchchip { margin-left: 0.45rem; vertical-align: middle; }
1293
1300
.sub .count {
@@ -1288,6 +1288,13 @@ a.flowpipe.passed .mark::after { left: 4px; top: 2px; width: 3px; height: 6px; }1288
.mrreviews li { display: flex; flex-wrap: wrap; gap: 0.35rem; align-items: center; padding: 0.15rem 0; }1288
.mrreviews li { display: flex; flex-wrap: wrap; gap: 0.35rem; align-items: center; padding: 0.15rem 0; }1289
.mrreviews form { margin: 0; }1289
.mrreviews form { margin: 0; }1290
.mergeacts { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; }1290
.mergeacts { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; }1291
.diskuse { display: grid; gap: var(--sp-2); margin: 0 0 var(--sp-4); }1292
.diskuse p { margin: 0; }1293
.diskbar { display: flex; align-items: center; gap: var(--sp-2); }1294
.diskbar-svg { flex: 1; width: 100%; height: 16px; display: block; border-radius: 999px; }1295
.diskbar-svg .track { fill: var(--line); }1296
.diskbar-svg .fill { fill: var(--blue); }1297
.diskbar span { min-width: 3rem; text-align: right; font-variant-numeric: tabular-nums; }1291
.mergedby { margin: 0; }1298
.mergedby { margin: 0; }1292
.mergedby .branchchip { margin-left: 0.45rem; vertical-align: middle; }1299
.mergedby .branchchip { margin-left: 0.45rem; vertical-align: middle; }1293
.sub .count {1300
.sub .count {@@ -5,7 +5,19 @@
5
5
<p class="flash bad">{{t "setup.changeWarn"}}</p>
6
6
{{end}}
7
7
<section class="panel">
8
{{if .StorageFree}}<p>{{t "setup.free" .StorageFree .StorageTotal}}</p>{{end}}
8
{{if .StorageTotal}}
9
<div class="diskuse">
10
{{if .StorageBlueGit}}<p>{{t "setup.usedDir" .StorageBlueGit}}{{if .StoragePartial}} <span class="muted">{{t "setup.usedDirPartial"}}</span>{{end}}</p>{{end}}
11
<p>{{t "setup.diskStat" .StorageTotal .StorageUsed .StorageFree}}</p>
12
<div class="diskbar">
13
<svg class="diskbar-svg" viewBox="0 0 100 8" preserveAspectRatio="none" role="img" aria-label="{{t "setup.diskMeter"}}">
14
<rect class="track" width="100" height="8"></rect>
15
<rect class="fill" width="{{.StoragePercent}}" height="8"></rect>
16
</svg>
17
<span>{{.StoragePercent}}%</span>
18
</div>
19
</div>
20
{{end}}
9
21
<form method="post" action="/setup">
10
22
<input type="hidden" name="csrf" value="{{.CSRF}}">
11
23
<label>{{t "setup.disk"}}
@@ -5,7 +5,19 @@5
<p class="flash bad">{{t "setup.changeWarn"}}</p>5
<p class="flash bad">{{t "setup.changeWarn"}}</p>6
{{end}}6
{{end}}7
<section class="panel">7
<section class="panel">8
{{if .StorageFree}}<p>{{t "setup.free" .StorageFree .StorageTotal}}</p>{{end}}8
{{if .StorageTotal}}9
<div class="diskuse">10
{{if .StorageBlueGit}}<p>{{t "setup.usedDir" .StorageBlueGit}}{{if .StoragePartial}} <span class="muted">{{t "setup.usedDirPartial"}}</span>{{end}}</p>{{end}}11
<p>{{t "setup.diskStat" .StorageTotal .StorageUsed .StorageFree}}</p>12
<div class="diskbar">13
<svg class="diskbar-svg" viewBox="0 0 100 8" preserveAspectRatio="none" role="img" aria-label="{{t "setup.diskMeter"}}">14
<rect class="track" width="100" height="8"></rect>15
<rect class="fill" width="{{.StoragePercent}}" height="8"></rect>16
</svg>17
<span>{{.StoragePercent}}%</span>18
</div>19
</div>20
{{end}}9
<form method="post" action="/setup">21
<form method="post" action="/setup">10
<input type="hidden" name="csrf" value="{{.CSRF}}">22
<input type="hidden" name="csrf" value="{{.CSRF}}">11
<label>{{t "setup.disk"}}23
<label>{{t "setup.disk"}}@@ -0,0 +1,32 @@
1
package server
2
3
import (
4
"bytes"
5
"os"
6
"path/filepath"
7
"testing"
8
)
9
10
func TestBlueGitUsageIsCached(t *testing.T) {
11
dir := t.TempDir()
12
if err := os.WriteFile(filepath.Join(dir, "a"), bytes.Repeat([]byte("x"), 100), 0o644); err != nil {
13
t.Fatal(err)
14
}
15
srv := &Server{}
16
n, partial, ok := srv.bluegitUsage(dir)
17
if !ok || partial || n < 100 {
18
t.Fatalf("eerste telling %d partial=%v ok=%v", n, partial, ok)
19
}
20
if err := os.WriteFile(filepath.Join(dir, "b"), bytes.Repeat([]byte("y"), 8000), 0o644); err != nil {
21
t.Fatal(err)
22
}
23
again, partial, ok := srv.bluegitUsage(dir)
24
if !ok || partial || again != n {
25
t.Fatalf("cache %d -> %d partial=%v ok=%v", n, again, partial, ok)
26
}
27
other := t.TempDir()
28
fresh, partial, ok := srv.bluegitUsage(other)
29
if !ok || partial || fresh == 0 || fresh == n {
30
t.Fatalf("andere map %d (was %d) partial=%v ok=%v", fresh, n, partial, ok)
31
}
32
}
@@ -0,0 +1,32 @@1
package server2
3
import (4
"bytes"5
"os"6
"path/filepath"7
"testing"8
)9
10
func TestBlueGitUsageIsCached(t *testing.T) {11
dir := t.TempDir()12
if err := os.WriteFile(filepath.Join(dir, "a"), bytes.Repeat([]byte("x"), 100), 0o644); err != nil {13
t.Fatal(err)14
}15
srv := &Server{}16
n, partial, ok := srv.bluegitUsage(dir)17
if !ok || partial || n < 100 {18
t.Fatalf("eerste telling %d partial=%v ok=%v", n, partial, ok)19
}20
if err := os.WriteFile(filepath.Join(dir, "b"), bytes.Repeat([]byte("y"), 8000), 0o644); err != nil {21
t.Fatal(err)22
}23
again, partial, ok := srv.bluegitUsage(dir)24
if !ok || partial || again != n {25
t.Fatalf("cache %d -> %d partial=%v ok=%v", n, again, partial, ok)26
}27
other := t.TempDir()28
fresh, partial, ok := srv.bluegitUsage(other)29
if !ok || partial || fresh == 0 || fresh == n {30
t.Fatalf("andere map %d (was %d) partial=%v ok=%v", fresh, n, partial, ok)31
}32
}@@ -4,8 +4,10 @@
4
4
package state
5
5
6
6
import (
7
"context"
7
8
"errors"
8
9
"fmt"
10
"io/fs"
9
11
"os"
10
12
"path/filepath"
11
13
"strings"
@@ -90,12 +92,12 @@ func Inspect(path string) (Info, error) {
90
92
if !st.IsDir() {
91
93
return info, i18n.E("err.pathDir")
92
94
}
93
var fs syscall.Statfs_t
94
if err := syscall.Statfs(path, &fs); err != nil {
95
var stat syscall.Statfs_t
96
if err := syscall.Statfs(path, &stat); err != nil {
95
97
return info, i18n.E("err.pathFree", err.Error())
96
98
}
97
info.Free = uint64(fs.Bavail) * uint64(fs.Bsize)
98
info.Total = uint64(fs.Blocks) * uint64(fs.Bsize)
99
info.Free = uint64(stat.Bavail) * uint64(stat.Bsize)
100
info.Total = uint64(stat.Blocks) * uint64(stat.Bsize)
99
101
probe := filepath.Join(path, ".bluegit-write-test")
100
102
f, err := os.OpenFile(probe, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)
101
103
if err != nil {
@@ -109,6 +111,58 @@ func Inspect(path string) (Info, error) {
109
111
return info, nil
110
112
}
111
113
114
// Used is de bezette ruimte: totaal min wat nog vrij is.
115
// Vrij komt uit Bavail, dus gereserveerde blokken tellen als bezet.
116
func (i Info) Used() uint64 {
117
if i.Free >= i.Total {
118
return 0
119
}
120
return i.Total - i.Free
121
}
122
123
// Percent rondt used/total af op een heel percentage.
124
// Een leeg totaal is 0. Meer dan vol blijft 100.
125
func Percent(used, total uint64) int {
126
if total == 0 {
127
return 0
128
}
129
if used > total {
130
used = total
131
}
132
return int((used*100 + total/2) / total)
133
}
134
135
// DirSize telt de schijnbare grootte van path, recursief.
136
// Symlinks worden niet gevolgd. Een afgelopen context stopt de wandeling
137
// en geeft terug wat al geteld is, samen met ctx.Err().
138
func DirSize(ctx context.Context, root string) (uint64, error) {
139
var total uint64
140
err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
141
if ctx.Err() != nil {
142
return ctx.Err()
143
}
144
if err != nil {
145
if path == root {
146
return err
147
}
148
return nil
149
}
150
info, ierr := d.Info()
151
if ierr != nil {
152
return nil
153
}
154
if info.Mode()&os.ModeSymlink != 0 {
155
return nil
156
}
157
total += uint64(info.Size())
158
return nil
159
})
160
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
161
return total, err
162
}
163
return total, err
164
}
165
112
166
// Format maakt een korte grootte, bijvoorbeeld "1.5 GiB".
113
167
func Format(n uint64) string {
114
168
const unit = 1024
@@ -4,8 +4,10 @@4
package state4
package state5
5
6
import (6
import (7
"context"7
"errors"8
"errors"8
"fmt"9
"fmt"10
"io/fs"9
"os"11
"os"10
"path/filepath"12
"path/filepath"11
"strings"13
"strings"@@ -90,12 +92,12 @@ func Inspect(path string) (Info, error) {90
if !st.IsDir() {92
if !st.IsDir() {91
return info, i18n.E("err.pathDir")93
return info, i18n.E("err.pathDir")92
}94
}93
var fs syscall.Statfs_t95
var stat syscall.Statfs_t94
if err := syscall.Statfs(path, &fs); err != nil {96
if err := syscall.Statfs(path, &stat); err != nil {95
return info, i18n.E("err.pathFree", err.Error())97
return info, i18n.E("err.pathFree", err.Error())96
}98
}97
info.Free = uint64(fs.Bavail) * uint64(fs.Bsize)99
info.Free = uint64(stat.Bavail) * uint64(stat.Bsize)98
info.Total = uint64(fs.Blocks) * uint64(fs.Bsize)100
info.Total = uint64(stat.Blocks) * uint64(stat.Bsize)99
probe := filepath.Join(path, ".bluegit-write-test")101
probe := filepath.Join(path, ".bluegit-write-test")100
f, err := os.OpenFile(probe, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)102
f, err := os.OpenFile(probe, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)101
if err != nil {103
if err != nil {@@ -109,6 +111,58 @@ func Inspect(path string) (Info, error) {109
return info, nil111
return info, nil110
}112
}111
113
114
// Used is de bezette ruimte: totaal min wat nog vrij is.115
// Vrij komt uit Bavail, dus gereserveerde blokken tellen als bezet.116
func (i Info) Used() uint64 {117
if i.Free >= i.Total {118
return 0119
}120
return i.Total - i.Free121
}122
123
// Percent rondt used/total af op een heel percentage.124
// Een leeg totaal is 0. Meer dan vol blijft 100.125
func Percent(used, total uint64) int {126
if total == 0 {127
return 0128
}129
if used > total {130
used = total131
}132
return int((used*100 + total/2) / total)133
}134
135
// DirSize telt de schijnbare grootte van path, recursief.136
// Symlinks worden niet gevolgd. Een afgelopen context stopt de wandeling137
// en geeft terug wat al geteld is, samen met ctx.Err().138
func DirSize(ctx context.Context, root string) (uint64, error) {139
var total uint64140
err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {141
if ctx.Err() != nil {142
return ctx.Err()143
}144
if err != nil {145
if path == root {146
return err147
}148
return nil149
}150
info, ierr := d.Info()151
if ierr != nil {152
return nil153
}154
if info.Mode()&os.ModeSymlink != 0 {155
return nil156
}157
total += uint64(info.Size())158
return nil159
})160
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {161
return total, err162
}163
return total, err164
}165
112
// Format maakt een korte grootte, bijvoorbeeld "1.5 GiB".166
// Format maakt een korte grootte, bijvoorbeeld "1.5 GiB".113
func Format(n uint64) string {167
func Format(n uint64) string {114
const unit = 1024168
const unit = 1024@@ -1,6 +1,9 @@
1
1
package state
2
2
3
3
import (
4
"bytes"
5
"context"
6
"errors"
4
7
"os"
5
8
"path/filepath"
6
9
"strings"
@@ -50,4 +53,57 @@ func TestInspect(t *testing.T) {
50
53
if _, err := os.Stat(filepath.Join(dir, ".bluegit-write-test")); !os.IsNotExist(err) {
51
54
t.Fatal("schrijftest bleef achter")
52
55
}
56
if info.Used()+info.Free != info.Total {
57
t.Fatalf("bezet %d + vrij %d != totaal %d", info.Used(), info.Free, info.Total)
58
}
59
if Percent(info.Used(), info.Total) < 0 || Percent(info.Used(), info.Total) > 100 {
60
t.Fatal(Percent(info.Used(), info.Total))
61
}
62
}
63
64
func TestPercentAndUsed(t *testing.T) {
65
if Percent(0, 0) != 0 || Percent(1, 2) != 50 || Percent(2, 2) != 100 || Percent(1, 3) != 33 || Percent(5, 2) != 100 {
66
t.Fatalf("0=%d half=%d vol=%d derde=%d over=%d", Percent(0, 0), Percent(1, 2), Percent(2, 2), Percent(1, 3), Percent(5, 2))
67
}
68
if (Info{Free: 30, Total: 10}).Used() != 0 || (Info{Free: 4, Total: 10}).Used() != 6 {
69
t.Fatal("used")
70
}
71
}
72
73
func TestDirSizeCountsTreeAndStops(t *testing.T) {
74
root := t.TempDir()
75
if err := os.WriteFile(filepath.Join(root, "a"), bytes.Repeat([]byte("x"), 1000), 0o644); err != nil {
76
t.Fatal(err)
77
}
78
sub := filepath.Join(root, "sub")
79
if err := os.Mkdir(sub, 0o755); err != nil {
80
t.Fatal(err)
81
}
82
if err := os.WriteFile(filepath.Join(sub, "b"), bytes.Repeat([]byte("y"), 500), 0o644); err != nil {
83
t.Fatal(err)
84
}
85
outside := filepath.Join(t.TempDir(), "groot")
86
if err := os.WriteFile(outside, bytes.Repeat([]byte("z"), 2<<20), 0o644); err != nil {
87
t.Fatal(err)
88
}
89
if err := os.Symlink(outside, filepath.Join(root, "link")); err != nil {
90
t.Fatal(err)
91
}
92
n, err := DirSize(context.Background(), root)
93
if err != nil {
94
t.Fatal(err)
95
}
96
if n < 1500 || n >= 2<<20 {
97
t.Fatalf("grootte %d volgt de symlink of mist bestanden", n)
98
}
99
again, err := DirSize(context.Background(), root)
100
if err != nil || again != n {
101
t.Fatalf("opnieuw %d %v", again, err)
102
}
103
ctx, cancel := context.WithCancel(context.Background())
104
cancel()
105
stopped, err := DirSize(ctx, root)
106
if !errors.Is(err, context.Canceled) || stopped != 0 {
107
t.Fatalf("stop: %d %v", stopped, err)
108
}
53
109
}
@@ -1,6 +1,9 @@1
package state1
package state2
2
3
import (3
import (4
"bytes"5
"context"6
"errors"4
"os"7
"os"5
"path/filepath"8
"path/filepath"6
"strings"9
"strings"@@ -50,4 +53,57 @@ func TestInspect(t *testing.T) {50
if _, err := os.Stat(filepath.Join(dir, ".bluegit-write-test")); !os.IsNotExist(err) {53
if _, err := os.Stat(filepath.Join(dir, ".bluegit-write-test")); !os.IsNotExist(err) {51
t.Fatal("schrijftest bleef achter")54
t.Fatal("schrijftest bleef achter")52
}55
}56
if info.Used()+info.Free != info.Total {57
t.Fatalf("bezet %d + vrij %d != totaal %d", info.Used(), info.Free, info.Total)58
}59
if Percent(info.Used(), info.Total) < 0 || Percent(info.Used(), info.Total) > 100 {60
t.Fatal(Percent(info.Used(), info.Total))61
}62
}63
64
func TestPercentAndUsed(t *testing.T) {65
if Percent(0, 0) != 0 || Percent(1, 2) != 50 || Percent(2, 2) != 100 || Percent(1, 3) != 33 || Percent(5, 2) != 100 {66
t.Fatalf("0=%d half=%d vol=%d derde=%d over=%d", Percent(0, 0), Percent(1, 2), Percent(2, 2), Percent(1, 3), Percent(5, 2))67
}68
if (Info{Free: 30, Total: 10}).Used() != 0 || (Info{Free: 4, Total: 10}).Used() != 6 {69
t.Fatal("used")70
}71
}72
73
func TestDirSizeCountsTreeAndStops(t *testing.T) {74
root := t.TempDir()75
if err := os.WriteFile(filepath.Join(root, "a"), bytes.Repeat([]byte("x"), 1000), 0o644); err != nil {76
t.Fatal(err)77
}78
sub := filepath.Join(root, "sub")79
if err := os.Mkdir(sub, 0o755); err != nil {80
t.Fatal(err)81
}82
if err := os.WriteFile(filepath.Join(sub, "b"), bytes.Repeat([]byte("y"), 500), 0o644); err != nil {83
t.Fatal(err)84
}85
outside := filepath.Join(t.TempDir(), "groot")86
if err := os.WriteFile(outside, bytes.Repeat([]byte("z"), 2<<20), 0o644); err != nil {87
t.Fatal(err)88
}89
if err := os.Symlink(outside, filepath.Join(root, "link")); err != nil {90
t.Fatal(err)91
}92
n, err := DirSize(context.Background(), root)93
if err != nil {94
t.Fatal(err)95
}96
if n < 1500 || n >= 2<<20 {97
t.Fatalf("grootte %d volgt de symlink of mist bestanden", n)98
}99
again, err := DirSize(context.Background(), root)100
if err != nil || again != n {101
t.Fatalf("opnieuw %d %v", again, err)102
}103
ctx, cancel := context.WithCancel(context.Background())104
cancel()105
stopped, err := DirSize(ctx, root)106
if !errors.Is(err, context.Canceled) || stopped != 0 {107
t.Fatalf("stop: %d %v", stopped, err)108
}53
}109
}