Flutter Engine
The Flutter Engine
Loading...
Searching...
No Matches
Classes | Functions | Variables
utils Namespace Reference

Classes

class  BaseCoreDumpArchiver
 
class  chdir
 
class  Error
 
class  git_branch
 
class  IncreasedNumberOfFileDescriptors
 
class  LinuxCoreDumpArchiver
 
class  LinuxCoreDumpEnabler
 
class  MacOSCoreDumpArchiver
 
class  PosixCoreDumpArchiver
 
class  PosixCoreDumpEnabler
 
class  print_timings
 
class  TempDir
 
class  tmp_dir
 
class  UnexpectedCrash
 
class  Version
 
class  WindowsCoreDumpArchiver
 
class  WindowsCoreDumpEnabler
 

Functions

 GuessOS ()
 
 GuessArchitecture ()
 
 GuessCpus ()
 
 IsWindows ()
 
 ReadLinesFrom (name)
 
 ListArgCallback (option, opt_str, value, parser)
 
 ListDashArgCallback (option, opt_str, value, parser)
 
 GetBuildMode (mode)
 
 GetBuildConf (mode, arch)
 
 GetBuildRoot (host_os, mode=None, arch=None, sanitizer=None)
 
 RunCommand (command, input=None, pollFn=None, outStream=None, errStream=None, killOnEarlyReturn=True, verbose=False, debug=False, printErrorInfo=False)
 
 Main (argv)
 
 GetArchFamily (arch)
 
 GetBuildDir (host_os)
 
 GetBuildSanitizer (sanitizer)
 
 GetBaseDir ()
 
 load_source (modname, filename)
 
 GetBotUtils (repo_path=DART_DIR)
 
 GetMinidumpUtils (repo_path=DART_DIR)
 
 IsRosetta ()
 
 HostArchitectures ()
 
 IsCrossBuild (target_os, arch)
 
 GetBuildConf (mode, arch, conf_os=None, sanitizer=None)
 
 GetBuildRoot (host_os, mode=None, arch=None, target_os=None, sanitizer=None)
 
 GetVersion (no_git_hash=False, version_file=None, git_revision_file=None)
 
 GetChannel (version_file=None)
 
 ReadVersionFile (version_file=None)
 
 GetGitRevision (git_revision_file=None, repo_path=DART_DIR)
 
 GetShortGitHash (repo_path=DART_DIR)
 
 GetGitTimestamp (git_timestamp_file=None, repo_path=DART_DIR)
 
 IsCrashExitCode (exit_code)
 
 DiagnoseExitCode (exit_code, command)
 
 CheckedInSdkPath ()
 
 CheckedInSdkExecutable ()
 
 CheckLinuxCoreDumpPattern (fatal=False)
 
 TryUnlink (file)
 
 NooptContextManager ()
 
 CoreDumpArchiver (args)
 
 FileDescriptorLimitIncreaser ()
 
 Main ()
 
 git_clone (repo_url, dest_dir)
 
 RemoveDirectory (*path)
 

Variables

dict BUILD_MODES
 
dict BUILD_ROOT
 
str SEMANTIC_VERSION_PATTERN = r'^(?P<major>0|[1-9]\d*)\.(?P<minor>0|[1-9]\d*)\.(?P<patch>0|[1-9]\d*)(?:-(?P<prerelease>(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+(?P<buildmetadata>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$'
 
int GIT_NUMBER_BASE = 100000
 
dict BUILD_SANITIZERS
 
dict ARCH_FAMILY
 
 BASE_DIR = os.path.abspath(os.path.join(os.curdir, '..'))
 
 DART_DIR = os.path.abspath(os.path.join(__file__, '..', '..'))
 
 VERSION_FILE = os.path.join(DART_DIR, 'tools', 'VERSION')
 
str SKIA_REPO = 'https://skia.googlesource.com/skia.git'
 
str GCLIENT = 'win32' else 'gclient'
 
str WHICH = 'win32' else 'which'
 
 GIT = subprocess.check_output([WHICH, 'git']).decode('utf-8').splitlines()[0]
 

Function Documentation

◆ CheckedInSdkExecutable()

utils.CheckedInSdkExecutable ( )

Definition at line 504 of file utils.py.

504def CheckedInSdkExecutable():
505 name = 'dart'
506 if IsWindows():
507 name = 'dart.exe'
508 return os.path.join(CheckedInSdkPath(), 'bin', name)
509
510

◆ CheckedInSdkPath()

utils.CheckedInSdkPath ( )

Definition at line 499 of file utils.py.

499def CheckedInSdkPath():
500 tools_dir = os.path.dirname(os.path.realpath(__file__))
501 return os.path.join(tools_dir, 'sdks', 'dart-sdk')
502
503

◆ CheckLinuxCoreDumpPattern()

utils.CheckLinuxCoreDumpPattern (   fatal = False)

