|
| 1 | +// This file is part of arduino-cli. |
| 2 | +// |
| 3 | +// Copyright 2019 ARDUINO SA (http://www.arduino.cc/) |
| 4 | +// |
| 5 | +// This software is released under the GNU General Public License version 3, |
| 6 | +// which covers the main part of arduino-cli. |
| 7 | +// The terms of this license can be found at: |
| 8 | +// https://www.gnu.org/licenses/gpl-3.0.en.html |
| 9 | +// |
| 10 | +// You can be released from the requirements of the above licenses by purchasing |
| 11 | +// a commercial license. Buying such a license is mandatory if you want to modify or |
| 12 | +// otherwise use the software for commercial activities involving the Arduino |
| 13 | +// software without disclosing the source code of your own applications. To purchase |
| 14 | +// a commercial license, send an email to [email protected]. |
| 15 | + |
| 16 | +package globals |
| 17 | + |
| 18 | +import ( |
| 19 | + "fmt" |
| 20 | + "strings" |
| 21 | +) |
| 22 | + |
| 23 | +// ReferenceArg represents a reference item (core or library) passed to the CLI |
| 24 | +// interface |
| 25 | +type ReferenceArg struct { |
| 26 | + PackageName string |
| 27 | + Architecture string |
| 28 | + Version string |
| 29 | +} |
| 30 | + |
| 31 | +func (r *ReferenceArg) String() string { |
| 32 | + if r.Version != "" { |
| 33 | + return r.PackageName + ":" + r.Architecture + "@" + r.Version |
| 34 | + } |
| 35 | + return r.PackageName + ":" + r.Architecture |
| 36 | +} |
| 37 | + |
| 38 | +// ParseReferenceArgs is a convenient wrapper that operates on a slice of strings and |
| 39 | +// calls ParseReferenceArg for each of them. It returns at the first invalid argument. |
| 40 | +func ParseReferenceArgs(args []string, parseArch bool) ([]*ReferenceArg, error) { |
| 41 | + ret := []*ReferenceArg{} |
| 42 | + for _, arg := range args { |
| 43 | + reference, err := ParseReferenceArg(arg, parseArch) |
| 44 | + if err != nil { |
| 45 | + return nil, err |
| 46 | + } |
| 47 | + ret = append(ret, reference) |
| 48 | + } |
| 49 | + return ret, nil |
| 50 | +} |
| 51 | + |
| 52 | +// ParseReferenceArg parses a string and return a ReferenceArg object. If `parseArch` is passed, |
| 53 | +// the method also tries to parse the architecture bit, i.e. string must be in the form |
| 54 | +// "packager:arch@version", useful to represent a platform (or core) name. |
| 55 | +func ParseReferenceArg(arg string, parseArch bool) (*ReferenceArg, error) { |
| 56 | + ret := &ReferenceArg{} |
| 57 | + |
| 58 | + toks := strings.SplitN(arg, "@", 2) |
| 59 | + ret.PackageName = toks[0] |
| 60 | + if len(toks) > 1 { |
| 61 | + ret.Version = toks[1] |
| 62 | + } |
| 63 | + |
| 64 | + if parseArch { |
| 65 | + toks = strings.Split(ret.PackageName, ":") |
| 66 | + if len(toks) != 2 { |
| 67 | + return nil, fmt.Errorf("invalid item %s", arg) |
| 68 | + } |
| 69 | + ret.PackageName = toks[0] |
| 70 | + ret.Architecture = toks[1] |
| 71 | + } |
| 72 | + |
| 73 | + return ret, nil |
| 74 | +} |
0 commit comments