GitRoot

craft your forge, build your project, grow your community freely
 1// SPDX-FileCopyrightText: 2025 Romain Maneschi <romain@gitroot.dev>
 2//
 3// SPDX-License-Identifier: EUPL-1.2
 4
 5package plugin
 6
 7import (
 8	"context"
 9	"encoding/json"
10	"io/fs"
11
12	"github.com/go-git/go-git/v5/plumbing"
13	grfs "gitroot.dev/server/fs"
14	"gitroot.dev/server/logger"
15	"gitroot.dev/server/repository"
16)
17
18func (r *runtime) sendReports(ctx context.Context, repo *repository.GitRootRepository, repoWriter *repository.GitRootRepositoryWrite, plugins []Plugin) {
19	r.logger.Debug("start sendReports", logger.NewLoggerPair("nb reports", len(r.reports)))
20	r.repo = repo
21	r.repoWriter = repoWriter
22	r.command = nil
23
24	fs := grfs.NewMultiple(ctx, map[string]fs.FS{
25		"worktree":   r.repoWriter.ToFs(ctx),
26		"webcontent": r.manager.conf.DataWeb(r.repo.Name()),
27	})
28
29	currentBranch, err := repo.CurrentBranch()
30	if err != nil {
31		r.logger.Error("can't get current branch for sendReport", err)
32		return
33	}
34
35	for _, plugin := range plugins {
36		fs.UpdateSubFs("cache", r.manager.conf.Cache(r.repo.Name(), plugin.Name))
37		r.plugin = plugin
38		m, err := r.loadModule(r.ctx, plugin, fs)
39		if err != nil {
40			r.logger.Error("loadModule for sendReports error", err, logger.NewLoggerPair("name", plugin.Name))
41			continue
42		}
43
44		reporter := m.ExportedFunction("report")
45		if reporter == nil {
46			r.logger.Debug("not a reporter", logger.NewLoggerPair("plugin", plugin.Name))
47			continue
48		}
49
50		malloc := m.ExportedFunction("gitrootAlloc")
51		if malloc == nil {
52			malloc = m.ExportedFunction("malloc")
53		}
54
55		for _, report := range r.reports {
56			for _, pluginRun := range plugin.Run {
57				isAuthorized := checkBranch(pluginRun, plumbing.NewBranchReferenceName(report.FromBranch))
58				if !isAuthorized {
59					continue
60				}
61				r.pluginRun = pluginRun
62
63				if err := repoWriter.Checkout(plumbing.NewBranchReferenceName(report.FromBranch)); err != nil {
64					r.logger.Error("can't Checkout from report", err, logger.NewLoggerPair("branch", report.FromBranch))
65					continue
66				}
67
68				reportJson, err := json.Marshal(report)
69				if err != nil {
70					r.logger.Error("can't marshal report", err, logger.NewLoggerPair("name", plugin.Name))
71					continue
72				}
73
74				if err := r.writeMemoryAndCall(m, reporter, malloc, string(reportJson)); err != nil {
75					r.logger.Error("can't report to plugin", err, logger.NewLoggerPair("plugin", plugin.Name))
76					continue
77				}
78			}
79		}
80	}
81
82	if err := repoWriter.Checkout(currentBranch); err != nil {
83		r.logger.Error("can't Checkout to current branch report", err, logger.NewLoggerPair("branch", currentBranch.Short()))
84	}
85}