Definition at line 511 of file utils.py.

511def CheckLinuxCoreDumpPattern(fatal=False):
512 core_pattern_file = '/proc/sys/kernel/core_pattern'
513 core_pattern = open(core_pattern_file).read()
514
515 expected_core_pattern = 'core.%p'
516 if core_pattern.strip() != expected_core_pattern:
517 message = (
518 'Invalid core_pattern configuration. '
519 'The configuration of core dump handling is *not* correct for '
520 'a buildbot. The content of {0} must be "{1}" instead of "{2}".'.
521 format(core_pattern_file, expected_core_pattern, core_pattern))
522 if fatal:
523 raise Exception(message)
524 print(message)
525 return False
526 return True
527
528
static bool read(SkStream *stream, void *buffer, size_t amount)
void print(void *str)
Definition bridge.cpp:126
uint32_t uint32_t * format

◆ CoreDumpArchiver()

utils.CoreDumpArchiver (   args)

Definition at line 973 of file utils.py.

973def CoreDumpArchiver(args):
974 enabled = '--copy-coredumps' in args
975 prefix = '--output-directory='
976 output_directory = next(
977 (arg[len(prefix):] for arg in args if arg.startswith(prefix)), None)
978
979 if not enabled:
980 return (NooptContextManager(),)
981
982 osname = GuessOS()
983 if osname == 'linux':
984 return (LinuxCoreDumpEnabler(), LinuxCoreDumpArchiver(output_directory))
985 elif osname == 'macos':
986 return (PosixCoreDumpEnabler(), MacOSCoreDumpArchiver(output_directory))
987 elif osname == 'win32':
988 return (WindowsCoreDumpEnabler(),
989 WindowsCoreDumpArchiver(output_directory))
990
991 # We don't have support for MacOS yet.
992 return (NooptContextManager(),)
993
994
static float next(float f)

◆ DiagnoseExitCode()

utils.DiagnoseExitCode (   exit_code,
  command 
)

Definition at line 492 of file utils.py.

492def DiagnoseExitCode(exit_code, command):
493 if IsCrashExitCode(exit_code):
494 sys.stderr.write(
495 'Command: {}\nCRASHED with exit code {} (0x{:x})\n'.format(
496 ' '.join(command), exit_code, exit_code & 0xffffffff))
497
498

◆ FileDescriptorLimitIncreaser()

utils.FileDescriptorLimitIncreaser ( )

Definition at line 995 of file utils.py.

995def FileDescriptorLimitIncreaser():
996 osname = GuessOS()
997 if osname == 'macos':
998 return IncreasedNumberOfFileDescriptors(nofiles=10000)
999
1000 assert osname in ('linux', 'win32')
1001 # We don't have support for MacOS yet.
1002 return NooptContextManager()
1003
1004

◆ GetArchFamily()

utils.GetArchFamily (   arch)

Definition at line 95 of file utils.py.

95def GetArchFamily(arch):
96 return ARCH_FAMILY[arch]
97
98

◆ GetBaseDir()

utils.GetBaseDir ( )

Definition at line 111 of file utils.py.

111def GetBaseDir():
112 return BASE_DIR
113
114

◆ GetBotUtils()

utils.GetBotUtils (   repo_path = DART_DIR)
Dynamically load the tools/bots/bot_utils.py python module.

Definition at line 128 of file utils.py.

128def GetBotUtils(repo_path=DART_DIR):
129 '''Dynamically load the tools/bots/bot_utils.py python module.'''
130 return load_source('bot_utils',
131 os.path.join(repo_path, 'tools', 'bots', 'bot_utils.py'))
132
133
static SkString load_source(skiatest::Reporter *r, const char *testFile, const char *permutationSuffix)
Definition SkSLTest.cpp:226

◆ GetBuildConf() [1/2]

utils.GetBuildConf (   mode,
  arch 
)

Definition at line 139 of file utils.py.

139def GetBuildConf(mode, arch):
140 return GetBuildMode(mode) + arch.upper()
141
142

◆ GetBuildConf() [2/2]

utils.GetBuildConf (   mode,
  arch,
  conf_os = None,
  sanitizer = None 
)

Definition at line 336 of file utils.py.

336def GetBuildConf(mode, arch, conf_os=None, sanitizer=None):
337 if conf_os is not None and conf_os != GuessOS() and conf_os != 'host':
338 return '{}{}{}'.format(GetBuildMode(mode), conf_os.title(),
339 arch.upper())
340
341 # Ask for a cross build if the host and target architectures don't match.
342 cross_build = ''
343 if IsCrossBuild(conf_os, arch):
344 cross_build = 'X'
345 return '{}{}{}{}'.format(GetBuildMode(mode), GetBuildSanitizer(sanitizer),
346 cross_build, arch.upper())
347
348

◆ GetBuildDir()

utils.GetBuildDir (   host_os)

Definition at line 99 of file utils.py.

