-
Notifications
You must be signed in to change notification settings - Fork 0
/
gclient.py
executable file
·4310 lines (3816 loc) · 171 KB
/
gclient.py
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
#!/usr/bin/env python3
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Meta checkout dependency manager for Git."""
# Files
# .gclient : Current client configuration, written by 'config' command.
# Format is a Python script defining 'solutions', a list whose
# entries each are maps binding the strings "name" and "url"
# to strings specifying the name and location of the client
# module, as well as "custom_deps" to a map similar to the
# deps section of the DEPS file below, as well as
# "custom_hooks" to a list similar to the hooks sections of
# the DEPS file below.
# .gclient_entries : A cache constructed by 'update' command. Format is a
# Python script defining 'entries', a list of the names
# of all modules in the client
# <module>/DEPS : Python script defining var 'deps' as a map from each
# requisite submodule name to a URL where it can be found (via
# one SCM)
#
# Hooks
# .gclient and DEPS files may optionally contain a list named "hooks" to
# allow custom actions to be performed based on files that have changed in the
# working copy as a result of a "sync"/"update" or "revert" operation. This
# can be prevented by using --nohooks (hooks run by default). Hooks can also
# be forced to run with the "runhooks" operation. If "sync" is run with
# --force, all known but not suppressed hooks will run regardless of the state
# of the working copy.
#
# Each item in a "hooks" list is a dict, containing these two keys:
# "pattern" The associated value is a string containing a regular
# expression. When a file whose pathname matches the expression
# is checked out, updated, or reverted, the hook's "action" will
# run.
# "action" A list describing a command to run along with its arguments, if
# any. An action command will run at most one time per gclient
# invocation, regardless of how many files matched the pattern.
# The action is executed in the same directory as the .gclient
# file. If the first item in the list is the string "python",
# the current Python interpreter (sys.executable) will be used
# to run the command. If the list contains string
# "$matching_files" it will be removed from the list and the list
# will be extended by the list of matching files.
# "name" An optional string specifying the group to which a hook belongs
# for overriding and organizing.
#
# Example:
# hooks = [
# { "pattern": "\\.(gif|jpe?g|pr0n|png)$",
# "action": ["python", "image_indexer.py", "--all"]},
# { "pattern": ".",
# "name": "gyp",
# "action": ["python", "src/build/gyp_chromium"]},
# ]
#
# Pre-DEPS Hooks
# DEPS files may optionally contain a list named "pre_deps_hooks". These are
# the same as normal hooks, except that they run before the DEPS are
# processed. Pre-DEPS run with "sync" and "revert" unless the --noprehooks
# flag is used.
#
# Specifying a target OS
# An optional key named "target_os" may be added to a gclient file to specify
# one or more additional operating systems that should be considered when
# processing the deps_os/hooks_os dict of a DEPS file.
#
# Example:
# target_os = [ "android" ]
#
# If the "target_os_only" key is also present and true, then *only* the
# operating systems listed in "target_os" will be used.
#
# Example:
# target_os = [ "ios" ]
# target_os_only = True
#
# Specifying a target CPU
# To specify a target CPU, the variables target_cpu and target_cpu_only
# are available and are analogous to target_os and target_os_only.
__version__ = '0.7'
import copy
import hashlib
import json
import logging
import optparse
import os
import platform
import posixpath
import pprint
import re
import sys
import shutil
import tarfile
import tempfile
import time
import urllib.parse
from collections.abc import Collection, Mapping, Sequence
import detect_host_arch
import download_from_google_storage
import git_common
import gclient_eval
import gclient_paths
import gclient_scm
import gclient_utils
import git_cache
import metrics
import metrics_utils
import scm as scm_git
import setup_color
import subcommand
import subprocess2
from third_party.repo.progress import Progress
# TODO: Should fix these warnings.
# pylint: disable=line-too-long
DEPOT_TOOLS_DIR = os.path.dirname(os.path.abspath(os.path.realpath(__file__)))
# Singleton object to represent an unset cache_dir (as opposed to a disabled
# one, e.g. if a spec explicitly says `cache_dir = None`.)
UNSET_CACHE_DIR = object()
PREVIOUS_CUSTOM_VARS_FILE = '.gclient_previous_custom_vars'
PREVIOUS_SYNC_COMMITS_FILE = '.gclient_previous_sync_commits'
PREVIOUS_SYNC_COMMITS = 'GCLIENT_PREVIOUS_SYNC_COMMITS'
NO_SYNC_EXPERIMENT = 'no-sync'
PRECOMMIT_HOOK_VAR = 'GCLIENT_PRECOMMIT'
class GNException(Exception):
pass
def ToGNString(value):
"""Returns a stringified GN equivalent of the Python value."""
if isinstance(value, str):
if value.find('\n') >= 0:
raise GNException("Trying to print a string with a newline in it.")
return '"' + \
value.replace('\\', '\\\\').replace('"', '\\"').replace('$', '\\$') + \
'"'
if isinstance(value, bool):
if value:
return "true"
return "false"
# NOTE: some type handling removed compared to chromium/src copy.
raise GNException("Unsupported type when printing to GN.")
class Hook(object):
"""Descriptor of command ran before/after sync or on demand."""
def __init__(self,
action,
pattern=None,
name=None,
cwd=None,
condition=None,
variables=None,
verbose=False,
cwd_base=None):
"""Constructor.
Arguments:
action (list of str): argv of the command to run
pattern (str regex): noop with git; deprecated
name (str): optional name; no effect on operation
cwd (str): working directory to use
condition (str): condition when to run the hook
variables (dict): variables for evaluating the condition
"""
self._action = gclient_utils.freeze(action)
self._pattern = pattern
self._name = name
self._cwd = cwd
self._condition = condition
self._variables = variables
self._verbose = verbose
self._cwd_base = cwd_base
@staticmethod
def from_dict(d,
variables=None,
verbose=False,
conditions=None,
cwd_base=None):
"""Creates a Hook instance from a dict like in the DEPS file."""
# Merge any local and inherited conditions.
gclient_eval.UpdateCondition(d, 'and', conditions)
return Hook(
d['action'],
d.get('pattern'),
d.get('name'),
d.get('cwd'),
d.get('condition'),
variables=variables,
# Always print the header if not printing to a TTY.
verbose=verbose or not setup_color.IS_TTY,
cwd_base=cwd_base)
@property
def action(self):
return self._action
@property
def pattern(self):
return self._pattern
@property
def name(self):
return self._name
@property
def condition(self):
return self._condition
@property
def effective_cwd(self):
cwd = self._cwd_base
if self._cwd:
cwd = os.path.join(cwd, self._cwd)
return cwd
def matches(self, file_list):
"""Returns true if the pattern matches any of files in the list."""
if not self._pattern:
return True
pattern = re.compile(self._pattern)
return bool([f for f in file_list if pattern.search(f)])
def run(self):
"""Executes the hook's command (provided the condition is met)."""
if (self._condition and not gclient_eval.EvaluateCondition(
self._condition, self._variables)):
return
cmd = list(self._action)
if cmd[0] == 'vpython3' and _detect_host_os() == 'win':
cmd[0] += '.bat'
exit_code = 2
try:
start_time = time.time()
gclient_utils.CheckCallAndFilter(cmd,
cwd=self.effective_cwd,
print_stdout=True,
show_header=True,
always_show_header=self._verbose)
exit_code = 0
except (gclient_utils.Error, subprocess2.CalledProcessError) as e:
# Use a discrete exit status code of 2 to indicate that a hook
# action failed. Users of this script may wish to treat hook action
# failures differently from VC failures.
print('Error: %s' % str(e), file=sys.stderr)
sys.exit(exit_code)
finally:
elapsed_time = time.time() - start_time
metrics.collector.add_repeated(
'hooks', {
'action':
gclient_utils.CommandToStr(cmd),
'name':
self._name,
'cwd':
os.path.relpath(os.path.normpath(self.effective_cwd),
self._cwd_base),
'condition':
self._condition,
'execution_time':
elapsed_time,
'exit_code':
exit_code,
})
if elapsed_time > 10:
print("Hook '%s' took %.2f secs" %
(gclient_utils.CommandToStr(cmd), elapsed_time))
class DependencySettings(object):
"""Immutable configuration settings."""
def __init__(self, parent, url, managed, custom_deps, custom_vars,
custom_hooks, deps_file, should_process, relative, condition):
# These are not mutable:
self._parent = parent
self._deps_file = deps_file
self._url = url
# The condition as string (or None). Useful to keep e.g. for flatten.
self._condition = condition
# 'managed' determines whether or not this dependency is synced/updated
# by gclient after gclient checks it out initially. The difference
# between 'managed' and 'should_process' is that the user specifies
# 'managed' via the --unmanaged command-line flag or a .gclient config,
# where 'should_process' is dynamically set by gclient if it goes over
# its recursion limit and controls gclient's behavior so it does not
# misbehave.
self._managed = managed
self._should_process = should_process
# If this is a recursed-upon sub-dependency, and the parent has
# use_relative_paths set, then this dependency should check out its own
# dependencies relative to that parent's path for this, rather than
# relative to the .gclient file.
self._relative = relative
# This is a mutable value which has the list of 'target_os' OSes listed
# in the current deps file.
self.local_target_os = None
# These are only set in .gclient and not in DEPS files.
self._custom_vars = custom_vars or {}
self._custom_deps = custom_deps or {}
self._custom_hooks = custom_hooks or []
# Post process the url to remove trailing slashes.
if isinstance(self.url, str):
# urls are sometime incorrectly written as proto://host/path/@rev.
# Replace it to proto://host/path@rev.
self.set_url(self.url.replace('/@', '@'))
elif not isinstance(self.url, (None.__class__)):
raise gclient_utils.Error(
('dependency url must be either string or None, '
'instead of %s') % self.url.__class__.__name__)
# Make any deps_file path platform-appropriate.
if self._deps_file:
for sep in ['/', '\\']:
self._deps_file = self._deps_file.replace(sep, os.sep)
@property
def deps_file(self):
return self._deps_file
@property
def managed(self):
return self._managed
@property
def parent(self):
return self._parent
@property
def root(self):
"""Returns the root node, a GClient object."""
if not self.parent:
# This line is to signal pylint that it could be a GClient instance.
return self or GClient(None, None)
return self.parent.root
@property
def should_process(self):
"""True if this dependency should be processed, i.e. checked out."""
return self._should_process
@property
def custom_vars(self):
return self._custom_vars.copy()
@property
def custom_deps(self):
return self._custom_deps.copy()
@property
def custom_hooks(self):
return self._custom_hooks[:]
@property
def url(self):
"""URL after variable expansion."""
return self._url
@property
def condition(self):
return self._condition
@property
def target_os(self):
if self.local_target_os is not None:
return tuple(set(self.local_target_os).union(self.parent.target_os))
return self.parent.target_os
@property
def target_cpu(self):
return self.parent.target_cpu
def set_url(self, url):
self._url = url
def get_custom_deps(self, name, url):
"""Returns a custom deps if applicable."""
if self.parent:
url = self.parent.get_custom_deps(name, url)
# None is a valid return value to disable a dependency.
return self.custom_deps.get(name, url)
class Dependency(gclient_utils.WorkItem, DependencySettings):
"""Object that represents a dependency checkout."""
def __init__(self,
parent,
name,
url,
managed,
custom_deps,
custom_vars,
custom_hooks,
deps_file,
should_process,
should_recurse,
relative,
condition,
protocol='https',
git_dependencies_state=gclient_eval.DEPS,
print_outbuf=False):
gclient_utils.WorkItem.__init__(self, name)
DependencySettings.__init__(self, parent, url, managed, custom_deps,
custom_vars, custom_hooks, deps_file,
should_process, relative, condition)
# This is in both .gclient and DEPS files:
self._deps_hooks = []
self._pre_deps_hooks = []
# Calculates properties:
self._dependencies = []
self._vars = {}
# A cache of the files affected by the current operation, necessary for
# hooks.
self._file_list = []
# List of host names from which dependencies are allowed.
# Default is an empty set, meaning unspecified in DEPS file, and hence
# all hosts will be allowed. Non-empty set means allowlist of hosts.
# allowed_hosts var is scoped to its DEPS file, and so it isn't
# recursive.
self._allowed_hosts = frozenset()
self._gn_args_from = None
# Spec for .gni output to write (if any).
self._gn_args_file = None
self._gn_args = []
# If it is not set to True, the dependency wasn't processed for its
# child dependency, i.e. its DEPS wasn't read.
self._deps_parsed = False
# This dependency has been processed, i.e. checked out
self._processed = False
# This dependency had its pre-DEPS hooks run
self._pre_deps_hooks_ran = False
# This dependency had its hook run
self._hooks_ran = False
# This is the scm used to checkout self.url. It may be used by
# dependencies to get the datetime of the revision we checked out.
self._used_scm = None
self._used_revision = None
# The actual revision we ended up getting, or None if that information
# is unavailable
self._got_revision = None
# Whether this dependency should use relative paths.
self._use_relative_paths = False
# recursedeps is a mutable value that selectively overrides the default
# 'no recursion' setting on a dep-by-dep basis.
#
# It will be a dictionary of {deps_name: depfile_namee}
self.recursedeps = {}
# Whether we should process this dependency's DEPS file.
self._should_recurse = should_recurse
# Whether we should sync git/cipd dependencies and hooks from the
# DEPS file.
# This is set based on skip_sync_revisions and must be done
# after the patch refs are applied.
# If this is False, we will still run custom_hooks and process
# custom_deps, if any.
self._should_sync = True
self._OverrideUrl()
# This is inherited from WorkItem. We want the URL to be a resource.
if self.url and isinstance(self.url, str):
# The url is usually given to gclient either as https://blah@123
# or just https://blah. The @123 portion is irrelevant.
self.resources.append(self.url.split('@')[0])
# Controls whether we want to print git's output when we first clone the
# dependency
self.print_outbuf = print_outbuf
self.protocol = protocol
self.git_dependencies_state = git_dependencies_state
if not self.name and self.parent:
raise gclient_utils.Error('Dependency without name')
def _OverrideUrl(self):
"""Resolves the parsed url from the parent hierarchy."""
parsed_url = self.get_custom_deps(
self._name.replace(os.sep, posixpath.sep) \
if self._name else self._name, self.url)
if parsed_url != self.url:
logging.info('Dependency(%s)._OverrideUrl(%s) -> %s', self._name,
self.url, parsed_url)
self.set_url(parsed_url)
return
if self.url is None:
logging.info('Dependency(%s)._OverrideUrl(None) -> None',
self._name)
return
if not isinstance(self.url, str):
raise gclient_utils.Error('Unknown url type')
# self.url is a local path
path, at, rev = self.url.partition('@')
if os.path.isdir(path):
return
# self.url is a URL
parsed_url = urllib.parse.urlparse(self.url)
if parsed_url[0] or re.match(r'^\w+\@[\w\.-]+\:[\w\/]+', parsed_url[2]):
return
# self.url is relative to the parent's URL.
if not path.startswith('/'):
raise gclient_utils.Error(
'relative DEPS entry \'%s\' must begin with a slash' % self.url)
parent_url = self.parent.url
parent_path = self.parent.url.split('@')[0]
if os.path.isdir(parent_path):
# Parent's URL is a local path. Get parent's URL dirname and append
# self.url.
parent_path = os.path.dirname(parent_path)
parsed_url = parent_path + path.replace('/', os.sep) + at + rev
else:
# Parent's URL is a URL. Get parent's URL, strip from the last '/'
# (equivalent to unix dirname) and append self.url.
parsed_url = parent_url[:parent_url.rfind('/')] + self.url
logging.info('Dependency(%s)._OverrideUrl(%s) -> %s', self.name,
self.url, parsed_url)
self.set_url(parsed_url)
def PinToActualRevision(self):
"""Updates self.url to the revision checked out on disk."""
if self.url is None:
return
url = None
scm = self.CreateSCM()
if scm.name == 'cipd':
revision = scm.revinfo(None, None, None)
package = self.GetExpandedPackageName()
url = '%s/p/%s/+/%s' % (scm.GetActualRemoteURL(None), package,
revision)
if os.path.isdir(scm.checkout_path):
revision = scm.revinfo(None, None, None)
url = '%s@%s' % (gclient_utils.SplitUrlRevision(
self.url)[0], revision)
self.set_url(url)
def ToLines(self):
# () -> Sequence[str]
"""Returns strings representing the deps (info, graphviz line)"""
s = []
condition_part = ([' "condition": %r,' %
self.condition] if self.condition else [])
s.extend([
' # %s' % self.hierarchy(include_url=False),
' "%s": {' % (self.name, ),
' "url": "%s",' % (self.url, ),
] + condition_part + [
' },',
'',
])
return s
@property
def requirements(self):
"""Calculate the list of requirements."""
requirements = set()
# self.parent is implicitly a requirement. This will be recursive by
# definition.
if self.parent and self.parent.name:
requirements.add(self.parent.name)
# For a tree with at least 2 levels*, the leaf node needs to depend
# on the level higher up in an orderly way.
# This becomes messy for >2 depth as the DEPS file format is a
# dictionary, thus unsorted, while the .gclient format is a list thus
# sorted.
#
# Interestingly enough, the following condition only works in the case
# we want: self is a 2nd level node. 3rd level node wouldn't need this
# since they already have their parent as a requirement.
if self.parent and self.parent.parent and not self.parent.parent.parent:
requirements |= set(i.name for i in self.root.dependencies
if i.name)
if self.name:
requirements |= set(
obj.name for obj in self.root.subtree(False)
if (obj is not self and obj.name
and self.name.startswith(posixpath.join(obj.name, ''))))
requirements = tuple(sorted(requirements))
logging.info('Dependency(%s).requirements = %s' %
(self.name, requirements))
return requirements
@property
def should_recurse(self):
return self._should_recurse
def verify_validity(self):
"""Verifies that this Dependency is fine to add as a child of another one.
Returns True if this entry should be added, False if it is a duplicate of
another entry.
"""
logging.info('Dependency(%s).verify_validity()' % self.name)
if self.name in [s.name for s in self.parent.dependencies]:
raise gclient_utils.Error(
'The same name "%s" appears multiple times in the deps section'
% self.name)
if not self.should_process:
# Return early, no need to set requirements.
return not any(d.name == self.name for d in self.root.subtree(True))
# This require a full tree traversal with locks.
siblings = [d for d in self.root.subtree(False) if d.name == self.name]
for sibling in siblings:
# Allow to have only one to be None or ''.
if self.url != sibling.url and bool(self.url) == bool(sibling.url):
raise gclient_utils.Error(
('Dependency %s specified more than once:\n'
' %s [%s]\n'
'vs\n'
' %s [%s]') % (self.name, sibling.hierarchy(),
sibling.url, self.hierarchy(), self.url))
# In theory we could keep it as a shadow of the other one. In
# practice, simply ignore it.
logging.warning("Won't process duplicate dependency %s" % sibling)
return False
return True
def _postprocess_deps(self, deps, rel_prefix):
# type: (Mapping[str, Mapping[str, str]], str) ->
# Mapping[str, Mapping[str, str]]
"""Performs post-processing of deps compared to what's in the DEPS file."""
# If we don't need to sync, only process custom_deps, if any.
if not self._should_sync:
if not self.custom_deps:
return {}
processed_deps = {}
for dep_name, dep_info in self.custom_deps.items():
if dep_info and not dep_info.endswith('@unmanaged'):
if dep_name in deps:
# custom_deps that should override an existing deps gets
# applied in the Dependency itself with _OverrideUrl().
processed_deps[dep_name] = deps[dep_name]
else:
processed_deps[dep_name] = {
'url': dep_info,
'dep_type': 'git'
}
else:
processed_deps = dict(deps)
# If a line is in custom_deps, but not in the solution, we want to
# append this line to the solution.
for dep_name, dep_info in self.custom_deps.items():
# Don't add it to the solution for the values of "None" and
# "unmanaged" in order to force these kinds of custom_deps to
# act as revision overrides (via revision_overrides). Having
# them function as revision overrides allows them to be applied
# to recursive dependencies. https://crbug.com/1031185
if (dep_name not in processed_deps and dep_info
and not dep_info.endswith('@unmanaged')):
processed_deps[dep_name] = {
'url': dep_info,
'dep_type': 'git'
}
# Make child deps conditional on any parent conditions. This ensures
# that, when flattened, recursed entries have the correct restrictions,
# even if not explicitly set in the recursed DEPS file. For instance, if
# "src/ios_foo" is conditional on "checkout_ios=True", then anything
# recursively included by "src/ios_foo/DEPS" should also require
# "checkout_ios=True".
if self.condition:
for value in processed_deps.values():
gclient_eval.UpdateCondition(value, 'and', self.condition)
if not rel_prefix:
return processed_deps
logging.warning('use_relative_paths enabled.')
rel_deps = {}
for d, url in processed_deps.items():
# normpath is required to allow DEPS to use .. in their
# dependency local path.
# We are following the same pattern when use_relative_paths = False,
# which uses slashes.
rel_deps[os.path.normpath(os.path.join(rel_prefix, d)).replace(
os.path.sep, '/')] = url
logging.warning('Updating deps by prepending %s.', rel_prefix)
return rel_deps
def _deps_to_objects(self, deps, use_relative_paths):
# type: (Mapping[str, Mapping[str, str]], bool) -> Sequence[Dependency]
"""Convert a deps dict to a list of Dependency objects."""
deps_to_add = []
cached_conditions = {}
for name, dep_value in deps.items():
should_process = self.should_process
if dep_value is None:
continue
condition = dep_value.get('condition')
dep_type = dep_value.get('dep_type')
if condition and not self._get_option('process_all_deps', False):
if condition not in cached_conditions:
cached_conditions[
condition] = gclient_eval.EvaluateCondition(
condition, self.get_vars())
should_process = should_process and cached_conditions[condition]
# The following option is only set by the 'revinfo' command.
if self._get_option('ignore_dep_type', None) == dep_type:
continue
if dep_type == 'cipd':
cipd_root = self.GetCipdRoot()
for package in dep_value.get('packages', []):
deps_to_add.append(
CipdDependency(parent=self,
name=name,
dep_value=package,
cipd_root=cipd_root,
custom_vars=self.custom_vars,
should_process=should_process,
relative=use_relative_paths,
condition=condition))
elif dep_type == 'gcs':
deps_to_add.append(
GcsDependency(parent=self,
name=name,
bucket=dep_value['bucket'],
object_name=dep_value['object_name'],
sha256sum=dep_value['sha256sum'],
custom_vars=self.custom_vars,
should_process=should_process,
relative=use_relative_paths,
condition=condition))
else:
url = dep_value.get('url')
deps_to_add.append(
GitDependency(
parent=self,
name=name,
# Update URL with scheme in protocol_override
url=GitDependency.updateProtocol(url, self.protocol),
managed=True,
custom_deps=None,
custom_vars=self.custom_vars,
custom_hooks=None,
deps_file=self.recursedeps.get(name, self.deps_file),
should_process=should_process,
should_recurse=name in self.recursedeps,
relative=use_relative_paths,
condition=condition,
protocol=self.protocol,
git_dependencies_state=self.git_dependencies_state))
# TODO(crbug.com/1341285): Understand why we need this and remove
# it if we don't.
deps_to_add.sort(key=lambda x: x.name)
return deps_to_add
def ParseDepsFile(self):
# type: () -> None
"""Parses the DEPS file for this dependency."""
assert not self.deps_parsed
assert not self.dependencies
deps_content = None
# First try to locate the configured deps file. If it's missing,
# fallback to DEPS.
deps_files = [self.deps_file]
if 'DEPS' not in deps_files:
deps_files.append('DEPS')
for deps_file in deps_files:
filepath = os.path.join(self.root.root_dir, self.name, deps_file)
if os.path.isfile(filepath):
logging.info('ParseDepsFile(%s): %s file found at %s',
self.name, deps_file, filepath)
break
logging.info('ParseDepsFile(%s): No %s file found at %s', self.name,
deps_file, filepath)
if os.path.isfile(filepath):
deps_content = gclient_utils.FileRead(filepath)
logging.debug('ParseDepsFile(%s) read:\n%s', self.name,
deps_content)
local_scope = {}
if deps_content:
try:
local_scope = gclient_eval.Parse(deps_content, filepath,
self.get_vars(),
self.get_builtin_vars())
except SyntaxError as e:
gclient_utils.SyntaxErrorToError(filepath, e)
if 'git_dependencies' in local_scope:
self.git_dependencies_state = local_scope['git_dependencies']
if 'allowed_hosts' in local_scope:
try:
self._allowed_hosts = frozenset(
local_scope.get('allowed_hosts'))
except TypeError: # raised if non-iterable
pass
if not self._allowed_hosts:
logging.warning("allowed_hosts is specified but empty %s",
self._allowed_hosts)
raise gclient_utils.Error(
'ParseDepsFile(%s): allowed_hosts must be absent '
'or a non-empty iterable' % self.name)
self._gn_args_from = local_scope.get('gclient_gn_args_from')
self._gn_args_file = local_scope.get('gclient_gn_args_file')
self._gn_args = local_scope.get('gclient_gn_args', [])
# It doesn't make sense to set all of these, since setting gn_args_from
# to another DEPS will make gclient ignore any other local gn_args*
# settings.
assert not (self._gn_args_from and self._gn_args_file), \
'Only specify one of "gclient_gn_args_from" or ' \
'"gclient_gn_args_file + gclient_gn_args".'
self._vars = local_scope.get('vars', {})
if self.parent:
for key, value in self.parent.get_vars().items():
if key in self._vars:
self._vars[key] = value
# Since we heavily post-process things, freeze ones which should
# reflect original state of DEPS.
self._vars = gclient_utils.freeze(self._vars)
# If use_relative_paths is set in the DEPS file, regenerate
# the dictionary using paths relative to the directory containing
# the DEPS file. Also update recursedeps if use_relative_paths is
# enabled.
# If the deps file doesn't set use_relative_paths, but the parent did
# (and therefore set self.relative on this Dependency object), then we
# want to modify the deps and recursedeps by prepending the parent
# directory of this dependency.
self._use_relative_paths = local_scope.get('use_relative_paths', False)
rel_prefix = None
if self._use_relative_paths:
rel_prefix = self.name
elif self._relative:
rel_prefix = os.path.dirname(self.name)
if 'recursion' in local_scope:
logging.warning('%s: Ignoring recursion = %d.', self.name,
local_scope['recursion'])
if 'recursedeps' in local_scope:
for ent in local_scope['recursedeps']:
if isinstance(ent, str):
self.recursedeps[ent] = self.deps_file
else: # (depname, depsfilename)
self.recursedeps[ent[0]] = ent[1]
logging.warning('Found recursedeps %r.', repr(self.recursedeps))
if rel_prefix:
logging.warning('Updating recursedeps by prepending %s.',
rel_prefix)
rel_deps = {}
for depname, options in self.recursedeps.items():
rel_deps[os.path.normpath(os.path.join(rel_prefix,
depname)).replace(
os.path.sep,
'/')] = options
self.recursedeps = rel_deps
# To get gn_args from another DEPS, that DEPS must be recursed into.
if self._gn_args_from:
assert self.recursedeps and self._gn_args_from in self.recursedeps, \
'The "gclient_gn_args_from" value must be in recursedeps.'
# If present, save 'target_os' in the local_target_os property.
if 'target_os' in local_scope:
self.local_target_os = local_scope['target_os']
deps = local_scope.get('deps', {})
# If dependencies are configured within git submodules, add them to
# deps. We don't add for SYNC since we expect submodules to be in sync.
if self.git_dependencies_state == gclient_eval.SUBMODULES:
deps.update(self.ParseGitSubmodules())
deps_to_add = self._deps_to_objects(
self._postprocess_deps(deps, rel_prefix), self._use_relative_paths)
# compute which working directory should be used for hooks
if local_scope.get('use_relative_hooks', False):
print('use_relative_hooks is deprecated, please remove it from '
'%s DEPS. (it was merged in use_relative_paths)' % self.name,
file=sys.stderr)
hooks_cwd = self.root.root_dir
if self._use_relative_paths:
hooks_cwd = os.path.join(hooks_cwd, self.name)
elif self._relative:
hooks_cwd = os.path.join(hooks_cwd, os.path.dirname(self.name))
logging.warning('Using hook base working directory: %s.', hooks_cwd)
# Only add all hooks if we should sync, otherwise just add custom hooks.
# override named sets of hooks by the custom hooks
hooks_to_run = []
if self._should_sync:
hook_names_to_suppress = [
c.get('name', '') for c in self.custom_hooks
]
for hook in local_scope.get('hooks', []):
if hook.get('name', '') not in hook_names_to_suppress:
hooks_to_run.append(hook)
# add the replacements and any additions
for hook in self.custom_hooks:
if 'action' in hook:
hooks_to_run.append(hook)
if self.should_recurse and deps_to_add:
self._pre_deps_hooks = [
Hook.from_dict(hook,
variables=self.get_vars(),
verbose=True,
conditions=self.condition,
cwd_base=hooks_cwd)
for hook in local_scope.get('pre_deps_hooks', [])
]
self.add_dependencies_and_close(deps_to_add,
hooks_to_run,
hooks_cwd=hooks_cwd)
logging.info('ParseDepsFile(%s) done' % self.name)
def ParseGitSubmodules(self):
# type: () -> Mapping[str, str]
"""
Parses git submodules and returns a dict of path to DEPS git url entries.
e.g {<path>: <url>@<commit_hash>}
"""
cwd = os.path.join(self.root.root_dir, self.name)
filepath = os.path.join(cwd, '.gitmodules')
if not os.path.isfile(filepath):
logging.warning('ParseGitSubmodules(): No .gitmodules found at %s',
filepath)
return {}
# Get .gitmodules fields
gitmodules_entries = subprocess2.check_output(
['git', 'config', '--file', filepath, '-l']).decode('utf-8')
gitmodules = {}
for entry in gitmodules_entries.splitlines():
key, value = entry.split('=', maxsplit=1)
# git config keys consist of section.name.key, e.g.,
# submodule.foo.path
section, submodule_key = key.split('.', maxsplit=1)
# Only parse [submodule "foo"] sections from .gitmodules.
if section.strip() != 'submodule':
continue
# The name of the submodule can contain '.', hence split from the
# back.
submodule, sub_key = submodule_key.rsplit('.', maxsplit=1)
if submodule not in gitmodules:
gitmodules[submodule] = {}
if sub_key in ('url', 'gclient-condition', 'path'):