blob: 7ee97852bcb5511d5485296daaaac7e0b9b53e83 [file] [log] [blame]
Mike Frysinger1c57dfe2020-02-06 00:28:22 -05001#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3# Copyright 2020 The Chromium OS Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
7"""Wrapper around chromite executable scripts.
8
9This takes care of creating a consistent environment for chromite scripts
10(like setting up import paths) so we don't have to duplicate the logic in
11lots of places.
12"""
13
14from __future__ import print_function
15
16import importlib
17import os
18import sys
19
20
21# Assert some minimum Python versions as we don't test or support any others.
22# We only support Python 3.6+.
Mike Frysinger54545bc2020-02-16 05:37:56 +000023if sys.version_info < (3, 6):
Mike Frysinger7e865ed2020-07-29 03:30:51 -040024 print('%s: chromite: error: Python-3.6+ is required, but "%s" is "%s"' %
25 (sys.argv[0], sys.executable, sys.version.replace('\n', ' ')),
Mike Frysinger1c57dfe2020-02-06 00:28:22 -050026 file=sys.stderr)
27 sys.exit(1)
Mike Frysinger1c57dfe2020-02-06 00:28:22 -050028
29
30CHROMITE_PATH = None
31
32
33class ChromiteImporter(object):
34 """Virtual chromite module
35
36 If the checkout is not named 'chromite', trying to do 'from chromite.xxx'
37 to import modules fails horribly. Instead, manually locate the chromite
38 directory (whatever it is named), load & return it whenever someone tries
39 to import it. This lets us use the stable name 'chromite' regardless of
40 how things are structured on disk.
41
42 This also lets us keep the sys.path search clean. Otherwise we'd have to
43 worry about what other dirs chromite were checked out near to as doing an
44 import would also search those for .py modules.
45 """
46
47 # When trying to load the chromite dir from disk, we'll get called again,
48 # so make sure to disable our logic to avoid an infinite loop.
49 _loading = False
50
51 def find_module(self, fullname, _path=None):
52 """Handle the 'chromite' module"""
53 if fullname == 'chromite' and not self._loading:
54 return self
55 return None
56
57 def load_module(self, _fullname):
58 """Return our cache of the 'chromite' module"""
59 # Locate the top of the chromite dir by searching for the PRESUBMIT.cfg
60 # file. This assumes that file isn't found elsewhere in the tree.
61 path = os.path.dirname(os.path.realpath(__file__))
62 while not os.path.exists(os.path.join(path, 'PRESUBMIT.cfg')):
63 path = os.path.dirname(path)
64
65 # pylint: disable=global-statement
66 global CHROMITE_PATH
67 CHROMITE_PATH = path + '/'
68
69 # Finally load the chromite dir.
70 path, mod = os.path.split(path)
71 sys.path.insert(0, path)
72 self._loading = True
73 try:
74 return importlib.import_module(mod)
75 finally:
76 # We can't pop by index as the import might have changed sys.path.
77 sys.path.remove(path)
78 self._loading = False
79
80
81sys.meta_path.insert(0, ChromiteImporter())
82
83# We have to put these imports after our meta-importer above.
84# pylint: disable=wrong-import-position
85from chromite.lib import commandline
86
87
88def FindTarget(target):
89 """Turn the path into something we can import from the chromite tree.
90
91 This supports a variety of ways of running chromite programs:
92 # Loaded via depot_tools in $PATH.
93 $ cros_sdk --help
94 # Loaded via .../chromite/bin in $PATH.
95 $ cros --help
96 # No $PATH needed.
97 $ ./bin/cros --help
98 # Loaded via ~/bin in $PATH to chromite bin/ subdir.
99 $ ln -s $PWD/bin/cros ~/bin; cros --help
100 # No $PATH needed.
101 $ ./cbuildbot/cbuildbot --help
102 # No $PATH needed, but symlink inside of chromite dir.
103 $ ln -s ./cbuildbot/cbuildbot; ./cbuildbot --help
104 # Loaded via ~/bin in $PATH to non-chromite bin/ subdir.
105 $ ln -s $PWD/cbuildbot/cbuildbot ~/bin/; cbuildbot --help
106 # No $PATH needed, but a relative symlink to a symlink to the chromite dir.
107 $ cd ~; ln -s bin/cbuildbot ./; ./cbuildbot --help
108 # External chromite module
109 $ ln -s ../chromite/scripts/wrapper.py foo; ./foo
110
111 Args:
112 target: Path to the script we're trying to run.
113
114 Returns:
115 The module main functor.
116 """
117 # We assume/require the script we're wrapping ends in a .py.
118 full_path = target + '.py'
119 while True:
120 # Walk back one symlink at a time until we get into the chromite dir.
121 parent, base = os.path.split(target)
122 parent = os.path.realpath(parent)
123 if parent.startswith(CHROMITE_PATH):
124 target = base
125 break
126 target = os.path.join(os.path.dirname(target), os.readlink(target))
127
128 # If we walked all the way back to wrapper.py, it means we're trying to run
129 # an external module. So we have to import it by filepath and not via the
130 # chromite.xxx.yyy namespace.
131 if target != 'wrapper3.py':
132 assert parent.startswith(CHROMITE_PATH), (
133 'could not figure out leading path\n'
134 '\tparent: %s\n'
135 '\tCHROMITE_PATH: %s' % (parent, CHROMITE_PATH))
136 parent = parent[len(CHROMITE_PATH):].split(os.sep)
137 target = ['chromite'] + parent + [target]
138
139 if target[1] == 'bin':
140 # Convert chromite/bin/foo -> chromite/scripts/foo.
141 # Since chromite/bin/ is in $PATH, we want to keep it clean.
142 target[1] = 'scripts'
Mike Frysinger1c57dfe2020-02-06 00:28:22 -0500143
144 try:
145 module = importlib.import_module('.'.join(target))
146 except ImportError as e:
147 print(
148 '%s: could not import chromite module: %s: %s' % (sys.argv[0],
149 full_path, e),
150 file=sys.stderr)
151 raise
152 else:
153 import types
154 try:
155 loader = importlib.machinery.SourceFileLoader('main', full_path)
156 module = types.ModuleType(loader.name)
157 loader.exec_module(module)
158 except IOError as e:
159 print(
160 '%s: could not import external module: %s: %s' % (sys.argv[0],
161 full_path, e),
162 file=sys.stderr)
163 raise
164
165 # Run the module's main func if it has one.
166 main = getattr(module, 'main', None)
167 if main:
168 return main
169
170 # Is this a unittest?
171 if target[-1].rsplit('_', 1)[-1] in ('test', 'unittest'):
172 from chromite.lib import cros_test_lib
173 return lambda _argv: cros_test_lib.main(module=module)
174
175
176def DoMain():
177 commandline.ScriptWrapperMain(FindTarget)
178
179
180if __name__ == '__main__':
181 DoMain()