99def GetBuildDir(host_os):
100 return BUILD_ROOT[host_os]
101
102

◆ GetBuildMode()

utils.GetBuildMode (   mode)

Definition at line 134 of file utils.py.

134def GetBuildMode(mode):
135 global BUILD_MODES
136 return BUILD_MODES[mode]
137
138

◆ GetBuildRoot() [1/2]

utils.GetBuildRoot (   host_os,
  mode = None,
  arch = None,
  sanitizer = None 
)

Definition at line 143 of file utils.py.

143def GetBuildRoot(host_os, mode=None, arch=None, sanitizer=None):
144 global BUILD_ROOT
145 if mode:
146 return os.path.join(BUILD_ROOT[host_os],
147 GetBuildConf(mode, arch, sanitizer))
148 else:
149 return BUILD_ROOT[host_os]
150
151

◆ GetBuildRoot() [2/2]

utils.GetBuildRoot (   host_os,
  mode = None,
  arch = None,
  target_os = None,
  sanitizer = None 
)

Definition at line 349 of file utils.py.

349def GetBuildRoot(host_os, mode=None, arch=None, target_os=None, sanitizer=None):
350 build_root = GetBuildDir(host_os)
351 if mode:
352 build_root = os.path.join(
353 build_root, GetBuildConf(mode, arch, target_os, sanitizer))
354 return build_root
355
356

◆ GetBuildSanitizer()

utils.GetBuildSanitizer (   sanitizer)

Definition at line 107 of file utils.py.

107def GetBuildSanitizer(sanitizer):
108 return BUILD_SANITIZERS[sanitizer]
109
110

◆ GetChannel()

utils.GetChannel (   version_file = None)

Definition at line 376 of file utils.py.

376def GetChannel(version_file=None):
377 version = ReadVersionFile(version_file)
378 return version.channel
379
380

◆ GetGitRevision()

utils.GetGitRevision (   git_revision_file = None,
  repo_path = DART_DIR 
)

Definition at line 415 of file utils.py.

415def GetGitRevision(git_revision_file=None, repo_path=DART_DIR):
416 # When building from tarball use tools/GIT_REVISION
417 if git_revision_file is None:
418 git_revision_file = os.path.join(repo_path, 'tools', 'GIT_REVISION')
419 try:
420 with open(git_revision_file) as fd:
421 return fd.read().strip()
422 except:
423 pass
424 p = subprocess.Popen(['git', 'rev-parse', 'HEAD'],
425 stdout=subprocess.PIPE,
426 stderr=subprocess.PIPE,
427 shell=IsWindows(),
428 cwd=repo_path)
429 out, err = p.communicate()
430 # TODO(https://github.com/dart-lang/sdk/issues/51865): Don't ignore errors.
431 # if p.wait() != 0:
432 # raise Exception('git rev-parse failed: ' + str(err))
433 revision = out.decode('utf-8').strip()
434 # We expect a full git hash
435 if len(revision) != 40:
436 print('Warning: Could not parse git commit, output was {}'.format(
437 revision),
438 file=sys.stderr)
439 return None
440 return revision
441
442

◆ GetGitTimestamp()

utils.GetGitTimestamp (   git_timestamp_file = None,
  repo_path = DART_DIR 
)

Definition at line 458 of file utils.py.

458def GetGitTimestamp(git_timestamp_file=None, repo_path=DART_DIR):
459 # When building from tarball use tools/GIT_TIMESTAMP
460 if git_timestamp_file is None:
461 git_timestamp_file = os.path.join(repo_path, 'tools', 'GIT_TIMESTAMP')
462 try:
463 with open(git_timestamp_file) as fd:
464 return fd.read().strip()
465 except:
466 pass
467 p = subprocess.Popen(['git', 'log', '-n', '1', '--pretty=format:%cd'],
468 stdout=subprocess.PIPE,
469 stderr=subprocess.PIPE,
470 shell=IsWindows(),
471 cwd=repo_path)
472 out, err = p.communicate()
473 if p.wait() != 0:
474 # TODO(https://github.com/dart-lang/sdk/issues/51865): Don't ignore errors.
475 # raise Exception('git log failed: ' + str(err))
476 return None
477 timestamp = out.decode('utf-8').strip()
478 return timestamp
479
480
481# TODO(42528): Can we remove this? It's basically just an alias for Exception.

◆ GetMinidumpUtils()

utils.GetMinidumpUtils (   repo_path = DART_DIR)
Dynamically load the tools/minidump.py python module.

Definition at line 134 of file utils.py.

134def GetMinidumpUtils(repo_path=DART_DIR):
135 '''Dynamically load the tools/minidump.py python module.'''
136 return load_source('minidump',
137 os.path.join(repo_path, 'tools', 'minidump.py'))
138
139
140@total_ordering

◆ GetShortGitHash()

utils.GetShortGitHash (   repo_path = DART_DIR)

