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
|
//go:build mage
// +build mage
package main
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/rclone/rclone/fs/config/obscure"
)
const (
outputDir = "build"
pluginName = "librcloneplugin_backend_studip.so"
binaryName = "rclone-studip"
goExperiment = "nodwarf5"
rcloneModulePath = "github.com/rclone/rclone"
studipModulePath = "github.com/mewsen/rclone-studip-backend-oot"
pluginModFileName = "studip.plugin.mod"
pluginSumFileName = "studip.plugin.sum"
pluginBuildTreeDir = "rclone"
pluginEntrypointDir = "cmd/studipplugin"
pluginEntrypointSrc = "package main\n\nimport _ \"github.com/mewsen/rclone-studip-backend-oot/backend/studip\"\n"
studIPDemoBaseURL = "http://localhost:8034/jsonapi.php/v1/"
studIPDemoUsername = "test_dozent"
studIPDemoPassword = "testing"
studIPDemoLicense = "SELFMADE_NONPUB"
studIPConfigName = "test-rclone.conf"
)
var Default = BuildPluginAndStandaloneBinary
type studIPTestConfig struct {
BaseURL string
Username string
Password string
CourseID string
License string
ConfigPath string
}
type studIPCoursesResponse struct {
Data []studIPCourse `json:"data"`
}
type studIPCourse struct {
ID string `json:"id"`
Attributes struct {
Title string `json:"title"`
CourseType int `json:"course-type"`
} `json:"attributes"`
Relationships struct {
Folders struct {
Links struct {
Related string `json:"related"`
} `json:"links"`
} `json:"folders"`
} `json:"relationships"`
}
type studIPFoldersResponse struct {
Data []struct {
Attributes struct {
FolderType string `json:"folder-type"`
IsReadable bool `json:"is-readable"`
IsWritable bool `json:"is-writable"`
} `json:"attributes"`
} `json:"data"`
}
func TestAgainstContainer() error {
err := runCommandWithEnv(nil, "git", "submodule", "update", "--init", "--recursive")
if err != nil {
return err
}
if err := os.MkdirAll(outputDir, 0o755); err != nil {
return fmt.Errorf("create output dir %q: %w", outputDir, err)
}
config, course, err := prepareStudIPTestEnvironment()
if err != nil {
return err
}
fmt.Printf(">> using Stud.IP demo account %q\n", config.Username)
fmt.Printf(">> using demo course %q (%s)\n", course.Attributes.Title, course.ID)
fmt.Printf(">> wrote rclone config to %s\n", config.ConfigPath)
fmt.Printf(">> running backend tests: RCLONE_CONFIG=%s go test -parallel=1 -v -count=1 ./backend/studip/studip_test.go\n", config.ConfigPath)
defer func() {
fmt.Println(">> stopping Stud.IP demo stack")
if downErr := runCommandWithEnv(nil, "docker", "compose", "--progress", "plain", "down", "--volumes", "--remove-orphans"); downErr != nil {
fmt.Fprintf(os.Stderr, "failed to stop Stud.IP demo stack: %v\n", downErr)
}
}()
err = runCommandWithEnv(
[]string{"RCLONE_CONFIG=" + config.ConfigPath},
"go", "test", "-parallel=16", "-v", "-count=1", "./backend/studip/studip_test.go",
)
if err != nil {
return err
}
err = runCommandWithEnv(
[]string{"RCLONE_CONFIG=" + config.ConfigPath},
"go", "-C", "fs/sync", "test", "-parallel=16", "-remote", "TestStudIP:fs/sync", "-v", "-count=1",
)
if err != nil {
return err
}
err = runCommandWithEnv(
[]string{"RCLONE_CONFIG=" + config.ConfigPath},
"go", "-C", "fs/sync", "test", "-parallel=16", "-remote", "TestStudIP:fs/operations", "-v", "-count=1",
)
if err != nil {
return err
}
return nil
}
func BuildPluginAndStandaloneBinary() error {
if err := Plugin(); err != nil {
return err
}
return Standalone()
}
func Plugin() error {
if runtime.GOOS == "windows" {
return fmt.Errorf("go plugin buildmode is not supported on windows")
}
if err := os.MkdirAll(outputDir, 0o755); err != nil {
return fmt.Errorf("create output dir %q: %w", outputDir, err)
}
repoRoot, err := os.Getwd()
if err != nil {
return fmt.Errorf("resolve repo root: %w", err)
}
repoRoot, err = filepath.Abs(repoRoot)
if err != nil {
return fmt.Errorf("resolve absolute repo root: %w", err)
}
rcloneModuleDir, err := goModuleDir(rcloneModulePath)
if err != nil {
return err
}
buildTree := pluginBuildTreePath()
if err := os.RemoveAll(buildTree); err != nil {
return fmt.Errorf("remove old plugin build tree: %w", err)
}
if err := copyDirWritable(rcloneModuleDir, buildTree); err != nil {
return fmt.Errorf("copy rclone module tree: %w", err)
}
if err := writePluginEntrypoint(buildTree); err != nil {
return err
}
if err := preparePluginModfile(buildTree, repoRoot); err != nil {
return err
}
return runInDirWithEnv(
buildTree,
[]string{"GOEXPERIMENT=" + goExperiment},
"go", "build",
"-modfile="+pluginModFileName,
"-trimpath",
"-buildmode=plugin",
"-o", filepath.Join(repoRoot, pluginOutputPath()),
"./"+pluginEntrypointDir,
)
}
func InstallPlugin() error {
if err := Plugin(); err != nil {
return err
}
dst, err := installedPluginPath()
if err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {
return fmt.Errorf("create plugin dir: %w", err)
}
data, err := os.ReadFile(pluginOutputPath())
if err != nil {
return err
}
err = os.WriteFile(dst, data, 0o644)
if err != nil {
return err
}
fmt.Printf(">> installed plugin to %s\n", dst)
return nil
}
func UninstallPlugin() error {
dst, err := installedPluginPath()
if err != nil {
return err
}
if err := os.Remove(dst); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("remove installed plugin %q: %w", dst, err)
}
fmt.Printf(">> removed plugin from %s\n", dst)
return nil
}
func Standalone() error {
if err := os.MkdirAll(outputDir, 0o755); err != nil {
return fmt.Errorf("create output dir %q: %w", outputDir, err)
}
type target struct {
goos string
goarch string
}
targets := []target{
{goos: "linux", goarch: "amd64"},
{goos: "linux", goarch: "arm64"},
{goos: "windows", goarch: "amd64"},
{goos: "windows", goarch: "arm64"},
{goos: "darwin", goarch: "amd64"},
{goos: "darwin", goarch: "arm64"},
}
for _, t := range targets {
out := binaryOutputPathFor(t.goos, t.goarch)
env := []string{
"GOEXPERIMENT=" + goExperiment,
"GOOS=" + t.goos,
"GOARCH=" + t.goarch,
"CGO_ENABLED=0",
}
if err := runCommandWithEnv(
env,
"go", "build", "-o", out, ".",
); err != nil {
return fmt.Errorf("build %s/%s: %w", t.goos, t.goarch, err)
}
}
return nil
}
func binaryOutputPathFor(goos, goarch string) string {
name := fmt.Sprintf("rclone-studip-%s-%s", goos, goarch)
if goos == "windows" {
name += ".exe"
}
return filepath.Join(outputDir, name)
}
func RunStandalone(args ...string) error {
if err := Standalone(); err != nil {
return err
}
emptyPluginDir, err := os.MkdirTemp("", "rclone-empty-plugins-*")
if err != nil {
return fmt.Errorf("create empty plugin dir: %w", err)
}
defer os.RemoveAll(emptyPluginDir)
return runCommandWithEnv(
[]string{"RCLONE_PLUGIN_PATH=" + emptyPluginDir},
binaryOutputPath(),
args...,
)
}
func Clean() error {
for _, artifact := range []string{pluginOutputPath(), binaryOutputPath()} {
if err := os.Remove(artifact); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("remove %q: %w", artifact, err)
}
}
if err := os.RemoveAll(pluginBuildTreePath()); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("remove %q: %w", pluginBuildTreePath(), err)
}
return nil
}
func prepareStudIPTestEnvironment() (studIPTestConfig, studIPCourse, error) {
config := studIPTestConfig{
BaseURL: envOrDefault("STUDIP_TEST_BASE_URL", studIPDemoBaseURL),
Username: envOrDefault("STUDIP_TEST_USERNAME", studIPDemoUsername),
Password: envOrDefault("STUDIP_TEST_PASSWORD", studIPDemoPassword),
License: envOrDefault("STUDIP_TEST_LICENSE", studIPDemoLicense),
ConfigPath: envOrDefault("RCLONE_CONFIG", filepath.Join(outputDir, studIPConfigName)),
}
configPath, err := filepath.Abs(config.ConfigPath)
if err != nil {
return config, studIPCourse{}, fmt.Errorf("resolve rclone config path: %w", err)
}
config.ConfigPath = configPath
if err := recreateStudIPDemoStack(); err != nil {
return config, studIPCourse{}, err
}
var course studIPCourse
course, err = waitForStudIPDemoCourse(config.BaseURL, config.Username, config.Password, 2*time.Minute)
if err != nil {
return config, studIPCourse{}, err
}
config.CourseID = course.ID
if err := writeStudIPTestConfig(config); err != nil {
return config, studIPCourse{}, err
}
return config, course, nil
}
func recreateStudIPDemoStack() error {
fmt.Println(">> recreating fresh Stud.IP demo stack")
if err := runCommandWithEnv(nil, "docker", "compose", "--progress", "plain", "down", "--volumes", "--remove-orphans"); err != nil {
return err
}
return runCommandWithEnv(nil, "docker", "compose", "--progress", "plain", "up", "-d", "--build")
}
func waitForStudIPDemoCourse(baseURL, username, password string, timeout time.Duration) (studIPCourse, error) {
var (
course studIPCourse
lastErr error
)
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
course, lastErr = discoverStudIPDemoCourse(baseURL, username, password)
if lastErr == nil {
return course, nil
}
time.Sleep(2 * time.Second)
}
if lastErr == nil {
lastErr = errors.New("no writable demo course became available")
}
return studIPCourse{}, fmt.Errorf("wait for Stud.IP demo course: %w", lastErr)
}
func waitForStudIPCourse(baseURL, username, password, courseID string, timeout time.Duration) (studIPCourse, error) {
var (
course studIPCourse
lastErr error
)
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
course, lastErr = fetchStudIPCourse(baseURL, username, password, courseID)
if lastErr == nil {
lastErr = verifyStudIPCourseFolders(baseURL, username, password, courseID)
}
if lastErr == nil {
return course, nil
}
time.Sleep(2 * time.Second)
}
if lastErr == nil {
lastErr = fmt.Errorf("course %q never became readable", courseID)
}
return studIPCourse{}, fmt.Errorf("wait for Stud.IP course %q: %w", courseID, lastErr)
}
func discoverStudIPDemoCourse(baseURL, username, password string) (studIPCourse, error) {
courses, err := fetchStudIPCourses(baseURL, username, password)
if err != nil {
return studIPCourse{}, err
}
var lastErr error
for _, course := range courses.Data {
if strings.TrimSpace(course.Relationships.Folders.Links.Related) == "" {
continue
}
if err := verifyStudIPCourseFolders(baseURL, username, password, course.ID); err != nil {
lastErr = err
continue
}
return course, nil
}
if lastErr != nil {
return studIPCourse{}, lastErr
}
return studIPCourse{}, errors.New("courses endpoint returned no course with folder access")
}
func fetchStudIPCourses(baseURL, username, password string) (*studIPCoursesResponse, error) {
response := new(studIPCoursesResponse)
if err := studIPGetJSON(baseURL, username, password, "courses", response); err != nil {
return nil, err
}
return response, nil
}
func fetchStudIPCourse(baseURL, username, password, courseID string) (studIPCourse, error) {
var response struct {
Data studIPCourse `json:"data"`
}
if err := studIPGetJSON(baseURL, username, password, fmt.Sprintf("courses/", courseID), &response); err != nil {
return studIPCourse{}, err
}
return response.Data, nil
}
func verifyStudIPCourseFolders(baseURL, username, password, courseID string) error {
response := new(studIPFoldersResponse)
if err := studIPGetJSON(baseURL, username, password, fmt.Sprintf("courses/%s/folders", courseID), response); err != nil {
return err
}
for _, folder := range response.Data {
if folder.Attributes.FolderType != "RootFolder" {
continue
}
if !folder.Attributes.IsReadable {
return fmt.Errorf("course %q root folder is not readable", courseID)
}
if !folder.Attributes.IsWritable {
return fmt.Errorf("course %q root folder is not writable", courseID)
}
return nil
}
return fmt.Errorf("course %q has no root folder in the folders response", courseID)
}
func studIPGetJSON(baseURL, username, password, relativePath string, out any) error {
requestURL, err := studIPAPIURL(baseURL, relativePath)
if err != nil {
return err
}
req, err := http.NewRequest(http.MethodGet, requestURL, nil)
if err != nil {
return fmt.Errorf("create request %q: %w", requestURL, err)
}
req.SetBasicAuth(username, password)
req.Header.Set("Accept", "application/vnd.api+json")
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("GET %s failed: %w", requestURL, err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("GET %s returned %s: %s", requestURL, resp.Status, strings.TrimSpace(string(body)))
}
if err := json.NewDecoder(resp.Body).Decode(out); err != nil {
return fmt.Errorf("decode %s response: %w", requestURL, err)
}
return nil
}
func studIPAPIURL(baseURL, relativePath string) (string, error) {
base, err := url.Parse(strings.TrimSpace(baseURL))
if err != nil {
return "", fmt.Errorf("parse Stud.IP base URL %q: %w", baseURL, err)
}
relativePath = strings.TrimLeft(strings.TrimSpace(relativePath), "/")
ref, err := url.Parse(relativePath)
if err != nil {
return "", fmt.Errorf("parse Stud.IP relative path %q: %w", relativePath, err)
}
return base.ResolveReference(ref).String(), nil
}
func writeStudIPTestConfig(config studIPTestConfig) error {
if err := os.MkdirAll(filepath.Dir(config.ConfigPath), 0o755); err != nil {
return fmt.Errorf("create rclone config dir: %w", err)
}
obscuredPassword, err := obscure.Obscure(config.Password)
if err != nil {
return fmt.Errorf("obscure Stud.IP password: %w", err)
}
data := strings.Join([]string{
"[TestStudIP]",
"type = studip",
"base_url = " + config.BaseURL,
"username = " + config.Username,
"password = " + obscuredPassword,
"course_id = " + config.CourseID,
"license = " + config.License,
"",
}, "\n")
if err := os.WriteFile(config.ConfigPath, []byte(data), 0o600); err != nil {
return fmt.Errorf("write rclone config %q: %w", config.ConfigPath, err)
}
return nil
}
func envOrDefault(key, fallback string) string {
if value := strings.TrimSpace(os.Getenv(key)); value != "" {
return value
}
return fallback
}
func installedPluginPath() (string, error) {
if p := os.Getenv("RCLONE_PLUGIN_PATH"); p != "" {
return filepath.Join(p, pluginName), nil
}
return "", errors.New("RCLONE_PLUGIN_PATH not set")
}
func runInDirWithEnv(dir string, extraEnv []string, name string, args ...string) error {
cmd := exec.Command(name, args...)
cmd.Dir = dir
cmd.Env = append(os.Environ(), extraEnv...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("command failed in %s: %s %s: %w", dir, name, strings.Join(args, " "), err)
}
return nil
}
func runCommandWithEnv(extraEnv []string, name string, args ...string) error {
cmd := exec.Command(name, args...)
cmd.Env = append(os.Environ(), extraEnv...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("command failed: %s %s: %w", name, strings.Join(args, " "), err)
}
return nil
}
func goModuleDir(module string) (string, error) {
cmd := exec.Command("go", "list", "-m", "-f", "{{.Dir}}", module)
out, err := cmd.CombinedOutput()
if err != nil {
return "", fmt.Errorf("go list module dir for %q failed: %w\n%s", module, err, strings.TrimSpace(string(out)))
}
dir := strings.TrimSpace(string(out))
if dir != "" {
return dir, nil
}
cmd = exec.Command("go", "mod", "download", "-json", module)
out, err = cmd.CombinedOutput()
if err != nil {
return "", fmt.Errorf("go mod download for %q failed: %w\n%s", module, err, strings.TrimSpace(string(out)))
}
var meta struct {
Dir string `json:"Dir"`
}
if err := json.Unmarshal(out, &meta); err != nil {
return "", fmt.Errorf("parse go mod download output for %q: %w\n%s", module, err, strings.TrimSpace(string(out)))
}
if strings.TrimSpace(meta.Dir) == "" {
return "", fmt.Errorf("empty module dir for %q", module)
}
return strings.TrimSpace(meta.Dir), nil
}
func copyDirWritable(src, dst string) error {
if err := os.MkdirAll(dst, 0o755); err != nil {
return err
}
return filepath.WalkDir(src, func(path string, d os.DirEntry, walkErr error) error {
if walkErr != nil {
return walkErr
}
rel, err := filepath.Rel(src, path)
if err != nil {
return err
}
if rel == "." {
return nil
}
dstPath := filepath.Join(dst, rel)
info, err := d.Info()
if err != nil {
return err
}
if d.IsDir() {
return os.MkdirAll(dstPath, 0o755)
}
if info.Mode()&os.ModeSymlink != 0 {
target, err := os.Readlink(path)
if err != nil {
return err
}
return os.Symlink(target, dstPath)
}
if !info.Mode().IsRegular() {
return nil
}
data, err := os.ReadFile(path)
if err != nil {
return err
}
return os.WriteFile(dstPath, data, 0o644)
})
}
func writePluginEntrypoint(buildTree string) error {
entryDir := filepath.Join(buildTree, pluginEntrypointDir)
if err := os.MkdirAll(entryDir, 0o755); err != nil {
return fmt.Errorf("create plugin entrypoint dir: %w", err)
}
entryFile := filepath.Join(entryDir, "main.go")
if err := os.WriteFile(entryFile, []byte(pluginEntrypointSrc), 0o644); err != nil {
return fmt.Errorf("write plugin entrypoint: %w", err)
}
return nil
}
func preparePluginModfile(buildTree, repoRoot string) error {
modFile := filepath.Join(buildTree, pluginModFileName)
sumFile := filepath.Join(buildTree, pluginSumFileName)
data, err := os.ReadFile(filepath.Join(buildTree, "go.mod"))
if err != nil {
return err
}
err = os.WriteFile(modFile, data, 0o644)
if err != nil {
return err
}
data, err = os.ReadFile(filepath.Join(buildTree, "go.sum"))
if err != nil {
return err
}
err = os.WriteFile(sumFile, data, 0o644)
if err != nil {
return err
}
if err := runInDirWithEnv(
buildTree,
nil,
"go", "mod", "edit",
"-modfile="+pluginModFileName,
"-require="+studipModulePath+"@v0.0.0",
); err != nil {
return fmt.Errorf("configure plugin modfile require: %w", err)
}
if err := runInDirWithEnv(
buildTree,
nil,
"go", "mod", "edit",
"-modfile="+pluginModFileName,
"-replace="+studipModulePath+"="+repoRoot,
); err != nil {
return fmt.Errorf("configure plugin modfile replace: %w", err)
}
if err := runInDirWithEnv(
buildTree,
[]string{"GOEXPERIMENT=" + goExperiment},
"go", "mod", "tidy",
"-modfile="+pluginModFileName,
); err != nil {
return fmt.Errorf("tidy plugin modfile: %w", err)
}
return nil
}
func pluginOutputPath() string { return filepath.Join(outputDir, pluginName) }
func binaryOutputPath() string { return filepath.Join(outputDir, binaryName) }
func pluginBuildTreePath() string { return filepath.Join(outputDir, pluginBuildTreeDir) }
|