-
-
Notifications
You must be signed in to change notification settings - Fork 335
Expand file tree
/
Copy pathmagefile.go
More file actions
2100 lines (1788 loc) · 61.5 KB
/
magefile.go
File metadata and controls
2100 lines (1788 loc) · 61.5 KB
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Vikunja is a to-do list application to facilitate your life.
// Copyright 2018-present Vikunja and contributors. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//go:build mage
package main
import (
"bufio"
"bytes"
"context"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"math"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"syscall"
"time"
"github.com/iancoleman/strcase"
"github.com/magefile/mage/mg"
"golang.org/x/sync/errgroup"
)
const (
PACKAGE = `code.vikunja.io/api`
DIST = `dist`
)
var (
Executable = "vikunja"
Ldflags = ""
Tags = ""
VersionNumber = "dev"
Version = "unstable" // This holds the built version, unstable by default, when building from a tag or release branch, their name
BinLocation = ""
PkgVersion = "unstable"
// Aliases are mage aliases of targets
Aliases = map[string]any{
"build": Build.Build,
"check:got-swag": Check.GotSwag,
"release": Release.Release,
"release:os-package": Release.OsPackage,
"release:prepare-nfpm-config": Release.PrepareNFPMConfig,
"dev:make-migration": Dev.MakeMigration,
"dev:make-event": Dev.MakeEvent,
"dev:make-listener": Dev.MakeListener,
"dev:make-notification": Dev.MakeNotification,
"dev:prepare-worktree": Dev.PrepareWorktree,
"dev:tag-release": Dev.TagRelease,
"test:e2e": Test.E2E,
"test:e2e-api": Test.E2EApi,
"plugins:build": Plugins.Build,
"lint": Check.Golangci,
"lint:fix": Check.GolangciFix,
"generate:config-yaml": Generate.ConfigYAML,
"generate:swagger-docs": Generate.SwaggerDocs,
}
)
func goDetectVerboseFlag() string {
return fmt.Sprintf("-v=%t", mg.Verbose())
}
func runGitCommandWithOutput(ctx context.Context, arg ...string) (output []byte, err error) {
cmd := exec.CommandContext(ctx, "git", arg...)
output, err = cmd.Output()
if err != nil {
var ee *exec.ExitError
if errors.As(err, &ee) {
return nil, fmt.Errorf("error running command: %s, %w", string(ee.Stderr), err)
}
return nil, fmt.Errorf("error running command: %w", err)
}
return output, nil
}
func getRawVersionString(ctx context.Context) (version string, err error) {
version, err = getRawVersionNumber(ctx)
if err != nil {
return
}
if version == "main" {
version = "unstable"
}
if version != "" && version != "unstable" {
return
}
return
}
func getRawVersionNumber(ctx context.Context) (version string, err error) {
versionEnv := os.Getenv("RELEASE_VERSION")
if versionEnv != "" {
return versionEnv, nil
}
if os.Getenv("DRONE_TAG") != "" {
return os.Getenv("DRONE_TAG"), nil
}
if os.Getenv("DRONE_BRANCH") != "" {
return strings.Replace(os.Getenv("DRONE_BRANCH"), "release/v", "", 1), nil
}
versionBytes, err := runGitCommandWithOutput(ctx, "describe", "--tags", "--always", "--abbrev=10")
return string(versionBytes), err
}
func setVersion(ctx context.Context) error {
versionNumber, err := getRawVersionNumber(ctx)
if err != nil {
return err
}
VersionNumber = strings.Trim(versionNumber, "\n")
VersionNumber = strings.Replace(VersionNumber, "-g", "-", 1)
version, err := getRawVersionString(ctx)
if err != nil {
return fmt.Errorf("error getting version: %w", err)
}
Version = version
return nil
}
func setBinLocation() {
if os.Getenv("DRONE_WORKSPACE") != "" {
BinLocation = DIST + `/binaries/` + Executable + `-` + Version + `-linux-amd64`
} else {
BinLocation = Executable
}
}
func setPkgVersion() {
if Version == "unstable" {
PkgVersion = VersionNumber
}
}
func setExecutable() {
if runtime.GOOS == "windows" {
Executable += ".exe"
}
}
// Some variables can always get initialized, so we do just that.
func init() {
setExecutable()
}
// Some variables have external dependencies (like git) which may not always be available.
func initVars(ctx context.Context) error {
// Always include osusergo to use pure Go os/user implementation instead of CGO.
// This prevents SIGFPE crashes when running under systemd without HOME set,
// caused by glibc's getpwuid_r() failing in certain environments.
// See: https://github.com/go-vikunja/vikunja/issues/2170
Tags = "osusergo " + strings.ReplaceAll(os.Getenv("TAGS"), ",", " ")
if err := setVersion(ctx); err != nil {
return err
}
setBinLocation()
setPkgVersion()
Ldflags = `-X "` + PACKAGE + `/pkg/version.Version=` + VersionNumber + `" -X "main.Tags=` + Tags + `"`
return nil
}
func runAndStreamOutput(ctx context.Context, cmd string, args ...string) error {
c := exec.CommandContext(ctx, cmd, args...)
c.Env = os.Environ()
c.Stdout = os.Stdout
c.Stderr = os.Stderr
fmt.Printf("%s\n\n", c.String())
return c.Run()
}
// Will check if the tool exists and if not install it from the provided import path
// If any errors occur, it will exit with a status code of 1.
func checkAndInstallGoTool(ctx context.Context, tool, importPath string) error {
if err := exec.CommandContext(ctx, tool).Run(); err != nil && strings.Contains(err.Error(), "executable file not found") {
fmt.Printf("%s not installed, installing %s...\n", tool, importPath)
if err := exec.CommandContext(ctx, "go", "install", goDetectVerboseFlag(), importPath).Run(); err != nil { //nolint:gosec // Every caller to checkAndInstallGoTool is hard-coded at time of writing, so no injection possible.
return fmt.Errorf("error installing %s: %w", tool, err)
}
fmt.Println("Installed.")
}
return nil
}
// Calculates a hash of a file
func calculateSha256FileHash(path string) (hash string, err error) {
f, err := os.Open(path)
if err != nil {
return "", err
}
defer f.Close()
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return "", err
}
return fmt.Sprintf("%x", h.Sum(nil)), nil
}
// Copy the src file to dst. Any existing file will be overwritten and will not
// copy file attributes.
func copyFile(src, dst string) error {
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
out, err := os.Create(dst)
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, in)
if err != nil {
return err
}
si, err := os.Stat(src)
if err != nil {
return err
}
if err := os.Chmod(dst, si.Mode()); err != nil {
return err
}
return out.Close()
}
// os.Rename has issues with moving files between docker volumes.
// Because of this limitation, it fails in drone.
// Source: https://gist.github.com/var23rav/23ae5d0d4d830aff886c3c970b8f6c6b
func moveFile(src, dst string) error {
inputFile, err := os.Open(src)
if err != nil {
return fmt.Errorf("couldn't open source file: %w", err)
}
defer inputFile.Close()
outputFile, err := os.Create(dst)
if err != nil {
return fmt.Errorf("couldn't open dest file: %w", err)
}
defer outputFile.Close()
_, err = io.Copy(outputFile, inputFile)
if err != nil {
return fmt.Errorf("writing to output file failed: %w", err)
}
// Make sure to copy copy the permissions of the original file as well
si, err := os.Stat(src)
if err != nil {
return err
}
if err := os.Chmod(dst, si.Mode()); err != nil {
return err
}
// The copy was successful, so now delete the original file
err = os.Remove(src)
if err != nil {
return fmt.Errorf("failed removing original file: %w", err)
}
return nil
}
func appendToFile(filename, content string) error {
f, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0o600)
if err != nil {
return err
}
defer f.Close()
_, err = f.WriteString(content)
return err
}
const InfoColor = "\033[1;32m%s\033[0m"
func printSuccess(text string, args ...any) {
text = fmt.Sprintf(text, args...)
fmt.Printf(InfoColor+"\n", text)
}
// getE2EPort returns the port from the given env var, or a random available port.
func getE2EPort(ctx context.Context, envVar string) (int, error) {
if v := os.Getenv(envVar); v != "" {
return strconv.Atoi(v)
}
return getRandomPort(ctx)
}
// getRandomPort finds a random available TCP port.
func getRandomPort(ctx context.Context) (int, error) {
l, err := (&net.ListenConfig{}).Listen(ctx, "tcp", "127.0.0.1:0")
if err != nil {
return 0, err
}
defer l.Close()
return l.Addr().(*net.TCPAddr).Port, nil
}
// setProcessGroup configures a command to run in its own process group,
// so that all child processes can be killed together.
func setProcessGroup(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
}
// killProcessGroup sends a signal to the entire process group of the given command.
func killProcessGroup(cmd *exec.Cmd) error {
if cmd.Process == nil {
return nil
}
if pgid, err := syscall.Getpgid(cmd.Process.Pid); err == nil { // use best-effort to kill full process group
err = syscall.Kill(-pgid, syscall.SIGTERM)
if err != nil {
return err
}
}
return cmd.Wait()
}
// waitForHTTP polls a URL until it returns a 200 status or the timeout expires.
func waitForHTTP(ctx context.Context, url string, timeout time.Duration) error {
deadline := time.Now().Add(timeout)
client := &http.Client{Timeout: 2 * time.Second}
for time.Now().Before(deadline) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return err
}
resp, err := client.Do(req)
if err == nil {
resp.Body.Close()
if resp.StatusCode == http.StatusOK {
return nil
}
}
time.Sleep(500 * time.Millisecond)
}
return fmt.Errorf("timed out waiting for %s after %s", url, timeout)
}
// Fmt formats the code using go fmt
func Fmt(ctx context.Context) error {
mg.Deps(initVars)
var goFiles []string
err := filepath.Walk(".", func(path string, info fs.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() && filepath.Ext(path) == ".go" {
goFiles = append(goFiles, path)
}
return nil
})
if err != nil {
return err
}
args := append([]string{"-s", "-w"}, goFiles...)
return runAndStreamOutput(ctx, "gofmt", args...)
}
type Test mg.Namespace
// Feature runs the feature tests
func (Test) Feature(ctx context.Context) error {
mg.Deps(initVars)
// We run everything sequentially and not in parallel to prevent issues with real test databases
return runAndStreamOutput(ctx, "go", "test", goDetectVerboseFlag(), "-p", "1", "-coverprofile", "cover.out", "-timeout", "45m", "-short", "./...")
}
// Coverage runs the tests and builds the coverage html file from coverage output
func (Test) Coverage(ctx context.Context) error {
mg.Deps(initVars)
mg.Deps(Test.Feature)
return runAndStreamOutput(ctx, "go", "tool", "cover", "-html=cover.out", "-o", "cover.html")
}
// Web runs the web tests
func (Test) Web(ctx context.Context) error {
mg.Deps(initVars)
// We run everything sequentially and not in parallel to prevent issues with real test databases
args := []string{"test", goDetectVerboseFlag(), "-p", "1", "-timeout", "45m", "./pkg/webtests"}
return runAndStreamOutput(ctx, "go", args...)
}
func (Test) Filter(ctx context.Context, filter string) error {
mg.Deps(initVars)
// We run everything sequentially and not in parallel to prevent issues with real test databases
return runAndStreamOutput(ctx, "go", "test", goDetectVerboseFlag(), "-p", "1", "-timeout", "45m", "-run", filter, "-short", "./...")
}
func (Test) All() {
mg.Deps(initVars)
mg.Deps(Test.Feature, Test.Web, Test.E2EApi)
}
// E2EApi runs the end-to-end API tests in pkg/e2etests.
// These tests use the real event system (not events.Fake()) to verify
// the full async pipeline: web handler → DB → event dispatch → watermill → listener.
func (Test) E2EApi(ctx context.Context) error {
mg.Deps(initVars)
return runAndStreamOutput(ctx, "go", "test", goDetectVerboseFlag(), "-p", "1", "-timeout", "45m", "./pkg/e2etests")
}
// E2E builds the API, starts it with an in-memory database and the frontend dev server,
// runs the Playwright e2e tests against them, then tears everything down.
// This does not touch your local database.
//
// Any arguments are passed through to Playwright. Examples:
//
// mage test:e2e "" # run all tests
// mage test:e2e "tests/e2e/misc/menu.spec.ts" # run a specific test file
// mage test:e2e "--grep menu" # filter by test name
// mage test:e2e "--headed" # run in headed browser mode
// mage test:e2e "--headed tests/e2e/misc/menu.spec.ts" # combine flags
//
// Environment variable overrides:
// - VIKUNJA_E2E_API_PORT: API port (default: random)
// - VIKUNJA_E2E_FRONTEND_PORT: Frontend port (default: random)
// - VIKUNJA_E2E_TESTING_TOKEN: Testing token for seed endpoints (default: random)
// - VIKUNJA_E2E_SKIP_BUILD: Set to "true" to skip rebuilding the API binary (default: false)
func (Test) E2E(ctx context.Context, args string) error {
mg.Deps(initVars)
// Determine ports
apiPort, err := getE2EPort(ctx, "VIKUNJA_E2E_API_PORT")
if err != nil {
return fmt.Errorf("could not get API port: %w", err)
}
frontendPort, err := getE2EPort(ctx, "VIKUNJA_E2E_FRONTEND_PORT")
if err != nil {
return fmt.Errorf("could not get frontend port: %w", err)
}
// Generate a random testing token
testingToken := os.Getenv("VIKUNJA_E2E_TESTING_TOKEN")
if testingToken == "" {
testingToken = fmt.Sprintf("e2e-test-token-%d", time.Now().UnixNano())
}
fmt.Printf("E2E test configuration:\n")
fmt.Printf(" API port: %d\n", apiPort)
fmt.Printf(" Frontend port: %d\n", frontendPort)
fmt.Printf(" Testing token: %s\n", testingToken)
// Build the API binary (unless skipped)
if os.Getenv("VIKUNJA_E2E_SKIP_BUILD") != "true" {
fmt.Println("\n--- Building API binary ---")
if err := (Build{}).Build(ctx); err != nil {
return fmt.Errorf("failed to build API: %w", err)
}
}
// Create temp directory for file uploads and rootpath
tmpDir, err := os.MkdirTemp("", "vikunja-e2e-*")
if err != nil {
return fmt.Errorf("failed to create temp dir: %w", err)
}
defer func() {
fmt.Println("\n--- Cleaning up temp directory ---")
os.RemoveAll(tmpDir)
}()
if err := os.MkdirAll(filepath.Join(tmpDir, "files"), 0o755); err != nil {
return fmt.Errorf("failed to create files dir: %w", err)
}
// Start the API server — all config via env vars, no config file
// Uses in-memory SQLite (no DB file on disk)
fmt.Println("\n--- Starting API server ---")
apiCmd := exec.CommandContext(ctx, "./vikunja", "web")
apiCmd.Env = append(os.Environ(),
fmt.Sprintf("VIKUNJA_SERVICE_INTERFACE=:%d", apiPort),
fmt.Sprintf("VIKUNJA_SERVICE_PUBLICURL=http://127.0.0.1:%d/", apiPort),
fmt.Sprintf("VIKUNJA_SERVICE_TESTINGTOKEN=%s", testingToken),
fmt.Sprintf("VIKUNJA_SERVICE_ROOTPATH=%s", tmpDir),
"VIKUNJA_SERVICE_JWTSECRET=e2e-test-jwt-secret-do-not-use-in-production",
"VIKUNJA_DATABASE_TYPE=sqlite",
"VIKUNJA_DATABASE_PATH=memory",
fmt.Sprintf("VIKUNJA_FILES_BASEPATH=%s", filepath.Join(tmpDir, "files")),
"VIKUNJA_LOG_LEVEL=WARNING",
"VIKUNJA_MAILER_ENABLED=false",
"VIKUNJA_REDIS_ENABLED=false",
"VIKUNJA_RATELIMIT_NOAUTHLIMIT=1000",
)
apiCmd.Stdout = os.Stdout
apiCmd.Stderr = os.Stderr
setProcessGroup(apiCmd)
if err := apiCmd.Start(); err != nil {
return fmt.Errorf("failed to start API: %w", err)
}
defer func() {
fmt.Println("\n--- Stopping API server ---")
if err := killProcessGroup(apiCmd); err != nil {
fmt.Println("Failed to stop API server:", err)
}
}()
// Wait for API to be ready
apiBase := fmt.Sprintf("http://127.0.0.1:%d/api/v1", apiPort)
fmt.Printf("Waiting for API at %s ...\n", apiBase)
if err := waitForHTTP(ctx, apiBase+"/info", 30*time.Second); err != nil {
return fmt.Errorf("API failed to start: %w", err)
}
printSuccess("API is ready!")
// Build the frontend
fmt.Println("\n--- Building frontend ---")
buildFrontendCmd := exec.CommandContext(ctx, "pnpm", "build:dev")
buildFrontendCmd.Dir = "frontend"
buildFrontendCmd.Stdout = os.Stdout
buildFrontendCmd.Stderr = os.Stderr
if err := buildFrontendCmd.Run(); err != nil {
return fmt.Errorf("failed to build frontend: %w", err)
}
printSuccess("Frontend built!")
// Serve the built frontend with vite preview (static, no file watchers)
fmt.Println("\n--- Starting frontend preview server ---")
frontendCmd := exec.CommandContext(ctx, "pnpm", "preview:dev", "--port", strconv.Itoa(frontendPort)) //nolint:gosec // This mage task runs end to end tests with environment-based configuration, it must use the port environment variable to suit its current environment.
frontendCmd.Dir = "frontend"
frontendCmd.Stdout = os.Stdout
frontendCmd.Stderr = os.Stderr
setProcessGroup(frontendCmd)
if err := frontendCmd.Start(); err != nil {
return fmt.Errorf("failed to start frontend: %w", err)
}
defer func() {
fmt.Println("\n--- Stopping frontend preview server ---")
if err := killProcessGroup(frontendCmd); err != nil {
fmt.Println("Failed to stop API server:", err)
}
}()
// Wait for frontend to be ready
frontendBase := fmt.Sprintf("http://127.0.0.1:%d", frontendPort)
fmt.Printf("Waiting for frontend at %s ...\n", frontendBase)
if err := waitForHTTP(ctx, frontendBase, 60*time.Second); err != nil {
return fmt.Errorf("frontend failed to start: %w", err)
}
printSuccess("Frontend is ready!")
// Run Playwright tests
fmt.Println("\n--- Running Playwright e2e tests ---")
playwrightArgs := []string{"test:e2e"}
if strings.TrimSpace(args) != "" {
playwrightArgs = append(playwrightArgs, strings.Fields(args)...)
}
playwrightCmd := exec.CommandContext(ctx, "pnpm", playwrightArgs...)
playwrightCmd.Dir = "frontend"
playwrightCmd.Env = append(os.Environ(),
fmt.Sprintf("API_URL=%s/", apiBase),
fmt.Sprintf("BASE_URL=%s", frontendBase),
fmt.Sprintf("VIKUNJA_SERVICE_TESTINGTOKEN=%s", testingToken),
fmt.Sprintf("TEST_SECRET=%s", testingToken),
)
playwrightCmd.Stdout = os.Stdout
playwrightCmd.Stderr = os.Stderr
testErr := playwrightCmd.Run()
if testErr != nil {
return fmt.Errorf("e2e tests failed: %w", testErr)
}
printSuccess("All e2e tests passed!")
return nil
}
type Check mg.Namespace
// GotSwag checks if the swagger docs need to be re-generated from the code annotations
func (Check) GotSwag(ctx context.Context) error {
mg.Deps(initVars)
// The check is pretty cheaply done: We take the hash of the swagger.json file, generate the docs,
// hash the file again and compare the two hashes to see if anything changed. If that's the case,
// regenerating the docs is necessary.
// swag is not capable of just outputting the generated docs to stdout, therefore we need to do it this way.
// Another drawback of this is obviously it will only work once - we're not resetting the newly generated
// docs after the check. This behaviour is good enough for ci though.
oldHash, err := calculateSha256FileHash("./pkg/swagger/swagger.json")
if err != nil {
return fmt.Errorf("error getting old hash of the swagger docs: %w", err)
}
if generateErr := (Generate{}).SwaggerDocs(ctx); generateErr != nil {
return generateErr
}
newHash, err := calculateSha256FileHash("./pkg/swagger/swagger.json")
if err != nil {
return fmt.Errorf("error getting new hash of the swagger docs: %w", err)
}
if oldHash != newHash {
return fmt.Errorf("swagger docs are not up to date: run 'mage generate:swagger-docs' and commit the result")
}
return nil
}
// Translations checks if all translation keys used in the code exist in the English translation file
func (Check) Translations() error {
mg.Deps(initVars)
fmt.Println("Checking for missing translation keys...")
// Load translations from the English translation file
translationFile := "./pkg/i18n/lang/en.json"
translations, err := loadTranslations(translationFile)
if err != nil {
return fmt.Errorf("error loading translations: %w", err)
}
fmt.Printf("Loaded %d translation keys from %s\n", len(translations), translationFile)
// Extract keys from codebase
keys, err := walkCodebaseForTranslationKeys(".")
if err != nil {
return fmt.Errorf("error walking codebase: %w", err)
}
fmt.Printf("Found %d translation keys in the codebase\n", len(keys))
// Check for missing keys
missingKeys := make(map[string][]TranslationKey)
for _, key := range keys {
if !translations[key.Key] {
missingKeys[key.Key] = append(missingKeys[key.Key], key)
}
}
// Print results
if len(missingKeys) > 0 {
var errs []error
for key, occurrences := range missingKeys {
var keyErrs []error
for _, occurrence := range occurrences {
keyErrs = append(keyErrs, fmt.Errorf("- %s:%d", occurrence.FilePath, occurrence.Line))
}
errs = append(errs, fmt.Errorf("missing key %s in files:\n%w", key, errors.Join(keyErrs...)))
}
return fmt.Errorf("found %d missing translation keys:\n%w", len(missingKeys), errors.Join(errs...))
}
printSuccess("All translation keys are present in the translation file!")
return nil
}
// TranslationKey represents a translation key found in the code
type TranslationKey struct {
Key string
FilePath string
Line int
}
// loadTranslations loads the English translation file and returns a flattened map
func loadTranslations(filePath string) (map[string]bool, error) {
data, err := os.ReadFile(filePath)
if err != nil {
return nil, fmt.Errorf("error reading translation file: %w", err)
}
var translationsMap map[string]any
if err := json.Unmarshal(data, &translationsMap); err != nil {
return nil, fmt.Errorf("error parsing JSON: %w", err)
}
// Flatten the nested structure
flattenedMap := make(map[string]bool)
flattenTranslations("", translationsMap, flattenedMap)
return flattenedMap, nil
}
// flattenTranslations recursively flattens a nested map structure into a flat map with dot-separated keys
func flattenTranslations(prefix string, src map[string]any, dest map[string]bool) {
for k, v := range src {
key := k
if prefix != "" {
key = prefix + "." + k
}
switch vv := v.(type) {
case string:
dest[key] = true
case map[string]any:
flattenTranslations(key, vv, dest)
}
}
}
// walkCodebaseForTranslationKeys walks the codebase and extracts all translation keys
func walkCodebaseForTranslationKeys(rootDir string) ([]TranslationKey, error) {
var allKeys []TranslationKey
pkgDir := filepath.Join(rootDir, "pkg")
err := filepath.Walk(pkgDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
// Skip hidden directories (starting with .)
if info.IsDir() && strings.HasPrefix(info.Name(), ".") {
return filepath.SkipDir
}
// Only process Go files
if !info.IsDir() && strings.HasSuffix(path, ".go") {
keys, err := extractTranslationKeysFromFile(path)
if err != nil {
fmt.Printf("Warning: %v\n", err)
return nil
}
allKeys = append(allKeys, keys...)
}
return nil
})
return allKeys, err
}
// extractTranslationKeysFromFile extracts all i18n.T calls from a file
func extractTranslationKeysFromFile(filePath string) ([]TranslationKey, error) {
// Read the file content
content, err := os.ReadFile(filePath)
if err != nil {
return nil, fmt.Errorf("error reading file %s: %w", filePath, err)
}
var keys []TranslationKey
// Regex to match i18n.T calls
re := regexp.MustCompile(`i18n\.(T)\([^,]+,\s*"([^"]+)"`)
matches := re.FindAllSubmatchIndex(content, -1)
for _, match := range matches {
if len(match) >= 4 {
// Extract the key from the match
keyStart, keyEnd := match[4], match[5]
key := string(content[keyStart:keyEnd])
// Count lines to determine the line number
beforeMatch := content[:keyStart]
lineCount := bytes.Count(beforeMatch, []byte("\n")) + 1
keys = append(keys, TranslationKey{
Key: key,
FilePath: filePath,
Line: lineCount,
})
}
}
return keys, nil
}
func checkGolangCiLintInstalled(ctx context.Context) error {
mg.Deps(initVars)
if err := exec.CommandContext(ctx, "golangci-lint").Run(); err != nil && strings.Contains(err.Error(), "executable file not found") {
return fmt.Errorf("golangci-lint executable failed to run, please manually install golangci-lint by running the command: curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v2.4.0")
}
return nil
}
func (Check) Golangci(ctx context.Context) error {
if err := checkGolangCiLintInstalled(ctx); err != nil {
return err
}
return runAndStreamOutput(ctx, "golangci-lint", "run")
}
func (Check) GolangciFix(ctx context.Context) error {
if err := checkGolangCiLintInstalled(ctx); err != nil {
return err
}
return runAndStreamOutput(ctx, "golangci-lint", "run", "--fix")
}
// All runs golangci and the swagger test in parallel
func (Check) All() {
mg.Deps(initVars)
mg.Deps(
Check.Golangci,
Check.GotSwag,
Check.Translations,
)
}
type Build mg.Namespace
// Clean cleans all build, executable and bindata files
func (Build) Clean(ctx context.Context) error {
mg.Deps(initVars)
if err := exec.CommandContext(ctx, "go", "clean", "./...").Run(); err != nil {
return err
}
if err := os.Remove(Executable); err != nil && !os.IsNotExist(err) {
return err
}
if err := os.RemoveAll(DIST); err != nil && !os.IsNotExist(err) {
return err
}
if err := os.RemoveAll(BinLocation); err != nil && !os.IsNotExist(err) {
return err
}
return nil
}
// Build builds a vikunja binary, ready to run
func (Build) Build(ctx context.Context) error {
mg.Deps(initVars)
// Check if the frontend dist folder exists
distPath := filepath.Join("frontend", "dist")
if _, err := os.Stat(distPath); os.IsNotExist(err) {
if err := os.MkdirAll(distPath, 0o755); err != nil {
return fmt.Errorf("error creating %s: %w", distPath, err)
}
}
indexFile := filepath.Join(distPath, "index.html")
if _, err := os.Stat(indexFile); os.IsNotExist(err) {
f, err := os.Create(indexFile)
if err != nil {
return fmt.Errorf("error creating %s: %w", indexFile, err)
}
f.Close()
fmt.Printf("Warning: %s not found, created empty file\n", indexFile)
}
return runAndStreamOutput(ctx, "go", "build", goDetectVerboseFlag(), "-tags", Tags, "-ldflags", "-s -w "+Ldflags, "-o", Executable)
}
func (Build) SaveVersionToFile() error {
// Open the file for writing. If the file doesn't exist, create it.
// If it exists, truncate it.
file, err := os.Create("VERSION")
if err != nil {
return fmt.Errorf("error creating VERSION file: %w", err)
}
defer file.Close()
// Write the version number to the file
_, err = file.WriteString(VersionNumber)
if err != nil {
return fmt.Errorf("error writing to VERSION file: %w", err)
}
fmt.Println("Version number saved successfully to VERSION file")
return nil
}
type Release mg.Namespace
// Release runs all steps in the right order to create release packages for various platforms
func (Release) Release(ctx context.Context) error {
mg.Deps(initVars)
mg.Deps(Release.Dirs, prepareXgo)
// Run compiling in parallel to speed it up
errs, _ := errgroup.WithContext(ctx)
errgroupGoWithContext(ctx, errs, (Release{}).Windows)
errgroupGoWithContext(ctx, errs, (Release{}).Linux)
errgroupGoWithContext(ctx, errs, (Release{}).Darwin)
if err := errs.Wait(); err != nil {
return err
}
if err := (Release{}).Compress(ctx); err != nil {
return err
}
if err := (Release{}).Copy(); err != nil {
return err
}
if err := (Release{}).Check(); err != nil {
return err
}
if err := (Release{}).OsPackage(); err != nil {
return err
}
if err := (Release{}).Zip(ctx); err != nil {
return err
}
return nil
}
func errgroupGoWithContext(ctx context.Context, errs *errgroup.Group, do func(context.Context) error) {
errs.Go(func() error {
return do(ctx)
})
}
// Dirs creates all directories needed to release vikunja
func (Release) Dirs() error {
for _, d := range []string{"binaries", "release", "zip"} {
if err := os.MkdirAll("./"+DIST+"/"+d, 0o755); err != nil {
return err
}
}
return nil
}
func prepareXgo(ctx context.Context) error {
mg.Deps(initVars)
if err := checkAndInstallGoTool(ctx, "xgo", "src.techknowlogick.com/xgo"); err != nil {
return err
}
fmt.Println("Pulling latest xgo docker image...")
return runAndStreamOutput(ctx, "docker", "pull", "ghcr.io/techknowlogick/xgo:latest")
}
func runXgo(ctx context.Context, targets string) error {
mg.Deps(initVars)
if err := checkAndInstallGoTool(ctx, "xgo", "src.techknowlogick.com/xgo"); err != nil {
return err
}
extraLdflags := `-linkmode external -extldflags "-static" `
// See https://github.com/techknowlogick/xgo/issues/79
if strings.HasPrefix(targets, "darwin") {
extraLdflags = ""
}
outName := os.Getenv("XGO_OUT_NAME")
if outName == "" {
outName = Executable + "-" + Version
}
if err := runAndStreamOutput(ctx, "xgo",
"-dest", "./"+DIST+"/binaries",
"-tags", "netgo "+Tags,
"-ldflags", extraLdflags+Ldflags,
"-targets", targets,
"-out", outName,
"."); err != nil {
return err
}
if os.Getenv("DRONE_WORKSPACE") != "" {
return filepath.Walk("/build/", func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
// Skip directories
if info.IsDir() {
return nil
}
return moveFile(path, "./"+DIST+"/binaries/"+info.Name())
})
}
return nil
}
// Windows builds binaries for windows
func (Release) Windows(ctx context.Context) error {