forked from arduino/arduino-cli
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsketch.go
319 lines (285 loc) · 10.2 KB
/
sketch.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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
// This file is part of arduino-cli.
//
// Copyright 2020 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 sketch
import (
"crypto/md5"
"encoding/hex"
"errors"
"fmt"
"sort"
"strings"
"github.com/arduino/arduino-cli/commands/cmderrors"
f "github.com/arduino/arduino-cli/internal/algorithms"
"github.com/arduino/arduino-cli/internal/arduino/globals"
"github.com/arduino/arduino-cli/internal/i18n"
rpc "github.com/arduino/arduino-cli/rpc/cc/arduino/cli/commands/v1"
"github.com/arduino/go-paths-helper"
)
// Sketch holds all the files composing a sketch
type Sketch struct {
Name string
MainFile *paths.Path
FullPath *paths.Path // FullPath is the path to the Sketch folder
OtherSketchFiles paths.PathList // Sketch files that end in .ino other than main file
AdditionalFiles paths.PathList
RootFolderFiles paths.PathList // All files that are in the Sketch root
Project *Project
}
// New creates an Sketch instance by reading all the files composing a sketch and grouping them
// by file type.
func New(path *paths.Path) (*Sketch, error) {
if path == nil {
return nil, errors.New(i18n.Tr("sketch path is not valid"))
}
path = path.Canonical()
if exist, err := path.ExistCheck(); err != nil {
return nil, fmt.Errorf("%s: %w", i18n.Tr("sketch path is not valid"), err)
} else if !exist {
return nil, fmt.Errorf("%s: %s", i18n.Tr("no such file or directory"), path)
}
if globals.MainFileValidExtensions[path.Ext()] && !path.IsDir() {
path = path.Parent()
}
var mainFile *paths.Path
for ext := range globals.MainFileValidExtensions {
candidateSketchMainFile := path.Join(path.Base() + ext)
if candidateSketchMainFile.Exist() {
if mainFile == nil {
mainFile = candidateSketchMainFile
} else {
return nil, errors.New(i18n.Tr("multiple main sketch files found (%[1]v, %[2]v)",
mainFile,
candidateSketchMainFile,
))
}
}
}
if mainFile == nil {
return nil, errors.New(i18n.Tr("main file missing from sketch: %s", path.Join(path.Base()+globals.MainFileValidExtension)))
}
sketch := &Sketch{
Name: path.Base(),
MainFile: mainFile,
FullPath: path,
OtherSketchFiles: paths.PathList{},
AdditionalFiles: paths.PathList{},
RootFolderFiles: paths.PathList{},
Project: &Project{},
}
if projectFile := sketch.GetProjectPath(); projectFile.Exist() {
prj, err := LoadProjectFile(projectFile)
if err != nil {
return nil, fmt.Errorf("%s %w", i18n.Tr("error loading sketch project file:"), err)
}
sketch.Project = prj
}
err := sketch.checkSketchCasing()
if e, ok := err.(*InvalidSketchFolderNameError); ok {
return nil, e
}
if err != nil {
return nil, err
}
sketchFolderFiles, err := sketch.supportedFiles()
if err != nil {
return nil, fmt.Errorf("%s: %w", i18n.Tr("reading sketch files"), err)
}
// Collect files
for _, p := range sketchFolderFiles {
ext := p.Ext()
if globals.MainFileValidExtensions[ext] {
if p.EqualsTo(mainFile) {
// The main file must not be included in the lists of other files
continue
}
// file is a valid sketch file, see if it's stored at the
// sketch root and ignore if it's not.
if p.Parent().EqualsTo(path) {
sketch.OtherSketchFiles.Add(p)
sketch.RootFolderFiles.Add(p)
}
} else if globals.AdditionalFileValidExtensions[ext] {
// If the user exported the compiles binaries to the Sketch "build" folder
// they would be picked up but we don't want them, so we skip them like so
if ok, _ := p.IsInsideDir(sketch.FullPath.Join("build")); ok {
continue
}
sketch.AdditionalFiles.Add(p)
if p.Parent().EqualsTo(path) {
sketch.RootFolderFiles.Add(p)
}
} else {
return nil, errors.New(i18n.Tr("unknown sketch file extension '%s'", ext))
}
}
sort.Sort(&sketch.AdditionalFiles)
sort.Sort(&sketch.OtherSketchFiles)
sort.Sort(&sketch.RootFolderFiles)
return sketch, nil
}
// supportedFiles reads all files recursively contained in Sketch and
// filter out unneded or unsupported ones and returns them
func (s *Sketch) supportedFiles() (paths.PathList, error) {
filterValidExtensions := func(p *paths.Path) bool {
return globals.MainFileValidExtensions[p.Ext()] || globals.AdditionalFileValidExtensions[p.Ext()]
}
filterOutBuildPaths := func(p *paths.Path) bool {
return !p.Join("build.options.json").Exist()
}
files, err := s.FullPath.ReadDirRecursiveFiltered(
filterOutBuildPaths,
paths.AndFilter(
paths.FilterOutPrefixes("."),
filterValidExtensions,
paths.FilterOutDirectories(),
),
)
if err != nil {
return nil, err
}
return files, nil
}
// GetProfile returns the requested profile or an error if not found
func (s *Sketch) GetProfile(profileName string) (*Profile, error) {
for _, p := range s.Project.Profiles {
if p.Name == profileName {
return p, nil
}
}
return nil, &cmderrors.UnknownProfileError{Profile: profileName}
}
// checkSketchCasing returns an error if the casing of the sketch folder and the main file are different.
// Correct:
//
// MySketch/MySketch.ino
//
// Wrong:
//
// MySketch/mysketch.ino
// mysketch/MySketch.ino
//
// This is mostly necessary to avoid errors on Mac OS X.
// For more info see: https://github.com/arduino/arduino-cli/issues/1174
func (s *Sketch) checkSketchCasing() error {
files, err := s.FullPath.ReadDir()
if err != nil {
return fmt.Errorf("%s: %w", i18n.Tr("reading files"), err)
}
files.FilterOutDirs()
candidateFileNames := []string{}
for ext := range globals.MainFileValidExtensions {
candidateFileNames = append(candidateFileNames, fmt.Sprintf("%s%s", s.Name, ext))
}
files.FilterPrefix(candidateFileNames...)
if files.Len() == 0 {
sketchFile := s.FullPath.Join(s.Name + globals.MainFileValidExtension)
return &InvalidSketchFolderNameError{
SketchFolder: s.FullPath,
SketchFile: sketchFile,
}
}
return nil
}
// GetProjectPath returns the path to the sketch project file (sketch.yaml or sketch.yml)
func (s *Sketch) GetProjectPath() *paths.Path {
projectFile := s.FullPath.Join("sketch.yaml")
if !projectFile.Exist() {
alternateProjectFile := s.FullPath.Join("sketch.yml")
if alternateProjectFile.Exist() {
return alternateProjectFile
}
}
return projectFile
}
// GetDefaultFQBN returns the default FQBN for the sketch (from the sketch.yaml project file), or the
// empty string if not set.
func (s *Sketch) GetDefaultFQBN() string {
return s.Project.DefaultFqbn
}
// GetDefaultPortAddressAndProtocol returns the default port address and port protocol for the sketch
// (from the sketch.yaml project file), or empty strings if not set.
func (s *Sketch) GetDefaultPortAddressAndProtocol() (string, string) {
return s.Project.DefaultPort, s.Project.DefaultProtocol
}
// GetDefaultProgrammer return the default Programmer for the sketch (from the sketch.yaml project file),
// ore the empty string if not set.
func (s *Sketch) GetDefaultProgrammer() string {
return s.Project.DefaultProgrammer
}
// SetDefaultFQBN sets the default FQBN for the sketch and saves it in the sketch.yaml project file.
func (s *Sketch) SetDefaultFQBN(fqbn string) error {
s.Project.DefaultFqbn = fqbn
return updateOrAddYamlRootEntry(s.GetProjectPath(), "default_fqbn", fqbn)
}
// SetDefaultPort sets the default port address and port protocol for the sketch and saves it in the
// sketch.yaml project file.
func (s *Sketch) SetDefaultPort(address, protocol string) error {
s.Project.DefaultPort = address
s.Project.DefaultProtocol = protocol
if err := updateOrAddYamlRootEntry(s.GetProjectPath(), "default_port", address); err != nil {
return err
}
return updateOrAddYamlRootEntry(s.GetProjectPath(), "default_protocol", protocol)
}
// SetDefaultFQBN sets the default programmer for the sketch and saves it in the sketch.yaml project file.
func (s *Sketch) SetDefaultProgrammer(programmer string) error {
s.Project.DefaultProgrammer = programmer
return updateOrAddYamlRootEntry(s.GetProjectPath(), "default_programmer", programmer)
}
// InvalidSketchFolderNameError is returned when the sketch directory doesn't match the sketch name
type InvalidSketchFolderNameError struct {
SketchFolder *paths.Path
SketchFile *paths.Path
}
func (e *InvalidSketchFolderNameError) Error() string {
return i18n.Tr("no valid sketch found in %[1]s: missing %[2]s", e.SketchFolder, e.SketchFile)
}
// Hash generate a unique hash for the given sketch.
func (s *Sketch) Hash() string {
path := s.FullPath.String()
md5SumBytes := md5.Sum([]byte(path))
return strings.ToUpper(hex.EncodeToString(md5SumBytes[:]))
}
// ToRpc converts this Sketch into a rpc.LoadSketchResponse
func (s *Sketch) ToRpc() *rpc.Sketch {
defaultPort, defaultProtocol := s.GetDefaultPortAddressAndProtocol()
var defaultPortConfig *rpc.MonitorPortConfiguration
if len(s.Project.DefaultPortConfig) > 0 {
defaultPortConfig = &rpc.MonitorPortConfiguration{}
for k, v := range s.Project.DefaultPortConfig {
defaultPortConfig.Settings = append(defaultPortConfig.Settings, &rpc.MonitorPortSetting{
SettingId: k,
Value: v,
})
}
}
res := &rpc.Sketch{
MainFile: s.MainFile.String(),
LocationPath: s.FullPath.String(),
OtherSketchFiles: s.OtherSketchFiles.AsStrings(),
AdditionalFiles: s.AdditionalFiles.AsStrings(),
RootFolderFiles: s.RootFolderFiles.AsStrings(),
DefaultFqbn: s.GetDefaultFQBN(),
DefaultPort: defaultPort,
DefaultPortConfig: defaultPortConfig,
DefaultProtocol: defaultProtocol,
DefaultProgrammer: s.GetDefaultProgrammer(),
Profiles: f.Map(s.Project.Profiles, (*Profile).ToRpc),
}
if defaultProfile, err := s.GetProfile(s.Project.DefaultProfile); err == nil {
res.DefaultProfile = defaultProfile.ToRpc()
}
return res
}