Definition at line 443 of file utils.py.

443def GetShortGitHash(repo_path=DART_DIR):
444 p = subprocess.Popen(['git', 'rev-parse', '--short=10', 'HEAD'],
445 stdout=subprocess.PIPE,
446 stderr=subprocess.PIPE,
447 shell=IsWindows(),
448 cwd=repo_path)
449 out, err = p.communicate()
450 if p.wait() != 0:
451 # TODO(https://github.com/dart-lang/sdk/issues/51865): Don't ignore errors.
452 # raise Exception('git rev-parse failed: ' + str(err))
453 return None
454 revision = out.decode('utf-8').strip()
455 return revision
456
457

◆ GetVersion()

utils.GetVersion (   no_git_hash = False,
  version_file = None,
  git_revision_file = None 
)

Definition at line 357 of file utils.py.

357def GetVersion(no_git_hash=False, version_file=None, git_revision_file=None):
358 version = ReadVersionFile(version_file)
359 if not version:
360 return None
361
362 suffix = ''
363 if version.channel in ['main', 'be']:
364 suffix = '-edge' if no_git_hash else '-edge.{}'.format(
365 GetGitRevision(git_revision_file))
366 elif version.channel in ('beta', 'dev'):
367 suffix = '-{}.{}.{}'.format(version.prerelease,
368 version.prerelease_patch, version.channel)
369 else:
370 assert version.channel == 'stable'
371
372 return '{}.{}.{}{}'.format(version.major, version.minor, version.patch,
373 suffix)
374
375

◆ git_clone()

utils.git_clone (   repo_url,
  dest_dir 
)
Clone the given repo into the given destination directory.

Definition at line 77 of file utils.py.

77def git_clone(repo_url, dest_dir):
78 """Clone the given repo into the given destination directory."""
79 subprocess.check_call([GIT, 'clone', repo_url, dest_dir])
80
81

◆ GuessArchitecture()

utils.GuessArchitecture ( )

Definition at line 42 of file utils.py.

42def GuessArchitecture():
43 id = platform.machine()
44 if id.startswith('arm'):
45 return 'arm'
46 elif (not id) or (not re.match('(x|i[3-6])86', id) is None):
47 return 'ia32'
48 elif id == 'i86pc':
49 return 'ia32'
50 else:
51 return None
52
53
54# Try to guess the number of cpus on this machine.

◆ GuessCpus()

utils.GuessCpus ( )

Definition at line 55 of file utils.py.

55def GuessCpus():
56 if os.path.exists("/proc/cpuinfo"):
57 return int(
58 getoutput(
59 "GREP_OPTIONS= grep -E '^processor' /proc/cpuinfo | wc -l"))
60 if os.path.exists("/usr/bin/hostinfo"):
61 return int(
62 getoutput(
63 '/usr/bin/hostinfo | GREP_OPTIONS= grep "processors are logically available." | awk "{ print \\$1 }"'
64 ))
65 win_cpu_count = os.getenv("NUMBER_OF_PROCESSORS")
66 if win_cpu_count:
67 return int(win_cpu_count)
68 return int(os.getenv("DART_NUMBER_OF_CORES", 2))
69
70
71# Returns true if we're running under Windows.
Type::kYUV Type::kRGBA() int(0.7 *637)

◆ GuessOS()

utils.GuessOS ( )

Definition at line 21 of file utils.py.

21def GuessOS():
22 id = platform.system()
23 if id == "Linux":
24 return "linux"
25 elif id == "Darwin":
26 return "macos"
27 elif id == "Windows" or id == "Microsoft":
28 # On Windows Vista platform.system() can return "Microsoft" with some
29 # versions of Python, see http://bugs.python.org/issue1082 for details.
30 return "win32"
31 elif id == 'FreeBSD':
32 return 'freebsd'
33 elif id == 'OpenBSD':
34 return 'openbsd'
35 elif id == 'SunOS':
36 return 'solaris'
37 else:
38 return None
39
40
41# Try to guess the host architecture.

◆ HostArchitectures()

utils.HostArchitectures ( )

Definition at line 263 of file utils.py.

263def HostArchitectures():
264 m = platform.machine()
265 if platform.system() == 'Darwin':
266 if m == 'arm64' or IsRosetta():
267 # ARM64 Macs also support X64.
268 return ['arm64', 'x64']
269 if m == 'x86_64':
270 # X64 Macs no longer support IA32.
271 return ['x64']
272 # Icky use of CIPD_ARCHITECTURE should be effectively dead whenever the
273 # Python on bots becomes native ARM64.
274 if ((platform.system() == 'Windows') and
275 (os.environ.get("CIPD_ARCHITECTURE") == "arm64")):
276 # ARM64 Windows also can emulate X64.
277 return ['arm64', 'x64']
278
279 if m in ['aarch64', 'arm64', 'arm64e', 'ARM64']:
280 return ['arm64']
281 if m in ['armv7l', 'armv8l']:
282 return ['arm']
283 if m in ['i386', 'i686', 'ia32', 'x86']:
284 return ['x86', 'ia32']
285 if m in ['x64', 'x86-64', 'x86_64', 'amd64', 'AMD64']:
286 return ['x64', 'x86', 'ia32']
287 if m in ['riscv64']:
288 return ['riscv64']
289 raise Exception('Failed to determine host architectures for %s %s',
290 platform.machine(), platform.system())
291
292
293# Try to guess the host architecture.

