Coding style.

- Converted to f-strings.
This commit is contained in:
Andrew Hamilton 2018-05-15 16:34:52 +10:00
parent 7cfbcae685
commit e34e896800
11 changed files with 60 additions and 69 deletions

View file

@ -82,9 +82,9 @@ def install_vigil():
def make_app_dir(app_dir, new_paths): def make_app_dir(app_dir, new_paths):
os.mkdir(app_dir) os.mkdir(app_dir)
make_sub_container("ubuntu", app_dir, new_paths) make_sub_container("ubuntu", app_dir, new_paths)
cmd("cp -a %s/tests %s" % (VIGIL_PATH, app_dir)) cmd(f"cp -a {VIGIL_PATH}/tests {app_dir}")
cmd("cp -a %s/test-all %s" % (VIGIL_PATH, app_dir)) cmd(f"cp -a {VIGIL_PATH}/test-all {app_dir}")
cmd("cp %s/appimage/* %s" % (VIGIL_PATH, app_dir)) cmd(f"cp {VIGIL_PATH}/appimage/* {app_dir}")
# if not os.path.exists("libunionpreload.so"): # if not os.path.exists("libunionpreload.so"):
# make_libunionpreload() # make_libunionpreload()
# cmd("cp libunionpreload.so " + app_dir) # cmd("cp libunionpreload.so " + app_dir)

View file

