-
-
Notifications
You must be signed in to change notification settings - Fork 398
/
Copy patharduino-cli.go
304 lines (273 loc) · 9.14 KB
/
arduino-cli.go
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
// This file is part of arduino-cli.
//
// Copyright 2022 ARDUINO SA (http://www.arduino.cc/)
//
// This software is released under the GNU General Public License version 3,
// which covers the main part of arduino-cli.
// The terms of this license can be found at:
// https://www.gnu.org/licenses/gpl-3.0.en.html
//
// You can be released from the requirements of the above licenses by purchasing
// a commercial license. Buying such a license is mandatory if you want to
// modify or otherwise use the software for commercial activities involving the
// Arduino software without disclosing the source code of your own applications.
// To purchase a commercial license, send an email to [email protected].
package integrationtest
import (
"bytes"
"context"
"fmt"
"io"
"os"
"strings"
"sync"
"testing"
"time"
"github.com/arduino/arduino-cli/executils"
"github.com/arduino/arduino-cli/rpc/cc/arduino/cli/commands/v1"
"github.com/arduino/go-paths-helper"
"github.com/fatih/color"
"github.com/stretchr/testify/require"
"go.bug.st/testsuite"
"google.golang.org/grpc"
)
// FindRepositoryRootPath returns the repository root path
func FindRepositoryRootPath(t *testing.T) *paths.Path {
repoRootPath := paths.New(".")
require.NoError(t, repoRootPath.ToAbs())
for !repoRootPath.Join(".git").Exist() {
require.Contains(t, repoRootPath.String(), "arduino-cli", "Error searching for repository root path")
repoRootPath = repoRootPath.Parent()
}
return repoRootPath
}
// CreateArduinoCLIWithEnvironment performs the minimum amount of actions
// to build the default test environment.
func CreateArduinoCLIWithEnvironment(t *testing.T) (*testsuite.Environment, *ArduinoCLI) {
env := testsuite.NewEnvironment(t)
cli := NewArduinoCliWithinEnvironment(env, &ArduinoCLIConfig{
ArduinoCLIPath: FindRepositoryRootPath(t).Join("arduino-cli"),
UseSharedStagingFolder: true,
})
return env, cli
}
// ArduinoCLI is an Arduino CLI client.
type ArduinoCLI struct {
path *paths.Path
t *require.Assertions
proc *executils.Process
cliEnvVars []string
cliConfigPath *paths.Path
stagingDir *paths.Path
dataDir *paths.Path
sketchbookDir *paths.Path
daemonAddr string
daemonConn *grpc.ClientConn
daemonClient commands.ArduinoCoreServiceClient
}
// ArduinoCLIConfig is the configuration of the ArduinoCLI client
type ArduinoCLIConfig struct {
ArduinoCLIPath *paths.Path
UseSharedStagingFolder bool
}
// NewArduinoCliWithinEnvironment creates a new Arduino CLI client inside the given environment.
func NewArduinoCliWithinEnvironment(env *testsuite.Environment, config *ArduinoCLIConfig) *ArduinoCLI {
color.NoColor = false
cli := &ArduinoCLI{
path: config.ArduinoCLIPath,
t: require.New(env.T()),
dataDir: env.RootDir().Join("Arduino15"),
sketchbookDir: env.RootDir().Join("Arduino"),
stagingDir: env.RootDir().Join("Arduino15/staging"),
}
if config.UseSharedStagingFolder {
cli.stagingDir = env.SharedDownloadsDir()
}
cli.cliEnvVars = []string{
fmt.Sprintf("ARDUINO_DATA_DIR=%s", cli.dataDir),
fmt.Sprintf("ARDUINO_DOWNLOADS_DIR=%s", cli.stagingDir),
fmt.Sprintf("ARDUINO_SKETCHBOOK_DIR=%s", cli.sketchbookDir),
}
env.RegisterCleanUpCallback(cli.CleanUp)
return cli
}
// CleanUp closes the Arduino CLI client.
func (cli *ArduinoCLI) CleanUp() {
if cli.proc != nil {
cli.daemonConn.Close()
cli.proc.Kill()
cli.proc.Wait()
}
}
// DataDir returns the data directory
func (cli *ArduinoCLI) DataDir() *paths.Path {
return cli.dataDir
}
// SketchbookDir returns the sketchbook directory
func (cli *ArduinoCLI) SketchbookDir() *paths.Path {
return cli.sketchbookDir
}
// Run executes the given arduino-cli command and returns the output.
func (cli *ArduinoCLI) Run(args ...string) ([]byte, []byte, error) {
if cli.cliConfigPath != nil {
args = append([]string{"--config-file", cli.cliConfigPath.String()}, args...)
}
fmt.Println(color.HiBlackString(">>> Running: ") + color.HiYellowString("%s %s", cli.path, strings.Join(args, " ")))
cliProc, err := executils.NewProcessFromPath(cli.cliEnvVars, cli.path, args...)
cli.t.NoError(err)
stdout, err := cliProc.StdoutPipe()
cli.t.NoError(err)
stderr, err := cliProc.StderrPipe()
cli.t.NoError(err)
_, err = cliProc.StdinPipe()
cli.t.NoError(err)
cli.t.NoError(cliProc.Start())
var stdoutBuf, stderrBuf bytes.Buffer
stdoutCtx, stdoutCancel := context.WithCancel(context.Background())
stderrCtx, stderrCancel := context.WithCancel(context.Background())
go func() {
io.Copy(&stdoutBuf, io.TeeReader(stdout, os.Stdout))
stdoutCancel()
}()
go func() {
io.Copy(&stderrBuf, io.TeeReader(stderr, os.Stderr))
stderrCancel()
}()
cliErr := cliProc.Wait()
<-stdoutCtx.Done()
<-stderrCtx.Done()
fmt.Println(color.HiBlackString("<<< Run completed (err = %v)", cliErr))
return stdoutBuf.Bytes(), stderrBuf.Bytes(), cliErr
}
// StartDaemon starts the Arduino CLI daemon. It returns the address of the daemon.
func (cli *ArduinoCLI) StartDaemon(verbose bool) string {
args := []string{"daemon", "--format", "json"}
if cli.cliConfigPath != nil {
args = append([]string{"--config-file", cli.cliConfigPath.String()}, args...)
}
if verbose {
args = append(args, "-v", "--log-level", "debug")
}
cliProc, err := executils.NewProcessFromPath(cli.cliEnvVars, cli.path, args...)
cli.t.NoError(err)
stdout, err := cliProc.StdoutPipe()
cli.t.NoError(err)
stderr, err := cliProc.StderrPipe()
cli.t.NoError(err)
_, err = cliProc.StdinPipe()
cli.t.NoError(err)
cli.t.NoError(cliProc.Start())
cli.proc = cliProc
cli.daemonAddr = "127.0.0.1:50051"
copy := func(dst io.Writer, src io.Reader) {
buff := make([]byte, 1024)
for {
n, err := src.Read(buff)
if err != nil {
return
}
dst.Write([]byte(color.YellowString(string(buff[:n]))))
}
}
go copy(os.Stdout, stdout)
go copy(os.Stderr, stderr)
conn, err := grpc.Dial(cli.daemonAddr, grpc.WithInsecure(), grpc.WithBlock())
cli.t.NoError(err)
cli.daemonConn = conn
cli.daemonClient = commands.NewArduinoCoreServiceClient(conn)
return cli.daemonAddr
}
// ArduinoCLIInstance is an Arduino CLI gRPC instance.
type ArduinoCLIInstance struct {
cli *ArduinoCLI
instance *commands.Instance
}
var logCallfMutex sync.Mutex
func logCallf(format string, a ...interface{}) {
logCallfMutex.Lock()
fmt.Print(color.HiRedString(format, a...))
logCallfMutex.Unlock()
}
// Create calls the "Create" gRPC method.
func (cli *ArduinoCLI) Create() *ArduinoCLIInstance {
logCallf(">>> Create()")
resp, err := cli.daemonClient.Create(context.Background(), &commands.CreateRequest{})
cli.t.NoError(err)
logCallf(" -> %v\n", resp)
return &ArduinoCLIInstance{
cli: cli,
instance: resp.Instance,
}
}
// Init calls the "Init" gRPC method.
func (inst *ArduinoCLIInstance) Init(profile string, sketchPath string, respCB func(*commands.InitResponse)) error {
initReq := &commands.InitRequest{
Instance: inst.instance,
Profile: profile,
SketchPath: sketchPath,
}
logCallf(">>> Init(%v)\n", initReq)
initClient, err := inst.cli.daemonClient.Init(context.Background(), initReq)
if err != nil {
return err
}
for {
msg, err := initClient.Recv()
if err == io.EOF {
logCallf("<<< Init EOF\n")
return nil
}
if err != nil {
return err
}
if respCB != nil {
respCB(msg)
}
}
}
// BoardList calls the "BoardList" gRPC method.
func (inst *ArduinoCLIInstance) BoardList(timeout time.Duration) (*commands.BoardListResponse, error) {
boardListReq := &commands.BoardListRequest{
Instance: inst.instance,
Timeout: timeout.Milliseconds(),
}
logCallf(">>> BoardList(%v) -> ", boardListReq)
resp, err := inst.cli.daemonClient.BoardList(context.Background(), boardListReq)
logCallf("err=%v\n", err)
return resp, err
}
// BoardListWatch calls the "BoardListWatch" gRPC method.
func (inst *ArduinoCLIInstance) BoardListWatch() (commands.ArduinoCoreService_BoardListWatchClient, error) {
boardListWatchReq := &commands.BoardListWatchRequest{
Instance: inst.instance,
}
logCallf(">>> BoardListWatch(%v)\n", boardListWatchReq)
watcher, err := inst.cli.daemonClient.BoardListWatch(context.Background())
if err != nil {
return watcher, err
}
return watcher, watcher.Send(boardListWatchReq)
}
// PlatformInstall calls the "PlatformInstall" gRPC method.
func (inst *ArduinoCLIInstance) PlatformInstall(ctx context.Context, packager, arch, version string, skipPostInst bool) (commands.ArduinoCoreService_PlatformInstallClient, error) {
installCl, err := inst.cli.daemonClient.PlatformInstall(ctx, &commands.PlatformInstallRequest{
Instance: inst.instance,
PlatformPackage: packager,
Architecture: arch,
Version: version,
SkipPostInstall: skipPostInst,
})
logCallf(">>> PlatformInstall(%v:%v %v)\n", packager, arch, version)
return installCl, err
}
// Compile calls the "Compile" gRPC method.
func (inst *ArduinoCLIInstance) Compile(ctx context.Context, fqbn, sketchPath string) (commands.ArduinoCoreService_CompileClient, error) {
compileCl, err := inst.cli.daemonClient.Compile(ctx, &commands.CompileRequest{
Instance: inst.instance,
Fqbn: fqbn,
SketchPath: sketchPath,
Verbose: true,
})
logCallf(">>> Compile(%v %v)\n", fqbn, sketchPath)
return compileCl, err
}