◆ IsCrashExitCode()

utils.IsCrashExitCode (   exit_code)

Definition at line 486 of file utils.py.

486def IsCrashExitCode(exit_code):
487 if IsWindows():
488 return 0x80000000 & exit_code
489 return exit_code < 0
490
491

◆ IsCrossBuild()

utils.IsCrossBuild (   target_os,
  arch 
)

Definition at line 323 of file utils.py.

323def IsCrossBuild(target_os, arch):
324 if (target_os not in [None, 'host']) and (target_os != GuessOS()):
325 return True
326 if arch.startswith('sim'):
327 return False
328 if arch.endswith('c'):
329 # Strip 'compressed' suffix.
330 arch = arch[:-1]
331 if arch in HostArchitectures():
332 return False
333 return True
334
335

◆ IsRosetta()

utils.IsRosetta ( )

Definition at line 252 of file utils.py.

252def IsRosetta():
253 if platform.system() == 'Darwin':
254 p = subprocess.Popen(['sysctl', '-in', 'sysctl.proc_translated'],
255 stdout=subprocess.PIPE,
256 stderr=subprocess.STDOUT)
257 output, _ = p.communicate()
258 return output.decode('utf-8').strip() == '1'
259 return False
260
261
262# Returns the architectures that can run on the current machine.

◆ IsWindows()

utils.IsWindows ( )

Definition at line 72 of file utils.py.

72def IsWindows():
73 return GuessOS() == 'win32'
74
75
76# Reads a text file into an array of strings - one for each
77# line. Strips comments in the process.

◆ ListArgCallback()

utils.ListArgCallback (   option,
  opt_str,
  value,
  parser 
)

Definition at line 92 of file utils.py.

92def ListArgCallback(option, opt_str, value, parser):
93 if value is None:
94 value = []
95
96 for arg in parser.rargs:
97 if arg[:2].startswith('--'):
98 break
99 value.append(arg)
100
101 del parser.rargs[:len(value)]
102 setattr(parser.values, option.dest, value)
103
104
105# Filters out all argument until the first non '-' or the
106# '--' argument occurs.

◆ ListDashArgCallback()

utils.ListDashArgCallback (   option,
  opt_str,
  value,
  parser 
)

Definition at line 107 of file utils.py.

107def ListDashArgCallback(option, opt_str, value, parser):
108 if value is None:
109 value = []
110
111 for arg in parser.rargs:
112 if arg[:2].startswith('--') or arg[0] != '-':
113 break
114 value.append(arg)
115
116 del parser.rargs[:len(value)]
117 setattr(parser.values, option.dest, value)
118
119
120# Mapping table between build mode and build configuration.

◆ load_source()

utils.load_source (   modname,
  filename 
)

Definition at line 115 of file utils.py.

115def load_source(modname, filename):
116 loader = importlib.machinery.SourceFileLoader(modname, filename)
117 spec = importlib.util.spec_from_file_location(modname,
118 filename,
119 loader=loader)
120 module = importlib.util.module_from_spec(spec)
121 # The module is always executed and not cached in sys.modules.
122 # Uncomment the following line to cache the module.
123 # sys.modules[module.__name__] = module
124 loader.exec_module(module)
125 return module
126
127

◆ Main() [1/2]

utils.Main ( )

Definition at line 1005 of file utils.py.

1005def Main():
1006 print('GuessOS() -> ', GuessOS())
1007 print('GuessArchitecture() -> ', GuessArchitecture())
1008 print('GuessCpus() -> ', GuessCpus())
1009 print('IsWindows() -> ', IsWindows())
1010 print('GetGitRevision() -> ', GetGitRevision())
1011 print('GetGitTimestamp() -> ', GetGitTimestamp())
1012 print('ReadVersionFile() -> ', ReadVersionFile())
1013
1014

◆ Main() [2/2]

utils.Main (   argv)

Definition at line 268 of file utils.py.

268def Main(argv):
269 print("GuessOS() -> ", GuessOS())
270 print("GuessArchitecture() -> ", GuessArchitecture())
271 print("GuessCpus() -> ", GuessCpus())
272 print("IsWindows() -> ", IsWindows())
273
274

◆ NooptContextManager()

utils.NooptContextManager ( )

Definition at line 969 of file utils.py.

969def NooptContextManager():
970 yield
971
972