@ -10,8 +10,7 @@ import vigil.tools as tools
def tool_markup(tool): def tool_markup(tool):
url = tools.url_of_tool(tool) url = tools.url_of_tool(tool)
return (tool.__name__ if url is None else return (tool.__name__ if url is None else f"[{tool.__name__}]({url})")
"[%s](%s)" % (tool.__name__, url))
print("""\ print("""\

View file

@ -18,25 +18,22 @@ def cmd(command):
def mount_squashfs_iso(iso, squashfs_path, mount_point): def mount_squashfs_iso(iso, squashfs_path, mount_point):
cmd("mkdir iso && sudo mount -o loop %s iso" % iso) cmd(f"mkdir iso && sudo mount -o loop {iso} iso")
cmd("mkdir lower && sudo mount -t squashfs iso/%s lower" % squashfs_path) cmd(f"mkdir lower && sudo mount -t squashfs iso/{squashfs_path} lower")
cmd("mkdir upper work %s && sudo mount -t overlay " cmd(f"mkdir upper work {mount_point} && sudo mount -t overlay "
"-o lowerdir=lower,upperdir=upper,workdir=work overlay %s" % f"-o lowerdir=lower,upperdir=upper,workdir=work overlay {mount_point}")
(mount_point, mount_point))
def umount_squashfs_iso(mount_point): def umount_squashfs_iso(mount_point):
cmd("sudo umount %s && sudo rm -rf upper work %s" % cmd(f"sudo umount {mount_point} && sudo rm -rf upper work {mount_point}")
(mount_point, mount_point))
cmd("sudo umount lower && rmdir lower") cmd("sudo umount lower && rmdir lower")
cmd("sudo umount iso && rmdir iso") cmd("sudo umount iso && rmdir iso")
def run_in_container(container, command): def run_in_container(container, command):
option = "--directory" if os.path.isdir(container) else "--image" option = "--directory" if os.path.isdir(container) else "--image"
cmd("sudo systemd-nspawn --quiet --chdir=/vigil --overlay=%s:/vigil " cmd(f"sudo systemd-nspawn --quiet --chdir=/vigil --overlay={VIGIL_PATH}:/vigil "
'%s=%s /bin/bash --login -c "%s"' % f'{option}={container} /bin/bash --login -c "{command}"')
(VIGIL_PATH, option, container, command))
def build_ubuntu(): def build_ubuntu():
@ -53,8 +50,8 @@ def build_ubuntu():
def build_fedora(): def build_fedora():
image = "Fedora-Cloud-Base-25-1.3.x86_64.raw" image = "Fedora-Cloud-Base-25-1.3.x86_64.raw"
cmd("wget --continue https://dl.fedoraproject.org/pub/fedora/linux/" cmd("wget --continue https://dl.fedoraproject.org/pub/fedora/linux/"
"releases/25/CloudImages/x86_64/images/%s.xz" % image) f"releases/25/CloudImages/x86_64/images/{image}.xz")
cmd("unxz %s.xz" % image) cmd(f"unxz {image}.xz")
os.rename(image, "fedora") os.rename(image, "fedora")
@ -134,21 +131,21 @@ def main():
# FIX: Reenable: fedora debian archlinux opensuse pixel gentoo # FIX: Reenable: fedora debian archlinux opensuse pixel gentoo
for distribution in ["ubuntu"]: for distribution in ["ubuntu"]:
if os.path.exists(distribution): if os.path.exists(distribution):
print("%s container already exists." % distribution) print(distribution, "container already exists.")
else: else:
print("Building %s container..." % distribution) print(f"Building {distribution} container...")
globals()["build_" + distribution]() globals()["build_" + distribution]()
print("Installing vigil's dependencies in %s..." % distribution) print(f"Installing vigil's dependencies in {distribution}...")
run_in_container(distribution, "./install-dependencies") run_in_container(distribution, "./install-dependencies")
print("Installing vigil in %s..." % distribution) print(f"Installing vigil in {distribution}...")
run_in_container(distribution, "apt-get install --yes python3-pip") run_in_container(distribution, "apt-get install --yes python3-pip")
run_in_container(distribution, "pip3 install .") run_in_container(distribution, "pip3 install .")
print("Testing vigil in %s..." % distribution) print(f"Testing vigil in {distribution}...")
run_in_container(distribution, "./test-all") run_in_container(distribution, "./test-all")
print("Running vigil in %s..." % distribution) print(f"Running vigil in {distribution}...")
run_in_container(distribution, "vigil --help") run_in_container(distribution, "vigil --help")
print("Successfully installed vigil in %s." % distribution) print(f"Successfully installed vigil in {distribution}.")
print("Removing %s container..." % distribution) print(f"Removing {distribution} container...")
try: try:
globals()["remove_" + distribution]() globals()["remove_" + distribution]()
except KeyError: except KeyError:

View file

@ -15,7 +15,7 @@ def _accept_actual(failed):
for actual_str, golden_path in failed: for actual_str, golden_path in failed:
with open(golden_path, "wb") as golden_file: with open(golden_path, "wb") as golden_file:
golden_file.write(actual_str) golden_file.write(actual_str)
print("Wrote golden file: %s" % golden_path) print("Wrote golden file:", golden_path)
def _show_differences(failed): def _show_differences(failed):
@ -52,12 +52,12 @@ def assertGolden(actual, golden_path):
_FAILED.add((actual, golden_path)) _FAILED.add((actual, golden_path))
if expected is None: if expected is None:
raise unittest.TestCase.failureException( raise unittest.TestCase.failureException(
'The golden file does not exist: %r\nUse "--diff" or' f'The golden file does not exist: {golden_path!r}\n'
' "--accept" to create the golden file.' % golden_path) 'Use "--diff" or "--accept" to create the golden file.')
else: else:
raise unittest.TestCase.failureException( raise unittest.TestCase.failureException(
'Output does not match golden file: %r\nUse "--diff" or' f'Output does not match golden file: {golden_path!r}\n'
' "--accept" to update the golden file.' % golden_path) 'Use "--diff" or "--accept" to update the golden file.')
def main(): def main():

View file

@ -258,7 +258,7 @@ def test_against_ls(root_path, environment):
if os.path.exists(path): # Some paths are already gone. e.g. in /proc if os.path.exists(path): # Some paths are already gone. e.g. in /proc
color_code = lscolors.color_code_for_path(path, color_codes) color_code = lscolors.color_code_for_path(path, color_codes)
if color_code != ls_color_code: if color_code != ls_color_code:
print("%s %r %r" % (path, color_code, ls_color_code)) print(path, repr(color_code), repr(ls_color_code))
RICH_COLOR_CODES = ( RICH_COLOR_CODES = (

View file

@ -179,7 +179,7 @@ def type_sort(path):
def log_filesystem_changed(log, added, removed, modified): def log_filesystem_changed(log, added, removed, modified):
def part(stat, text, color): def part(stat, text, color):
return termstr.TermStr("%2s %s." % (stat, text)).fg_color( return termstr.TermStr(f"{stat:2} {text}.").fg_color(
termstr.Color.grey_100 if stat == 0 else color) termstr.Color.grey_100 if stat == 0 else color)
parts = [part(added, "added", termstr.Color.green), parts = [part(added, "added", termstr.Color.green),
part(removed, "removed", termstr.Color.red), part(removed, "removed", termstr.Color.red),
@ -733,10 +733,10 @@ class Screen:
line_num = (self._summary.get_selection().entry[0]. line_num = (self._summary.get_selection().entry[0].
scroll_position[1] + 1) scroll_position[1] + 1)
self._log.log_message([in_green("Editing "), path_colored, self._log.log_message([in_green("Editing "), path_colored,
in_green(' at line %s...' % line_num)]) in_green(f" at line {line_num}...")])
subprocess.run("%s +%s %s" % subprocess.run(f"{self.editor_command} +{line_num} {path}",
(self.editor_command, line_num, path), shell=True, shell=True, stdout=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE) stderr=subprocess.PIPE)
def toggle_status_style(self): def toggle_status_style(self):
self._summary.toggle_status_style(self._log) self._summary.toggle_status_style(self._log)
@ -745,7 +745,7 @@ class Screen:
self._summary.is_directory_sort = not self._summary.is_directory_sort self._summary.is_directory_sort = not self._summary.is_directory_sort
sort_order = ("directory then type" if self._summary.is_directory_sort sort_order = ("directory then type" if self._summary.is_directory_sort
else "type then directory") else "type then directory")
self._log.log_command("Ordering files by %s." % sort_order) self._log.log_command(f"Ordering files by {sort_order}.")
self._summary.sync_with_filesystem(self._log) self._summary.sync_with_filesystem(self._log)
def toggle_pause(self): def toggle_pause(self):
@ -881,7 +881,7 @@ class Screen:
paused_indicator = (termstr.TermStr("paused ").fg_color( paused_indicator = (termstr.TermStr("paused ").fg_color(
termstr.Color.yellow) if is_paused else termstr.TermStr("running"). termstr.Color.yellow) if is_paused else termstr.TermStr("running").
fg_color(termstr.Color.light_blue)) fg_color(termstr.Color.light_blue))
indicators = " " + paused_indicator + " order:%s " % ordering_text indicators = " " + paused_indicator + f" order:{ordering_text} "
spacing = " " * (width - len(self._STATUS_BAR) - len(indicators)) spacing = " " * (width - len(self._STATUS_BAR) - len(indicators))
bar = (self._STATUS_BAR[:width - len(indicators)] + spacing + bar = (self._STATUS_BAR[:width - len(indicators)] + spacing +
indicators)[:width] indicators)[:width]
@ -1004,7 +1004,7 @@ def main(root_path, loop, worker_count=None, editor_command=None, theme=None,
watch_manager_fd = add_watch_manager_to_mainloop( watch_manager_fd = add_watch_manager_to_mainloop(
root_path, loop, on_filesystem_change, is_path_excluded) root_path, loop, on_filesystem_change, is_path_excluded)
try: try:
log.log_message("Starting workers (%s) ..." % worker_count) log.log_message(f"Starting workers ({worker_count}) ...")
screen.make_workers(worker_count, is_being_tested) screen.make_workers(worker_count, is_being_tested)
def exit_loop(): def exit_loop():
@ -1068,7 +1068,7 @@ def check_arguments():
if arguments["--theme"] is not None: if arguments["--theme"] is not None:
themes = list(pygments.styles.get_all_styles()) themes = list(pygments.styles.get_all_styles())
if arguments["--theme"] not in themes: if arguments["--theme"] not in themes:
print("--theme must be one of: %s" % " ".join(themes)) print("--theme must be one of:", " ".join(themes))
sys.exit(1) sys.exit(1)
editor_command = arguments["--editor"] or os.environ.get("EDITOR", None)\ editor_command = arguments["--editor"] or os.environ.get("EDITOR", None)\
or os.environ.get("VISUAL", None) or os.environ.get("VISUAL", None)

View file

@ -23,15 +23,15 @@ restore = ESC + "8"
def color(color_number, is_foreground): def color(color_number, is_foreground):
return "\x1b[%s;5;%im" % ("38" if is_foreground else "48", color_number) return f"\x1b[{'38' if is_foreground else '48'};5;{color_number:d}m"
def rgb_color(rgb, is_foreground): def rgb_color(rgb, is_foreground):
return "\x1b[%s;2;" % ("38" if is_foreground else "48") + "%i;%i;%im" % rgb return f"\x1b[{'38' if is_foreground else '48'};2;" + "%i;%i;%im" % rgb
def move(x, y): def move(x, y):
return "\x1b[%i;%iH" % (y + 1, x + 1) return f"\x1b[{y + 1:d};{x + 1:d}H"
@contextlib.contextmanager @contextlib.contextmanager
@ -55,7 +55,7 @@ def hidden_cursor():
@contextlib.contextmanager @contextlib.contextmanager
def console_title(title): def console_title(title):
sys.stdout.write(save) sys.stdout.write(save)
sys.stdout.write("\033]0;%s\007" % title) sys.stdout.write(f"\033]0;{title}\007")
try: try:
yield yield
finally: finally:

View file

@ -89,8 +89,8 @@ class CharStyle:
attributes.append("i") attributes.append("i")
if self.is_underlined: if self.is_underlined:
attributes.append("u") attributes.append("u")
return ("<CharStyle: fg:%s bg:%s attr:%s>" % return (f"<CharStyle: fg:{self.fg_color} bg:{self.bg_color}"
(self.fg_color, self.bg_color, ",".join(attributes))) f" attr:{','.join(attributes)}>")
def termcode_of_color(self, color, is_foreground): def termcode_of_color(self, color, is_foreground):
if isinstance(color, int): if isinstance(color, int):
@ -122,10 +122,9 @@ class CharStyle:
else xterm_color_to_rgb(self.fg_color)) else xterm_color_to_rgb(self.fg_color))
bg_color = (self.bg_color if type(self.bg_color) == tuple bg_color = (self.bg_color if type(self.bg_color) == tuple
else xterm_color_to_rgb(self.bg_color)) else xterm_color_to_rgb(self.bg_color))
return ("<style>.S%i {font-size:80%%; color:rgb%r; " return (f"<style>.S{id(self)} {{font-size:80%%; color:rgb{fg_color!r}; "
"background-color:rgb%r; %s%s%s}</style>" % f"background-color:rgb{bg_color!r}; "
(id(self), fg_color, bg_color, bold_code, f"{bold_code}{italic_code}{underline_code}}}</style>")
italic_code, underline_code))
def _join_lists(lists): def _join_lists(lists):
@ -176,7 +175,7 @@ class TermStr(collections.UserString):
[terminal.normal]) [terminal.normal])
def __repr__(self): def __repr__(self):
return "<TermStr: %r>" % self.data return f"<TermStr: {self.data!r}>"
def __add__(self, other): def __add__(self, other):
if isinstance(other, str): if isinstance(other, str):
@ -295,5 +294,5 @@ class TermStr(collections.UserString):
encoded = str(html.escape(str_).encode( encoded = str(html.escape(str_).encode(
"ascii", "xmlcharrefreplace"))[2:-1] "ascii", "xmlcharrefreplace"))[2:-1]
encoded = encoded.replace("\\\\", "\\") encoded = encoded.replace("\\\\", "\\")
result.append('<span class="S%i">%s</span>' % (id(style), encoded)) result.append(f'<span class="S{id(style):d}">{encoded}</span>')
return "".join(result), styles return "".join(result), styles

View file

@ -216,7 +216,7 @@ def _pretty_bytes(bytes):
unit_index = int(math.floor(math.log(bytes, 1024))) unit_index = int(math.floor(math.log(bytes, 1024)))
power = math.pow(1024, unit_index) power = math.pow(1024, unit_index)
conversion = round(bytes/power, 2) conversion = round(bytes/power, 2)
return "%s %s" % (conversion, units[unit_index]) return f"{conversion} {units[unit_index]}"
def _md5(path): def _md5(path):
@ -228,8 +228,7 @@ def _md5(path):
def metadata(path): def metadata(path):
def detail(value, unit): def detail(value, unit):
result = (" (%s)" % value if unit is None else " (%s %s)" % result = f" ({value})" if unit is None else f" ({value} {unit})"
(value, unit))
return termstr.TermStr(result).fg_color(termstr.Color.grey_100) return termstr.TermStr(result).fg_color(termstr.Color.grey_100)
is_symlink = "yes" if os.path.islink(path) else "no" is_symlink = "yes" if os.path.islink(path) else "no"
stat_result = os.stat(path) stat_result = os.stat(path)
@ -290,7 +289,7 @@ def _is_python_syntax_correct(path, python_version):
if python_version == "python": if python_version == "python":
stdin, stdout, returncode = _do_command( stdin, stdout, returncode = _do_command(
["python", "-c", ["python", "-c",
"__import__('compiler').parse(open('%s').read())" % path]) f"__import__('compiler').parse(open('{path}').read())"])
return returncode == 0 return returncode == 0
else: # python3 else: # python3
with open(path) as f: with open(path) as f:
@ -761,8 +760,8 @@ class Result:
self.is_completed = True self.is_completed = True
log.log_message( log.log_message(
["Finished running ", tool_name, " on ", path, ". ", ["Finished running ", tool_name, " on ", path, ". ",
status_to_str(new_status), " %s secs" % status_to_str(new_status),
round(end_time - start_time, 2)]) f" {round(end_time - start_time, 2)} secs"])
def reset(self): def reset(self):
self.is_placeholder = True self.is_placeholder = True
@ -773,9 +772,8 @@ class Result:
def as_html(self): def as_html(self):
html, styles = termstr.TermStr(status_to_str(self.status)).as_html() html, styles = termstr.TermStr(status_to_str(self.status)).as_html()
return ('<a title="%s" href="%s/%s">%s</a>' % return (f'<a title="{self.tool.__name__}" '
(self.tool.__name__, self.path, self.tool.__name__, html), f'href="{self.path}/{self.tool.__name__}">{html}</a>', styles)
styles)
def generic_tools(): def generic_tools():
@ -913,8 +911,7 @@ def tool_name_colored(tool, path):
@functools.lru_cache() @functools.lru_cache()
def get_homepage_of_package(package): def get_homepage_of_package(package):
line = subprocess.getoutput("dpkg-query --status %s | grep Homepage" line = subprocess.getoutput(f"dpkg-query --status {package}|grep Homepage")
% package)
return line.split()[1] return line.split()[1]

View file

@ -23,9 +23,9 @@ Example:
def make_page(body_html, title): def make_page(body_html, title):
return ("<html><head><title>%s</title></head><body>" return (f"<html><head><title>{title}</title></head><body><style>body "
"<style>body { background-color: black; } </style>%s</body></html>" f"{{ background-color: black; }} </style>{body_html}</body></html>"
% (title, body_html)).encode("utf-8") ).encode("utf-8")
class Webserver(http.server.BaseHTTPRequestHandler): class Webserver(http.server.BaseHTTPRequestHandler):
@ -44,7 +44,7 @@ class Webserver(http.server.BaseHTTPRequestHandler):
result = index[(path, tool)] result = index[(path, tool)]
body = fill3.appearance_as_html( body = fill3.appearance_as_html(
fill3.Border(result).appearance_min()) fill3.Border(result).appearance_min())
page = make_page(body, "%s of %s" % (tool, path)) page = make_page(body, f"{tool} of {path}")
else: else:
return return
self.wfile.write(page) self.wfile.write(page)

View file

@ -30,8 +30,7 @@ class Worker:
os.setpriority(os.PRIO_PGRP, self.child_pgid, 19) os.setpriority(os.PRIO_PGRP, self.child_pgid, 19)
async def run_tool(self, path, tool): async def run_tool(self, path, tool):
self.process.stdin.write(("%s\n%s\n" % self.process.stdin.write(f"{tool.__qualname__}\n{path}\n".encode("utf-8"))
(tool.__qualname__, path)).encode("utf-8"))
data = await self.process.stdout.readline() data = await self.process.stdout.readline()
return tools.Status(int(data)) return tools.Status(int(data))