# HG changeset patch # User Alain Leufroy # Date 1615063839 -3600 # Sat Mar 06 21:50:39 2021 +0100 # Node ID 02e1bd10d88cdd13d6e2a119d30d62704f90a39c # Parent 0bf9886164b4faf447897d027f67c95c20e180e2 normalize code diff --git a/Makefile b/Makefile --- a/Makefile +++ b/Makefile @@ -1,5 +1,5 @@ normalize: - black -S overlayctl + black --skip-string-normalization --line-length=99 overlayctl test: python -m unittest test_overlayctl diff --git a/overlayctl b/overlayctl --- a/overlayctl +++ b/overlayctl @@ -34,9 +34,7 @@ init() except ImportError: - Fore = Back = Style = type( - 'mock', (), - {'__getattribute__': lambda * a: ''})() + Fore = Back = Style = type('mock', (), {'__getattribute__': lambda *a: ''})() logger = logging.getLogger(__name__) @@ -111,7 +109,7 @@ def __init__(self, name): super(Layer, self).__init__(name) self._lowers = None - #XXX cache properties + # XXX cache properties @property def lowers(self): @@ -208,8 +206,9 @@ re.search('upperdir=(.*?)[,$]', content).groups()[0].replace('\\\\', '\\') ) lowerdirs = re.search('lowerdir=(.*?)[,$]', content).groups()[0].split(':') - assert [lower.lowerdir for lower in self.get_ascendants()] \ - == [Path(p.replace('\\\\', '\\')) for p in lowerdirs if p] + assert [lower.lowerdir for lower in self.get_ascendants()] == [ + Path(p.replace('\\\\', '\\')) for p in lowerdirs if p + ] assert self.workdir == Path( re.search('workdir=(.*?)[,\n]', content).groups()[0].replace('\\\\', '\\') ) @@ -221,21 +220,15 @@ def dump(self): """Write the given overlay metadata to disk.""" - info = { - 'name': self.name, - 'lowers': [lower.name for lower in self.lowers] - } + info = {'name': self.name, 'lowers': [lower.name for lower in self.lowers]} data = info.copy() data['lowerdir'] = ':'.join( - str(lower.lowerdir).replace('\\', '\\\\') - for lower in self.get_ascendants() + str(lower.lowerdir).replace('\\', '\\\\') for lower in self.get_ascendants() ) data['upperdir'] = str(self.upperdir).replace('\\', '\\\\') data['workdir'] = str(self.workdir).replace('\\', '\\\\') data['mountdir'] = str(self.mountdir).replace('\\', '\\\\') - self.infopath.write_text( - json.dumps(info, indent=2), encoding='utf-8' - ) + self.infopath.write_text(json.dumps(info, indent=2), encoding='utf-8') logger.debug('%s written.', self.infopath) self.upperdir.mkdir(parents=True, exist_ok=True) self.workdir.mkdir(parents=True, exist_ok=True) @@ -295,7 +288,6 @@ class UnmanagedLayer(BaseLayer): - @property def lowers(self): """Lower layers.""" @@ -374,7 +366,6 @@ return 'active' in systemctl.status(self.path.name)['Active'].split() - class MountUnit(GenericUnit): """Systemd mount unit.""" @@ -404,8 +395,6 @@ class systemctl: - - @classmethod def start(cls, unitname): cls._execute('start', unitname) @@ -429,9 +418,7 @@ @classmethod def status(cls, unit): """Return a disctionary containing data from `systemctl status {unit}`.""" - stdout, dummy_stderr = Popen( - ['systemctl', 'status', unit], stdout=PIPE - ).communicate() + stdout, dummy_stderr = Popen(['systemctl', 'status', unit], stdout=PIPE).communicate() return dict( map(str.strip, line.split(':', 1)) for line in stdout.decode('utf-8').splitlines() @@ -484,9 +471,7 @@ return layers lowers = set(chain(*(layer.lowers for layer in layers))) heads = list(set(layers) - lowers) - return ( - layer for layer in _get_linearized_lowers(None, heads) if layer in layers - ) + return (layer for layer in _get_linearized_lowers(None, heads) if layer in layers) def _iter_tree(current, next_layers_getter): @@ -523,9 +508,7 @@ http://www.python.org/download/releases/2.3/mro/ """ graph = [list(x) for x in graph] # don't mutate anything - result = ( - OrderedDict() - ) # ordered uniq names (there is no OrderedSet in stdlib for now) + result = OrderedDict() # ordered uniq names (there is no OrderedSet in stdlib for now) def isheadclean(current): return all(current[0] not in other[1:] for other in graph) @@ -587,7 +570,8 @@ else: raise ActiveBranchError( 'The following units should be stopped: %s' - % ', '.join(x.name for x in activated)) + % ', '.join(x.name for x in activated) + ) yield if interrupt and restart: for layer in activated: @@ -625,8 +609,10 @@ descendants = list(_iter_descendants(layer)) if descendants: # XXX allow this with automatic updates. - raise DeletionError("\"%s\" is a lower directory of another overlay: %s" - % (name, ', '.join(x.name for x in descendants))) + raise DeletionError( + "\"%s\" is a lower directory of another overlay: %s" + % (name, ', '.join(x.name for x in descendants)) + ) layer.delete() systemctl.daemon_reload() logger.info("\"%s\" deleted", layer.name) @@ -637,9 +623,7 @@ Popen(cmd, shell=True).wait() -def editer( - name, appended=None, prepended=None, removed=None, - interrupt=False, preserve=False): +def editer(name, appended=None, prepended=None, removed=None, interrupt=False, preserve=False): """Ask user to edit lowers of the given overlay name, rewrite the metadata and unit files accordingly, finaly retart systemd units of the edited overlay. @@ -669,7 +653,8 @@ lowers = chain( prepended, (lower for lower in layer.lowers if lower not in removed), - appended) + appended, + ) if lowers == layer.lowers: return layer.lowers[:] = lowers @@ -698,9 +683,7 @@ layer.stop(permanent) -def lister( - unit_name, ordered_deps, reversed_deps, no_info, regexp, depends_on, terminal -): +def lister(unit_name, ordered_deps, reversed_deps, no_info, regexp, depends_on, terminal): """List managed overlays and display overlay inheritance.""" layers = _iter_layers(ordered_deps or reversed_deps) layers = reversed(list(layers)) if reversed_deps else layers @@ -727,12 +710,7 @@ 'others': ', '.join(map(str, grandchildren)) if grandchildren else '', 'name': layer.name, } - fmt = ( - Fore.GREEN - + Style.BRIGHT - + '{name}' - + Style.RESET_ALL - ) + fmt = Fore.GREEN + Style.BRIGHT + '{name}' + Style.RESET_ALL if layer.mountunit.is_active(): icon = Fore.GREEN + ' 🖴 ' + Style.RESET_ALL elif layer.automountunit.is_active(): @@ -801,6 +779,7 @@ """Main entry point for the CLI""" from argparse import ArgumentParser + ensure_directories_exist() parser = ArgumentParser(description="Manage images as overlays for machinectl.") @@ -838,21 +817,26 @@ def add_interrupt_preserve_arguments(parser): parser.add_argument( - '--interrupt', '-i', + '--interrupt', + '-i', action='store_true', default=False, - help=('automatically interrupt descendants to prevent broken mount point. ' - 'Restart them afterward.') + help=( + 'automatically interrupt descendants to prevent broken mount point. ' + 'Restart them afterward.' + ), ) parser.add_argument( - '--preserve', '-K', + '--preserve', + '-K', action='store_true', default=False, - help=('do not check if descendant overlays are started ' - '(may produce inconsistant behaviours)') + help=( + 'do not check if descendant overlays are started ' + '(may produce inconsistant behaviours)' + ), ) - # create create = subparser.add_parser( 'create', @@ -889,14 +873,18 @@ % (os.path.sep, MOUNTDIR), ) create.add_argument( - '--start', '-s', - action='store_true', default=False, - help='start the overlay immediatly' + '--start', + '-s', + action='store_true', + default=False, + help='start the overlay immediatly', ) create.add_argument( - '--permanent', '-p', - action='store_true', default=False, - help='make changes permanent on reboot' + '--permanent', + '-p', + action='store_true', + default=False, + help='make changes permanent on reboot', ) def _creater(args): @@ -1013,15 +1001,26 @@ help="edit existing overlay", description=( "edit an overlay created by this tool. " - "An editor is started if --add nor --remove provided."), + "An editor is started if --add nor --remove provided." + ), ) - edit.add_argument('-p', '--prepend', action='store_true', - help="prepend the following names", ) edit.add_argument( - '-a', '--append', action='append', help="append the following names", + '-p', + '--prepend', + action='store_true', + help="prepend the following names", ) edit.add_argument( - '-d', '--delete', action='append', help="append the following names", + '-a', + '--append', + action='append', + help="append the following names", + ) + edit.add_argument( + '-d', + '--delete', + action='append', + help="append the following names", ) add_interrupt_preserve_arguments(edit) edit.add_argument( @@ -1034,8 +1033,14 @@ ) def _editer(args): - editer(args.mountdir, args.append, args.prepend, args.delete, - interrupt=args.interrupt, preserve=args.preserve) + editer( + args.mountdir, + args.append, + args.prepend, + args.delete, + interrupt=args.interrupt, + preserve=args.preserve, + ) edit.set_defaults(func=_editer) @@ -1045,7 +1050,8 @@ help="move existing overlay", description=( "move an overlay created by this tool. " - "Other overlays that depends on it are updated"), + "Other overlays that depends on it are updated" + ), ) add_interrupt_preserve_arguments(move) move.add_argument('old', metavar='OLD', help="existing overlay name.") @@ -1076,14 +1082,20 @@ ) add_interrupt_preserve_arguments(start) start.add_argument( - '--permanent', '-p', - action='store_true', default=False, - help='make changes permanent on reboot' + '--permanent', + '-p', + action='store_true', + default=False, + help='make changes permanent on reboot', ) def _start(args): - starter(args.mountdir, interrupt=args.interrupt, - preserve=args.preserve, permanent=args.permanent) + starter( + args.mountdir, + interrupt=args.interrupt, + preserve=args.preserve, + permanent=args.permanent, + ) start.set_defaults(func=_start) @@ -1104,9 +1116,11 @@ ), ) stop.add_argument( - '--permanent', '-p', - action='store_true', default=False, - help='make changes permanent on reboot' + '--permanent', + '-p', + action='store_true', + default=False, + help='make changes permanent on reboot', ) def _stop(args):