lib-installer 3.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. lib_installer/__init__.py +51 -0
  2. lib_installer/__main__.py +8 -0
  3. lib_installer/arduino/__init__.py +1 -0
  4. lib_installer/arduino/arduino.py +334 -0
  5. lib_installer/arduino/properties.py +168 -0
  6. lib_installer/arduino/sketchbook.py +133 -0
  7. lib_installer/cli.py +38 -0
  8. lib_installer/core/__init__.py +8 -0
  9. lib_installer/core/blocks.py +373 -0
  10. lib_installer/core/cli.py +1432 -0
  11. lib_installer/core/console.py +132 -0
  12. lib_installer/core/download.py +781 -0
  13. lib_installer/core/files.py +35 -0
  14. lib_installer/core/installer.py +1222 -0
  15. lib_installer/core/manifest.py +1487 -0
  16. lib_installer/core/steps.py +222 -0
  17. lib_installer/core/target.py +261 -0
  18. lib_installer/core/updates.py +120 -0
  19. lib_installer/core/usercode.py +193 -0
  20. lib_installer/core/yamlreader.py +417 -0
  21. lib_installer/esp32/__init__.py +1 -0
  22. lib_installer/esp32/component.py +354 -0
  23. lib_installer/esp32/esp32.py +491 -0
  24. lib_installer/esp32/project.py +768 -0
  25. lib_installer/pio/__init__.py +1 -0
  26. lib_installer/pio/ini.py +304 -0
  27. lib_installer/pio/library_json.py +161 -0
  28. lib_installer/pio/pio.py +208 -0
  29. lib_installer/stm32/__init__.py +1 -0
  30. lib_installer/stm32/checks.py +204 -0
  31. lib_installer/stm32/ide/__init__.py +110 -0
  32. lib_installer/stm32/ide/base.py +269 -0
  33. lib_installer/stm32/ide/cmake.py +299 -0
  34. lib_installer/stm32/ide/cubeide.py +344 -0
  35. lib_installer/stm32/ide/iar.py +509 -0
  36. lib_installer/stm32/ide/keil.py +419 -0
  37. lib_installer/stm32/ide/makefile.py +376 -0
  38. lib_installer/stm32/stm32.py +101 -0
  39. lib_installer/zephyr/__init__.py +1 -0
  40. lib_installer/zephyr/app.py +648 -0
  41. lib_installer/zephyr/module.py +375 -0
  42. lib_installer/zephyr/zephyr.py +620 -0
  43. lib_installer-3.0.1.dist-info/METADATA +583 -0
  44. lib_installer-3.0.1.dist-info/RECORD +48 -0
  45. lib_installer-3.0.1.dist-info/WHEEL +5 -0
  46. lib_installer-3.0.1.dist-info/entry_points.txt +2 -0
  47. lib_installer-3.0.1.dist-info/licenses/LICENSE +201 -0
  48. lib_installer-3.0.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1432 @@