◆ ReadLinesFrom()

utils.ReadLinesFrom (   name)

Definition at line 78 of file utils.py.

78def ReadLinesFrom(name):
79 result = []
80 for line in open(name):
81 if '#' in line:
82 line = line[:line.find('#')]
83 line = line.strip()
84 if len(line) == 0:
85 continue
86 result.append(line)
87 return result
88
89
90# Filters out all arguments until the next '--' argument
91# occurs.

◆ ReadVersionFile()

utils.ReadVersionFile (   version_file = None)

Definition at line 381 of file utils.py.

381def ReadVersionFile(version_file=None):
382
383 def match_against(pattern, file_content):
384 match = re.search(pattern, file_content, flags=re.MULTILINE)
385 if match:
386 return match.group(1)
387 return None
388
389 if version_file == None:
390 version_file = VERSION_FILE
391
392 content = None
393 try:
394 with open(version_file) as fd:
395 content = fd.read()
396 except:
397 print('Warning: Could not read VERSION file ({})'.format(version_file))
398 return None
399
400 channel = match_against('^CHANNEL ([A-Za-z0-9]+)$', content)
401 major = match_against('^MAJOR (\\d+)$', content)
402 minor = match_against('^MINOR (\\d+)$', content)
403 patch = match_against('^PATCH (\\d+)$', content)
404 prerelease = match_against('^PRERELEASE (\\d+)$', content)
405 prerelease_patch = match_against('^PRERELEASE_PATCH (\\d+)$', content)
406
407 if (channel and major and minor and prerelease and prerelease_patch):
408 return Version(channel, major, minor, patch, prerelease,
409 prerelease_patch)
410
411 print('Warning: VERSION file ({}) has wrong format'.format(version_file))
412 return None
413
414

◆ RemoveDirectory()

utils.RemoveDirectory ( path)
Recursively removes a directory, even if it's marked read-only.

This was copied from:
https://chromium.googlesource.com/chromium/tools/build/+/f3e7ff03613cd59a463b2ccc49773c3813e77404/scripts/common/chromium_utils.py#491

Remove the directory located at *path, if it exists.

shutil.rmtree() doesn't work on Windows if any of the files or directories
are read-only, which svn repositories and some .svn files are.  We need to
be able to force the files to be writable (i.e., deletable) as we traverse
the tree.

Even with all this, Windows still sometimes fails to delete a file, citing
a permission error (maybe something to do with antivirus scans or disk
indexing).  The best suggestion any of the user forums had was to wait a
bit and try again, so we do that too.  It's hand-waving, but sometimes it
works. :/

Definition at line 118 of file utils.py.

118def RemoveDirectory(*path):
119 """Recursively removes a directory, even if it's marked read-only.
120
121 This was copied from:
122 https://chromium.googlesource.com/chromium/tools/build/+/f3e7ff03613cd59a463b2ccc49773c3813e77404/scripts/common/chromium_utils.py#491
123
124 Remove the directory located at *path, if it exists.
125
126 shutil.rmtree() doesn't work on Windows if any of the files or directories
127 are read-only, which svn repositories and some .svn files are. We need to
128 be able to force the files to be writable (i.e., deletable) as we traverse
129 the tree.
130
131 Even with all this, Windows still sometimes fails to delete a file, citing
132 a permission error (maybe something to do with antivirus scans or disk
133 indexing). The best suggestion any of the user forums had was to wait a
134 bit and try again, so we do that too. It's hand-waving, but sometimes it
135 works. :/
136 """
137 file_path = os.path.join(*path)
138 if not os.path.exists(file_path):
139 return
140
141 if sys.platform == 'win32':
142 # Give up and use cmd.exe's rd command.
143 file_path = os.path.normcase(file_path)
144 for _ in range(3):
145 print('RemoveDirectory running %s' % (' '.join(
146 ['cmd.exe', '/c', 'rd', '/q', '/s', file_path])))
147 if not subprocess.call(['cmd.exe', '/c', 'rd', '/q', '/s', file_path]):
148 break
149 print(' Failed')
150 time.sleep(3)
151 return
152
153 def RemoveWithRetry_non_win(rmfunc, path):
154 if os.path.islink(path):
155 return os.remove(path)
156 else:
157 return rmfunc(path)
158
159 remove_with_retry = RemoveWithRetry_non_win
160
161 def RmTreeOnError(function, path, excinfo):
162 r"""This works around a problem whereby python 2.x on Windows has no ability
163 to check for symbolic links. os.path.islink always returns False. But
164 shutil.rmtree will fail if invoked on a symbolic link whose target was
165 deleted before the link. E.g., reproduce like this:
166 > mkdir test
167 > mkdir test\1
168 > mklink /D test\current test\1
169 > python -c "import chromium_utils; chromium_utils.RemoveDirectory('test')"
170 To avoid this issue, we pass this error-handling function to rmtree. If
171 we see the exact sort of failure, we ignore it. All other failures we re-
172 raise.
173 """
174
175 exception_type = excinfo[0]
176 exception_value = excinfo[1]
177 # If shutil.rmtree encounters a symbolic link on Windows, os.listdir will
178 # fail with a WindowsError exception with an ENOENT errno (i.e., file not
179 # found). We'll ignore that error. Note that WindowsError is not defined
180 # for non-Windows platforms, so we use OSError (of which it is a subclass)
181 # to avoid lint complaints about an undefined global on non-Windows
182 # platforms.
183 if (function is os.listdir) and issubclass(exception_type, OSError):
184 if exception_value.errno == errno.ENOENT:
185 # File does not exist, and we're trying to delete, so we can ignore the
186 # failure.
187 print('WARNING: Failed to list %s during rmtree. Ignoring.\n' % path)
188 else:
189 raise
190 else:
191 raise
192
193 for root, dirs, files in os.walk(file_path, topdown=False):
194 # For POSIX: making the directory writable guarantees removability.
195 # Windows will ignore the non-read-only bits in the chmod value.
196 os.chmod(root, 0o770)
197 for name in files:
198 remove_with_retry(os.remove, os.path.join(root, name))
199 for name in dirs:
200 remove_with_retry(lambda p: shutil.rmtree(p, onerror=RmTreeOnError),
201 os.path.join(root, name))
202
203 remove_with_retry(os.rmdir, file_path)
#define RemoveDirectory

