forked from arduino/arduino-cli
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathinstall.go
332 lines (292 loc) · 10.8 KB
/
install.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
320
321
322
323
324
325
326
327
328
329
330
331
332
// 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 librariesmanager
import (
"context"
"errors"
"fmt"
"net/url"
"os"
"strings"
"github.com/arduino/arduino-cli/commands/cmderrors"
"github.com/arduino/arduino-cli/internal/arduino/globals"
"github.com/arduino/arduino-cli/internal/arduino/libraries"
"github.com/arduino/arduino-cli/internal/arduino/utils"
"github.com/arduino/arduino-cli/internal/i18n"
paths "github.com/arduino/go-paths-helper"
"github.com/codeclysm/extract/v4"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
semver "go.bug.st/relaxed-semver"
)
// LibraryInstallPlan contains the main information required to perform a library
// install, like the path where the library should be installed and the library
// that is going to be replaced by the new one.
// This is the result of a call to InstallPrerequisiteCheck.
type LibraryInstallPlan struct {
// Name of the library to install
Name string
// Version of the library to install
Version *semver.Version
// TargetPath is the path where the library should be installed.
TargetPath *paths.Path
// ReplacedLib is the library that is going to be replaced by the new one.
ReplacedLib *libraries.Library
// UpToDate is true if the library to install has the same version of the library we are going to replace.
UpToDate bool
}
// InstallPrerequisiteCheck performs prequisite checks to install a library. It returns the
// install path, where the library should be installed and the possible library that is already
// installed on the same folder and it's going to be replaced by the new one.
func (lmi *Installer) InstallPrerequisiteCheck(name string, version *semver.Version, installLocation libraries.LibraryLocation) (*LibraryInstallPlan, error) {
installDir, err := lmi.getLibrariesDir(installLocation)
if err != nil {
return nil, err
}
lmi.RescanLibraries()
libs := lmi.FindByReference(name, nil, installLocation)
if len(libs) > 1 {
libsDir := paths.NewPathList()
for _, lib := range libs {
libsDir.Add(lib.InstallDir)
}
return nil, &cmderrors.MultipleLibraryInstallDetected{
LibName: name,
LibsDir: libsDir,
Message: i18n.Tr("Automatic library install can't be performed in this case, please manually remove all duplicates and retry."),
}
}
var replaced *libraries.Library
var upToDate bool
if len(libs) == 1 {
lib := libs[0]
replaced = lib
upToDate = lib.Version != nil && lib.Version.Equal(version)
}
libPath := installDir.Join(utils.SanitizeName(name))
if libPath.IsDir() {
if replaced == nil || !replaced.InstallDir.EquivalentTo(libPath) {
return nil, errors.New(i18n.Tr("destination dir %s already exists, cannot install", libPath))
}
}
return &LibraryInstallPlan{
Name: name,
Version: version,
TargetPath: libPath,
ReplacedLib: replaced,
UpToDate: upToDate,
}, nil
}
// importLibraryFromDirectory installs a library by copying it from the given directory.
func (lmi *Installer) importLibraryFromDirectory(libPath *paths.Path, overwrite bool) error {
// Check if the library is valid and load metatada
if err := validateLibrary(libPath); err != nil {
return err
}
library, err := libraries.Load(libPath, libraries.User)
if err != nil {
return err
}
// Check if the library is already installed and determine install path
installPlan, err := lmi.InstallPrerequisiteCheck(library.Name, library.Version, libraries.User)
if err != nil {
return err
}
if installPlan.UpToDate {
if !overwrite {
return errors.New(i18n.Tr("library %s already installed", installPlan.Name))
}
}
if installPlan.ReplacedLib != nil {
if !overwrite {
return errors.New(i18n.Tr("Library %[1]s is already installed, but with a different version: %[2]s", installPlan.Name, installPlan.ReplacedLib))
}
if err := lmi.Uninstall(installPlan.ReplacedLib); err != nil {
return err
}
}
if installPlan.TargetPath.Exist() {
return fmt.Errorf("%s: %s", i18n.Tr("destination directory already exists"), installPlan.TargetPath)
}
if err := libPath.CopyDirTo(installPlan.TargetPath); err != nil {
return fmt.Errorf("%s: %w", i18n.Tr("copying library to destination directory:"), err)
}
return nil
}
// Uninstall removes a Library
func (lmi *Installer) Uninstall(lib *libraries.Library) error {
if lib == nil || lib.InstallDir == nil {
return errors.New(i18n.Tr("install directory not set"))
}
if err := lib.InstallDir.RemoveAll(); err != nil {
return errors.New(i18n.Tr("removing library directory: %s", err))
}
alternatives := lmi.libraries[lib.Name]
alternatives.Remove(lib)
lmi.libraries[lib.Name] = alternatives
return nil
}
// InstallZipLib installs a Zip library on the specified path.
func (lmi *Installer) InstallZipLib(ctx context.Context, archivePath *paths.Path, overwrite bool) error {
// Clone library in a temporary directory
tmpDir, err := paths.MkTempDir("", "")
if err != nil {
return err
}
defer tmpDir.RemoveAll()
file, err := archivePath.Open()
if err != nil {
return err
}
defer file.Close()
// Extract to a temporary directory so we can check if the zip is structured correctly.
// We also use the top level folder from the archive to infer the library name.
if err := extract.Archive(ctx, file, tmpDir.String(), nil); err != nil {
return fmt.Errorf("%s: %w", i18n.Tr("extracting archive"), err)
}
libRootFiles, err := tmpDir.ReadDir()
if err != nil {
return err
}
libRootFiles.FilterOutPrefix("__MACOSX") // Ignores metadata from Mac OS X
if len(libRootFiles) > 1 {
return errors.New(i18n.Tr("archive is not valid: multiple files found in zip file top level"))
}
if len(libRootFiles) == 0 {
return errors.New(i18n.Tr("archive is not valid: no files found in zip file top level"))
}
tmpInstallPath := libRootFiles[0]
// Install extracted library in the destination directory
if err := lmi.importLibraryFromDirectory(tmpInstallPath, overwrite); err != nil {
return errors.New(i18n.Tr("moving extracted archive to destination dir: %s", err))
}
return nil
}
// InstallGitLib installs a library hosted on a git repository on the specified path.
func (lmi *Installer) InstallGitLib(argURL string, overwrite bool) error {
libraryName, gitURL, ref, err := parseGitArgURL(argURL)
if err != nil {
return err
}
// Clone library in a temporary directory
tmp, err := paths.MkTempDir("", "")
if err != nil {
return err
}
defer tmp.RemoveAll()
tmpInstallPath := tmp.Join(libraryName)
depth := 1
if ref != "" {
depth = 0
}
if _, err := git.PlainClone(tmpInstallPath.String(), false, &git.CloneOptions{
URL: gitURL,
Depth: depth,
Progress: os.Stdout,
ReferenceName: ref,
}); err != nil {
return err
}
// We don't want the installed library to be a git repository thus we delete this folder
tmpInstallPath.Join(".git").RemoveAll()
// Install extracted library in the destination directory
if err := lmi.importLibraryFromDirectory(tmpInstallPath, overwrite); err != nil {
return errors.New(i18n.Tr("moving extracted archive to destination dir: %s", err))
}
return nil
}
// parseGitArgURL tries to recover a library name from a git URL.
// Returns an error in case the URL is not a valid git URL.
func parseGitArgURL(argURL string) (string, string, plumbing.ReferenceName, error) {
// On Windows handle paths with backslashes in the form C:\Path\to\library
if path := paths.New(argURL); path != nil && path.Exist() {
return path.Base(), argURL, "", nil
}
// Handle commercial git-specific address in the form "[email protected]:arduino-libraries/SigFox.git"
prefixes := map[string]string{
"[email protected]:": "https://github.com/",
"[email protected]:": "https://gitlab.com/",
"[email protected]:": "https://bitbucket.org/",
}
for prefix, replacement := range prefixes {
if strings.HasPrefix(argURL, prefix) {
// We can't parse these as URLs
argURL = replacement + strings.TrimPrefix(argURL, prefix)
}
}
parsedURL, err := url.Parse(argURL)
if err != nil {
return "", "", "", fmt.Errorf("%s: %w", i18n.Tr("invalid git url"), err)
}
if parsedURL.String() == "" {
return "", "", "", errors.New(i18n.Tr("invalid git url"))
}
// Extract lib name from "https://github.com/arduino-libraries/SigFox.git#1.0.3"
// path == "/arduino-libraries/SigFox.git"
slash := strings.LastIndex(parsedURL.Path, "/")
if slash == -1 {
return "", "", "", errors.New(i18n.Tr("invalid git url"))
}
libName := strings.TrimSuffix(parsedURL.Path[slash+1:], ".git")
if libName == "" {
return "", "", "", errors.New(i18n.Tr("invalid git url"))
}
// fragment == "1.0.3"
rev := plumbing.ReferenceName(parsedURL.Fragment)
// gitURL == "https://github.com/arduino-libraries/SigFox.git"
parsedURL.Fragment = ""
gitURL := parsedURL.String()
return libName, gitURL, rev, nil
}
// validateLibrary verifies the dir contains a valid library, meaning it has either
// library.properties file and an header in src/ or an header in its root folder.
// Returns nil if dir contains a valid library, error on all other cases.
func validateLibrary(dir *paths.Path) error {
if dir.NotExist() {
return errors.New(i18n.Tr("directory doesn't exist: %s", dir))
}
searchHeaderFile := func(d *paths.Path) (bool, error) {
if d.NotExist() {
// A directory that doesn't exist can't obviously contain any header file
return false, nil
}
dirContent, err := d.ReadDir()
if err != nil {
return false, fmt.Errorf("%s: %w", i18n.Tr("reading directory %s content", dir), err)
}
dirContent.FilterOutDirs()
headerExtensions := []string{}
for k := range globals.HeaderFilesValidExtensions {
headerExtensions = append(headerExtensions, k)
}
dirContent.FilterSuffix(headerExtensions...)
return len(dirContent) > 0, nil
}
// Recursive library layout
// https://arduino.github.io/arduino-cli/latest/library-specification/#source-code
if headerFound, err := searchHeaderFile(dir.Join("src")); err != nil {
return err
} else if dir.Join("library.properties").Exist() && headerFound {
return nil
}
// Flat library layout
// https://arduino.github.io/arduino-cli/latest/library-specification/#source-code
if headerFound, err := searchHeaderFile(dir); err != nil {
return err
} else if headerFound {
return nil
}
return errors.New(i18n.Tr("library not valid"))
}