1
+ """
2
+ The command line front end, the same for every installer.
3
+
4
+ One argument says what to install, and it can be any of these:
5
+
6
+ installer owner/example GitHub, by owner and name
7
+ installer example GitHub, owner nimaltd
8
+ installer https://github.com/owner/example GitHub, by address
9
+ installer D:/Downloads/example-main.zip the zip GitHub hands out
10
+ installer D:/Downloads/example-main a folder anywhere on disk
11
+ installer example a folder already in the project
12
+
13
+ A path that exists always wins over a name, so a folder called "example" in the
14
+ project is used as it is and never confused with the repository of that name.
15
+
16
+ Several can be given in one run, such as a library and the zip of a library it
17
+ needs. A library lists what it needs under requires.libraries. What is missing
18
+ or too old goes in first, from the command line or else from GitHub, and what
19
+ is already in the project at a version that will do is left alone.
20
+
21
+ Where the library comes from decides what happens to it:
22
+
23
+ - From GitHub, from a zip, or from a folder outside the project, the files the
24
+ manifest lists are copied into a folder of the project, asked for or given with
25
+ --dir. The source is never changed.
26
+ - A folder already inside the project becomes the library where it stands. The
27
+ repository scaffolding is removed from it, because STM32CubeIDE compiles every
28
+ .c under the project and a test harness brings a second main() with it.
29
+
30
+ Either way the work happens in the same order: check the project against what the
31
+ library needs, copy the files, then register them with the project. The checks and
32
+ the registering are the target's, see target.py.
33
+ """
34
+
35
+ import argparse
36
+ import os
37
+ import re
38
+ import sys
39
+ from pathlib import Path, PurePosixPath
40
+
41
+ from . import console, download, installer, manifest, steps, target, updates, yamlreader
42
+
43
+ # A drive letter, as in D:/Downloads or C:\Users.
44
+ _DRIVE = re.compile(r"^[A-Za-z]:")
45
+
46
+ # Given --yes: every question takes the answer it offers, and run steps run.
47
+ _assume_yes = False
48
+
49
+ # --run and --no-run, by step label, for this run.
50
+ _run_on = ()
51
+ _run_off = ()
52
+
53
+
54
+ def _header(library):
55
+ """The block printed before anything is written."""
56
+ lines = [console.banner(library.name, library.version, library.description)]
57
+ lines.append(console.note(library.summary()))
58
+
59
+ return "\n".join(lines)
60
+
61
+
62
+ def _answer(prompt):
63
+ """
64
+ Ask a question and return what was typed, or None when nobody can answer.
65
+
66
+ Piped into Python, the installer arrives on stdin, so stdin cannot also carry
67
+ the answer. The console is read directly instead: /dev/tty on Linux and
68
+ macOS, CONIN$ on Windows. That is only tried when the output is going to a
69
+ screen. Otherwise nobody is there to read the question, and waiting for an
70
+ answer would hang a script or a build server for ever.
71
+ """
72
+ if _assume_yes:
73
+ print(prompt + console.note("(--yes)"))
74
+ return ""
75
+
76
+ try:
77
+ if sys.stdin is not None and sys.stdin.isatty():
78
+ return input(prompt).strip()
79
+
80
+ if sys.stdout is None or not sys.stdout.isatty():
81
+ return None
82
+
83
+ device = "CONIN$" if os.name == "nt" else "/dev/tty"
84
+
85
+ with open(device, "r") as terminal:
86
+ print(prompt, end="", flush=True)
87
+ return terminal.readline().strip()
88
+ except (OSError, EOFError):
89
+ return None
90
+
91
+
92
+ def _ask_folder(default, name=None):
93
+ """
94
+ Ask where a library should go, or take the default when nobody can answer.
95
+
96
+ name is said in the question once more than one library may be installed in
97
+ one run, so it is clear which one the folder is for.
98
+ """
99
+ what = f"{name} " if name else ""
100
+
101
+ return _answer(console.strong(f"Folder to install {what}into [{default}]: ")) or default
102
+
103
+
104
+ def _choose_options(library, project_root, turn_on=(), turn_off=(), ask=False):
105
+ """
106
+ Settle which of a library's options this install takes, and say so.
107
+
108
+ An option named with --with or --without is that. One the project has an
109
+ answer for, from the last install, keeps it without a question: an update
110
+ is not the moment to ask again, and the line printed says how to change it.
111
+ Anything else is asked when it may be, and is no otherwise, since nobody
112
+ chose it.
113
+ """
114
+ if not library.options:
115
+ return
116
+
117
+ recorded = installer.installed_libraries(project_root).get(library.name)
118
+ before = recorded.get("options") if isinstance(recorded, dict) else None
119
+ before = before if isinstance(before, dict) else {}
120
+ chosen = []
121
+
122
+ print()
123
+ print(console.heading("Options"))
124
+
125
+ for name, option in library.options.items():
126
+ label = f" {name:<10} "
127
+ brings = ", ".join(d.name for d in option.libraries)
128
+
129
+ if name in turn_on:
130
+ taken, said = True, f"yes, as asked with --with {name}"
131
+ elif name in turn_off:
132
+ taken, said = False, f"no, as asked with --without {name}"
133
+
134
+ if before.get(name) is True and brings:
135
+ said += f". Its files go. {brings} stays in the project, for anything else using it"
136
+ elif name in before:
137
+ taken = before[name] is True
138
+ said = (f"yes, as before. Change it with --without {name}" if taken
139
+ else f"no, as before. Add it with --with {name}")
140
+ elif ask:
141
+ reply = _answer(label + console.strong(f"{option.description or name}. Add it? [y/N]: "))
142
+ taken = reply is not None and reply.lower() in ("y", "yes")
143
+ said = None if reply is not None else f"no, nobody was asked. Add it with --with {name}"
144
+ else:
145
+ # A library that came in because another needs it. The flags are
146
+ # for the libraries named on the command line, so this says how.
147
+ taken, said = False, (f"no. Add it with: {target.current.command} {library.name} "
148
+ f"--with {name}")
149
+
150
+ if taken:
151
+ chosen.append(name)
152
+
153
+ if said:
154
+ print(label + said)
155
+
156
+ library.choose(chosen)
157
+
158
+
159
+ def _print_requirements(findings):
160
+ """What the library needs, and whether the project looks ready for it."""
161
+ if not findings:
162
+ return
163
+
164
+ print()
165
+ print(console.heading("Requirements"))
166
+
167
+ marks = {
168
+ target.OK: ("ok", console.GREEN),
169
+ target.WARN: ("check", console.YELLOW),
170
+ target.INFO: ("note", console.GREY),
171
+ }
172
+
173
+ for finding in findings:
174
+ mark, colour = marks.get(finding.level, ("note", None))
175
+ print(console.item(mark, "", finding.message, colour))
176
+
177
+ if finding.hint and finding.level != target.OK:
178
+ print(f" {console.note(finding.hint)}")
179
+
180
+
181
+ def _print_files(result, root, library=None):
182
+ """Every file written, created, or deliberately left alone."""
183
+ # The files of an option not taken, by where they would land, so a file
184
+ # that went because the option was turned off says that rather than that
185
+ # the library dropped it.
186
+ unchosen = {}
187
+
188
+ for name, option in (library.options.items() if library is not None else []):
189
+ if name not in library.chosen:
190
+ for entry in option.code_files:
191
+ unchosen[(result.destination / entry.destination).resolve()] = name
192
+
193
+ print()
194
+ print(console.heading("Files"))
195
+
196
+ for path in result.installed:
197
+ print(console.item("written", "", _show(path, root), console.GREEN))
198
+
199
+ # The library's own files in the project's folder, from a 2.1.0 manifest.
200
+ for path in result.placed:
201
+ print(console.item("written", "", _show(path, root), console.GREEN))
202
+
203
+ for path in result.created:
204
+ print(console.item("created", "yours to edit", _show(path, root), console.CYAN))
205
+
206
+ # The project's own files, in its own folder, from a 2.0.0 manifest.
207
+ for path in result.yours_created:
208
+ print(console.item("created", "yours from now on", _show(path, root), console.CYAN))
209
+
210
+ for path in result.yours_kept:
211
+ print(console.item("kept", "yours", _show(path, root), console.CYAN))
212
+
213
+ moved_to = {new for _, new in result.moved}
214
+
215
+ for path in result.kept:
216
+ if path not in moved_to:
217
+ print(console.item("kept", "not overwritten", _show(path, root), console.YELLOW))
218
+
219
+ for old, new in result.moved:
220
+ print(console.item("moved", "yours, kept as it was",
221
+ f"{_show(old, root)} -> {_show(new, root)}", console.CYAN))
222
+
223
+ # A file that took the user's sections to its new place says so. One with
224
+ # none to take is only an old copy gone, and is reported as removed.
225
+ carried = {Path(old).resolve() for old, _, kept in result.carried if kept}
226
+
227
+ for old, new, kept in result.carried:
228
+ if kept:
229
+ print(console.item("moved", "your USER CODE " + ", ".join(kept) + " went with it",
230
+ f"{_show(old, root)} -> {_show(new, root)}", console.CYAN))
231
+
232
+ for path in result.dropped:
233
+ if Path(path).resolve() in carried:
234
+ continue
235
+
236
+ option = unchosen.get(Path(path).resolve())
237
+ why = f"option {option} is off" if option else "no longer part of the library"
238
+ print(console.item("removed", why, _show(path, root), console.YELLOW))
239
+
240
+ moved_with = {Path(new).resolve() for _, new, kept in result.carried if kept}
241
+
242
+ for path, names in result.preserved:
243
+ # Already said on its "moved" line.
244
+ if Path(path).resolve() in moved_with:
245
+ continue
246
+
247
+ print(console.item("kept", "your USER CODE " + ", ".join(names), _show(path, root),
248
+ console.CYAN))
249
+
250
+ for path, saved, reason in result.backups:
251
+ print(console.item("saved", "", f"{_show(saved, root)} {console.warn(reason)}",
252
+ console.YELLOW))
253
+
254
+ if result.removed:
255
+ print()
256
+ print(console.note(" Removed, since they are part of the repository, not the firmware:"))
257
+ print(console.note(" " + ", ".join(sorted(result.removed))))
258
+
259
+
260
+ def _print_ide(outcomes):
261
+ """What was done to the project files, and what is left for the user."""
262
+ if not outcomes:
263
+ print()
264
+ print(console.warn(target.current.no_project))
265
+ print(console.note(" " + target.current.no_project_hint))
266
+ return
267
+
268
+ _print_outcomes(outcomes)
269
+
270
+
271
+ def _print_outcomes(outcomes):
272
+ """Each project file changed, or left for the user, under its heading."""
273
+ print()
274
+ print(console.heading("Project"))
275
+
276
+ for outcome in outcomes:
277
+ if outcome.status == target.CHANGED:
278
+ print(console.item("updated", "", f"{console.strong(outcome.ide)} {outcome.message}", console.GREEN))
279
+ elif outcome.status == target.ALREADY:
280
+ print(console.item("ok", "", f"{console.strong(outcome.ide)} {outcome.message}", console.GREEN))
281
+ else:
282
+ print(console.item("manual", "", f"{console.strong(outcome.ide)} {outcome.message}", console.YELLOW))
283
+
284
+ for step in outcome.steps:
285
+ print(f" {console.note(step)}")
286
+
287
+ if outcome.backup:
288
+ print(f" {console.note('backup: ' + outcome.backup.name)}")
289
+
290
+
291
+ def _include_name(library):
292
+ """
293
+ What goes between the quotes of the #include for this library.
294
+
295
+ The first header the manifest lists, relative to the include folder it sits
296
+ in. Not the library's name with .h added: the sequencer library's header is
297
+ seq.h, and telling people to include sequencer.h sends them looking for a
298
+ file that does not exist.
299
+ """
300
+ if not library.headers:
301
+ return None
302
+
303
+ landed = PurePosixPath(library.headers[0].destination)
304
+
305
+ for folder in sorted(library.include_dirs, key=len, reverse=True):
306
+ if folder in (".", ""):
307
+ continue
308
+
309
+ try:
310
+ return landed.relative_to(folder).as_posix()
311
+ except ValueError:
312
+ continue
313
+
314
+ return landed.as_posix()
315
+
316
+
317
+ def _print_next(result, root, library):
318
+ """The last word, which is the one people actually read."""
319
+ folder = _show(result.destination, root)
320
+ header = target.current.include_line(library, result.destination, root) or _include_name(library)
321
+
322
+ print()
323
+
324
+ if header:
325
+ print(console.good(f'Done. #include "{header}" and you are away.'))
326
+ else:
327
+ print(console.good("Done."))
328
+
329
+ if result.was_update:
330
+ print(console.note("This was an update. The library replaced, what was yours kept."))
331
+
332
+ if result.backups:
333
+ print(console.warn("Something of yours could not be carried over. Each copy marked saved "
334
+ "holds the file as it was: take what you need from it, then delete it."))
335
+
336
+ for warning in getattr(library, "warnings", []):
337
+ print(console.note(f" manifest: {warning}"))
338
+
339
+ return folder
340
+
341
+
342
+ def _show(path, root):
343
+ """A path relative to the project when possible, so output stays readable."""
344
+ try:
345
+ return Path(path).relative_to(root).as_posix()
346
+ except ValueError:
347
+ return Path(path).as_posix()
348
+
349
+
350
+ def _finish(library, result, project_root, only_ide):
351
+ """The part shared by every install route. Returns 1 when a run step failed."""
352
+ _print_files(result, project_root, library)
353
+
354
+ outcomes = target.current.integrate(project_root, library, result.destination, only=only_ide,
355
+ dropped=result.dropped,
356
+ dropped_defines=result.dropped_defines)
357
+ _print_ide(outcomes)
358
+
359
+ # The blocks the target wrote, so the next install can tell an edit inside one.
360
+ written = {}
361
+
362
+ for outcome in outcomes:
363
+ for name, found in (getattr(outcome, "blocks", None) or {}).items():
364
+ written.setdefault(name, {}).update(found)
365
+
366
+ if written:
367
+ installer.note(project_root, library.name, blocks=written)
368
+
369
+ code = _run_steps(library, result, project_root)
370
+ _print_next(result, project_root, library)
371
+
372
+ return code
373
+
374
+
375
+ def _run_steps(library, result, project_root):
376
+ """
377
+ The library's run steps, once everything else is in, and what ran recorded
378
+ so an update does not run it again. Returns 1 when one failed, else 0.
379
+ """
380
+ if not library.run:
381
+ return 0
382
+
383
+ folder = target.current.once_root(project_root)
384
+
385
+ # Nowhere to run them, such as Arduino's libraries folder, which belongs to
386
+ # no sketch: left unrun, as a no would leave them, with the way to run them.
387
+ if folder is None:
388
+ print()
389
+ print(console.heading("Run"))
390
+
391
+ for step in library.run:
392
+ print(f" {step.label:<12} " + console.note("not run, there is no project folder here to run it in"))
393
+
394
+ print(console.note(f" {target.current.no_once_root}"))
395
+ return 0
396
+
397
+ entry = installer.installed_libraries(project_root).get(library.name)
398
+ recorded = entry.get("ran") if isinstance(entry, dict) else None
399
+ outcomes = steps.run(library, folder, result.destination, _answer, _run_on, _run_off,
400
+ _assume_yes, recorded)
401
+
402
+ ran = dict(recorded) if isinstance(recorded, dict) else {}
403
+
404
+ for outcome in outcomes:
405
+ if outcome.status == steps.RAN:
406
+ ran[outcome.step.label] = outcome.step.fingerprint()
407
+
408
+ installer.note(project_root, library.name, ran=ran)
409
+
410
+ failed = [o.step.label for o in outcomes if o.status == steps.FAILED]
411
+
412
+ if failed:
413
+ print()
414
+ print(console.warn(f"{', '.join(failed)} did not finish. The library is installed; run "
415
+ f"{'them' if len(failed) > 1 else 'it'} again with --run once the reason "
416
+ "above is put right."))
417
+ return 1
418
+
419
+ return 0
420
+
421
+
422
+ def _uninstall_order(names, project_root):
423
+ """
424
+ The libraries to take out, each before any of the others it needs.
425
+
426
+ ee24 needs osal, so "--uninstall osal ee24" takes ee24 out first, and osal
427
+ is then needed by nothing. A circle, which the record should never hold,
428
+ keeps the order given.
429
+ """
430
+ installed = installer.installed_libraries(project_root)
431
+ left = list(dict.fromkeys(names))
432
+ order = []
433
+
434
+ while left:
435
+ ready = [name for name in left
436
+ if not any(name in (installed.get(other) or {}).get("needs", []) for other in left if other != name)]
437
+ step = ready[0] if ready else left[0]
438
+ order.append(step)
439
+ left.remove(step)
440
+
441
+ return order
442
+
443
+
444
+ def _print_removal(removal, root):
445
+ """What an uninstall did, and what it left."""
446
+ library = removal.library
447
+ folder = _show(library.destination, root) if library.destination else ""
448
+
449
+ print()
450
+ print(console.banner(library.name, library.version, f"out of {folder}"))
451
+
452
+ if removal.outcomes:
453
+ _print_outcomes(removal.outcomes)
454
+
455
+ print()
456
+ print(console.heading("Files"))
457
+
458
+ for path in removal.removed:
459
+ print(console.item("removed", "", _show(path, root), console.YELLOW))
460
+
461
+ for path, saved, reason in removal.backups:
462
+ print(console.item("saved", "", f"{_show(saved, root)} {console.warn(reason)}", console.CYAN))
463
+
464
+ saved = {copy for _, copy, _ in removal.backups}
465
+ others = [path for path in removal.left if path not in saved]
466
+
467
+ for path in others:
468
+ print(console.item("kept", "not the library's", _show(path, root), console.CYAN))
469
+
470
+ for path in removal.yours:
471
+ print(console.item("kept", "yours, not removed", _show(path, root), console.CYAN))
472
+
473
+ print()
474
+ print(console.good(f"Done. {library.name} is out of the project."))
475
+
476
+ if not removal.folder_removed and library.destination is not None and library.destination.is_dir():
477
+ if others:
478
+ print(console.note(f"{folder} stays, for the files above that were not the library's."))
479
+ else:
480
+ print(console.note(f"{folder} stays, for what was saved above. Delete it once you have "
481
+ "taken what you need."))
482
+
483
+ for name in removal.unneeded:
484
+ print(console.note(
485
+ f"{name} came in for {library.name}, and nothing here needs it now. "
486
+ f"Take it out too with: {target.current.command} --uninstall {name}"
487
+ ))
488
+
489
+
490
+ def _project_root(args):
491
+ """
492
+ The folder the run works in: --project or the current folder, as the
493
+ target sees it. Returns None once the reason it cannot be had is printed.
494
+ """
495
+ given = Path(args.project).resolve() if args.project else Path.cwd().resolve()
496
+
497
+ # A project an installer before 3.0.0 installed into moves over first, so
498
+ # all that follows reads lib-installer's record and markers.
499
+ for root in getattr(target.current, "legacy_roots", lambda folder: [])(given):
500
+ moved = installer.migrate(root)
501
+
502
+ if moved:
503
+ print(console.note(
504
+ f"Moved over from {target.current.legacy} to {target.current.name}: "
505
+ f"{', '.join(_show(path, root) for path in moved)}. Each was saved first as a .bak."
506
+ ))
507
+
508
+ try:
509
+ return target.current.project_root(given)
510
+ except installer.InstallError as error:
511
+ _error(error)
512
+ return None
513
+
514
+
515
+ def _uninstall(args):
516
+ """Take the libraries named after --uninstall out of the project. Returns an exit code."""
517
+ if args.library or args.local:
518
+ _error("--uninstall takes libraries out. Install on a run of its own.")
519
+ return 2
520
+
521
+ project_root = _project_root(args)
522
+
523
+ if project_root is None:
524
+ return 2
525
+
526
+ for name in _uninstall_order(args.uninstall, project_root):
527
+ try:
528
+ removal = installer.uninstall(project_root, name)
529
+ except installer.InstallError as error:
530
+ _error(error)
531
+ return 2
532
+
533
+ _print_removal(removal, project_root)
534
+
535
+ return 0
536
+
537
+
538
+ def _looks_like_path(text):
539
+ """
540
+ Whether the argument can only be a path, never a library name.
541
+
542
+ A path that does not exist is then reported as missing, rather than sent to
543
+ GitHub, where a mistyped D:/Downloads/example.zip would come back as a
544
+ baffling "repository not found" for an owner called "D:".
545
+ """
546
+ # A ref after an @ is a branch, and a branch can hold a slash: feature/x.
547
+ name = text.partition("@")[0]
548
+
549
+ return (
550
+ text.lower().endswith(".zip")
551
+ or "\\" in name
552
+ or text.startswith((".", "/", "~"))
553
+ or bool(_DRIVE.match(text))
554
+ or (not text.startswith(("http://", "https://")) and name.count("/") > 1)
555
+ )
556
+
557
+
558
+ def _kind(path):
559
+ """
560
+ What is on disk at path: "zip", "file", "folder", or None for nothing.
561
+
562
+ Never raises. A string that only looks like a path, or holds a character
563
+ Windows refuses in a file name, is simply not there.
564
+ """
565
+ try:
566
+ if path.is_dir():
567
+ return "folder"
568
+
569
+ if path.is_file():
570
+ return "zip" if path.suffix.lower() == ".zip" else "file"
571
+ except OSError:
572
+ pass
573
+
574
+ return None
575
+
576
+
577
+ def _inside(path, root):
578
+ """
579
+ Whether path is strictly inside root.
580
+
581
+ Written out rather than Path.is_relative_to, which only arrived in Python
582
+ 3.9, and this still runs on 3.8.
583
+ """
584
+ try:
585
+ path.relative_to(root)
586
+ except ValueError:
587
+ return False
588
+
589
+ return path != root
590
+
591
+
592
+ def _error(message):
593
+ """An error, on stderr, where a script looks for it."""
594
+ print(console.bad(f"Error: {message}"), file=sys.stderr)
595
+
596
+
597
+ class _Source:
598
+ """
599
+ A library on disk, ready to install, and how it gets into the project.
600
+
601
+ in_place is a folder already inside the project, which becomes the library
602
+ where it stands. staging is a temporary folder this run made, the download
603
+ or the unpacked zip, which is removed once the run is over. project_root is
604
+ set only when the project is not the one the run was given: an install.py
605
+ from an older release runs inside the library, whose parent is the project.
606
+ """
607
+
608
+ def __init__(self, root, in_place=False, staging=None, project_root=None, origin=None):
609
+ self.root = root
610
+ self.in_place = in_place
611
+ self.staging = staging
612
+ self.project_root = project_root
613
+ self.library = None
614
+ # Where it came from, for the record: see download.origin().
615
+ self.origin = origin or {}
616
+
617
+
618
+ class _Step:
619
+ """One install, in the order the plan puts them."""
620
+
621
+ def __init__(self, source, needed_by=None, dependency=None, installed=None):
622
+ self.source = source
623
+ self.needed_by = needed_by
624
+ self.dependency = dependency
625
+ self.installed = installed
626
+
627
+
628
+ class _PlanError(Exception):
629
+ """A library that cannot be had. Raised before anything is installed."""
630
+
631
+
632
+ def _stage_folder(folder, project_root):
633
+ """A library folder on disk: converted where it stands, or copied in."""
634
+ folder = folder.resolve()
635
+ root = download.find_root(folder) or folder
636
+
637
+ # Run from inside the library folder itself, which is what an install.py from
638
+ # an older release does. The folder is the library and its parent the project.
639
+ if root == project_root:
640
+ return _Source(root, in_place=True, project_root=root.parent)
641
+
642
+ if _inside(root, project_root):
643
+ return _Source(root, in_place=True)
644
+
645
+ print(console.note(f"Reading {folder.as_posix()} ..."))
646
+
647
+ return _Source(root)
648
+
649
+
650
+ def _stage(given, ref, project_root, local=False):
651
+ """
652
+ Get one library named on the command line onto disk.
653
+
654
+ Returns a _Source, or None once the reason it could not be had is printed.
655
+ """
656
+ if not given.startswith(("http://", "https://")):
657
+ path = Path(given).expanduser()
658
+ kind = _kind(path)
659
+
660
+ if kind == "zip":
661
+ print(console.note(f"Reading {path.name} ..."))
662
+
663
+ try:
664
+ staging, root = download.unpack(path.resolve())
665
+ except download.DownloadError as error:
666
+ _error(error)
667
+ return None
668
+
669
+ return _Source(root, staging=staging, origin={"kind": "zip", "path": path.name})
670
+
671
+ if kind == "folder":
672
+ return _stage_folder(path, project_root)
673
+
674
+ if kind == "file":
675
+ _error(
676
+ f"{given} is not a .zip. Give the zip GitHub offers under "
677
+ "Code, Download ZIP, or the folder it unpacks to."
678
+ )
679
+ return None
680
+
681
+ if local or _looks_like_path(given):
682
+ _error(f"{given} does not exist.")
683
+ return None
684
+
685
+ print(console.note(f"Fetching {given} ..."))
686
+
687
+ try:
688
+ staged = download.fetch(given, ref=ref)
689
+ except download.DownloadError as error:
690
+ _error(error)
691
+ return None
692
+
693
+ return _Source(staged, staging=staged, origin=download.origin(staged))
694
+
695
+
696
+ def _load(source, project_root):
697
+ """
698
+ Read a source's installer.yml.
699
+
700
+ Returns None when it was read, otherwise the exit code to stop with, the
701
+ reason already printed.
702
+ """
703
+ try:
704
+ source.library = manifest.load(source.root)
705
+ source.library.origin = source.origin or {"kind": "folder", "path": source.root.as_posix()}
706
+ except manifest.ManifestError as error:
707
+ # Installing in place removes installer.yml, so the most likely reason it
708
+ # is missing there is that this folder has already been installed once.
709
+ if source.in_place:
710
+ root = source.project_root or project_root
711
+ known = installer.installed_libraries(root)
712
+ where = _show(source.root, root)
713
+ already = next((n for n, d in known.items() if d.get("folder") == where), None)
714
+
715
+ if already:
716
+ print(console.warn(f"{already} is already installed in {where}."))
717
+ print(console.note(" To update it, run this again with a fresh download."))
718
+ return 0
719
+
720
+ _error(error)
721
+ return 2
722
+
723
+ return None
724
+
725
+
726
+ def _fetch_dependency(dependency, needed_by, staged, needer_root=None):
727
+ """
728
+ Download a library another one needs, from GitHub.
729
+
730
+ At the ref the needing library names, or the default branch. A library
731
+ with no installer.yml of its own comes with the one the needing library
732
+ carries for it, from needer_root.
733
+
734
+ Raises _PlanError when it cannot be had, saying how to get it without the
735
+ internet, since a missing connection is the usual reason.
736
+ """
737
+ print(console.note(f"{needed_by} needs {dependency}. Fetching {dependency.fetch} ..."))
738
+
739
+ carried = None
740
+
741
+ if dependency.manifest is not None and needer_root is not None:
742
+ try:
743
+ carried = (Path(needer_root) / dependency.manifest).read_bytes()
744
+ except OSError as error:
745
+ raise _PlanError(
746
+ f"{needed_by} carries an installer.yml for {dependency.name} at "
747
+ f"{dependency.manifest.as_posix()}, and it cannot be read: {error}"
748
+ ) from error
749
+
750
+ try:
751
+ root = download.fetch(dependency.fetch, **({"carried": carried} if carried is not None else {}))
752
+ except download.DownloadError as error:
753
+ raise _PlanError(
754
+ f"{needed_by} needs {dependency}, which is not in this project, and it could "
755
+ f"not be fetched: {error}\n"
756
+ f"Without the internet, download {dependency.name} as well, and give both "
757
+ f"zips on one line:\n"
758
+ f" {target.current.command} {needed_by}-main.zip {dependency.name}-main.zip"
759
+ ) from error
760
+
761
+ staged.append(root)
762
+ source = _Source(root, staging=root, origin=download.origin(root))
763
+
764
+ try:
765
+ source.library = manifest.load(root)
766
+ source.library.origin = source.origin
767
+ except manifest.ManifestError as error:
768
+ raise _PlanError(f"{dependency.name}, which {needed_by} needs: {error}") from error
769
+
770
+ return source
771
+
772
+
773
+ def _plan(requested, project_root, staged):
774
+ """
775
+ Put the installs in order: every library after the libraries it needs.
776
+
777
+ A library that is needed and already in the project at a version that will
778
+ do is left alone, and nobody is asked anything about it. One that is missing
779
+ or too old comes from a zip or folder given on the same command line, or
780
+ else from GitHub. All of that is worked out, and fetched, before anything
781
+ is installed, so a library that cannot be had stops the run with the
782
+ project untouched.
783
+
784
+ staged collects every temporary folder made on the way, for the caller to
785
+ remove.
786
+ """
787
+ # What other libraries need may live somewhere else, such as Arduino's
788
+ # libraries folder for a library in a sketch.
789
+ elsewhere = target.current.dependency_root(project_root)
790
+ recorded = installer.installed_libraries(elsewhere)
791
+ given = {source.library.name: source for source in requested}
792
+ planned = {}
793
+ steps = []
794
+
795
+ def visit(source, chain):
796
+ name = source.library.name
797
+
798
+ for dependency in source.library.dependencies:
799
+ if dependency.name in chain:
800
+ circle = " -> ".join(chain + [dependency.name])
801
+ raise _PlanError(f"These libraries need each other in a circle: {circle}")
802
+
803
+ # Already sorted out for an earlier library: in the project, or on
804
+ # its way in. It only has to be new enough for this one as well.
805
+ if dependency.name in planned:
806
+ if not dependency.satisfied_by(planned[dependency.name]):
807
+ raise _PlanError(
808
+ f"{name} needs {dependency}, but {dependency.name} "
809
+ f"{planned[dependency.name]} is the one this run has."
810
+ )
811
+ continue
812
+
813
+ have = recorded.get(dependency.name)
814
+ have = have if isinstance(have, dict) else None
815
+ have_version = have.get("version") if have else None
816
+
817
+ # In the project and new enough: nothing to do, nothing to ask. A
818
+ # copy given on the command line is installed anyway, as asked.
819
+ if have and dependency.name not in given and dependency.satisfied_by(have_version):
820
+ print(console.note(
821
+ f"{name} needs {dependency}. {dependency.name} {have_version} is "
822
+ "already in this project, kept."
823
+ ))
824
+ planned[dependency.name] = have_version
825
+ continue
826
+
827
+ other = given.get(dependency.name)
828
+
829
+ if other is None:
830
+ other = _fetch_dependency(dependency, name, staged, source.library.root)
831
+ # Its options before what it needs, since they can bring more.
832
+ _choose_options(other.library, elsewhere)
833
+
834
+ if elsewhere != project_root and not other.in_place:
835
+ other.project_root = elsewhere
836
+
837
+ if not dependency.satisfied_by(other.library.version):
838
+ raise _PlanError(
839
+ f"{name} needs {dependency}, and the newest {dependency.name} to be "
840
+ f"had is {other.library.version}."
841
+ )
842
+
843
+ # What it needs comes before it.
844
+ visit(other, chain + [dependency.name])
845
+
846
+ steps.append(_Step(other, needed_by=name, dependency=dependency, installed=have))
847
+ planned[dependency.name] = other.library.version
848
+
849
+ for source in requested:
850
+ # Given on the command line, and already installed as what an earlier
851
+ # one needs.
852
+ if source.library.name in planned:
853
+ continue
854
+
855
+ visit(source, [source.library.name])
856
+ steps.append(_Step(source))
857
+ planned[source.library.name] = source.library.version
858
+
859
+ return steps
860
+
861
+
862
+ def _settle_options(requested, project_root, args):
863
+ """
864
+ Choose the options of every library named on the command line.
865
+
866
+ A name given to --with or --without that none of them has is refused
867
+ before anything is asked or installed, since it is almost always a typo,
868
+ and going ahead without it would install something other than what was
869
+ asked for. Returns None, or the exit code to stop with.
870
+ """
871
+ turn_on = list(args.with_options or [])
872
+ turn_off = list(args.without_options or [])
873
+ offered = sorted({name for source in requested for name in source.library.options})
874
+
875
+ both = sorted(set(turn_on) & set(turn_off))
876
+
877
+ if both:
878
+ _error(f"{', '.join(both)} is given to both --with and --without. Give it to one.")
879
+ return 2
880
+
881
+ unknown = sorted(set(turn_on + turn_off) - set(offered))
882
+
883
+ if unknown:
884
+ has = (f"What is installed here has: {', '.join(offered)}." if offered
885
+ else "What is installed here has no options.")
886
+ _error(f"No option called {', '.join(unknown)}. {has}")
887
+ return 2
888
+
889
+ for source in requested:
890
+ _choose_options(source.library, source.project_root or project_root, turn_on, turn_off, ask=True)
891
+
892
+ return _settle_run(requested, args)
893
+
894
+
895
+ def _settle_run(requested, args):
896
+ """
897
+ Check --run and --no-run against the steps of the libraries named, the way
898
+ --with and --without are checked. Returns None, or the exit code to stop with.
899
+ """
900
+ global _run_on, _run_off
901
+
902
+ _run_on = tuple(getattr(args, "run", None) or [])
903
+ _run_off = tuple(getattr(args, "no_run", None) or [])
904
+ offered = sorted({step.label for source in requested for step in source.library.run})
905
+ both = sorted(set(_run_on) & set(_run_off))
906
+
907
+ if both:
908
+ _error(f"{', '.join(both)} is given to both --run and --no-run. Give it to one.")
909
+ return 2
910
+
911
+ unknown = sorted(set(_run_on + _run_off) - set(offered))
912
+
913
+ if unknown:
914
+ has = (f"What is named here has: {', '.join(offered)}." if offered
915
+ else "What is named here has no steps to run.")
916
+ _error(f"No run step called {', '.join(unknown)}. {has}")
917
+ return 2
918
+
919
+ return None
920
+
921
+
922
+ def _default_folder(library, project_root):
923
+ """
924
+ The folder offered for a library: where it already is, or the target's choice.
925
+
926
+ Offering the name for a library installed somewhere else, such as Libs/x,
927
+ used to put a second copy of it in ./x on an update.
928
+ """
929
+ recorded = installer.installed_libraries(project_root).get(library.name)
930
+
931
+ if isinstance(recorded, dict) and recorded.get("folder"):
932
+ return recorded["folder"]
933
+
934
+ return target.current.folder_for(library, project_root)
935
+
936
+
937
+ def _install_step(step, project_root, folder, only_ide):
938
+ """Install one library of the plan. Returns an exit code."""
939
+ source = step.source
940
+ library = source.library
941
+ root = source.project_root or project_root
942
+
943
+ if step.needed_by and step.installed:
944
+ print()
945
+ print(console.note(
946
+ f"{step.needed_by} needs {step.dependency}, newer than the "
947
+ f"{step.installed.get('version')} in this project. Updating {library.name} first."
948
+ ))
949
+ elif step.needed_by:
950
+ print()
951
+ print(console.note(
952
+ f"{step.needed_by} needs {step.dependency}, which is not in this project. "
953
+ f"Installing {library.name} first."
954
+ ))
955
+
956
+ print()
957
+ print(_header(library))
958
+
959
+ _print_requirements(target.current.check(library, root))
960
+
961
+ try:
962
+ if source.in_place:
963
+ result = installer.install_in_place(library, project_root=root)
964
+ else:
965
+ print()
966
+
967
+ # A library being updated because another needs a newer one goes
968
+ # where it already is, without a question: it is not new to the
969
+ # user. Anything else is asked for, or given with --dir.
970
+ if step.needed_by and step.installed and step.installed.get("folder"):
971
+ chosen = step.installed["folder"]
972
+ else:
973
+ chosen = folder or _ask_folder(_default_folder(library, root), library.name)
974
+
975
+ result = installer.install_to(library, root / chosen, project_root=root)
976
+ except installer.InstallError as error:
977
+ _error(error)
978
+ return 2
979
+
980
+ return _finish(library, result, root, only_ide)
981
+
982
+
983
+ def _run(args, parser, library_root):
984
+ """Get every library onto disk, work out the order, then install them in it."""
985
+ project_root = _project_root(args)
986
+
987
+ if project_root is None:
988
+ return 2
989
+
990
+ # An install.py from an older release passes the folder it sits in.
991
+ if library_root is not None:
992
+ targets = [str(library_root)]
993
+ else:
994
+ targets = ([args.local] if args.local else []) + list(args.library or [])
995
+
996
+ if not targets:
997
+ parser.print_help()
998
+ print(
999
+ console.bad(
1000
+ f"\nError: say what to install, for example: {target.current.command} owner/example"
1001
+ ),
1002
+ file=sys.stderr,
1003
+ )
1004
+ return 2
1005
+
1006
+ if args.folder and len(targets) > 1:
1007
+ _error(
1008
+ "--dir names the folder for one library. Give one library with it, or "
1009
+ "leave it out and answer the question for each."
1010
+ )
1011
+ return 2
1012
+
1013
+ staged = []
1014
+
1015
+ try:
1016
+ requested = []
1017
+
1018
+ # Not called target, which is the module: a local of that name hid it
1019
+ # from the whole function, and a run with nothing to install crashed
1020
+ # on the line that says so.
1021
+ for given in targets:
1022
+ source = _stage(given, args.ref, project_root, local=given == args.local)
1023
+
1024
+ if source is None:
1025
+ return 2
1026
+
1027
+ if source.staging is not None:
1028
+ staged.append(source.staging)
1029
+
1030
+ if source.in_place and args.folder:
1031
+ where = _show(source.root, source.project_root or project_root)
1032
+ _error(
1033
+ f"{where} is already in the project, so it becomes the library where "
1034
+ "it is and --dir has nothing to do.\n"
1035
+ "Rename the folder instead, or install from a copy outside the project."
1036
+ )
1037
+ return 2
1038
+
1039
+ code = _load(source, project_root)
1040
+
1041
+ if code is not None:
1042
+ return code
1043
+
1044
+ requested.append(source)
1045
+
1046
+ # Before the plan, since an option taken can bring libraries of its own.
1047
+ code = _settle_options(requested, project_root, args)
1048
+
1049
+ if code is not None:
1050
+ return code
1051
+
1052
+ try:
1053
+ plan = _plan(requested, project_root, staged)
1054
+ except _PlanError as error:
1055
+ _error(error)
1056
+ return 2
1057
+
1058
+ worst = 0
1059
+
1060
+ for step in plan:
1061
+ folder = args.folder if step.needed_by is None else None
1062
+ code = _install_step(step, project_root, folder, getattr(args, "ide", None))
1063
+
1064
+ # 1 is a run step that did not finish: the library is in, and so
1065
+ # can the rest be. Anything else stops the run.
1066
+ if code not in (0, 1):
1067
+ return code
1068
+
1069
+ worst = max(worst, code)
1070
+
1071
+ return worst
1072
+ finally:
1073
+ for path in staged:
1074
+ download.cleanup(path)
1075
+
1076
+
1077
+ def _peek(given, ref, local=False):
1078
+ """
1079
+ The parsed manifest of a library named on the command line, read before
1080
+ anything else for the platform it names: from a zip without unpacking it,
1081
+ from a folder, or from GitHub, where the fetch that follows asks nothing
1082
+ twice. Raises _PlanError with the reason when there is none to read.
1083
+ """
1084
+ raw = None
1085
+
1086
+ if given.startswith(("http://", "https://")):
1087
+ raw = download.peek(given, ref)
1088
+ else:
1089
+ path = Path(given).expanduser()
1090
+ kind = _kind(path)
1091
+
1092
+ if kind == "zip":
1093
+ raw = download.peek_zip(path)
1094
+ elif kind == "folder":
1095
+ found = manifest.manifest_path(download.find_root(path.resolve()) or path)
1096
+ raw = found.read_bytes() if found is not None else None
1097
+ elif kind == "file":
1098
+ raise _PlanError(f"{given} is not a .zip. Give the zip GitHub offers under Code, Download "
1099
+ "ZIP, or the folder it unpacks to.")
1100
+ elif local or _looks_like_path(given):
1101
+ raise _PlanError(f"{given} does not exist.")
1102
+ else:
1103
+ raw = download.peek(given, ref)
1104
+
1105
+ if raw is None:
1106
+ raise _PlanError(f"{given} holds no {manifest.MANIFEST_NAME}, so there is no library in it to install.")
1107
+
1108
+ data = yamlreader.parse(raw.decode("utf-8"))
1109
+
1110
+ return data if isinstance(data, dict) else {}
1111
+
1112
+
1113
+ def _recorded(folder, made):
1114
+ """The platform a folder's record says: lib-installer's, or the name of an older installer's."""
1115
+ found = installer.recorded_platform(folder)
1116
+
1117
+ if found in made:
1118
+ return found
1119
+
1120
+ return next((name for name, platform in made.items() if (folder / platform.legacy_record).is_file()), None)
1121
+
1122
+
1123
+ def _ask_platform(name, choices):
1124
+ """Which of a library's platforms this project is, asked. None when nobody answers."""
1125
+ print()
1126
+ print(console.heading(f"{name} works on more than one platform. Which is this project?"))
1127
+
1128
+ for number, choice in enumerate(choices, 1):
1129
+ print(f" {number} {choice}")
1130
+
1131
+ answer = (_answer(console.strong("Platform: ")) or "").strip().lower()
1132
+
1133
+ if answer.isdigit() and 1 <= int(answer) <= len(choices):
1134
+ return choices[int(answer) - 1]
1135
+
1136
+ return answer if answer in choices else None
1137
+
1138
+
1139
+ def _choose_platform(args, made, library_root):
1140
+ """
1141
+ The platform of this run: the one the libraries named on the command line
1142
+ give under platform in installer.yml, or --platform, which a library that
1143
+ names none needs, and one that names several can take. An uninstall takes
1144
+ the project's record. Returns the name, or None once the reason is printed.
1145
+ """
1146
+ names = ", ".join(made)
1147
+ folder = Path(args.project).resolve() if args.project else Path.cwd().resolve()
1148
+ recorded = _recorded(folder, made)
1149
+
1150
+ if recorded and args.platform and args.platform != recorded:
1151
+ _error(f"This project's record says {recorded}, and --platform gives {args.platform}.")
1152
+ return None
1153
+
1154
+ if args.uninstall:
1155
+ if not (args.platform or recorded):
1156
+ _error(f"Nothing here says which platform this project is. Say it with --platform, one of {names}.")
1157
+
1158
+ return args.platform or recorded
1159
+
1160
+ if library_root is not None:
1161
+ targets = [str(library_root)]
1162
+ else:
1163
+ targets = ([args.local] if args.local else []) + list(args.library or [])
1164
+
1165
+ # Nothing to install: the run says so, whichever platform.
1166
+ if not targets:
1167
+ return args.platform or recorded or next(iter(made))
1168
+
1169
+ said = []
1170
+
1171
+ try:
1172
+ for given in targets:
1173
+ data = _peek(given, args.ref, local=given == args.local)
1174
+ platforms = manifest.platforms_of(data)
1175
+
1176
+ if platforms is not None:
1177
+ said.append((str(data.get("name") or given), platforms))
1178
+ except (_PlanError, download.DownloadError, manifest.ManifestError, yamlreader.YamlError,
1179
+ UnicodeDecodeError) as error:
1180
+ _error(error)
1181
+ return None
1182
+
1183
+ if args.platform:
1184
+ for name, platforms in said:
1185
+ if args.platform not in platforms:
1186
+ _error(f"{name} is for {', '.join(platforms)}, and --platform gives {args.platform}.")
1187
+ return None
1188
+
1189
+ return args.platform
1190
+
1191
+ if not said:
1192
+ what = " and ".join(targets)
1193
+ hint = (f"This project's record says {recorded}, so add --platform {recorded}." if recorded else
1194
+ f"Say which it goes into with --platform, one of {names}.")
1195
+ _error(f"{what} names no platform in its {manifest.MANIFEST_NAME}. {hint}")
1196
+ return None
1197
+
1198
+ common = [name for name in said[0][1] if all(name in platforms for _, platforms in said)]
1199
+
1200
+ if not common:
1201
+ each = "; ".join(f"{name} for {', '.join(platforms)}" for name, platforms in said)
1202
+ _error(f"These libraries are for different platforms: {each}. Install them in runs of their own.")
1203
+ return None
1204
+
1205
+ if len(common) == 1:
1206
+ chosen = common[0]
1207
+ elif recorded in common:
1208
+ chosen = recorded
1209
+ else:
1210
+ chosen = _ask_platform(said[0][0], common)
1211
+
1212
+ if chosen is None:
1213
+ _error(f"{said[0][0]} works on {', '.join(common)}. Say which this project is with --platform.")
1214
+ return None
1215
+
1216
+ if recorded and recorded != chosen:
1217
+ _error(f"This project's record says {recorded}, and {said[0][0]} is for {chosen}.")
1218
+ return None
1219
+
1220
+ return chosen
1221
+
1222
+
1223
+ def _add_platform_arguments(parser, platform):
1224
+ """A target's own options: --ide for one that knows several IDEs, and whatever it adds."""
1225
+ if platform.integrations and not any("--ide" in a.option_strings for a in parser._actions):
1226
+ parser.add_argument(
1227
+ "--ide",
1228
+ default=None,
1229
+ choices=list(platform.integrations),
1230
+ help="only register with this IDE. Default is every one found.",
1231
+ )
1232
+
1233
+ platform.add_arguments(parser)
1234
+
1235
+
1236
+ def main(argv=None, library_root=None, platforms=None):
1237
+ """
1238
+ Entry point. Returns a process exit code.
1239
+
1240
+ platforms, {name: a function making its Target}, is lib-installer's: the
1241
+ platform is then the one the library names, or --platform, and every
1242
+ platform's own options are on the command line. Without it the run is
1243
+ the current target's, as the tests have it.
1244
+ """
1245
+ made = {name: make() for name, make in platforms.items()} if platforms else None
1246
+
1247
+ if made:
1248
+ hub = target.Platform()
1249
+ hub.version = next(iter(made.values())).version
1250
+ hub.project = "project"
1251
+ target.use(hub)
1252
+
1253
+ installer_ = target.current
1254
+ parser = argparse.ArgumentParser(
1255
+ prog=installer_.name,
1256
+ description=f"Install a library into your {installer_.project}.",
1257
+ epilog=f"Run this from the root of your {installer_.project}.",
1258
+ )
1259
+ parser.add_argument(
1260
+ "library",
1261
+ nargs="*",
1262
+ default=None,
1263
+ help='what to install: a name like "owner/example", a GitHub URL, '
1264
+ "a downloaded .zip, or a folder. Give several to install them together, "
1265
+ "such as a library and the zip of one it needs.",
1266
+ )
1267
+ parser.add_argument(
1268
+ "--ref",
1269
+ default=None,
1270
+ help="branch, tag or commit to fetch for the libraries named here, the same as "
1271
+ "owner/name@ref. Default the repository's default branch, whatever it is called. A "
1272
+ "library one of them needs comes from the ref its installer.yml names, or its "
1273
+ "default branch.",
1274
+ )
1275
+ parser.add_argument("--dir", dest="folder", default=None, help="folder to install into.")
1276
+ parser.add_argument(
1277
+ "--with",
1278
+ dest="with_options",
1279
+ action="append",
1280
+ metavar="OPTION",
1281
+ default=None,
1282
+ help="take this option of the library, such as littlefs for spif, without being "
1283
+ "asked. Give it once for each option.",
1284
+ )
1285
+ parser.add_argument(
1286
+ "--without",
1287
+ dest="without_options",
1288
+ action="append",
1289
+ metavar="OPTION",
1290
+ default=None,
1291
+ help="leave this option out, or take it out of a library already installed.",
1292
+ )
1293
+ parser.add_argument(
1294
+ "--project", default=None, help=f"root of your {installer_.project}. Defaults to this folder."
1295
+ )
1296
+ parser.add_argument(
1297
+ "--run",
1298
+ dest="run",
1299
+ action="append",
1300
+ metavar="STEP",
1301
+ default=None,
1302
+ help="run this step of the library once it is in, without being asked, such as one that "
1303
+ "makes a key. Give it once for each step.",
1304
+ )
1305
+ parser.add_argument(
1306
+ "--no-run",
1307
+ dest="no_run",
1308
+ action="append",
1309
+ metavar="STEP",
1310
+ default=None,
1311
+ help="leave this step of the library unrun, without being asked.",
1312
+ )
1313
+ parser.add_argument(
1314
+ "-y",
1315
+ "--yes",
1316
+ action="store_true",
1317
+ help="take the answer each question offers, without asking, and run every step. For a "
1318
+ "script or a build server.",
1319
+ )
1320
+ parser.add_argument(
1321
+ "--no-update-check",
1322
+ action="store_true",
1323
+ help="do not ask PyPI whether a newer installer is out. CI and INSTALLER_NO_UPDATE_CHECK "
1324
+ "turn it off as well.",
1325
+ )
1326
+ parser.add_argument(
1327
+ "--key",
1328
+ "--token",
1329
+ dest="key",
1330
+ default=None,
1331
+ metavar="TOKEN",
1332
+ help="a GitHub token, for a library in a private repository. GITHUB_TOKEN works as well, "
1333
+ "and keeps it out of your shell's history. Sent to GitHub and nowhere else.",
1334
+ )
1335
+ parser.add_argument(
1336
+ "--uninstall",
1337
+ nargs="+",
1338
+ default=None,
1339
+ metavar="NAME",
1340
+ help="take these libraries out of the project: their files, and their place in the build. "
1341
+ "What you wrote in them is saved beside them first.",
1342
+ )
1343
+ # Before a folder could be given as the plain argument, it took this option.
1344
+ # Kept working for anyone who still types it, but no longer advertised.
1345
+ parser.add_argument("--local", default=None, help=argparse.SUPPRESS)
1346
+ # Each platform's own options, by their name on the command line, so one
1347
+ # given for another platform is refused rather than quietly ignored.
1348
+ own = {}
1349
+
1350
+ if made:
1351
+ parser.add_argument(
1352
+ "--platform",
1353
+ choices=list(made),
1354
+ default=None,
1355
+ help="the platform to install into, for a library whose installer.yml names none, or "
1356
+ "several. Not needed otherwise: the library's own platform is used.",
1357
+ )
1358
+
1359
+ # Under a heading of each platform's in the help.
1360
+ for name, platform in made.items():
1361
+ before = list(parser._actions)
1362
+ _add_platform_arguments(parser.add_argument_group(f"{platform.label} only"), platform)
1363
+ own[name] = [action for action in parser._actions if action not in before]
1364
+ else:
1365
+ _add_platform_arguments(parser, installer_)
1366
+ # -V as well, because that is what pip and python answer to.
1367
+ parser.add_argument(
1368
+ "-V",
1369
+ "--version",
1370
+ action="version",
1371
+ version=f"%(prog)s {installer_.version}",
1372
+ help="show which version of the installer this is, and do nothing else.",
1373
+ )
1374
+
1375
+ args = parser.parse_args(argv)
1376
+
1377
+ # For this run only, so a second run in the same process starts clean.
1378
+ global _assume_yes, _run_on, _run_off
1379
+ _assume_yes = bool(args.yes)
1380
+ _run_on, _run_off = (), ()
1381
+
1382
+ download.use_token(args.key)
1383
+ check = updates.Check(installer_.name, installer_.version, enabled=not args.no_update_check)
1384
+
1385
+ # The platform first, from the libraries' installer.yml, with what GitHub
1386
+ # answers kept for the run, so the fetch that follows asks nothing twice.
1387
+ if made:
1388
+ download.remember()
1389
+
1390
+ try:
1391
+ if made:
1392
+ chosen = _choose_platform(args, made, library_root)
1393
+
1394
+ if chosen is None:
1395
+ return 2
1396
+
1397
+ for name, actions in own.items():
1398
+ for action in actions:
1399
+ if name != chosen and getattr(args, action.dest, None) not in (None, False, []):
1400
+ _error(f"{action.option_strings[0]} is for {made[name].label} projects, and "
1401
+ f"this one is for {made[chosen].label}.")
1402
+ return 2
1403
+
1404
+ installer_ = made[chosen]
1405
+
1406
+ if args.platform:
1407
+ installer_.command_suffix = f" --platform {chosen}"
1408
+
1409
+ target.use(installer_)
1410
+
1411
+ installer_.take_arguments(args, _answer)
1412
+
1413
+ if args.uninstall:
1414
+ return _uninstall(args)
1415
+
1416
+ return _run(args, parser, library_root)
1417
+ except KeyboardInterrupt:
1418
+ # Ctrl+C at the folder question used to mean "take the default" and go
1419
+ # ahead with the install. It means stop.
1420
+ print(console.warn("\nCancelled."), file=sys.stderr)
1421
+ return 130
1422
+ finally:
1423
+ download.forget()
1424
+ newer = check.message()
1425
+
1426
+ if newer:
1427
+ print()
1428
+ print(console.warn(newer))
1429
+
1430
+
1431
+ if __name__ == "__main__":
1432
+ sys.exit(main())