◆ RunCommand()

utils.RunCommand (   command,
  input = None,
  pollFn = None,
  outStream = None,
  errStream = None,
  killOnEarlyReturn = True,
  verbose = False,
  debug = False,
  printErrorInfo = False 
)
Run a command, with optional input and polling function.

Args:
command: list of the command and its arguments.
input: optional string of input to feed to the command, it should be
    short enough to fit in an i/o pipe buffer.
pollFn: if present will be called occasionally to check if the command
    should be finished early. If pollFn() returns true then the command
    will finish early.
outStream: if present, the stdout output of the command will be written to
    outStream.
errStream: if present, the stderr output of the command will be written to
    errStream.
killOnEarlyReturn: if true and pollFn returns true, then the subprocess will
    be killed, otherwise the subprocess will be detached.
verbose: if true, the command is echoed to stderr.
debug: if true, prints debugging information to stderr.
printErrorInfo: if true, prints error information when the subprocess
returns a non-zero exit code.
Returns: the output of the subprocess.

Exceptions:
Raises Error if the subprocess returns an error code.
Raises ValueError if called with invalid arguments.

Definition at line 152 of file utils.py.

160 printErrorInfo=False):
161 """
162 Run a command, with optional input and polling function.
163
164 Args:
165 command: list of the command and its arguments.
166 input: optional string of input to feed to the command, it should be
167 short enough to fit in an i/o pipe buffer.
168 pollFn: if present will be called occasionally to check if the command
169 should be finished early. If pollFn() returns true then the command
170 will finish early.
171 outStream: if present, the stdout output of the command will be written to
172 outStream.
173 errStream: if present, the stderr output of the command will be written to
174 errStream.
175 killOnEarlyReturn: if true and pollFn returns true, then the subprocess will
176 be killed, otherwise the subprocess will be detached.
177 verbose: if true, the command is echoed to stderr.
178 debug: if true, prints debugging information to stderr.
179 printErrorInfo: if true, prints error information when the subprocess
180 returns a non-zero exit code.
181 Returns: the output of the subprocess.
182
183 Exceptions:
184 Raises Error if the subprocess returns an error code.
185 Raises ValueError if called with invalid arguments.
186 """
187 if verbose:
188 sys.stderr.write("command %s\n" % command)
189 stdin = None
190 if input:
191 stdin = subprocess.PIPE
192 try:
193 process = subprocess.Popen(
194 args=command,
195 stdin=stdin,
196 bufsize=1,
197 stdout=subprocess.PIPE,
198 stderr=subprocess.PIPE)
199 except OSError as e:
200 if not isinstance(command, str):
201 command = ' '.join(command)
202 if printErrorInfo:
203 sys.stderr.write("Command failed: '%s'\n" % command)
204 raise Error(e)
205
206 def StartThread(out):
207 queue = queue.Queue()
208
209 def EnqueueOutput(out, queue):
210 for line in iter(out.readline, b''):
211 queue.put(line)
212 out.close()
213
214 thread = threading.Thread(target=EnqueueOutput, args=(out, queue))
215 thread.daemon = True
216 thread.start()
217 return queue
218
219 outQueue = StartThread(process.stdout)
220 errQueue = StartThread(process.stderr)
221
222 def ReadQueue(queue, out, out2):
223 try:
224 while True:
225 line = queue.get(False)
226 out.write(line)
227 if out2 != None:
228 out2.write(line)
229 except queue.Empty:
230 pass
231
232 outBuf = StringIO.StringIO()
233 errorBuf = StringIO.StringIO()
234 if input:
235 process.stdin.write(input)
236 while True:
237 returncode = process.poll()
238 if returncode != None:
239 break
240 ReadQueue(errQueue, errorBuf, errStream)
241 ReadQueue(outQueue, outBuf, outStream)
242 if pollFn != None and pollFn():
243 returncode = 0
244 if killOnEarlyReturn:
245 process.kill()
246 break
247 time.sleep(0.1)
248 # Drain queue
249 ReadQueue(errQueue, errorBuf, errStream)
250 ReadQueue(outQueue, outBuf, outStream)
251
252 out = outBuf.getvalue()
253 error = errorBuf.getvalue()
254 if returncode:
255 if not isinstance(command, str):
256 command = ' '.join(command)
257 if printErrorInfo:
258 sys.stderr.write("Command failed: '%s'\n" % command)
259 sys.stderr.write(" stdout: '%s'\n" % out)
260 sys.stderr.write(" stderr: '%s'\n" % error)
261 sys.stderr.write(" returncode: %d\n" % returncode)
262 raise Error("Command failed: %s" % command)
263 if debug:
264 sys.stderr.write("output: %s\n" % out)
265 return out
266
267

