1
2
3
4
5
6
7 package vcscmd
8
9 import (
10 "errors"
11 "fmt"
12 "path/filepath"
13 "slices"
14 "strings"
15 )
16
17 func New(bin lit, words ...lit) *Command {
18 if bin == "" {
19 return &Command{err: errors.New("empty command name")}
20 }
21 return (&Command{argv: []string{string(bin)}}).Add(words...)
22 }
23
24
25 type lit string
26
27
28
29 type Command struct {
30 argv []string
31 separated bool
32 err error
33 }
34
35
36
37
38 func (c *Command) Add(words ...lit) *Command {
39 if !c.beforeOperands() {
40 return c
41 }
42 for _, w := range words {
43 if w == "--" || w == "--end-of-options" {
44 c.err = fmt.Errorf("unexpected operand separator %q", w)
45 return c
46 }
47 c.argv = append(c.argv, string(w))
48 }
49 return c
50 }
51
52 func (c *Command) beforeOperands() bool {
53 if c.err != nil {
54 return false
55 }
56 switch {
57 case len(c.argv) == 0:
58 c.err = errors.New("empty command")
59 case c.separated:
60 c.err = errors.New("cannot add arguments after operands")
61 }
62 return c.err == nil
63 }
64
65
66
67
68
69
70 func (c *Command) Option(name lit, value string) *Command {
71 if !c.beforeOperands() {
72 return c
73 }
74 if c.argv[0] == "fossil" {
75 switch name {
76 case "-R":
77 if !filepath.IsAbs(value) {
78 c.err = fmt.Errorf("path %q is not absolute", value)
79 return c
80 }
81 c.argv = append(c.argv, "-R", value)
82 return c
83 case "-r":
84 c.argv = append(c.argv, "-r="+value)
85 return c
86 }
87 }
88 if !strings.HasPrefix(string(name), "--") || name == "--" || name == "--end-of-options" || strings.Contains(string(name), "=") {
89 c.err = fmt.Errorf("invalid long option name %q", name)
90 return c
91 }
92 c.argv = append(c.argv, string(name)+"="+value)
93 return c
94 }
95
96
97
98
99
100
101 func (c *Command) Operands(args ...string) *Command {
102 if !c.beforeOperands() {
103 return c
104 }
105 c.separated = true
106 if c.argv[0] == "git" {
107 c.argv = append(c.argv, "--end-of-options")
108 } else {
109 c.argv = append(c.argv, "--")
110 }
111 c.argv = append(c.argv, args...)
112 return c
113 }
114
115
116
117
118 func (c *Command) GitRevision(rev string, paths ...string) *Command {
119 if !c.beforeOperands() {
120 return c
121 }
122 if c.argv[0] != "git" {
123 c.err = errors.New("GitRevision requires a git command")
124 return c
125 }
126 if rev == "--" {
127 c.err = errors.New("Git revision cannot be --")
128 return c
129 }
130 c.separated = true
131 c.argv = append(c.argv, "--end-of-options", rev, "--")
132 c.argv = append(c.argv, paths...)
133 return c
134 }
135
136
137
138
139 func (c *Command) Build() ([]string, error) {
140 if len(c.argv) == 0 && c.err == nil {
141 return nil, errors.New("empty command")
142 }
143 return slices.Clone(c.argv), c.err
144 }
145
View as plain text