-
Notifications
You must be signed in to change notification settings - Fork 154
Expand file tree
/
Copy pathproject.py
More file actions
2777 lines (2383 loc) · 106 KB
/
project.py
File metadata and controls
2777 lines (2383 loc) · 106 KB
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2018, 2019 Nordic Semiconductor ASA
# Copyright 2018, 2019 Foundries.io
#
# SPDX-License-Identifier: Apache-2.0
'''West project commands'''
import argparse
import hashlib
import logging
import os
import shlex
import shutil
import subprocess
import sys
import textwrap
import time
from functools import partial
from os.path import abspath, basename, relpath
from pathlib import Path, PurePath
from time import perf_counter
from urllib.parse import urlparse
from west import util
from west.commands import CommandError, Verbosity, WestCommand
from west.configuration import Configuration
from west.manifest import (
_WEST_YML,
ImportFlag,
Manifest,
ManifestImportFailed,
ManifestProject,
Submodule,
_manifest_content_at,
)
from west.manifest import MANIFEST_REV_BRANCH as MANIFEST_REV
from west.manifest import QUAL_MANIFEST_REV_BRANCH as QUAL_MANIFEST_REV
from west.manifest import QUAL_REFS_WEST as QUAL_REFS
from west.manifest import is_group as is_project_group
from west.util import expand_path
#
# Project-related or multi-repo commands, like "init", "update",
# "diff", etc.
#
class _ProjectCommand(WestCommand):
# Helper class which contains common code needed by various commands
# in this file.
def _parser(self, parser_adder, **kwargs):
# Create and return a "standard" parser.
kwargs['help'] = self.help
kwargs['description'] = self.description
kwargs['formatter_class'] = argparse.RawDescriptionHelpFormatter
return parser_adder.add_parser(self.name, **kwargs)
def _cloned_projects(self, args, only_active=False):
# Returns _projects(args.projects, only_cloned=True) if
# args.projects is not empty (i.e., explicitly given projects
# are required to be cloned). Otherwise, returns all cloned
# projects.
if args.projects:
ret = self._projects(args.projects, only_cloned=True)
else:
ret = [p for p in self.manifest.projects if p.is_cloned()]
if args.projects or not only_active:
return ret
return [p for p in ret if self.manifest.is_active(p)]
def _projects(self, ids, only_cloned=False):
try:
return self.manifest.get_projects(ids, only_cloned=only_cloned)
except ValueError as ve:
if len(ve.args) != 2:
raise # not directly raised by get_projects()
# Die with an error message on unknown or uncloned projects.
unknown, uncloned = ve.args
if unknown:
self._die_unknown(unknown)
elif only_cloned and uncloned:
s = 's' if len(uncloned) > 1 else ''
names = ' '.join(p.name for p in uncloned)
self.die(f'uncloned project{s}: {names}.\n Hint: run "west update" and retry.')
else:
# Should never happen, but re-raise to fail fast and
# preserve a stack trace, to encourage a bug report.
raise
def _handle_failed(self, args, failed):
# Shared code for commands (like status, diff, update) that need
# to do the same thing to multiple projects, but collect
# and report errors if anything failed.
if not failed:
self.dbg(f'git {self.name} failed for zero project')
return
elif len(failed) < 20:
s = 's:' if len(failed) > 1 else ''
projects = ', '.join(f'{p.name}' for p in failed)
self.err(f'{self.name} failed for project{s} {projects}')
else:
self.err(f'{self.name} failed for multiple projects; see above')
raise CommandError(1)
def _die_unknown(self, unknown):
# Scream and die about unknown projects.
s = 's' if len(unknown) > 1 else ''
names = ' '.join(unknown)
self.die(
f'unknown project name{s}/path{s}: {names}\n'
' Hint: use "west list" to list all projects.'
)
def _has_nonempty_status(self, project):
# Check if the project has any status output to print. We
# manually use Popen in order to try to exit as quickly as
# possible if 'git status' prints anything.
popen = subprocess.Popen(
['git', 'status', '--porcelain'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=project.abspath,
)
def has_output():
# 'git status --porcelain' prints nothing if there
# are no notable changes, so any output at all
# means we should run 'git status' on the project.
stdout, stderr = None, None
try:
stdout, stderr = popen.communicate(timeout=0.1)
except subprocess.TimeoutExpired:
pass
return stdout or stderr
while True:
if has_output():
popen.kill()
return True
if popen.poll() is not None:
break
return has_output()
class Init(_ProjectCommand):
def __init__(self):
super().__init__(
'init',
'create a west workspace',
f'''\
Initialize a west workspace (topdir) from a west manifest (`west.yml`) by
creating a `.west` directory in the topdir and a local configuration file
`.west/config`.
The West manifest can come from either a git repository (that will be cloned
during workspace initialization) or from an already existing local directory.
Arguments
---------
--mf / --manifest-file
The relative path to the manifest file within the manifest repository
or directory. Config option `manifest.file` will be set to this value.
Defaults to '{_WEST_YML}' if not provided.
-t / --topdir
Specifies the directory where west should create the workspace.
The `.west` folder will be created inside this directory.
If it is an already existing directory, it must not contain a .west folder.
1. Using a Manifest Repository (default)
----------------------------------------
West clones the given repository (provided via `-m / --manifest-url`).
Note, that the repository must contain a west manifest.
If no `-m / --manifest-url` is provided, west uses Zephyr URL by default:
{MANIFEST_URL_DEFAULT}.
The topdir (where `.west` is created) is determined as follows:
- argument `-t / --topdir` if provided
- otherwise: the positional argument `directory` if provided
- otherwise: the current working directory
If both `-t / --topdir` and `directory` are provided, `-t / --topdir`
specifies the workspace directory, while positional argument `directory`
specifies the subfolder within the workspace where the manifest repository is
cloned during initialization (defaults to <directory>/zephyr/.git).
With `--mr`, the revision (branch, tag, or sha) of the repository can be
specified that will be used. It defaults to the repository's default branch.
2. Using a Local Manifest
-------------------------
If `-l / --local` is given, west initializes a workspace from an already
existing `west.yml`. Its location can be specified in the `manifest_directory`
positional argument, which defaults to current working directory.
The topdir (where `.west` is created) is determined as follows:
- argument `-t / --topdir` if provided
- otherwise: `manifest_directory`'s parent
Known Issues
------------
'west init' renames and/or deletes temporary files inside the
workspace being created. This fails on some filesystems when some
development tool or any other program is trying to read/index these
temporary files at the same time. For instance, it is required to stop
Visual Studio Code before running 'west init` on the Windows NTFS
filesystem. Find other, similar "Access is denied" examples in west
issue #558.
This is not required with most Linux filesystems that have an inode
indirection layer and can wait to
finalize the deletion until there is no concurrent user left.
If you cannot identify or cannot stop the background scanner
that is interfering with renames on your system, try the --rename-delay hack
below.
''',
requires_workspace=False,
)
def do_add_parser(self, parser_adder):
# We set a custom usage because there are two distinct ways
# to call this command, and the default usage generated by
# argparse doesn't make that very clear.
parser = self._parser(
parser_adder,
usage='''
init with a repository:
%(prog)s [-m URL] [--mr REVISION] [--mf FILE] [-o=GIT_CLONE_OPTION] [-t WORKSPACE_DIR] [directory]
init with an existing local manifest:
%(prog)s -l [-t WORKSPACE_DIR] [--mf FILE] [manifest_directory]
''',
)
# Remember to update the usage if you modify any arguments.
parser.add_argument(
'-m',
'--manifest-url',
metavar='URL',
help='''manifest repository URL to clone;
cannot be combined with -l''',
)
parser.add_argument(
'-o',
'--clone-opt',
action='append',
default=[],
metavar='GIT_CLONE_OPTION',
help='''additional option to pass to 'git clone'
(e.g. '-o=--depth=1'); may be given more than once;
cannot be combined with -l''',
)
parser.add_argument(
'--mr',
'--manifest-rev',
dest='manifest_rev',
metavar='REVISION',
help='''manifest repository branch or tag name
to check out first; cannot be combined with -l''',
)
parser.add_argument(
'-l',
'--local',
action='store_true',
help='''initialize workspace from an already existing local
manifest instead of cloning a manifest;
cannot be combined with -m''',
)
parser.add_argument(
'--mf',
'--manifest-file',
dest='manifest_file',
metavar='FILE',
help=f'''manifest file to use. It is the relative
path to the manifest file within the manifest_directory.
Defaults to {_WEST_YML}.''',
)
parser.add_argument(
'-t',
'--topdir',
dest='topdir',
metavar='WORKSPACE_DIR',
help='''the workspace directory where .west directory
will be created (WORKSPACE_DIR/.west);
the workspace directory may already exist
and WORKSPACE_DIR/.west must not exist''',
)
parser.add_argument(
'--rename-delay',
type=int,
help='''Number of seconds to wait before renaming
some temporary directories. Some filesystems like NTFS
cannot rename files in use; see above. This is a HACK
that may or may not give enough time for some random
background scanner to complete. ''',
)
parser.add_argument(
'directory',
nargs='?',
default=None,
metavar='directory',
help='''With --local: the path to a local directory which contains
a west manifest (west.yml);
Otherwise, if no --topdir is provided:
the location of the west workspace where .west directory
will be created (<directory>/.west)
Otherwise:
the location where west will clone the manifest repository
''',
)
return parser
def do_run(self, args, _):
if self.topdir:
zb = os.environ.get('ZEPHYR_BASE')
if zb:
msg = textwrap.dedent(f'''
Note:
In your environment, ZEPHYR_BASE is set to:
{zb}
This forces west to search for a workspace there.
Try unsetting ZEPHYR_BASE and re-running this command.''')
else:
west_dir = Path(self.topdir) / WEST_DIR
msg = (
"\n Hint: if you do not want a workspace there, \n"
" remove this directory and re-run this command:\n\n"
f" {west_dir}"
)
self.die_already(self.topdir, msg)
if args.local and (args.manifest_url or args.manifest_rev or args.clone_opt):
self.die('-l cannot be combined with -m, -o or --mr')
if args.manifest_file is not None and Path(args.manifest_file).is_absolute():
self.die(f'--mf {args.manifest_file} argument is not relative')
self.die_if_no_git()
if args.local:
topdir = self.local(args)
else:
topdir = self.bootstrap(args)
self.banner(f'Initialized. Now run "west update" inside {topdir}.')
def die_already(self, where, also=None):
self.die(f'already initialized in {where}, aborting.{also or ""}')
def local(self, args) -> Path:
if args.manifest_rev is not None:
self.die('--mr cannot be used with -l')
# We need to resolve this to handle the case that args.directory
# is '.'. In that case, Path('.').parent is just Path('.') instead of
# Path('..').
#
# https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.parent
manifest_dir = Path(args.directory or '.').resolve()
manifest_filename = args.manifest_file or _WEST_YML
manifest_file = manifest_dir / manifest_filename
if not manifest_file.is_file():
self.die(f'can\'t init: no {manifest_filename} found in {manifest_dir}')
topdir = Path(args.topdir or manifest_dir.parent).resolve()
if not manifest_file.is_relative_to(topdir):
self.die(f'{manifest_file} must be relative to west topdir {topdir}')
try:
already = util.west_topdir(manifest_dir, fall_back=False)
self.die_already(already)
except util.WestNotFound:
pass
rel_manifest = manifest_dir.relative_to(topdir)
west_dir = topdir / WEST_DIR
self.banner('Initializing with existing manifest', rel_manifest)
self.small_banner(f'Creating {west_dir} and local configuration file')
self.create(west_dir)
os.chdir(topdir)
self.config = Configuration(topdir=topdir)
self.config.set('manifest.path', os.fspath(rel_manifest))
self.config.set('manifest.file', manifest_filename)
return topdir
def bootstrap(self, args) -> Path:
manifest_subdir = Path()
if args.topdir:
topdir = Path(args.topdir).resolve()
if args.directory:
directory = Path(args.directory)
if not directory.is_absolute():
directory = directory.resolve()
if not directory.is_relative_to(topdir):
self.die(
f"directory '{args.directory}' must be inside west topdir '{args.topdir}'"
)
manifest_subdir = directory.relative_to(topdir)
elif args.directory:
topdir = Path(args.directory)
else:
topdir = Path()
topdir = topdir.resolve()
self.banner(f'Initializing in {topdir}')
manifest_url = args.manifest_url or MANIFEST_URL_DEFAULT
if args.manifest_rev:
# This works with tags, too.
branch_opt = ['--branch', args.manifest_rev]
else:
branch_opt = []
west_dir = topdir / WEST_DIR
try:
already = util.west_topdir(topdir, fall_back=False)
self.die_already(already)
except util.WestNotFound:
pass
if not topdir.is_dir():
self.create(topdir, exist_ok=False)
tempdir: Path = west_dir / 'manifest-tmp'
if tempdir.is_dir():
self.dbg('removing existing temporary manifest directory', tempdir)
shutil.rmtree(tempdir)
# Test that we can rename and delete directories. For the vast
# majority of users this is a no-op but some filesystem
# permissions can be weird; see October 2024 example in west
# issue #558. Git cloning can take a long time, so check this
# first. Failing ourselves is not just faster, it's also much
# clearer than when git is involved in the mix.
tempdir.mkdir(parents=True)
(tempdir / 'not empty').mkdir()
# Ignore the --rename-delay hack here not to double the wait;
# we only have a couple directories and no file at this point!
tempdir2 = tempdir.parent / 'renamed tempdir'
os.rename(tempdir, tempdir2)
# No need to delete west_dir parent
shutil.rmtree(tempdir2)
# Clone the manifest repository into a temporary directory.
try:
self.small_banner(
f'Cloning manifest repository from {manifest_url}'
+ (f', rev. {args.manifest_rev}' if args.manifest_rev else '')
)
self.check_call(
['git', 'clone'] + branch_opt + args.clone_opt + [manifest_url, os.fspath(tempdir)]
)
except subprocess.CalledProcessError:
shutil.rmtree(tempdir, ignore_errors=True)
raise
# Verify the manifest file exists.
temp_manifest_filename = args.manifest_file or _WEST_YML
temp_manifest = tempdir / temp_manifest_filename
if not temp_manifest.is_file():
self.die(
f'can\'t init: no {temp_manifest_filename} found in '
f'{tempdir}\n'
f' Hint: check --manifest-url={manifest_url}'
+ (f' and --manifest-rev={args.manifest_rev}' if args.manifest_rev else '')
+ f' You may need to remove {west_dir} before retrying.'
)
# Parse the manifest to get "self: path:", if it declares one.
# Otherwise, use the URL. Ignore imports -- all we really
# want to know is if there's a "self: path:" or not.
manifest = Manifest.from_data(
temp_manifest.read_text(encoding=Manifest.encoding), import_flags=ImportFlag.IGNORE
)
if manifest.yaml_path:
yaml_path = manifest.yaml_path
else:
# We use PurePath() here in case manifest_url is a
# windows-style path. That does the right thing in that
# case, without affecting POSIX platforms, where PurePath
# is PurePosixPath.
yaml_path = PurePath(urlparse(manifest_url).path).name
manifest_path = Path(manifest_subdir) / yaml_path
manifest_abspath = topdir / manifest_path
# Some filesystems like NTFS can't rename files in use.
# See west issue #558. Will ReFS address this?
ren_delay = args.rename_delay
if ren_delay is not None:
self.inf(f"HACK: waiting {ren_delay} seconds before renaming {tempdir}")
time.sleep(ren_delay)
self.dbg('moving', tempdir, 'to', manifest_abspath, level=Verbosity.DBG_EXTREME)
# As shutil.move() is used to relocate tempdir, if manifest_abspath
# is an existing directory, tmpdir will be moved _inside_ it, instead
# of _to_ that path - this must be avoided. If manifest_abspath exists
# but is not a directory, then semantics depend on os.rename(), so
# avoid that too...
if manifest_abspath.exists():
self.die(f'target directory already exists ({manifest_abspath})')
manifest_abspath.parent.mkdir(parents=True, exist_ok=True)
try:
shutil.move(os.fspath(tempdir), os.fspath(manifest_abspath))
except shutil.Error as e:
self.die(e)
self.small_banner('setting manifest.path to', manifest_path)
self.config = Configuration(topdir=topdir)
self.config.set('manifest.path', str(manifest_path))
self.config.set('manifest.file', temp_manifest_filename)
return topdir
def create(self, directory: Path, exist_ok: bool = True) -> None:
try:
directory.mkdir(parents=True, exist_ok=exist_ok)
except PermissionError:
self.die(f'Cannot initialize in {directory}: permission denied')
except FileExistsError:
self.die(f'Cannot initialize in {directory}: it already exists')
except Exception as e:
self.die(f"Can't create {directory}: {e}")
class List(_ProjectCommand):
def __init__(self):
super().__init__(
'list',
'print information about projects',
textwrap.dedent('''\
Print information about projects in the west manifest,
using format strings.'''),
)
def do_add_parser(self, parser_adder):
default_fmt = '{name:12} {path:28} {revision:40} {url}'
parser = self._parser(
parser_adder,
epilog=f'''\
{ACTIVE_PROJECTS_HELP}
Note: To list only inactive projects you can use --inactive.
FORMAT STRINGS
--------------
Projects are listed using a Python 3 format string. Arguments
to the format string are accessed by name.
The default format string is:
"{default_fmt}"
The following arguments are available:
- name: project name in the manifest
- description: project description in the manifest
- url: full remote URL as specified by the manifest
- path: the relative path to the project from the top level,
as specified in the manifest where applicable
- abspath: absolute and normalized path to the project
- posixpath: like abspath, but in posix style, that is, with '/'
as the separator character instead of '\\'
- revision: project's revision as it appears in the manifest
- sha: project's revision as a SHA. Note that use of this requires
that the project has been cloned.
- cloned: "cloned" if the project has been cloned, "not-cloned"
otherwise
- active: "active" if the project is currently active, "inactive" otherwise
- clone_depth: project clone depth if specified, "None" otherwise
- groups: project groups, as a comma-separated list
''',
)
group = parser.add_mutually_exclusive_group(required=False)
group.add_argument('-a', '--all', action='store_true', help='include inactive projects')
group.add_argument(
'-i', '--inactive', action='store_true', help='list only inactive projects'
)
parser.add_argument(
'--manifest-path-from-yaml',
action='store_true',
help='''print the manifest repository's path
according to the manifest file YAML, which may
disagree with the manifest.path configuration
option''',
)
parser.add_argument(
'-f',
'--format',
default=default_fmt,
help='''format string to use to list each
project; see FORMAT STRINGS below.''',
)
parser.add_argument(
'projects',
metavar='PROJECT',
nargs='*',
help='''projects (by name or path) to operate on;
see ACTIVE PROJECTS below''',
)
return parser
def do_run(self, args, user_args):
def sha_thunk(project):
self.die_if_no_git()
if not project.is_cloned():
self.die(
f'cannot get sha for uncloned project {project.name}; '
f'run "west update {project.name}" and retry'
)
elif isinstance(project, ManifestProject):
return f'{"N/A":40}'
else:
return project.sha(MANIFEST_REV)
def cloned_thunk(project):
self.die_if_no_git()
return "cloned" if project.is_cloned() else "not-cloned"
def active_thunk(project):
self.die_if_no_git()
return "active" if self.manifest.is_active(project) else "inactive"
def delay(func, project):
return DelayFormat(partial(func, project))
if args.inactive and args.projects:
self.parser.error('-i cannot be combined with an explicit project list')
for project in self._projects(args.projects):
# Include the project based on the inactive flag. If the flag is
# set, include only inactive projects. Otherwise, include only
# active ones.
include = self.manifest.is_active(project) != bool(args.inactive)
# Skip not included projects unless the user said
# --all or named some projects explicitly.
if not (args.all or args.projects or include):
self.dbg(f'{project.name}: skipping project')
continue
# Spelling out the format keys explicitly here gives us
# future-proofing if the internal Project representation
# ever changes.
#
# Using DelayFormat delays computing derived values, such
# as SHAs, unless they are specifically requested, and then
# ensures they are only computed once.
try:
if isinstance(project, ManifestProject):
# Special-case the manifest repository while it's
# still showing up in the 'projects' list. Yet
# more evidence we should tackle #327.
if args.manifest_path_from_yaml:
path = self.manifest.yaml_path
apath = abspath(os.path.join(self.topdir, path)) if path else None
ppath = Path(apath).as_posix() if apath else None
else:
path = self.manifest.repo_path
apath = self.manifest.repo_abspath
ppath = self.manifest.repo_posixpath
else:
path = project.path
apath = project.abspath
ppath = project.posixpath
result = args.format.format(
name=project.name,
description=project.description or "None",
url=project.url or 'N/A',
path=path,
abspath=apath,
posixpath=ppath,
revision=project.revision or 'N/A',
clone_depth=project.clone_depth or "None",
cloned=delay(cloned_thunk, project),
active=delay(active_thunk, project),
sha=delay(sha_thunk, project),
groups=','.join(project.groups),
)
except KeyError as e:
# The raised KeyError seems to just put the first
# invalid argument in the args tuple, regardless of
# how many unrecognizable keys there were.
self.die(f'unknown key "{e.args[0]}" in format string {shlex.quote(args.format)}')
except IndexError:
self.parser.print_usage()
self.die(f'invalid format string {shlex.quote(args.format)}')
except subprocess.CalledProcessError:
self.die(f'subprocess failed while listing {project.name}')
self.inf(result, colorize=False)
class ManifestCommand(_ProjectCommand):
# The slightly weird naming is to avoid a conflict with
# west.manifest.Manifest.
def __init__(self):
super().__init__(
'manifest',
'manage the west manifest',
textwrap.dedent('''\
Manages the west manifest.
The following actions are available. You must give exactly one.
- --resolve: print the current manifest with all imports applied,
as an equivalent single manifest file. Any imported manifests
must be cloned locally (with "west update").
- --freeze: like --resolve, but with all project revisions
converted to their current SHAs, based on the latest manifest-rev
branches. All projects must be cloned (with "west update").
- --validate: print an error and exit the process unsuccessfully
if the current manifest cannot be successfully parsed.
If the manifest can be parsed, print nothing and exit
successfully.
- --path: print the path to the top level manifest file.
If this file uses imports, it will not contain all the
manifest data.
- --untracked: print all files and directories inside the workspace that
are not tracked or managed by west. This effectively means any
file or directory that is outside all of the projects' directories on
disk (regardless of whether those projects are active or inactive).
This is similar to `git status` for untracked files. The
output format is relative to the current working directory and is
stable and suitable as input for scripting.
If the manifest file does not use imports, and all project
revisions are SHAs, the --freeze and --resolve output will
be identical after a "west update".
'''),
accepts_unknown_args=False,
)
def do_add_parser(self, parser_adder):
parser = self._parser(parser_adder)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument(
'--resolve', action='store_true', help='print the manifest with all imports resolved'
)
group.add_argument(
'--freeze',
action='store_true',
help='print the resolved manifest with SHAs for all project revisions',
)
group.add_argument(
'--validate',
action='store_true',
help='validate the current manifest, exiting with an error if there are issues',
)
group.add_argument(
'--path', action='store_true', help="print the top level manifest file's path"
)
group.add_argument(
'--untracked',
action='store_true',
help='print all files and directories not managed or tracked by west',
)
group = parser.add_argument_group('options for --resolve and --freeze')
group.add_argument('-o', '--out', help='output file, default is standard output')
group.add_argument(
'--active-only', action='store_true', help='only resolve active projects'
)
return parser
def do_run(self, args, user_args):
manifest = self.manifest
dump_kwargs = {'default_flow_style': False, 'sort_keys': False}
if args.validate:
pass # nothing more to do
elif args.resolve:
if not args.active_only:
self._die_if_manifest_project_filter('resolve')
self._dump(args, manifest.as_yaml(active_only=args.active_only, **dump_kwargs))
elif args.freeze:
if not args.active_only:
self._die_if_manifest_project_filter('freeze')
self._dump(args, manifest.as_frozen_yaml(active_only=args.active_only, **dump_kwargs))
elif args.untracked:
self._untracked()
elif args.path:
self.inf(manifest.path)
else:
# Can't happen.
raise RuntimeError(f'internal error: unhandled args {args}')
def _die_if_manifest_project_filter(self, action):
if self.config.get('manifest.project-filter') is not None:
self.die(
f'"west manifest --{action}" is not (yet) supported '
'when the manifest.project-filter option is set. '
f'Add --active-only to {action} only the projects '
'currently active in the workspace. Alternatively, '
'please clear the project-filter configuration '
'option and re-run this command, or contact the '
'west developers if you have a use case for resolving '
'the manifest while projects are made inactive by the '
'project filter.'
)
def _untracked(self):
'''"Performs a top-down search of the west topdir,
ignoring every directory that corresponds to a west project.
'''
ppaths = []
untracked = []
for project in self._projects(None):
# We do not check for self.manifest.is_active(project) because
# inactive projects are still considered "tracked directories".
ppaths.append(Path(project.abspath))
# Since west tolerates nested projects (i.e. a project inside the directory
# of another project) we must sort the project paths to ensure that we
# hit the "enclosing" project first when iterating.
ppaths.sort()
def _find_untracked(directory):
'''There are three cases for each element in a directory:
- It's a project -> Do nothing, ignore the directory.
- There are no projects inside -> add to untracked list.
- It's not a project directory but there are some projects inside it -> recurse.
The directory argument cannot be inside a project, otherwise all bets are off.
'''
self.dbg(f'looking for untracked files/directories in: {directory}')
for e in [e.absolute() for e in directory.iterdir()]:
if not e.is_dir() or e.is_symlink():
untracked.append(e)
continue
self.dbg(f'processing directory: {e}')
for ppath in ppaths:
# We cannot use samefile() because it requires the file
# to exist (not always the case with inactive or even
# uncloned projects).
if ppath == e:
# We hit a project root directory, skip it.
break
elif e in ppath.parents:
self.dbg(f'recursing into: {e}')
_find_untracked(e)
break
else:
# This is not a project and there is no project inside.
# Add to untracked elements.
untracked.append(e)
continue
# Avoid using Path.walk() since that returns all files and directories under
# a particular directory, which is overkill in our case. Instead, recurse
# only when required.
_find_untracked(Path(self.topdir))
# Exclude the .west directory, which is maintained by west
try:
untracked.remove((Path(self.topdir) / Path(WEST_DIR)).resolve())
except ValueError:
self.die(f'Directory {WEST_DIR} not found in workspace')
# Sort the results for displaying to the user.
untracked.sort()
for u in untracked:
# We cannot use Path.relative_to(p, walk_up=True) because the
# walk_up parameter was only added in 3.12
self.inf(os.path.relpath(u, Path.cwd()))
def _dump(self, args, to_dump):
if args.out:
with open(args.out, 'w') as f:
f.write(to_dump)
else:
sys.stdout.write(to_dump)
class Compare(_ProjectCommand):
def __init__(self):
super().__init__(
'compare',
"compare project status against the manifest",
textwrap.dedent('''\
Compare each project's working tree state against the results
of the most recent successful "west update" command.
This command prints output for a project if (and only if)
at least one of the following is true:
1. its checked out commit (HEAD) is different than the commit
checked out by the most recent successful "west update"
(which the manifest-rev branch will point to)
2. its working tree is not clean (i.e. there are local uncommitted
changes)
3. it has a local checked out branch (unless the configuration
option compare.ignore-branches is true or --ignore-branches
is given on the command line, either of which disable this)
The command also prints output for the manifest repository if it
has nonempty status.
The output is meant to be human-readable, and may change. It is
not a stable interface to write scripts against. This command
requires git 2.22 or later.'''),
)
def do_add_parser(self, parser_adder):
parser = self._parser(parser_adder, epilog=ACTIVE_CLONED_PROJECTS_HELP)
parser.add_argument(
'projects',
metavar='PROJECT',
nargs='*',
help='projects (by name or path) to operate on; defaults to active cloned projects',
)
parser.add_argument(
'-a', '--all', action='store_true', help='include output for inactive projects'
)
parser.add_argument(
'--exit-code',
action='store_true',
help='exit with status code 1 if status output was printed for any project',
)
parser.add_argument(
'--ignore-branches',
default=None,
action='store_true',
help='''skip output for projects with checked out
branches and clean working trees if the branch is
at the same commit as the last "west update"''',
)
parser.add_argument(
'--no-ignore-branches',
dest='ignore_branches',
action='store_false',
help='''overrides a previous --ignore-branches
or any compare.ignore-branches configuration
option''',
)
return parser
def do_run(self, args, ignored):
self.die_if_no_git()
if self.git_version_info < (2, 22):
# This is for git branch --show-current.
self.die('git version 2.22 or later is required')
if args.ignore_branches is not None:
self.ignore_branches = args.ignore_branches
else:
self.ignore_branches = self.config.getboolean('compare.ignore-branches', False)
failed = []
printed_output = False
for project in self._cloned_projects(args, only_active=not args.all):
if isinstance(project, ManifestProject):
# West doesn't track the relationship between the manifest
# repository and any remote, but users are still interested
# in printing output for comparisons that makes sense.
if self._has_nonempty_status(project):
try:
self.compare(project)
printed_output = True
except subprocess.CalledProcessError:
failed.append(project)
continue
# 'git status' output for all projects is noisy when there
# are lots of projects.
#
# We avoid this problem in 2 steps:
#