◆ TryUnlink()

utils.TryUnlink (   file)

Definition at line 603 of file utils.py.

603def TryUnlink(file):
604 try:
605 os.unlink(file)
606 except Exception as error:
607 print('ERROR: Failed to remove {}: {}'.format(file, error))
608
609

Variable Documentation

◆ ARCH_FAMILY

dict utils.ARCH_FAMILY
Initial value:
1= {
2 'ia32': 'ia32',
3 'x64': 'ia32',
4 'arm': 'arm',
5 'arm64': 'arm',
6 'arm_x64': 'arm',
7 'arm_arm64': 'arm',
8 'simarm': 'ia32',
9 'simarm64': 'ia32',
10 'simarm_x64': 'ia32',
11 'simarm_arm64': 'arm',
12 'x64c': 'ia32',
13 'arm64c': 'arm',
14 'simarm64c': 'ia32',
15 'simriscv32': 'ia32',
16 'simriscv64': 'ia32',
17 'simx64': 'arm',
18 'simx64c': 'arm',
19 'riscv32': 'riscv',
20 'riscv64': 'riscv',
21}

Definition at line 68 of file utils.py.

◆ BASE_DIR

utils.BASE_DIR = os.path.abspath(os.path.join(os.curdir, '..'))

Definition at line 90 of file utils.py.

◆ BUILD_MODES

dict utils.BUILD_MODES
Initial value:
1= {
2 'debug': 'Debug',
3 'release': 'Release',
4}

Definition at line 121 of file utils.py.

◆ BUILD_ROOT

dict utils.BUILD_ROOT
Initial value:
1= {
2 'linux': os.path.join('out'),
3 'freebsd': os.path.join('out'),
4 'macos': os.path.join('xcodebuild'),
5}

Definition at line 127 of file utils.py.

◆ BUILD_SANITIZERS

dict utils.BUILD_SANITIZERS
Initial value:
1= {
2 None: '',
3 'none': '',
4 'asan': 'ASAN',
5 'lsan': 'LSAN',
6 'msan': 'MSAN',
7 'tsan': 'TSAN',
8 'ubsan': 'UBSAN',
9}

Definition at line 49 of file utils.py.

◆ DART_DIR

utils.DART_DIR = os.path.abspath(os.path.join(__file__, '..', '..'))

Definition at line 91 of file utils.py.

◆ GCLIENT

str utils.GCLIENT = 'win32' else 'gclient'

Definition at line 23 of file utils.py.

◆ GIT

utils.GIT = subprocess.check_output([WHICH, 'git']).decode('utf-8').splitlines()[0]

Definition at line 25 of file utils.py.

◆ GIT_NUMBER_BASE

int utils.GIT_NUMBER_BASE = 100000

Definition at line 39 of file utils.py.

◆ SEMANTIC_VERSION_PATTERN

str utils.SEMANTIC_VERSION_PATTERN = r'^(?P<major>0|[1-9]\d*)\.(?P<minor>0|[1-9]\d*)\.(?P<patch>0|[1-9]\d*)(?:-(?P<prerelease>(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+(?P<buildmetadata>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$'

Definition at line 33 of file utils.py.

◆ SKIA_REPO

str utils.SKIA_REPO = 'https://skia.googlesource.com/skia.git'

Definition at line 21 of file utils.py.

◆ VERSION_FILE

utils.VERSION_FILE = os.path.join(DART_DIR, 'tools', 'VERSION')

Definition at line 92 of file utils.py.

◆ WHICH

str utils.WHICH = 'win32' else 'which'

Definition at line 24 of file utils.py.