aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorWolfgang E. Sanyer <WolfgangESanyer@gmail.com>2021-09-20 08:49:15 -0400
committerMatt Turner <mattst88@gentoo.org>2021-09-20 15:51:52 -0700
commitbbcd72b5fe85fe9bbca1913f8aa22077d94e75d0 (patch)
tree64a38c9e94cad7c800fcd1ca7307632f603e1315 /pym/gentoolkit/ekeyword
parentequery: Remove leftovers from 'changes' removal (diff)
downloadgentoolkit-bbcd72b5fe85fe9bbca1913f8aa22077d94e75d0.tar.gz
gentoolkit-bbcd72b5fe85fe9bbca1913f8aa22077d94e75d0.tar.bz2
gentoolkit-bbcd72b5fe85fe9bbca1913f8aa22077d94e75d0.zip
Change tabs to spaces (using autopep8). Also, format repo using black.
The following command was used to change the tabs to spaces: autopep8 --in-place --select=E101,E11,E121,E122,E123,E124,E125,E126,E127,E128,E129,E131,E133,E20,E211,E22,E224,E224,E226,E227,E228,E231,E241,E242,E251,E252,E26,E265,E266,E27,E301,E302,E303,E304,E305,E306,W291,W293,W391 -r . And then black was run as `black .` on the entire tree Signed-off-by: Wolfgang E. Sanyer <WolfgangESanyer@gmail.com> Signed-off-by: Matt Turner <mattst88@gentoo.org>
Diffstat (limited to 'pym/gentoolkit/ekeyword')
-rwxr-xr-xpym/gentoolkit/ekeyword/ekeyword.py825
-rwxr-xr-xpym/gentoolkit/ekeyword/test_ekeyword.py638
2 files changed, 769 insertions, 694 deletions
diff --git a/pym/gentoolkit/ekeyword/ekeyword.py b/pym/gentoolkit/ekeyword/ekeyword.py
index da0fd58..13b93ad 100755
--- a/pym/gentoolkit/ekeyword/ekeyword.py
+++ b/pym/gentoolkit/ekeyword/ekeyword.py
@@ -51,7 +51,7 @@ import portage
from portage.output import colorize, nocolor
-__version__ = 'git'
+__version__ = "git"
# Operation object that describes how to perform a change.
# Args:
@@ -62,432 +62,507 @@ __version__ = 'git'
# '^': Delete |arch| so it isn't listed at all
# arch: The required arch to update
# ref_arch: Set |arch| status to this arch (ignoring |op|)
-Op = collections.namedtuple('Op', ('op', 'arch', 'ref_arch'))
+Op = collections.namedtuple("Op", ("op", "arch", "ref_arch"))
def warning(msg):
- """Write |msg| as a warning to stderr"""
- print('warning: %s' % msg, file=sys.stderr)
+ """Write |msg| as a warning to stderr"""
+ print("warning: %s" % msg, file=sys.stderr)
def keyword_to_arch(keyword):
- """Given a keyword, strip it down to its arch value
+ """Given a keyword, strip it down to its arch value
- When an ARCH shows up in KEYWORDS, it may have prefixes like ~ or -.
- Strip all that cruft off to get back to the ARCH.
- """
- return keyword.lstrip('-~')
+ When an ARCH shows up in KEYWORDS, it may have prefixes like ~ or -.
+ Strip all that cruft off to get back to the ARCH.
+ """
+ return keyword.lstrip("-~")
def sort_keywords(arches):
- """Sort |arches| list in the order developers expect
+ """Sort |arches| list in the order developers expect
- This is vaguely defined because it is kind of vaguely defined once you get
- past the basic (Linux-only) keywords.
+ This is vaguely defined because it is kind of vaguely defined once you get
+ past the basic (Linux-only) keywords.
- Args:
- arches: An iterable of ARCH values.
+ Args:
+ arches: An iterable of ARCH values.
- Returns:
- A sorted list of |arches|
- """
- keywords = []
+ Returns:
+ A sorted list of |arches|
+ """
+ keywords = []
- # Globs always come first.
- for g in ('-*', '*', '~*'):
- if g in arches:
- arches.remove(g)
- keywords.append(g)
+ # Globs always come first.
+ for g in ("-*", "*", "~*"):
+ if g in arches:
+ arches.remove(g)
+ keywords.append(g)
- def arch_key(keyword):
- """Callback for python sorting functions
+ def arch_key(keyword):
+ """Callback for python sorting functions
- Used to turn a Gentoo keyword into a sortable form.
- """
- # Sort independent of leading marker (~ or -).
- arch = keyword_to_arch(keyword)
+ Used to turn a Gentoo keyword into a sortable form.
+ """
+ # Sort independent of leading marker (~ or -).
+ arch = keyword_to_arch(keyword)
- # A keyword may have a "-" in it. We split on that and sort
- # by the two resulting items. The part after the hyphen is
- # the primary key.
- if '-' in arch:
- arch, plat = arch.split('-', 1)
- else:
- arch, plat = arch, ''
+ # A keyword may have a "-" in it. We split on that and sort
+ # by the two resulting items. The part after the hyphen is
+ # the primary key.
+ if "-" in arch:
+ arch, plat = arch.split("-", 1)
+ else:
+ arch, plat = arch, ""
- return (plat, arch)
+ return (plat, arch)
- keywords += sorted(arches, key=arch_key)
+ keywords += sorted(arches, key=arch_key)
- return keywords
+ return keywords
-def diff_keywords(old_keywords, new_keywords, style='color-inline'):
- """Show pretty diff between list of keywords
+def diff_keywords(old_keywords, new_keywords, style="color-inline"):
+ """Show pretty diff between list of keywords
- Args:
- old_keywords: The old set of KEYWORDS
- new_keywords: The new set of KEYWORDS
- style: The diff style
+ Args:
+ old_keywords: The old set of KEYWORDS
+ new_keywords: The new set of KEYWORDS
+ style: The diff style
- Returns:
- A string containing the diff output ready to shown to the user
- """
- def show_diff(s):
- output = ''
+ Returns:
+ A string containing the diff output ready to shown to the user
+ """
- for tag, i0, i1, j0, j1 in s.get_opcodes():
+ def show_diff(s):
+ output = ""
- if tag == 'equal':
- output += s.a[i0:i1]
+ for tag, i0, i1, j0, j1 in s.get_opcodes():
- if tag in ('delete', 'replace'):
- o = s.a[i0:i1]
- if style == 'color-inline':
- o = colorize('bg_darkred', o)
- else:
- o = '-{%s}' % o
- output += o
+ if tag == "equal":
+ output += s.a[i0:i1]
- if tag in ('insert', 'replace'):
- o = s.b[j0:j1]
- if style == 'color-inline':
- o = colorize('bg_darkgreen', o)
- else:
- o = '+{%s}' % o
- output += o
+ if tag in ("delete", "replace"):
+ o = s.a[i0:i1]
+ if style == "color-inline":
+ o = colorize("bg_darkred", o)
+ else:
+ o = "-{%s}" % o
+ output += o
- return output
+ if tag in ("insert", "replace"):
+ o = s.b[j0:j1]
+ if style == "color-inline":
+ o = colorize("bg_darkgreen", o)
+ else:
+ o = "+{%s}" % o
+ output += o
- sold = str(' '.join(old_keywords))
- snew = str(' '.join(new_keywords))
- s = difflib.SequenceMatcher(str.isspace, sold, snew, autojunk=False)
- return show_diff(s)
+ return output
+
+ sold = str(" ".join(old_keywords))
+ snew = str(" ".join(new_keywords))
+ s = difflib.SequenceMatcher(str.isspace, sold, snew, autojunk=False)
+ return show_diff(s)
def process_keywords(keywords, ops, arch_status=None):
- """Process |ops| for |keywords|"""
- new_keywords = set(keywords).copy()
-
- # Process each op one at a time.
- for op, oarch, refarch in ops:
- # Figure out which keywords we need to modify.
- if oarch == 'all':
- if arch_status is None:
- raise ValueError('unable to process "all" w/out profiles.desc')
- old_arches = set([keyword_to_arch(a) for a in new_keywords])
- if op is None:
- # Process just stable keywords.
- arches = [k for k, v in arch_status.items()
- if v[1] == 'arch' and k in old_arches]
- else:
- # Process all possible keywords. We use the arch_status as a
- # master list. If it lacks some keywords, then we might miss
- # somethings here, but not much we can do.
- arches = list(old_arches)
-
- # We ignore the glob arch as we never want to tweak it.
- if '*' in arches:
- arches.remove('*')
-
- # For keywords that are explicitly disabled, do not update. When
- # people use `ekeyword ~all ...` or `ekeyword all ...`, they rarely
- # (if ever) want to change a '-sparc' to 'sparc' or '-sparc' to
- # '~sparc'. We force people to explicitly do `ekeyword sparc ...`
- # in these cases.
- arches = [x for x in arches if '-' + x not in new_keywords]
- else:
- arches = [oarch]
-
- if refarch:
- # Figure out the state for this arch based on the reference arch.
- # TODO: Add support for "all" keywords.
- # XXX: Should this ignore the '-' state ? Does it make sense to
- # sync e.g. "s390" to "-ppc" ?
- refkeyword = [x for x in new_keywords if refarch == keyword_to_arch(x)]
- if not refkeyword:
- op = '^'
- elif refkeyword[0].startswith('~'):
- op = '~'
- elif refkeyword[0].startswith('-'):
- op = '-'
- else:
- op = None
-
- # Finally do the actual update of the keywords list.
- for arch in arches:
- new_keywords -= set(['%s%s' % (x, arch) for x in ('', '~', '-')])
-
- if op is None:
- new_keywords.add(arch)
- elif op in ('~', '-'):
- new_keywords.add('%s%s' % (op, arch))
- elif op == '^':
- # Already deleted. Whee.
- pass
- else:
- raise ValueError('unknown operation %s' % op)
-
- return new_keywords
-
-
-def process_content(ebuild, data, ops, arch_status=None, verbose=0,
- quiet=0, style='color-inline'):
- """Process |ops| for |data|"""
- # Set up the user display style based on verbose/quiet settings.
- if verbose > 1:
- disp_name = ebuild
- def logit(msg):
- print('%s: %s' % (disp_name, msg))
- elif quiet > 1:
- def logit(_msg):
- pass
- else:
- # Chop the full path and the .ebuild suffix.
- disp_name = os.path.basename(ebuild)[:-7]
- def logit(msg):
- print('%s: %s' % (disp_name, msg))
-
- # Match any KEYWORDS= entry that isn't commented out.
- keywords_re = re.compile(r'^([^#]*\bKEYWORDS=)([\'"])(.*)(\2)(.*)')
- updated = False
- content = []
-
- # Walk each line of the ebuild looking for KEYWORDS to process.
- for line in data:
- m = keywords_re.match(line)
- if not m:
- content.append(line)
- continue
-
- # Ok, we've got it, now let's process things.
- old_keywords_original = m.group(3).split() # preserve original order
- old_keywords = set(old_keywords_original)
- new_keywords = process_keywords(
- old_keywords, ops, arch_status=arch_status)
-
- were_sorted_already = (
- old_keywords_original == sort_keywords(old_keywords_original))
-
- # Finally let's present the results to the user.
- if (new_keywords != old_keywords) or \
- (not ops and not were_sorted_already) or verbose:
- # Only do the diff work if something actually changed.
- updated = True
-
- if not ops:
- # We're sorting only so we want to compare with the
- # unsorted original (or changes in order will not show)
- old_keywords = old_keywords_original
- else:
- # We changed keywords so let's diff sorted versions
- # so that keywords changes are easy to spot
- old_keywords = sort_keywords(old_keywords)
-
- new_keywords = sort_keywords(new_keywords)
- line = '%s"%s"%s\n' % (m.group(1), ' '.join(new_keywords),
- m.group(5))
- if style in ('color-inline', 'inline'):
- logit(diff_keywords(old_keywords, new_keywords, style=style))
- else:
- if style == 'long-multi':
- logit(' '.join(['%*s' % (len(keyword_to_arch(x)) + 1, x)
- for x in old_keywords]))
- logit(' '.join(['%*s' % (len(keyword_to_arch(x)) + 1, x)
- for x in new_keywords]))
- else:
- deleted_keywords = [x for x in old_keywords
- if x not in new_keywords]
- logit('--- %s' % ' '.join(deleted_keywords))
- added_keywords = [x for x in new_keywords
- if x not in old_keywords]
- logit('+++ %s' % ' '.join(added_keywords))
-
- content.append(line)
-
- if not updated:
- logit('no updates')
-
- return updated, content
-
-
-def process_ebuild(ebuild, ops, arch_status=None, verbose=0, quiet=0,
- dry_run=False, style='color-inline', manifest=False):
- """Process |ops| for |ebuild|
-
- Args:
- ebuild: The ebuild file to operate on & update in place
- ops: An iterable of operations (Op objects) to perform on |ebuild|
- arch_status: A dict mapping default arches to their stability; see the
- load_profile_data function for more details
- verbose: Be verbose; show various status messages
- quiet: Be quiet; only show errors
- dry_run: Do not make any changes to |ebuild|; show what would be done
- style: The diff style
-
- Returns:
- Whether any updates were processed
- """
- with io.open(ebuild, encoding='utf8') as f:
- updated, content = process_content(
- ebuild, f, ops, arch_status=arch_status,
- verbose=verbose, quiet=quiet, style=style)
- if updated and not dry_run:
- with io.open(ebuild, 'w', encoding='utf8') as f:
- f.writelines(content)
- if manifest:
- subprocess.check_call(['ebuild', ebuild, 'manifest'])
- return updated
+ """Process |ops| for |keywords|"""
+ new_keywords = set(keywords).copy()
+
+ # Process each op one at a time.
+ for op, oarch, refarch in ops:
+ # Figure out which keywords we need to modify.
+ if oarch == "all":
+ if arch_status is None:
+ raise ValueError('unable to process "all" w/out profiles.desc')
+ old_arches = set([keyword_to_arch(a) for a in new_keywords])
+ if op is None:
+ # Process just stable keywords.
+ arches = [
+ k
+ for k, v in arch_status.items()
+ if v[1] == "arch" and k in old_arches
+ ]
+ else:
+ # Process all possible keywords. We use the arch_status as a
+ # master list. If it lacks some keywords, then we might miss
+ # somethings here, but not much we can do.
+ arches = list(old_arches)
+
+ # We ignore the glob arch as we never want to tweak it.
+ if "*" in arches:
+ arches.remove("*")
+
+ # For keywords that are explicitly disabled, do not update. When
+ # people use `ekeyword ~all ...` or `ekeyword all ...`, they rarely
+ # (if ever) want to change a '-sparc' to 'sparc' or '-sparc' to
+ # '~sparc'. We force people to explicitly do `ekeyword sparc ...`
+ # in these cases.
+ arches = [x for x in arches if "-" + x not in new_keywords]
+ else:
+ arches = [oarch]
+
+ if refarch:
+ # Figure out the state for this arch based on the reference arch.
+ # TODO: Add support for "all" keywords.
+ # XXX: Should this ignore the '-' state ? Does it make sense to
+ # sync e.g. "s390" to "-ppc" ?
+ refkeyword = [x for x in new_keywords if refarch == keyword_to_arch(x)]
+ if not refkeyword:
+ op = "^"
+ elif refkeyword[0].startswith("~"):
+ op = "~"
+ elif refkeyword[0].startswith("-"):
+ op = "-"
+ else:
+ op = None
+
+ # Finally do the actual update of the keywords list.
+ for arch in arches:
+ new_keywords -= set(["%s%s" % (x, arch) for x in ("", "~", "-")])
+
+ if op is None:
+ new_keywords.add(arch)
+ elif op in ("~", "-"):
+ new_keywords.add("%s%s" % (op, arch))
+ elif op == "^":
+ # Already deleted. Whee.
+ pass
+ else:
+ raise ValueError("unknown operation %s" % op)
+
+ return new_keywords
+
+
+def process_content(
+ ebuild, data, ops, arch_status=None, verbose=0, quiet=0, style="color-inline"
+):
+ """Process |ops| for |data|"""
+ # Set up the user display style based on verbose/quiet settings.
+ if verbose > 1:
+ disp_name = ebuild
+
+ def logit(msg):
+ print("%s: %s" % (disp_name, msg))
+
+ elif quiet > 1:
+
+ def logit(_msg):
+ pass
+
+ else:
+ # Chop the full path and the .ebuild suffix.
+ disp_name = os.path.basename(ebuild)[:-7]
+
+ def logit(msg):
+ print("%s: %s" % (disp_name, msg))
+
+ # Match any KEYWORDS= entry that isn't commented out.
+ keywords_re = re.compile(r'^([^#]*\bKEYWORDS=)([\'"])(.*)(\2)(.*)')
+ updated = False
+ content = []
+
+ # Walk each line of the ebuild looking for KEYWORDS to process.
+ for line in data:
+ m = keywords_re.match(line)
+ if not m:
+ content.append(line)
+ continue
+
+ # Ok, we've got it, now let's process things.
+ old_keywords_original = m.group(3).split() # preserve original order
+ old_keywords = set(old_keywords_original)
+ new_keywords = process_keywords(old_keywords, ops, arch_status=arch_status)
+
+ were_sorted_already = old_keywords_original == sort_keywords(
+ old_keywords_original
+ )
+
+ # Finally let's present the results to the user.
+ if (
+ (new_keywords != old_keywords)
+ or (not ops and not were_sorted_already)
+ or verbose
+ ):
+ # Only do the diff work if something actually changed.
+ updated = True
+
+ if not ops:
+ # We're sorting only so we want to compare with the
+ # unsorted original (or changes in order will not show)
+ old_keywords = old_keywords_original
+ else:
+ # We changed keywords so let's diff sorted versions
+ # so that keywords changes are easy to spot
+ old_keywords = sort_keywords(old_keywords)
+
+ new_keywords = sort_keywords(new_keywords)
+ line = '%s"%s"%s\n' % (m.group(1), " ".join(new_keywords), m.group(5))
+ if style in ("color-inline", "inline"):
+ logit(diff_keywords(old_keywords, new_keywords, style=style))
+ else:
+ if style == "long-multi":
+ logit(
+ " ".join(
+ [
+ "%*s" % (len(keyword_to_arch(x)) + 1, x)
+ for x in old_keywords
+ ]
+ )
+ )
+ logit(
+ " ".join(
+ [
+ "%*s" % (len(keyword_to_arch(x)) + 1, x)
+ for x in new_keywords
+ ]
+ )
+ )
+ else:
+ deleted_keywords = [
+ x for x in old_keywords if x not in new_keywords
+ ]
+ logit("--- %s" % " ".join(deleted_keywords))
+ added_keywords = [x for x in new_keywords if x not in old_keywords]
+ logit("+++ %s" % " ".join(added_keywords))
+
+ content.append(line)
+
+ if not updated:
+ logit("no updates")
+
+ return updated, content
+
+
+def process_ebuild(
+ ebuild,
+ ops,
+ arch_status=None,
+ verbose=0,
+ quiet=0,
+ dry_run=False,
+ style="color-inline",
+ manifest=False,
+):
+ """Process |ops| for |ebuild|
+
+ Args:
+ ebuild: The ebuild file to operate on & update in place
+ ops: An iterable of operations (Op objects) to perform on |ebuild|
+ arch_status: A dict mapping default arches to their stability; see the
+ load_profile_data function for more details
+ verbose: Be verbose; show various status messages
+ quiet: Be quiet; only show errors
+ dry_run: Do not make any changes to |ebuild|; show what would be done
+ style: The diff style
+
+ Returns:
+ Whether any updates were processed
+ """
+ with io.open(ebuild, encoding="utf8") as f:
+ updated, content = process_content(
+ ebuild,
+ f,
+ ops,
+ arch_status=arch_status,
+ verbose=verbose,
+ quiet=quiet,
+ style=style,
+ )
+ if updated and not dry_run:
+ with io.open(ebuild, "w", encoding="utf8") as f:
+ f.writelines(content)
+ if manifest:
+ subprocess.check_call(["ebuild", ebuild, "manifest"])
+ return updated
def portage_settings():
- """Return the portage settings we care about."""
- # Portage creates the db member on the fly which confuses the linter.
- return portage.db[portage.root]['vartree'].settings
+ """Return the portage settings we care about."""
+ # Portage creates the db member on the fly which confuses the linter.
+ return portage.db[portage.root]["vartree"].settings
def arg_to_op(arg):
- """Convert a command line |arg| to an Op"""
- arch_prefixes = ('-', '~', '^')
+ """Convert a command line |arg| to an Op"""
+ arch_prefixes = ("-", "~", "^")
- op = None
- arch = arg
- refarch = None
+ op = None
+ arch = arg
+ refarch = None
- if arg and arg[0] in arch_prefixes:
- op, arch = arg[0], arg[1:]
+ if arg and arg[0] in arch_prefixes:
+ op, arch = arg[0], arg[1:]
- if '=' in arch:
- if not op is None:
- raise ValueError('Cannot use an op and a refarch')
- arch, refarch = arch.split('=', 1)
+ if "=" in arch:
+ if not op is None:
+ raise ValueError("Cannot use an op and a refarch")
+ arch, refarch = arch.split("=", 1)
- return Op(op, arch, refarch)
+ return Op(op, arch, refarch)
def ignorable_arg(arg, quiet=0):
- """Whether it's ok to ignore this argument"""
- if os.path.isdir(arg):
- if not quiet:
- warning('ignoring directory %s' % arg)
- return True
-
- WHITELIST = (
- 'Manifest',
- 'metadata.xml',
- )
- base = os.path.basename(arg)
- if (base.startswith('ChangeLog') or
- base in WHITELIST or
- base.startswith('.') or
- base.endswith('~')):
- if not quiet:
- warning('ignoring file: %s' % arg)
- return True
-
- return False
+ """Whether it's ok to ignore this argument"""
+ if os.path.isdir(arg):
+ if not quiet:
+ warning("ignoring directory %s" % arg)
+ return True
+
+ WHITELIST = (
+ "Manifest",
+ "metadata.xml",
+ )
+ base = os.path.basename(arg)
+ if (
+ base.startswith("ChangeLog")
+ or base in WHITELIST
+ or base.startswith(".")
+ or base.endswith("~")
+ ):
+ if not quiet:
+ warning("ignoring file: %s" % arg)
+ return True
+
+ return False
def args_to_work(args, arch_status=None, _repo=None, quiet=0):
- """Process |args| into a list of work itmes (ebuild/arches to update)"""
- work = []
- todo_arches = []
- last_todo_arches = []
-
- for arg in args:
- if arg.endswith('.ebuild'):
- if not todo_arches:
- todo_arches = last_todo_arches
- work.append([arg, todo_arches])
- last_todo_arches = todo_arches
- todo_arches = []
- else:
- op = arg_to_op(arg)
- if not arch_status or op.arch in arch_status:
- todo_arches.append(op)
- elif not ignorable_arg(arg, quiet=quiet):
- raise ValueError('unknown arch/argument: %s' % arg)
-
- if todo_arches:
- raise ValueError('missing ebuilds to process!')
-
- return work
+ """Process |args| into a list of work itmes (ebuild/arches to update)"""
+ work = []
+ todo_arches = []
+ last_todo_arches = []
+
+ for arg in args:
+ if arg.endswith(".ebuild"):
+ if not todo_arches:
+ todo_arches = last_todo_arches
+ work.append([arg, todo_arches])
+ last_todo_arches = todo_arches
+ todo_arches = []
+ else:
+ op = arg_to_op(arg)
+ if not arch_status or op.arch in arch_status:
+ todo_arches.append(op)
+ elif not ignorable_arg(arg, quiet=quiet):
+ raise ValueError("unknown arch/argument: %s" % arg)
+
+ if todo_arches:
+ raise ValueError("missing ebuilds to process!")
+
+ return work
def get_parser():
- """Return an argument parser for ekeyword"""
- parser = argparse.ArgumentParser(
- description=__doc__,
- formatter_class=argparse.RawDescriptionHelpFormatter)
- parser.add_argument('-m', '--manifest', default=False, action='store_true',
- help='Run `ebuild manifest` on the ebuild after modifying it')
- parser.add_argument('-n', '--dry-run', default=False, action='store_true',
- help='Show what would be changed, but do not commit')
- parser.add_argument('-v', '--verbose', action='count', default=0,
- help='Be verbose while processing things')
- parser.add_argument('-q', '--quiet', action='count', default=0,
- help='Be quiet while processing things (only show errors)')
- parser.add_argument('--format', default='auto', dest='style',
- choices=('auto', 'color-inline', 'inline', 'short-multi', 'long-multi'),
- help='Select output format for showing differences')
- parser.add_argument('-V', '--version', action='version', version=__version__,
- help='Show version information')
- return parser
+ """Return an argument parser for ekeyword"""
+ parser = argparse.ArgumentParser(
+ description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
+ )
+ parser.add_argument(
+ "-m",
+ "--manifest",
+ default=False,
+ action="store_true",
+ help="Run `ebuild manifest` on the ebuild after modifying it",
+ )
+ parser.add_argument(
+ "-n",
+ "--dry-run",
+ default=False,
+ action="store_true",
+ help="Show what would be changed, but do not commit",
+ )
+ parser.add_argument(
+ "-v",
+ "--verbose",
+ action="count",
+ default=0,
+ help="Be verbose while processing things",
+ )
+ parser.add_argument(
+ "-q",
+ "--quiet",
+ action="count",
+ default=0,
+ help="Be quiet while processing things (only show errors)",
+ )
+ parser.add_argument(
+ "--format",
+ default="auto",
+ dest="style",
+ choices=("auto", "color-inline", "inline", "short-multi", "long-multi"),
+ help="Select output format for showing differences",
+ )
+ parser.add_argument(
+ "-V",
+ "--version",
+ action="version",
+ version=__version__,
+ help="Show version information",
+ )
+ return parser
def main(argv):
- if argv is None:
- argv = sys.argv[1:]
-
- # Extract the args ourselves. This is to allow things like -hppa
- # without tripping over the -h/--help flags. We can't use the
- # parse_known_args function either.
- # This sucks and really wish we didn't need to do this ...
- parse_args = []
- work_args = []
- while argv:
- arg = argv.pop(0)
- if arg.startswith('--'):
- if arg == '--':
- work_args += argv
- break
- else:
- parse_args.append(arg)
- # Handle flags that take arguments.
- if arg in ('--format',):
- if argv:
- parse_args.append(argv.pop(0))
- elif len(arg) == 2 and arg[0] == '-':
- parse_args.append(arg)
- else:
- work_args.append(arg)
-
- parser = get_parser()
- opts = parser.parse_args(parse_args)
- if not work_args:
- parser.error('need ebuilds to process')
-
- if opts.style == 'auto':
- if not portage_settings().get('NOCOLOR', 'false').lower() in ('no', 'false'):
- nocolor()
- opts.style = 'short'
- else:
- opts.style = 'color-inline'
-
- arch_status = load_profile_data()
- try:
- work = args_to_work(work_args, arch_status=arch_status, quiet=opts.quiet)
- except ValueError as e:
- parser.error(e)
-
- for ebuild, ops in work:
- process_ebuild(ebuild, ops, arch_status=arch_status,
- verbose=opts.verbose, quiet=opts.quiet,
- dry_run=opts.dry_run, style=opts.style,
- manifest=opts.manifest)
-
- return os.EX_OK
-
-
-if __name__ == '__main__':
- sys.exit(main(sys.argv[1:]))
+ if argv is None:
+ argv = sys.argv[1:]
+
+ # Extract the args ourselves. This is to allow things like -hppa
+ # without tripping over the -h/--help flags. We can't use the
+ # parse_known_args function either.
+ # This sucks and really wish we didn't need to do this ...
+ parse_args = []
+ work_args = []
+ while argv:
+ arg = argv.pop(0)
+ if arg.startswith("--"):
+ if arg == "--":
+ work_args += argv
+ break
+ else:
+ parse_args.append(arg)
+ # Handle flags that take arguments.
+ if arg in ("--format",):
+ if argv:
+ parse_args.append(argv.pop(0))
+ elif len(arg) == 2 and arg[0] == "-":
+ parse_args.append(arg)
+ else:
+ work_args.append(arg)
+
+ parser = get_parser()
+ opts = parser.parse_args(parse_args)
+ if not work_args:
+ parser.error("need ebuilds to process")
+
+ if opts.style == "auto":
+ if not portage_settings().get("NOCOLOR", "false").lower() in ("no", "false"):
+ nocolor()
+ opts.style = "short"
+ else:
+ opts.style = "color-inline"
+
+ arch_status = load_profile_data()
+ try:
+ work = args_to_work(work_args, arch_status=arch_status, quiet=opts.quiet)
+ except ValueError as e:
+ parser.error(e)
+
+ for ebuild, ops in work:
+ process_ebuild(
+ ebuild,
+ ops,
+ arch_status=arch_status,
+ verbose=opts.verbose,
+ quiet=opts.quiet,
+ dry_run=opts.dry_run,
+ style=opts.style,
+ manifest=opts.manifest,
+ )
+
+ return os.EX_OK
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv[1:]))
diff --git a/pym/gentoolkit/ekeyword/test_ekeyword.py b/pym/gentoolkit/ekeyword/test_ekeyword.py
index 0763783..3495aff 100755
--- a/pym/gentoolkit/ekeyword/test_ekeyword.py
+++ b/pym/gentoolkit/ekeyword/test_ekeyword.py
@@ -15,368 +15,368 @@ from unittest import mock
from gentoolkit.ekeyword import ekeyword
-TESTDIR = os.path.join(os.path.dirname(__file__), 'tests')
+TESTDIR = os.path.join(os.path.dirname(__file__), "tests")
class TestSortKeywords(unittest.TestCase):
- """Tests for sort_keywords"""
+ """Tests for sort_keywords"""
- def _test(self, input_data, exp_data):
- """Sort |input_data| and make sure it matches |exp_data|"""
- output_data = ekeyword.sort_keywords(input_data.split())
- self.assertEqual(exp_data.split(), output_data)
+ def _test(self, input_data, exp_data):
+ """Sort |input_data| and make sure it matches |exp_data|"""
+ output_data = ekeyword.sort_keywords(input_data.split())
+ self.assertEqual(exp_data.split(), output_data)
- def testNull(self):
- """Verify whitespace is collapsed"""
- self._test('', '')
- self._test(' ', '')
+ def testNull(self):
+ """Verify whitespace is collapsed"""
+ self._test("", "")
+ self._test(" ", "")
- def testGlob(self):
- """Verify globs get sorted before all others"""
- self._test('* arm', '* arm')
- self._test('arm -* x86', '-* arm x86')
- self._test('hppa ~* amd64', '~* amd64 hppa')
+ def testGlob(self):
+ """Verify globs get sorted before all others"""
+ self._test("* arm", "* arm")
+ self._test("arm -* x86", "-* arm x86")
+ self._test("hppa ~* amd64", "~* amd64 hppa")
- def testMixedPlatform(self):
- """Verify core arches get sorted before all w/suffix"""
- self._test('arm-linux alpha amd64-fbsd hppa',
- 'alpha hppa amd64-fbsd arm-linux')
+ def testMixedPlatform(self):
+ """Verify core arches get sorted before all w/suffix"""
+ self._test("arm-linux alpha amd64-fbsd hppa", "alpha hppa amd64-fbsd arm-linux")
- def testPrefixes(self):
- """Verify -/~ and such get ignored for sorting"""
- self._test('-hppa arm ~alpha -* ~arm-linux',
- '-* ~alpha arm -hppa ~arm-linux')
+ def testPrefixes(self):
+ """Verify -/~ and such get ignored for sorting"""
+ self._test("-hppa arm ~alpha -* ~arm-linux", "-* ~alpha arm -hppa ~arm-linux")
- def testPlatform(self):
- """Verify we sort based on platform first"""
- self._test('x86-linux ppc-macos x86-fbsd amd64-linux amd64-fbsd',
- 'amd64-fbsd x86-fbsd amd64-linux x86-linux ppc-macos')
+ def testPlatform(self):
+ """Verify we sort based on platform first"""
+ self._test(
+ "x86-linux ppc-macos x86-fbsd amd64-linux amd64-fbsd",
+ "amd64-fbsd x86-fbsd amd64-linux x86-linux ppc-macos",
+ )
class TestDiffKeywords(unittest.TestCase):
- """Tests for diff_keywords"""
+ """Tests for diff_keywords"""
- def testEmpty(self):
- """Test when there is no content to diff"""
- ret = ekeyword.diff_keywords([], [])
- self.assertEqual(ret, '')
+ def testEmpty(self):
+ """Test when there is no content to diff"""
+ ret = ekeyword.diff_keywords([], [])
+ self.assertEqual(ret, "")
- def testSame(self):
- """Test when there is no difference"""
- ret = ekeyword.diff_keywords(['a b c'], ['a b c'])
- self.assertEqual(ret, 'a b c')
+ def testSame(self):
+ """Test when there is no difference"""
+ ret = ekeyword.diff_keywords(["a b c"], ["a b c"])
+ self.assertEqual(ret, "a b c")
- def testInsert(self):
- """Test when content is simply added"""
- ret = ekeyword.diff_keywords(['a'], ['~a'])
- self.assertNotEqual(ret, '')
+ def testInsert(self):
+ """Test when content is simply added"""
+ ret = ekeyword.diff_keywords(["a"], ["~a"])
+ self.assertNotEqual(ret, "")
- def testDelete(self):
- """Test when content is simply deleted"""
- ret = ekeyword.diff_keywords(['~a'], ['a'])
- self.assertNotEqual(ret, '')
+ def testDelete(self):
+ """Test when content is simply deleted"""
+ ret = ekeyword.diff_keywords(["~a"], ["a"])
+ self.assertNotEqual(ret, "")
- def testReplace(self):
- """Test when some content replaces another"""
- ret = ekeyword.diff_keywords(['~a'], ['-a'])
- self.assertNotEqual(ret, '')
+ def testReplace(self):
+ """Test when some content replaces another"""
+ ret = ekeyword.diff_keywords(["~a"], ["-a"])
+ self.assertNotEqual(ret, "")
- def _testSmokeStyle(self, style):
- return ekeyword.diff_keywords(
- ['~a', 'b', '-abcde'],
- ['a', '-b', '-abxde'], style=style)
+ def _testSmokeStyle(self, style):
+ return ekeyword.diff_keywords(
+ ["~a", "b", "-abcde"], ["a", "-b", "-abxde"], style=style
+ )
- def testSmokeStyleColor(self):
- """Run a full smoke test for color-inline style"""
- ret = self._testSmokeStyle('color-inline')
- self.assertNotEqual(ret, '')
+ def testSmokeStyleColor(self):
+ """Run a full smoke test for color-inline style"""
+ ret = self._testSmokeStyle("color-inline")
+ self.assertNotEqual(ret, "")
- def testSmokeStyleNoColor(self):
- """Run a full smoke test for non-color-inline style"""
- self._testSmokeStyle('nocolor')
+ def testSmokeStyleNoColor(self):
+ """Run a full smoke test for non-color-inline style"""
+ self._testSmokeStyle("nocolor")
class TestProcessKeywords(unittest.TestCase):
- """Tests for process_keywords"""
-
- def _test(self, keywords, ops, exp, arch_status=None):
- # This func doesn't return sorted results (which is fine),
- # so do so ourselves to get stable tests.
- ret = ekeyword.process_keywords(
- keywords.split(), ops, arch_status=arch_status)
- self.assertEqual(sorted(ret), sorted(exp.split()))
-
- def testAdd(self):
- ops = (
- ekeyword.Op(None, 'arm', None),
- ekeyword.Op('~', 's390', None),
- ekeyword.Op('-', 'sh', None),
- )
- self._test('moo', ops, 'arm ~s390 -sh moo')
-
- def testModify(self):
- ops = (
- ekeyword.Op(None, 'arm', None),
- ekeyword.Op('~', 's390', None),
- ekeyword.Op('-', 'sh', None),
- )
- self._test('~arm s390 ~sh moo', ops, 'arm ~s390 -sh moo')
-
- def testDelete(self):
- ops = (
- ekeyword.Op('^', 'arm', None),
- ekeyword.Op('^', 's390', None),
- ekeyword.Op('^', 'x86', None),
- )
- self._test('arm -s390 ~x86 bar', ops, 'bar')
-
- def testSync(self):
- ops = (
- ekeyword.Op('=', 'arm64', 'arm'),
- ekeyword.Op('=', 'ppc64', 'ppc'),
- ekeyword.Op('=', 'amd64', 'x86'),
- ekeyword.Op('=', 'm68k', 'mips'),
- ekeyword.Op('=', 'ia64', 'alpha'),
- ekeyword.Op('=', 'sh', 'sparc'),
- ekeyword.Op('=', 's390', 's390x'),
- ekeyword.Op('=', 'boo', 'moo'),
- )
- self._test(
- 'arm64 arm '
- '~ppc64 ~ppc '
- '~amd64 x86 '
- 'm68k ~mips '
- '-ia64 alpha '
- 'sh -sparc '
- 's390 '
- 'moo ',
- ops,
- 'arm64 arm ~ppc64 ~ppc amd64 x86 ~m68k ~mips ia64 alpha '
- '-sh -sparc boo moo')
-
- def testAllNoStatus(self):
- ops = (
- ekeyword.Op(None, 'all', None),
- )
- self.assertRaises(ValueError, self._test, '', ops, '')
-
- def testAllStable(self):
- ops = (
- ekeyword.Op(None, 'all', None),
- )
- arch_status = {
- 'alpha': ('stable', '~arch'),
- 'arm': ('stable', 'arch'),
- 'm68k': ('exp', '~arch'),
- 's390': ('exp', 'arch'),
- }
- self._test('* ~alpha ~arm ~m68k ~mips ~s390 ~arm-linux', ops,
- '* ~alpha arm ~m68k ~mips s390 ~arm-linux', arch_status)
-
- def testAllUnstable(self):
- ops = (
- ekeyword.Op('~', 'all', None),
- )
- arch_status = {
- 'alpha': ('stable', '~arch'),
- 'arm': ('stable', 'arch'),
- 'm68k': ('exp', '~arch'),
- 's390': ('exp', 'arch'),
- }
- self._test('-* ~* * alpha arm m68k s390 arm-linux', ops,
- '-* ~* * ~alpha ~arm ~m68k ~s390 ~arm-linux', arch_status)
-
- def testAllMultiUnstableStable(self):
- ops = (
- ekeyword.Op('~', 'all', None),
- ekeyword.Op(None, 'all', None),
- )
- arch_status = {
- 'alpha': ('stable', '~arch'),
- 'arm': ('stable', 'arch'),
- 'm68k': ('exp', '~arch'),
- 's390': ('exp', 'arch'),
- }
- self._test('-* ~* * alpha arm m68k s390', ops,
- '-* ~* * ~alpha arm ~m68k s390', arch_status)
-
- def testAllDisabled(self):
- """Make sure ~all does not change -arch to ~arch"""
- ops = (
- ekeyword.Op('~', 'all', None),
- )
- self._test('alpha -sparc ~x86', ops,
- '~alpha -sparc ~x86', {})
+ """Tests for process_keywords"""
+
+ def _test(self, keywords, ops, exp, arch_status=None):
+ # This func doesn't return sorted results (which is fine),
+ # so do so ourselves to get stable tests.
+ ret = ekeyword.process_keywords(keywords.split(), ops, arch_status=arch_status)
+ self.assertEqual(sorted(ret), sorted(exp.split()))
+
+ def testAdd(self):
+ ops = (
+ ekeyword.Op(None, "arm", None),
+ ekeyword.Op("~", "s390", None),
+ ekeyword.Op("-", "sh", None),
+ )
+ self._test("moo", ops, "arm ~s390 -sh moo")
+
+ def testModify(self):
+ ops = (
+ ekeyword.Op(None, "arm", None),
+ ekeyword.Op("~", "s390", None),
+ ekeyword.Op("-", "sh", None),
+ )
+ self._test("~arm s390 ~sh moo", ops, "arm ~s390 -sh moo")
+
+ def testDelete(self):
+ ops = (
+ ekeyword.Op("^", "arm", None),
+ ekeyword.Op("^", "s390", None),
+ ekeyword.Op("^", "x86", None),
+ )
+ self._test("arm -s390 ~x86 bar", ops, "bar")
+
+ def testSync(self):
+ ops = (
+ ekeyword.Op("=", "arm64", "arm"),
+ ekeyword.Op("=", "ppc64", "ppc"),
+ ekeyword.Op("=", "amd64", "x86"),
+ ekeyword.Op("=", "m68k", "mips"),
+ ekeyword.Op("=", "ia64", "alpha"),
+ ekeyword.Op("=", "sh", "sparc"),
+ ekeyword.Op("=", "s390", "s390x"),
+ ekeyword.Op("=", "boo", "moo"),
+ )
+ self._test(
+ "arm64 arm "
+ "~ppc64 ~ppc "
+ "~amd64 x86 "
+ "m68k ~mips "
+ "-ia64 alpha "
+ "sh -sparc "
+ "s390 "
+ "moo ",
+ ops,
+ "arm64 arm ~ppc64 ~ppc amd64 x86 ~m68k ~mips ia64 alpha "
+ "-sh -sparc boo moo",
+ )
+
+ def testAllNoStatus(self):
+ ops = (ekeyword.Op(None, "all", None),)
+ self.assertRaises(ValueError, self._test, "", ops, "")
+
+ def testAllStable(self):
+ ops = (ekeyword.Op(None, "all", None),)
+ arch_status = {
+ "alpha": ("stable", "~arch"),
+ "arm": ("stable", "arch"),
+ "m68k": ("exp", "~arch"),
+ "s390": ("exp", "arch"),
+ }
+ self._test(
+ "* ~alpha ~arm ~m68k ~mips ~s390 ~arm-linux",
+ ops,
+ "* ~alpha arm ~m68k ~mips s390 ~arm-linux",
+ arch_status,
+ )
+
+ def testAllUnstable(self):
+ ops = (ekeyword.Op("~", "all", None),)
+ arch_status = {
+ "alpha": ("stable", "~arch"),
+ "arm": ("stable", "arch"),
+ "m68k": ("exp", "~arch"),
+ "s390": ("exp", "arch"),
+ }
+ self._test(
+ "-* ~* * alpha arm m68k s390 arm-linux",
+ ops,
+ "-* ~* * ~alpha ~arm ~m68k ~s390 ~arm-linux",
+ arch_status,
+ )
+
+ def testAllMultiUnstableStable(self):
+ ops = (
+ ekeyword.Op("~", "all", None),
+ ekeyword.Op(None, "all", None),
+ )
+ arch_status = {
+ "alpha": ("stable", "~arch"),
+ "arm": ("stable", "arch"),
+ "m68k": ("exp", "~arch"),
+ "s390": ("exp", "arch"),
+ }
+ self._test(
+ "-* ~* * alpha arm m68k s390",
+ ops,
+ "-* ~* * ~alpha arm ~m68k s390",
+ arch_status,
+ )
+
+ def testAllDisabled(self):
+ """Make sure ~all does not change -arch to ~arch"""
+ ops = (ekeyword.Op("~", "all", None),)
+ self._test("alpha -sparc ~x86", ops, "~alpha -sparc ~x86", {})
class TestProcessContent(unittest.TestCase):
- """Tests for process_content"""
-
- def _testKeywords(self, line):
- ops = (
- ekeyword.Op(None, 'arm', None),
- ekeyword.Op('~', 'sparc', None),
- )
- return ekeyword.process_content(
- 'file', ['%s\n' % line], ops, quiet=True)
-
- def testKeywords(self):
- """Basic KEYWORDS mod"""
- updated, ret = self._testKeywords('KEYWORDS=""')
- self.assertTrue(updated)
- self.assertEqual(ret, ['KEYWORDS="arm ~sparc"\n'])
-
- def testKeywordsIndented(self):
- """Test KEYWORDS indented by space"""
- updated, ret = self._testKeywords(' KEYWORDS=""')
- self.assertTrue(updated)
- self.assertEqual(ret, [' KEYWORDS="arm ~sparc"\n'])
-
- def testKeywordsSingleQuote(self):
- """Test single quoted KEYWORDS"""
- updated, ret = self._testKeywords("KEYWORDS=' '")
- self.assertTrue(updated)
- self.assertEqual(ret, ['KEYWORDS="arm ~sparc"\n'])
-
- def testKeywordsComment(self):
- """Test commented out KEYWORDS"""
- updated, ret = self._testKeywords('# KEYWORDS=""')
- self.assertFalse(updated)
- self.assertEqual(ret, ['# KEYWORDS=""\n'])
-
- def testKeywordsCode(self):
- """Test code leading KEYWORDS"""
- updated, ret = self._testKeywords('[[ ${PV} ]] && KEYWORDS=""')
- self.assertTrue(updated)
- self.assertEqual(ret, ['[[ ${PV} ]] && KEYWORDS="arm ~sparc"\n'])
-
- def testKeywordsEmpty(self):
- """Test KEYWORDS not set at all"""
- updated, ret = self._testKeywords(' KEYWORDS=')
- self.assertFalse(updated)
- self.assertEqual(ret, [' KEYWORDS=\n'])
-
- def _testSmoke(self, style='color-inline', verbose=0, quiet=0):
- ops = (
- ekeyword.Op(None, 'arm', None),
- ekeyword.Op('~', 'sparc', None),
- )
- ekeyword.process_content(
- 'asdf', ['KEYWORDS="arm"'], ops, verbose=verbose,
- quiet=quiet, style=style)
-
- def testSmokeQuiet(self):
- """Smoke test for quiet mode"""
- self._testSmoke(quiet=10)
-
- def testSmokeVerbose(self):
- """Smoke test for verbose mode"""
- self._testSmoke(verbose=10)
-
- def testSmokeStyleColor(self):
- """Smoke test for color-inline style"""
- self._testSmoke('color-inline')
-
- def testSmokeStyleInline(self):
- """Smoke test for inline style"""
- self._testSmoke('inline')
-
- def testSmokeStyleShortMulti(self):
- """Smoke test for short-multi style"""
- self._testSmoke('short-multi')
-
- def testSmokeStyleLongMulti(self):
- """Smoke test for long-multi style"""
- self._testSmoke('long-multi')
+ """Tests for process_content"""
+
+ def _testKeywords(self, line):
+ ops = (
+ ekeyword.Op(None, "arm", None),
+ ekeyword.Op("~", "sparc", None),
+ )
+ return ekeyword.process_content("file", ["%s\n" % line], ops, quiet=True)
+
+ def testKeywords(self):
+ """Basic KEYWORDS mod"""
+ updated, ret = self._testKeywords('KEYWORDS=""')
+ self.assertTrue(updated)
+ self.assertEqual(ret, ['KEYWORDS="arm ~sparc"\n'])
+
+ def testKeywordsIndented(self):
+ """Test KEYWORDS indented by space"""
+ updated, ret = self._testKeywords(' KEYWORDS=""')
+ self.assertTrue(updated)
+ self.assertEqual(ret, [' KEYWORDS="arm ~sparc"\n'])
+
+ def testKeywordsSingleQuote(self):
+ """Test single quoted KEYWORDS"""
+ updated, ret = self._testKeywords("KEYWORDS=' '")
+ self.assertTrue(updated)
+ self.assertEqual(ret, ['KEYWORDS="arm ~sparc"\n'])
+
+ def testKeywordsComment(self):
+ """Test commented out KEYWORDS"""
+ updated, ret = self._testKeywords('# KEYWORDS=""')
+ self.assertFalse(updated)
+ self.assertEqual(ret, ['# KEYWORDS=""\n'])
+
+ def testKeywordsCode(self):
+ """Test code leading KEYWORDS"""
+ updated, ret = self._testKeywords('[[ ${PV} ]] && KEYWORDS=""')
+ self.assertTrue(updated)
+ self.assertEqual(ret, ['[[ ${PV} ]] && KEYWORDS="arm ~sparc"\n'])
+
+ def testKeywordsEmpty(self):
+ """Test KEYWORDS not set at all"""
+ updated, ret = self._testKeywords(" KEYWORDS=")
+ self.assertFalse(updated)
+ self.assertEqual(ret, [" KEYWORDS=\n"])
+
+ def _testSmoke(self, style="color-inline", verbose=0, quiet=0):
+ ops = (
+ ekeyword.Op(None, "arm", None),
+ ekeyword.Op("~", "sparc", None),
+ )
+ ekeyword.process_content(
+ "asdf", ['KEYWORDS="arm"'], ops, verbose=verbose, quiet=quiet, style=style
+ )
+
+ def testSmokeQuiet(self):
+ """Smoke test for quiet mode"""
+ self._testSmoke(quiet=10)
+
+ def testSmokeVerbose(self):
+ """Smoke test for verbose mode"""
+ self._testSmoke(verbose=10)
+
+ def testSmokeStyleColor(self):
+ """Smoke test for color-inline style"""
+ self._testSmoke("color-inline")
+
+ def testSmokeStyleInline(self):
+ """Smoke test for inline style"""
+ self._testSmoke("inline")
+
+ def testSmokeStyleShortMulti(self):
+ """Smoke test for short-multi style"""
+ self._testSmoke("short-multi")
+
+ def testSmokeStyleLongMulti(self):
+ """Smoke test for long-multi style"""
+ self._testSmoke("long-multi")
class TestProcessEbuild(unittest.TestCase):
- """Tests for process_ebuild
-
- This is fairly light as most code is in process_content.
- """
-
- def _process_ebuild(self, *args, **kwargs):
- """Set up a writable copy of an ebuild for process_ebuild()"""
- with tempfile.NamedTemporaryFile() as tmp:
- with open(tmp.name, 'wb') as fw:
- with open(os.path.join(TESTDIR, 'process-1.ebuild'), 'rb') as f:
- orig_content = f.read()
- fw.write(orig_content)
- ekeyword.process_ebuild(tmp.name, *args, **kwargs)
- with open(tmp.name, 'rb') as f:
- return (orig_content, f.read())
-
- def _testSmoke(self, dry_run):
- ops = (
- ekeyword.Op(None, 'arm', None),
- ekeyword.Op('~', 'sparc', None),
- )
- orig_content, new_content = self._process_ebuild(ops, dry_run=dry_run)
- if dry_run:
- self.assertEqual(orig_content, new_content)
- else:
- self.assertNotEqual(orig_content, new_content)
-
- def testSmokeNotDry(self):
- self._testSmoke(False)
-
- def testSmokeDry(self):
- self._testSmoke(True)
-
- def testManifestUpdated(self):
- """Verify `ebuild ... manifest` runs on updated files"""
- with mock.patch.object(subprocess, 'check_call') as m:
- self._process_ebuild((ekeyword.Op('~', 'arm', None),),
- manifest=True)
- m.assert_called_once_with(['ebuild', mock.ANY, 'manifest'])
-
- def testManifestNotUpdated(self):
- """Verify we don't run `ebuild ... manifest` on unmodified files"""
- with mock.patch.object(subprocess, 'check_call') as m:
- self._process_ebuild((ekeyword.Op(None, 'arm', None),),
- manifest=True)
- self.assertEqual(m.call_count, 0)
+ """Tests for process_ebuild
+
+ This is fairly light as most code is in process_content.
+ """
+
+ def _process_ebuild(self, *args, **kwargs):
+ """Set up a writable copy of an ebuild for process_ebuild()"""
+ with tempfile.NamedTemporaryFile() as tmp:
+ with open(tmp.name, "wb") as fw:
+ with open(os.path.join(TESTDIR, "process-1.ebuild"), "rb") as f:
+ orig_content = f.read()
+ fw.write(orig_content)
+ ekeyword.process_ebuild(tmp.name, *args, **kwargs)
+ with open(tmp.name, "rb") as f:
+ return (orig_content, f.read())
+
+ def _testSmoke(self, dry_run):
+ ops = (
+ ekeyword.Op(None, "arm", None),
+ ekeyword.Op("~", "sparc", None),
+ )
+ orig_content, new_content = self._process_ebuild(ops, dry_run=dry_run)
+ if dry_run:
+ self.assertEqual(orig_content, new_content)
+ else:
+ self.assertNotEqual(orig_content, new_content)
+
+ def testSmokeNotDry(self):
+ self._testSmoke(False)
+
+ def testSmokeDry(self):
+ self._testSmoke(True)
+
+ def testManifestUpdated(self):
+ """Verify `ebuild ... manifest` runs on updated files"""
+ with mock.patch.object(subprocess, "check_call") as m:
+ self._process_ebuild((ekeyword.Op("~", "arm", None),), manifest=True)
+ m.assert_called_once_with(["ebuild", mock.ANY, "manifest"])
+
+ def testManifestNotUpdated(self):
+ """Verify we don't run `ebuild ... manifest` on unmodified files"""
+ with mock.patch.object(subprocess, "check_call") as m:
+ self._process_ebuild((ekeyword.Op(None, "arm", None),), manifest=True)
+ self.assertEqual(m.call_count, 0)
class TestArgToOps(unittest.TestCase):
- """Tests for arg_to_op()"""
+ """Tests for arg_to_op()"""
- def _test(self, arg, op):
- self.assertEqual(ekeyword.arg_to_op(arg), ekeyword.Op(*op))
+ def _test(self, arg, op):
+ self.assertEqual(ekeyword.arg_to_op(arg), ekeyword.Op(*op))
- def testStable(self):
- self._test('arm', (None, 'arm', None))
+ def testStable(self):
+ self._test("arm", (None, "arm", None))
- def testUnstable(self):
- self._test('~ppc64', ('~', 'ppc64', None))
+ def testUnstable(self):
+ self._test("~ppc64", ("~", "ppc64", None))
- def testDisabled(self):
- self._test('-sparc', ('-', 'sparc', None))
+ def testDisabled(self):
+ self._test("-sparc", ("-", "sparc", None))
- def testDeleted(self):
- self._test('^x86-fbsd', ('^', 'x86-fbsd', None))
+ def testDeleted(self):
+ self._test("^x86-fbsd", ("^", "x86-fbsd", None))
- def testSync(self):
- self._test('s390=x86', (None, 's390', 'x86'))
+ def testSync(self):
+ self._test("s390=x86", (None, "s390", "x86"))
class TestMain(unittest.TestCase):
- """Tests for the main entry point"""
+ """Tests for the main entry point"""
- def testSmoke(self):
- ekeyword.main(['arm', '--dry-run', os.path.join(TESTDIR, 'process-1.ebuild')])
+ def testSmoke(self):
+ ekeyword.main(["arm", "--dry-run", os.path.join(TESTDIR, "process-1.ebuild")])
- def testVersion(self):
- with self.assertRaises(SystemExit) as e:
- ekeyword.main(['--version', '--dry-run'])
- self.assertEqual(e.exception.code, os.EX_OK)
+ def testVersion(self):
+ with self.assertRaises(SystemExit) as e:
+ ekeyword.main(["--version", "--dry-run"])
+ self.assertEqual(e.exception.code, os.EX_OK)
- def testEmptyString(self):
- with self.assertRaises(SystemExit) as e:
- ekeyword.main(['', os.path.join(TESTDIR, 'process-1.ebuild')])
- self.assertNotEqual(e.exception.code, os.EX_OK)
+ def testEmptyString(self):
+ with self.assertRaises(SystemExit) as e:
+ ekeyword.main(["", os.path.join(TESTDIR, "process-1.ebuild")])
+ self.assertNotEqual(e.exception.code, os.EX_OK)
-if __name__ == '__main__':
- unittest.main()
+if __name__ == "__main__":
+ unittest.main()