Commit 22044e6d authored by Jordi Gutiérrez Hermoso's avatar Jordi Gutiérrez Hermoso
Browse files

style: kill ersatz if-else ternary operators

Although Python supports `X = Y if COND else Z`, this was only
introduced in Python 2.5. Since we have to support Python 2.4, it was
a very common thing to write instead `X = COND and Y or Z`, which is a
bit obscure at a glance. It requires some intricate knowledge of
Python to understand how to parse these one-liners.

We change instead all of these one-liners to 4-liners. This was
executed with the following perlism:

    find -name "*.py" -exec perl -pi -e 's,(\s*)([\.\w]+) = \(?(\S+)\s+and\s+(\S*)\)?\s+or\s+(\S*)$,$1if $3:\n$1    $2 = $4\n$1else:\n$1    $2 = $5,' {} \;

I tweaked the following cases from the automatic Perl output:

    prev = (parents and parents[0]) or nullid
    port = (use_ssl and 443 or 80)
    cwd = (pats and repo.getcwd()) or ''
    rename = fctx and webutil.renamelink(fctx) or []
    ctx = fctx and fctx or ctx
    self.base = (mapfile and os.path.dirname(mapfile)) or ''

I also added some newlines wherever they seemd appropriate for readability

There are probably a few ersatz ternary operators still in the code
somewhere, lurking away from the power of a simple regex.
parent 867c3649be5d
......@@ -359,7 +359,10 @@ def synthesize(ui, repo, descpath, **opts):
files.iterkeys(), filectxfn, ui.username(),
'%d %d' % util.makedate())
initnode = mc.commit()
hexfn = ui.debugflag and hex or short
if ui.debugflag:
hexfn = hex
else:
hexfn = short
ui.status(_('added commit %s with %d files\n')
% (hexfn(initnode), len(files)))
......@@ -475,7 +478,10 @@ def renamedirs(dirs, words):
if dirpath in replacements:
return replacements[dirpath]
head, _ = os.path.split(dirpath)
head = head and rename(head) or ''
if head:
head = rename(head)
else:
head = ''
renamed = os.path.join(head, wordgen.next())
replacements[dirpath] = renamed
return renamed
......
......@@ -31,7 +31,10 @@ class MissingTool(Exception):
def checktool(exe, name=None, abort=True):
name = name or exe
if not util.findexe(exe):
exc = abort and util.Abort or MissingTool
if abort:
exc = util.Abort
else:
exc = MissingTool
raise exc(_('cannot find required "%s" tool') % name)
class NoRepo(Exception):
......
......@@ -515,7 +515,11 @@ def convert(ui, src, dest=None, revmapfile=None, **opts):
sortmode = [m for m in sortmodes if opts.get(m)]
if len(sortmode) > 1:
raise util.Abort(_('more than one sort mode specified'))
sortmode = sortmode and sortmode[0] or defaultsort
if sortmode:
sortmode = sortmode[0]
else:
sortmode = defaultsort
if sortmode == 'sourcesort' and not srcc.hasnativeorder():
raise util.Abort(_('--sourcesort is not supported by this data source'))
if sortmode == 'closesort' and not srcc.hasnativeclose():
......
......@@ -209,7 +209,10 @@ class gnuarch_source(converter_source, commandline):
mode = os.lstat(os.path.join(self.tmppath, name)).st_mode
if stat.S_ISLNK(mode):
data = os.readlink(os.path.join(self.tmppath, name))
mode = mode and 'l' or ''
if mode:
mode = 'l'
else:
mode = ''
else:
data = open(os.path.join(self.tmppath, name), 'rb').read()
mode = (mode & 0111) and 'x' or ''
......
......@@ -87,7 +87,10 @@ class mercurial_sink(converter_sink):
if not branch:
branch = 'default'
pbranches = [(b[0], b[1] and b[1] or 'default') for b in pbranches]
pbranch = pbranches and pbranches[0][1] or 'default'
if pbranches:
pbranch = pbranches[0][1]
else:
pbranch = 'default'
branchpath = os.path.join(self.path, branch)
if setbranch:
......
......@@ -871,8 +871,16 @@ class svn_source(converter_source):
if self.ui.configbool('convert', 'localtimezone'):
date = makedatetimestamp(date[0])
log = message and self.recode(message) or ''
author = author and self.recode(author) or ''
if message:
log = self.recode(message)
else:
log = ''
if author:
author = self.recode(author)
else:
author = ''
try:
branch = self.module.split("/")[-1]
if branch == self.trunkname:
......@@ -1118,7 +1126,10 @@ class svn_sink(converter_sink, commandline):
self.opener = scmutil.opener(self.wc)
self.wopener = scmutil.opener(self.wc)
self.childmap = mapfile(ui, self.join('hg-childmap'))
self.is_exec = util.checkexec(self.wc) and util.isexec or None
if util.checkexec(self.wc):
self.is_exec = util.isexec
else:
self.is_exec = None
if created:
hook = os.path.join(created, 'hooks', 'pre-revprop-change')
......
......@@ -121,7 +121,10 @@ class ciamsg(object):
return patch.diffstat(pbuf.lines) or ''
def logmsg(self):
diffstat = self.cia.diffstat and self.diffstat() or ''
if self.cia.diffstat:
diffstat = self.diffstat()
else:
diffstat = ''
self.cia.ui.pushbuffer()
self.cia.templater.show(self.ctx, changes=self.ctx.changeset(),
baseurl=self.cia.ui.config('web', 'baseurl'),
......@@ -199,7 +202,10 @@ class hgcia(object):
style = self.ui.config('cia', 'style')
template = self.ui.config('cia', 'template')
if not template:
template = self.diffstat and self.dstemplate or self.deftemplate
if self.diffstat:
template = self.dstemplate
else:
template = self.deftemplate
template = templater.parsestring(template, quoted=False)
t = cmdutil.changeset_templater(self.ui, self.repo, False, None,
template, style, False)
......
......@@ -506,7 +506,10 @@ def files(ui, repo, *pats, **opts):
kwt = kwtools['templater']
wctx = repo[None]
status = _status(ui, repo, wctx, kwt, *pats, **opts)
cwd = pats and repo.getcwd() or ''
if pats:
cwd = repo.getcwd()
else:
cwd = ''
files = []
if not opts.get('unknown') or opts.get('all'):
files = sorted(status.modified + status.added + status.clean)
......
......@@ -418,7 +418,10 @@ class queue(object):
gitmode = ui.configbool('mq', 'git', None)
if gitmode is None:
raise error.ConfigError
self.gitmode = gitmode and 'yes' or 'no'
if gitmode:
self.gitmode = 'yes'
else:
self.gitmode = 'no'
except error.ConfigError:
self.gitmode = ui.config('mq', 'git', 'auto').lower()
self.plainmode = ui.configbool('mq', 'plain', False)
......@@ -610,7 +613,11 @@ class queue(object):
return True, ''
def explainpushable(self, idx, all_patches=False):
write = all_patches and self.ui.write or self.ui.warn
if all_patches:
write = self.ui.write
else:
write = self.ui.warn
if all_patches or self.ui.verbose:
if isinstance(idx, str):
idx = self.series.index(idx)
......@@ -1825,7 +1832,11 @@ class queue(object):
self.ui.write(pfx)
if summary:
ph = patchheader(self.join(patchname), self.plainmode)
msg = ph.message and ph.message[0] or ''
if ph.message:
msg = ph.message[0]
else:
msg = ''
if self.ui.formatted():
width = self.ui.termwidth() - len(pfx) - len(patchname) - 2
if width > 0:
......@@ -2228,7 +2239,10 @@ def unapplied(ui, repo, patch=None, **opts):
ui.write(_("all patches applied\n"))
return 1
length = opts.get('first') and 1 or None
if opts.get('first'):
length = 1
else:
length = None
q.qseries(repo, start=start, length=length, status='U',
summary=opts.get('summary'))
......@@ -2454,7 +2468,11 @@ def top(ui, repo, **opts):
Returns 0 on success."""
q = repo.mq
t = q.applied and q.seriesend(True) or 0
if q.applied:
t = q.seriesend(True)
else:
t = 0
if t:
q.qseries(repo, start=t - 1, length=1, status='A',
summary=opts.get('summary'))
......
......@@ -340,7 +340,10 @@ class notifier(object):
maxdiff = int(self.ui.config('notify', 'maxdiff', 300))
prev = ctx.p1().node()
ref = ref and ref.node() or ctx.node()
if ref:
ref = ref.node()
else:
ref = ctx.node()
chunks = patch.diff(self.repo, prev, ref,
opts=patch.diffallopts(self.ui))
difflines = ''.join(chunks).splitlines()
......
......@@ -489,7 +489,10 @@ def patchbomb(ui, repo, *revs, **opts):
if outgoing or bundle:
if len(revs) > 1:
raise util.Abort(_("too many destinations"))
dest = revs and revs[0] or None
if revs:
dest = revs[0]
else:
dest = None
revs = []
if rev:
......
......@@ -437,8 +437,15 @@ class _BaseFile(list):
# the keys are sorted in the .mo file
def cmp(_self, other):
# msgfmt compares entries with msgctxt if it exists
self_msgid = _self.msgctxt and _self.msgctxt or _self.msgid
other_msgid = other.msgctxt and other.msgctxt or other.msgid
if _self.msgctxt:
self_msgid = _self.msgctxt
else:
self_msgid = _self.msgid
if other.msgctxt:
other_msgid = other.msgctxt
else:
other_msgid = other.msgid
if self_msgid > other_msgid:
return 1
elif self_msgid < other_msgid:
......
......@@ -435,7 +435,10 @@ def diff(ui, dst, src):
diff = sorted(set(smarks) - set(dmarks))
for k in diff:
mark = ui.debugflag and smarks[k] or smarks[k][:12]
if ui.debugflag:
mark = smarks[k]
else:
mark = smarks[k][:12]
ui.write(" %-25s %s\n" % (k, mark))
if len(diff) <= 0:
......
......@@ -426,7 +426,10 @@ def getremotechanges(ui, repo, other, onlyheads=None, bundlename=None,
rheads = None
else:
cg = other.changegroupsubset(incoming, rheads, 'incoming')
bundletype = localrepo and "HG10BZ" or "HG10UN"
if localrepo:
bundletype = "HG10BZ"
else:
bundletype = "HG10UN"
fname = bundle = changegroup.writebundle(ui, cg, bundlename, bundletype)
# keep written bundle?
if bundlename:
......
......@@ -274,7 +274,11 @@ class FTPRangeHandler(urllib2.FTPHandler):
dirs = dirs[1:]
try:
fw = self.connect_ftp(user, passwd, host, port, dirs)
type = file and 'I' or 'D'
if file:
type = 'I'
else:
type = 'D'
for attr in attrs:
attr, value = splitattr(attr)
if attr.lower() == 'type' and \
......
......@@ -398,7 +398,10 @@ def makefileobj(repo, pat, node=None, desc=None, total=None,
writable = mode not in ('r', 'rb')
if not pat or pat == '-':
fp = writable and repo.ui.fout or repo.ui.fin
if writable:
fp = repo.ui.fout
else:
fp = repo.ui.fin
if util.safehasattr(fp, 'fileno'):
return os.fdopen(os.dup(fp.fileno()), mode)
else:
......@@ -474,7 +477,10 @@ def copy(ui, repo, pats, opts, rename=False):
def walkpat(pat):
srcs = []
badstates = after and '?' or '?r'
if after:
badstates = '?'
else:
badstates = '?r'
m = scmutil.match(repo[None], [pat], opts, globbed=True)
for abs in repo.walk(m):
state = repo.dirstate[abs]
......@@ -693,7 +699,10 @@ def service(opts, parentfn=None, initfn=None, runfn=None, logfile=None,
def writepid(pid):
if opts['pid_file']:
mode = appendpid and 'a' or 'w'
if appendpid:
mode = 'a'
else:
mode = 'w'
fp = open(opts['pid_file'], mode)
fp.write(str(pid) + '\n')
fp.close()
......@@ -929,7 +938,11 @@ def export(repo, revs, template='hg-%h.patch', fp=None, switch_parent=False,
branch = ctx.branch()
if switch_parent:
parents.reverse()
prev = (parents and parents[0]) or nullid
if parents:
prev = parents[0]
else:
prev = nullid
shouldclose = False
if not fp and len(template) > 0:
......@@ -1067,7 +1080,10 @@ class changeset_printer(object):
log = self.repo.changelog
date = util.datestr(ctx.date())
hexfunc = self.ui.debugflag and hex or short
if self.ui.debugflag:
hexfunc = hex
else:
hexfunc = short
parents = [(p, hexfunc(log.node(p)))
for p in self._meaningful_parentrevs(log, rev)]
......@@ -1866,7 +1882,10 @@ def _makelogrevset(repo, pats, opts, revs):
opts = dict(opts)
# follow or not follow?
follow = opts.get('follow') or opts.get('follow_first')
followfirst = opts.get('follow_first') and 1 or 0
if opts.get('follow_first'):
followfirst = 1
else:
followfirst = 0
# --follow with FILE behaviour depends on revs...
it = iter(revs)
startrev = it.next()
......
......@@ -277,7 +277,10 @@ def annotate(ui, repo, *pats, **opts):
opts['file'] = True
fm = ui.formatter('annotate', opts)
datefunc = ui.quiet and util.shortdate or util.datestr
if ui.quiet:
datefunc = util.shortdate
else:
datefunc = util.datestr
hexfn = fm.hexfunc
opmap = [('user', ' ', lambda x: x[0].user(), ui.shortuser),
......@@ -664,7 +667,10 @@ def bisect(ui, repo, rev=None, extra=None, command=None,
# one of the parent was not checked.
parents = repo[nodes[0]].parents()
if len(parents) > 1:
side = good and state['bad'] or state['good']
if good:
side = state['bad']
else:
side = state['good']
num = len(set(i.node() for i in parents) & set(side))
if num == 1:
return parents[0].ancestor(parents[1])
......@@ -3670,7 +3676,10 @@ def grep(ui, repo, pattern, *pats, **opts):
def display(fn, ctx, pstates, states):
rev = ctx.rev()
datefunc = ui.quiet and util.shortdate or util.datestr
if ui.quiet:
datefunc = util.shortdate
else:
datefunc = util.datestr
found = False
@util.cachefunc
def binary():
......@@ -3946,7 +3955,10 @@ def identify(ui, repo, source=None, rev=None,
raise util.Abort(_("there is no Mercurial repository here "
"(.hg not found)"))
hexfunc = ui.debugflag and hex or short
if ui.debugflag:
hexfunc = hex
else:
hexfunc = short
default = not (num or id or branch or tags or bookmarks)
output = []
revs = []
......@@ -4342,7 +4354,10 @@ def locate(ui, repo, *pats, **opts):
Returns 0 if a match is found, 1 otherwise.
"""
end = opts.get('print0') and '\0' or '\n'
if opts.get('print0'):
end = '\0'
else:
end = '\n'
rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
ret = 1
......@@ -4506,7 +4521,10 @@ def log(ui, repo, *pats, **opts):
rename = getrenamed(fn, rev)
if rename:
copies.append((fn, rename[0]))
revmatchfn = filematcher and filematcher(ctx.rev()) or None
if filematcher:
revmatchfn = filematcher(ctx.rev())
else:
revmatchfn = None
displayer.show(ctx, copies=copies, matchfn=revmatchfn)
if displayer.flush(rev):
count += 1
......@@ -5550,7 +5568,10 @@ def serve(ui, repo, **opts):
if opts.get('port'):
opts['port'] = util.getport(opts.get('port'))
baseui = repo and repo.baseui or ui
if repo:
baseui = repo.baseui
else:
baseui = ui
optlist = ("name templates style address port prefix ipv6"
" accesslog errorlog certificate encoding")
for o in optlist.split():
......@@ -5700,15 +5721,25 @@ def status(ui, repo, *pats, **opts):
else:
node1, node2 = scmutil.revpair(repo, revs)
cwd = (pats and repo.getcwd()) or ''
end = opts.get('print0') and '\0' or '\n'
if pats:
cwd = repo.getcwd()
else:
cwd = ''
if opts.get('print0'):
end = '\0'
else:
end = '\n'
copy = {}
states = 'modified added removed deleted unknown ignored clean'.split()
show = [k for k in states if opts.get(k)]
if opts.get('all'):
show += ui.quiet and (states[:4] + ['clean']) or states
if not show:
show = ui.quiet and states[:4] or states[:5]
if ui.quiet:
show = states[:4]
else:
show = states[:5]
stat = repo.status(node1, node2, scmutil.match(repo[node2], pats, opts),
'ignored' in show, 'clean' in show, 'unknown' in show,
......@@ -6029,7 +6060,11 @@ def tag(ui, repo, name1, *names, **opts):
rev_ = opts['rev']
message = opts.get('message')
if opts.get('remove'):
expectedtype = opts.get('local') and 'local' or 'global'
if opts.get('local'):
expectedtype = 'local'
else:
expectedtype = 'global'
for n in names:
if not repo.tagtype(n):
raise util.Abort(_("tag '%s' does not exist") % n)
......
......@@ -963,7 +963,11 @@ class basefilectx(object):
def ancestors(self, followfirst=False):
visit = {}
c = self
cut = followfirst and 1 or None
if followfirst:
cut = 1
else:
cut = None
while True:
for parent in c.parents()[:cut]:
visit[(parent.linkrev(), parent.filenode())] = parent
......@@ -1755,7 +1759,11 @@ class memctx(committablectx):
# "filectxfn" for performance (e.g. converting from another VCS)
self._filectxfn = util.cachefunc(filectxfn)
self._extra = extra and extra.copy() or {}
if extra:
self._extra = extra.copy()
else:
self._extra = {}
if self._extra.get('branch', '') == '':
self._extra['branch'] = 'default'
......
......@@ -88,7 +88,10 @@ class genericdag(basedag):
'''generic implementations for DAGs'''
def ancestorset(self, starts, stops=None):
stops = stops and set(stops) or set()
if stops:
stops = set(stops)
else:
stops = set()
seen = set()
pending = list(starts)
while pending:
......@@ -179,7 +182,10 @@ class revlogdag(revlogbaseddag):
def ancestorset(self, starts, stops=None):
rlog = self._revlog
idx = rlog.index
stops = stops and set(stops) or set()
if stops:
stops = set(stops)
else:
stops = set()
seen = set()
pending = list(starts)
while pending:
......
......@@ -218,7 +218,10 @@ def _oldheadssummary(repo, remoteheads, outgoing, inc=False):
r = repo.set('heads(%ln + %ln)', oldheads, outgoing.missing)
newheads = list(c.node() for c in r)
# set some unsynced head to issue the "unsynced changes" warning
unsynced = inc and set([None]) or set()
if inc:
unsynced = set([None])
else:
unsynced = set()
return {None: (oldheads, newheads, unsynced)}
def checkheads(repo, remote, outgoing, remoteheads, newbranch=False, inc=False,
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment