forked from arduino/arduino-cli
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsketches.go
91 lines (81 loc) · 2.54 KB
/
sketches.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
// 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 sketches
import (
"encoding/json"
"fmt"
"github.com/arduino/go-paths-helper"
)
// Sketch is a sketch for Arduino
type Sketch struct {
Name string
FullPath *paths.Path
Metadata *Metadata
}
// Metadata is the kind of data associated to a project such as the connected board
type Metadata struct {
CPU BoardMetadata `json:"cpu,omitempty" gorethink:"cpu"`
}
// BoardMetadata represents the board metadata for the sketch
type BoardMetadata struct {
Fqbn string `json:"fqbn,required"`
Name string `json:"name,omitempty"`
Port string `json:"port,omitepty"`
}
// NewSketchFromPath loads a sketch from the specified path
func NewSketchFromPath(path *paths.Path) (*Sketch, error) {
if !path.IsDir() {
path = path.Parent()
}
sketch := &Sketch{
FullPath: path,
Name: path.Base(),
Metadata: &Metadata{},
}
sketch.ImportMetadata()
return sketch, nil
}
// ImportMetadata imports metadata into the sketch from a sketch.json file in the root
// path of the sketch.
func (s *Sketch) ImportMetadata() error {
sketchJSON := s.FullPath.Join("sketch.json")
content, err := sketchJSON.ReadFile()
if err != nil {
return fmt.Errorf("reading sketch metadata %s: %s", sketchJSON, err)
}
var meta Metadata
err = json.Unmarshal(content, &meta)
if err != nil {
if s.Metadata == nil {
s.Metadata = new(Metadata)
}
return fmt.Errorf("encoding sketch metadata: %s", err)
}
s.Metadata = &meta
return nil
}
// ExportMetadata writes sketch metadata into a sketch.json file in the root path of
// the sketch
func (s *Sketch) ExportMetadata() error {
d, err := json.MarshalIndent(&s.Metadata, "", " ")
if err != nil {
return fmt.Errorf("decoding sketch metadata: %s", err)
}
sketchJSON := s.FullPath.Join("sketch.json")
if err := sketchJSON.WriteFile(d); err != nil {
return fmt.Errorf("writing sketch metadata %s: %s", sketchJSON, err)
}
return nil
}