1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3package domain
4
5import (
6 "errors"
7 "fmt"
8 "path"
9 "strings"
10 "unicode"
11)
12
13// WorkflowDir is the only directory the workflows of a repository are read
14// from (ADR 0019: no ermite dialect).
15const WorkflowDir = ".github/workflows"
16
17// maxWorkflowFileName bounds the file name of a workflow, as a file name of
18// Git trees is bounded on the usual file systems.
19const maxWorkflowFileName = 255
20
21// ErrWorkflowDisabled is returned by the store when a run is created for a
22// workflow the repository disabled. It is checked in the very transaction that
23// creates the run, so no disable can slip in between a check and the creation.
24var ErrWorkflowDisabled = errors.New("workflow is disabled")
25
26// ParseWorkflowPath normalizes the name of a workflow file, as `gh workflow`
27// takes it: either its file name ("release.yml") or its path
28// (".github/workflows/release.yml"). It returns the canonical path, and
29// refuses every other spelling of it ("./.github/workflows/x.yml",
30// ".github/workflows//x.yml", ".github/workflows/sub/../x.yml"), so one file has
31// one key. Only the shape is checked, never whether the file exists: the state
32// of a workflow can be set on a repository that is empty or that does not hold
33// the file yet. A file in a subdirectory, a name that does not end in .yml or
34// .yaml, and a name with a control character or a backslash are ErrInvalid.
35func ParseWorkflowPath(s string) (string, error) {
36 s = strings.TrimSpace(s)
37 if s == "" {
38 return "", fmt.Errorf("%w: the workflow file is required", ErrInvalid)
39 }
40 if !strings.Contains(s, "/") {
41 s = WorkflowDir + "/" + s
42 }
43 name, ok := strings.CutPrefix(s, WorkflowDir+"/")
44 ext := strings.ToLower(path.Ext(name))
45 switch {
46 case !ok,
47 strings.Contains(name, "/"),
48 ext != ".yml" && ext != ".yaml",
49 strings.TrimSuffix(name, path.Ext(name)) == "",
50 len(name) > maxWorkflowFileName,
51 strings.ContainsFunc(name, func(r rune) bool { return unicode.IsControl(r) || r == '\\' }):
52 return "", fmt.Errorf("%w: %q is not a workflow file of %s (a file name or the path %s/<file>, ending in .yml or .yaml)", ErrInvalid, s, WorkflowDir, WorkflowDir)
53 }
54 return s, nil
55}