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 exec
 6
 7import (
 8	"bytes"
 9	_ "embed"
10	"encoding/json"
11	"fmt"
12	"os"
13	"path/filepath"
14
15	"github.com/samber/oops"
16	pluginLib "gitroot.dev/libs/golang/plugin/model"
17)
18
19//go:embed resources/executor-linux-amd64
20var executorLinuxAmd64 []byte
21
22const TO_REPLACE = "# {{CMD_HERE}}"
23const filename = "executor"
24
25func prepareJobRunner(dir string) error {
26	err := os.MkdirAll(filepath.Join(dir, JOB_CONTEXT_DIR), os.ModePerm)
27	if err != nil {
28		return oops.Wrapf(err, "can't MkdirAll for jobRunner file")
29	}
30	f, err := os.OpenFile(filepath.Join(dir, JOB_CONTEXT_DIR, filename), os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0755)
31	if err != nil {
32		return oops.Wrapf(err, "can't open jobRunner file")
33	}
34	_, err = f.Write(executorLinuxAmd64)
35	if err != nil {
36		return oops.Wrapf(err, "can't write jobRunner file")
37	}
38	return f.Close()
39}
40
41func cmdToExec(exe pluginLib.Exec, protectArg bool) ([]string, error) {
42	j, err := json.Marshal(exe)
43	if err != nil {
44		return nil, oops.Wrapf(err, "can't Marshal cmdToExe")
45	}
46	if protectArg {
47		argsProtect := fmt.Sprintf("'%s'", j)
48		return []string{filepath.Join("..", JOB_CONTEXT_DIR, filename), argsProtect}, nil
49	}
50	return []string{filepath.Join("..", JOB_CONTEXT_DIR, filename), string(j)}, nil
51}
52
53func parseJobLog(input []byte) (*pluginLib.ExecStatus, error) {
54	in := bytes.TrimLeftFunc(input, func(r rune) bool {
55		return r != '{'
56	})
57	res := &pluginLib.ExecStatus{}
58	err := json.Unmarshal(in, res)
59	if err != nil {
60		return nil, err
61	}
62	return res, nil
63}