From e34e896800dc48541d630552772aa3e5ab0789e9 Mon Sep 17 00:00:00 2001 From: Andrew Hamilton Date: Tue, 15 May 2018 16:34:52 +1000 Subject: [PATCH] Coding style. - Converted to f-strings. --- make-appimage.py | 6 +++--- make-readme.py | 3 +-- test_distributions.py | 37 +++++++++++++++++-------------------- tests/golden.py | 10 +++++----- tests/lscolors_test.py | 2 +- vigil/__main__.py | 18 +++++++++--------- vigil/terminal.py | 8 ++++---- vigil/termstr.py | 15 +++++++-------- vigil/tools.py | 19 ++++++++----------- vigil/webserver.py | 8 ++++---- vigil/worker.py | 3 +-- 11 files changed, 60 insertions(+), 69 deletions(-) diff --git a/make-appimage.py b/make-appimage.py index 4e9667d..1133bcc 100755 --- a/make-appimage.py +++ b/make-appimage.py @@ -82,9 +82,9 @@ def install_vigil(): def make_app_dir(app_dir, new_paths): os.mkdir(app_dir) make_sub_container("ubuntu", app_dir, new_paths) - cmd("cp -a %s/tests %s" % (VIGIL_PATH, app_dir)) - cmd("cp -a %s/test-all %s" % (VIGIL_PATH, app_dir)) - cmd("cp %s/appimage/* %s" % (VIGIL_PATH, app_dir)) + cmd(f"cp -a {VIGIL_PATH}/tests {app_dir}") + cmd(f"cp -a {VIGIL_PATH}/test-all {app_dir}") + cmd(f"cp {VIGIL_PATH}/appimage/* {app_dir}") # if not os.path.exists("libunionpreload.so"): # make_libunionpreload() # cmd("cp libunionpreload.so " + app_dir) diff --git a/make-readme.py b/make-readme.py index e44dc2b..72cd355 100755 --- a/make-readme.py +++ b/make-readme.py @@ -10,8 +10,7 @@ import vigil.tools as tools def tool_markup(tool): url = tools.url_of_tool(tool) - return (tool.__name__ if url is None else - "[%s](%s)" % (tool.__name__, url)) + return (tool.__name__ if url is None else f"[{tool.__name__}]({url})") print("""\ diff --git a/test_distributions.py b/test_distributions.py index 5fe4644..f6f8d97 100755 --- a/test_distributions.py +++ b/test_distributions.py @@ -18,25 +18,22 @@ def cmd(command): def mount_squashfs_iso(iso, squashfs_path, mount_point): - cmd("mkdir iso && sudo mount -o loop %s iso" % iso) - cmd("mkdir lower && sudo mount -t squashfs iso/%s lower" % squashfs_path) - cmd("mkdir upper work %s && sudo mount -t overlay " - "-o lowerdir=lower,upperdir=upper,workdir=work overlay %s" % - (mount_point, mount_point)) + cmd(f"mkdir iso && sudo mount -o loop {iso} iso") + cmd(f"mkdir lower && sudo mount -t squashfs iso/{squashfs_path} lower") + cmd(f"mkdir upper work {mount_point} && sudo mount -t overlay " + f"-o lowerdir=lower,upperdir=upper,workdir=work overlay {mount_point}") def umount_squashfs_iso(mount_point): - cmd("sudo umount %s && sudo rm -rf upper work %s" % - (mount_point, mount_point)) + cmd(f"sudo umount {mount_point} && sudo rm -rf upper work {mount_point}") cmd("sudo umount lower && rmdir lower") cmd("sudo umount iso && rmdir iso") def run_in_container(container, command): option = "--directory" if os.path.isdir(container) else "--image" - cmd("sudo systemd-nspawn --quiet --chdir=/vigil --overlay=%s:/vigil " - '%s=%s /bin/bash --login -c "%s"' % - (VIGIL_PATH, option, container, command)) + cmd(f"sudo systemd-nspawn --quiet --chdir=/vigil --overlay={VIGIL_PATH}:/vigil " + f'{option}={container} /bin/bash --login -c "{command}"') def build_ubuntu(): @@ -53,8 +50,8 @@ def build_ubuntu(): def build_fedora(): image = "Fedora-Cloud-Base-25-1.3.x86_64.raw" cmd("wget --continue https://dl.fedoraproject.org/pub/fedora/linux/" - "releases/25/CloudImages/x86_64/images/%s.xz" % image) - cmd("unxz %s.xz" % image) + f"releases/25/CloudImages/x86_64/images/{image}.xz") + cmd(f"unxz {image}.xz") os.rename(image, "fedora") @@ -134,21 +131,21 @@ def main(): # FIX: Reenable: fedora debian archlinux opensuse pixel gentoo for distribution in ["ubuntu"]: if os.path.exists(distribution): - print("%s container already exists." % distribution) + print(distribution, "container already exists.") else: - print("Building %s container..." % distribution) + print(f"Building {distribution} container...") 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") - 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, "pip3 install .") - print("Testing vigil in %s..." % distribution) + print(f"Testing vigil in {distribution}...") run_in_container(distribution, "./test-all") - print("Running vigil in %s..." % distribution) + print(f"Running vigil in {distribution}...") run_in_container(distribution, "vigil --help") - print("Successfully installed vigil in %s." % distribution) - print("Removing %s container..." % distribution) + print(f"Successfully installed vigil in {distribution}.") + print(f"Removing {distribution} container...") try: globals()["remove_" + distribution]() except KeyError: diff --git a/tests/golden.py b/tests/golden.py index 34a25a6..6798c66 100644 --- a/tests/golden.py +++ b/tests/golden.py @@ -15,7 +15,7 @@ def _accept_actual(failed): for actual_str, golden_path in failed: with open(golden_path, "wb") as golden_file: golden_file.write(actual_str) - print("Wrote golden file: %s" % golden_path) + print("Wrote golden file:", golden_path) def _show_differences(failed): @@ -52,12 +52,12 @@ def assertGolden(actual, golden_path): _FAILED.add((actual, golden_path)) if expected is None: raise unittest.TestCase.failureException( - 'The golden file does not exist: %r\nUse "--diff" or' - ' "--accept" to create the golden file.' % golden_path) + f'The golden file does not exist: {golden_path!r}\n' + 'Use "--diff" or "--accept" to create the golden file.') else: raise unittest.TestCase.failureException( - 'Output does not match golden file: %r\nUse "--diff" or' - ' "--accept" to update the golden file.' % golden_path) + f'Output does not match golden file: {golden_path!r}\n' + 'Use "--diff" or "--accept" to update the golden file.') def main(): diff --git a/tests/lscolors_test.py b/tests/lscolors_test.py index 53df230..064fa2f 100755 --- a/tests/lscolors_test.py +++ b/tests/lscolors_test.py @@ -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 color_code = lscolors.color_code_for_path(path, color_codes) 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 = ( diff --git a/vigil/__main__.py b/vigil/__main__.py index bed5e83..7cf94f4 100755 --- a/vigil/__main__.py +++ b/vigil/__main__.py @@ -179,7 +179,7 @@ def type_sort(path): def log_filesystem_changed(log, added, removed, modified): 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) parts = [part(added, "added", termstr.Color.green), part(removed, "removed", termstr.Color.red), @@ -733,10 +733,10 @@ class Screen: line_num = (self._summary.get_selection().entry[0]. scroll_position[1] + 1) self._log.log_message([in_green("Editing "), path_colored, - in_green(' at line %s...' % line_num)]) - subprocess.run("%s +%s %s" % - (self.editor_command, line_num, path), shell=True, - stdout=subprocess.PIPE, stderr=subprocess.PIPE) + in_green(f" at line {line_num}...")]) + subprocess.run(f"{self.editor_command} +{line_num} {path}", + shell=True, stdout=subprocess.PIPE, + stderr=subprocess.PIPE) def toggle_status_style(self): self._summary.toggle_status_style(self._log) @@ -745,7 +745,7 @@ class Screen: self._summary.is_directory_sort = not self._summary.is_directory_sort sort_order = ("directory then type" if self._summary.is_directory_sort 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) def toggle_pause(self): @@ -881,7 +881,7 @@ class Screen: paused_indicator = (termstr.TermStr("paused ").fg_color( termstr.Color.yellow) if is_paused else termstr.TermStr("running"). 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)) bar = (self._STATUS_BAR[:width - len(indicators)] + spacing + 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( root_path, loop, on_filesystem_change, is_path_excluded) 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) def exit_loop(): @@ -1068,7 +1068,7 @@ def check_arguments(): if arguments["--theme"] is not None: themes = list(pygments.styles.get_all_styles()) 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) editor_command = arguments["--editor"] or os.environ.get("EDITOR", None)\ or os.environ.get("VISUAL", None) diff --git a/vigil/terminal.py b/vigil/terminal.py index fb9d138..aca372c 100644 --- a/vigil/terminal.py +++ b/vigil/terminal.py @@ -23,15 +23,15 @@ restore = ESC + "8" 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): - 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): - return "\x1b[%i;%iH" % (y + 1, x + 1) + return f"\x1b[{y + 1:d};{x + 1:d}H" @contextlib.contextmanager @@ -55,7 +55,7 @@ def hidden_cursor(): @contextlib.contextmanager def console_title(title): sys.stdout.write(save) - sys.stdout.write("\033]0;%s\007" % title) + sys.stdout.write(f"\033]0;{title}\007") try: yield finally: diff --git a/vigil/termstr.py b/vigil/termstr.py index 8982211..194112e 100644 --- a/vigil/termstr.py +++ b/vigil/termstr.py @@ -89,8 +89,8 @@ class CharStyle: attributes.append("i") if self.is_underlined: attributes.append("u") - return ("" % - (self.fg_color, self.bg_color, ",".join(attributes))) + return (f"") def termcode_of_color(self, color, is_foreground): if isinstance(color, int): @@ -122,10 +122,9 @@ class CharStyle: else xterm_color_to_rgb(self.fg_color)) bg_color = (self.bg_color if type(self.bg_color) == tuple else xterm_color_to_rgb(self.bg_color)) - return ("" % - (id(self), fg_color, bg_color, bold_code, - italic_code, underline_code)) + return (f"") def _join_lists(lists): @@ -176,7 +175,7 @@ class TermStr(collections.UserString): [terminal.normal]) def __repr__(self): - return "" % self.data + return f"" def __add__(self, other): if isinstance(other, str): @@ -295,5 +294,5 @@ class TermStr(collections.UserString): encoded = str(html.escape(str_).encode( "ascii", "xmlcharrefreplace"))[2:-1] encoded = encoded.replace("\\\\", "\\") - result.append('%s' % (id(style), encoded)) + result.append(f'{encoded}') return "".join(result), styles diff --git a/vigil/tools.py b/vigil/tools.py index f3117d5..9596844 100644 --- a/vigil/tools.py +++ b/vigil/tools.py @@ -216,7 +216,7 @@ def _pretty_bytes(bytes): unit_index = int(math.floor(math.log(bytes, 1024))) power = math.pow(1024, unit_index) conversion = round(bytes/power, 2) - return "%s %s" % (conversion, units[unit_index]) + return f"{conversion} {units[unit_index]}" def _md5(path): @@ -228,8 +228,7 @@ def _md5(path): def metadata(path): def detail(value, unit): - result = (" (%s)" % value if unit is None else " (%s %s)" % - (value, unit)) + result = f" ({value})" if unit is None else f" ({value} {unit})" return termstr.TermStr(result).fg_color(termstr.Color.grey_100) is_symlink = "yes" if os.path.islink(path) else "no" stat_result = os.stat(path) @@ -290,7 +289,7 @@ def _is_python_syntax_correct(path, python_version): if python_version == "python": stdin, stdout, returncode = _do_command( ["python", "-c", - "__import__('compiler').parse(open('%s').read())" % path]) + f"__import__('compiler').parse(open('{path}').read())"]) return returncode == 0 else: # python3 with open(path) as f: @@ -761,8 +760,8 @@ class Result: self.is_completed = True log.log_message( ["Finished running ", tool_name, " on ", path, ". ", - status_to_str(new_status), " %s secs" % - round(end_time - start_time, 2)]) + status_to_str(new_status), + f" {round(end_time - start_time, 2)} secs"]) def reset(self): self.is_placeholder = True @@ -773,9 +772,8 @@ class Result: def as_html(self): html, styles = termstr.TermStr(status_to_str(self.status)).as_html() - return ('%s' % - (self.tool.__name__, self.path, self.tool.__name__, html), - styles) + return (f'{html}', styles) def generic_tools(): @@ -913,8 +911,7 @@ def tool_name_colored(tool, path): @functools.lru_cache() def get_homepage_of_package(package): - line = subprocess.getoutput("dpkg-query --status %s | grep Homepage" - % package) + line = subprocess.getoutput(f"dpkg-query --status {package}|grep Homepage") return line.split()[1] diff --git a/vigil/webserver.py b/vigil/webserver.py index 46139cb..ed66d5b 100755 --- a/vigil/webserver.py +++ b/vigil/webserver.py @@ -23,9 +23,9 @@ Example: def make_page(body_html, title): - return ("%s" - "%s" - % (title, body_html)).encode("utf-8") + return (f"{title}{body_html}" + ).encode("utf-8") class Webserver(http.server.BaseHTTPRequestHandler): @@ -44,7 +44,7 @@ class Webserver(http.server.BaseHTTPRequestHandler): result = index[(path, tool)] body = fill3.appearance_as_html( fill3.Border(result).appearance_min()) - page = make_page(body, "%s of %s" % (tool, path)) + page = make_page(body, f"{tool} of {path}") else: return self.wfile.write(page) diff --git a/vigil/worker.py b/vigil/worker.py index 6c00e3e..530cc3a 100755 --- a/vigil/worker.py +++ b/vigil/worker.py @@ -30,8 +30,7 @@ class Worker: os.setpriority(os.PRIO_PGRP, self.child_pgid, 19) async def run_tool(self, path, tool): - self.process.stdin.write(("%s\n%s\n" % - (tool.__qualname__, path)).encode("utf-8")) + self.process.stdin.write(f"{tool.__qualname__}\n{path}\n".encode("utf-8")) data = await self.process.stdout.readline() return tools.Status(int(data))