general: Remove all pathlib usage

This commit is contained in:
Dylan Araps 2017-08-10 09:17:11 +10:00
parent 979ec3ee10
commit 05c271c3a7
11 changed files with 53 additions and 53 deletions

View File

@ -91,7 +91,8 @@ def process_args(args):
sys.stdout = sys.stderr = open(os.devnull, "w") sys.stdout = sys.stderr = open(os.devnull, "w")
if args.c: if args.c:
shutil.rmtree(str(CACHE_DIR / "schemes"), ignore_errors=True) scheme_dir = os.path.join(CACHE_DIR, "schemes")
shutil.rmtree(scheme_dir, ignore_errors=True)
if args.r: if args.r:
reload.colors(args.t) reload.colors(args.t)

View File

@ -2,6 +2,7 @@
Generate a colorscheme using imagemagick. Generate a colorscheme using imagemagick.
""" """
import collections import collections
import os
import re import re
import shutil import shutil
import subprocess import subprocess
@ -84,11 +85,10 @@ def get(img, cache_dir=CACHE_DIR,
color_count=COLOR_COUNT, notify=False): color_count=COLOR_COUNT, notify=False):
"""Get the colorscheme.""" """Get the colorscheme."""
# _home_dylan_img_jpg.json # _home_dylan_img_jpg.json
cache_file = cache_dir / "schemes" / \ cache_file = os.path.join(cache_dir, "schemes",
img.replace("/", "_").replace(".", "_") img.replace("/", "_"), ".json")
cache_file = cache_file.with_suffix(".json")
if cache_file.is_file(): if os.path.isfile(cache_file):
colors = util.read_file_json(cache_file) colors = util.read_file_json(cache_file)
print("colors: Found cached colorscheme.") print("colors: Found cached colorscheme.")

View File

@ -2,7 +2,6 @@
Export colors in various formats. Export colors in various formats.
""" """
import os import os
import pathlib
from .settings import CACHE_DIR, MODULE_DIR from .settings import CACHE_DIR, MODULE_DIR
from . import util from . import util
@ -43,10 +42,10 @@ def get_export_type(export_type):
def every(colors, output_dir=CACHE_DIR): def every(colors, output_dir=CACHE_DIR):
"""Export all template files.""" """Export all template files."""
all_colors = flatten_colors(colors) all_colors = flatten_colors(colors)
output_dir = pathlib.Path(output_dir) template_dir = os.path.join(MODULE_DIR, "templates")
for file in os.scandir(str(MODULE_DIR / "templates")): for file in os.scandir(template_dir):
template(all_colors, file.path, output_dir / file.name) template(all_colors, file.path, os.path.join(output_dir, file.name))
print("export: Exported all files.") print("export: Exported all files.")
@ -56,10 +55,10 @@ def color(colors, export_type, output_file=None):
all_colors = flatten_colors(colors) all_colors = flatten_colors(colors)
template_name = get_export_type(export_type) template_name = get_export_type(export_type)
template_file = MODULE_DIR / "templates" / template_name template_file = os.path.join(MODULE_DIR, "templates", template_name)
output_file = output_file or CACHE_DIR / template_name output_file = output_file or os.path.join(CACHE_DIR, template_name)
if template_file.is_file(): if os.path.isfile(template_file):
template(all_colors, template_file, output_file) template(all_colors, template_file, output_file)
print("export: Exported %s." % export_type) print("export: Exported %s." % export_type)
else: else:

View File

@ -2,7 +2,6 @@
Get the image file. Get the image file.
""" """
import os import os
import pathlib
import random import random
import sys import sys
@ -24,25 +23,23 @@ def get_random_image(img_dir):
print("image: No new images found (nothing to do), exiting...") print("image: No new images found (nothing to do), exiting...")
sys.exit(1) sys.exit(1)
return str(img_dir / random.choice(images).name) return os.path.join(img_dir, random.choice(images).name)
def get(img, cache_dir=CACHE_DIR): def get(img, cache_dir=CACHE_DIR):
"""Validate image input.""" """Validate image input."""
image = pathlib.Path(img) if os.path.isfile(img):
wal_img = img
if image.is_file(): elif os.path.isdir(img):
wal_img = str(image) wal_img = get_random_image(img)
elif image.is_dir():
wal_img = get_random_image(image)
else: else:
print("error: No valid image file found.") print("error: No valid image file found.")
sys.exit(1) sys.exit(1)
# Cache the image file path. # Cache the image file path.
util.save_file(wal_img, cache_dir / "wal") util.save_file(wal_img, os.path.join(cache_dir, "wal"))
print("image: Using image", wal_img) print("image: Using image", wal_img)
return wal_img return wal_img

View File

@ -1,6 +1,7 @@
""" """
Reload programs. Reload programs.
""" """
import os
import re import re
import shutil import shutil
import subprocess import subprocess
@ -12,28 +13,28 @@ from . import util
def xrdb(xrdb_file=None): def xrdb(xrdb_file=None):
"""Merge the colors into the X db so new terminals use them.""" """Merge the colors into the X db so new terminals use them."""
xrdb_file = xrdb_file or CACHE_DIR / "colors.Xresources" xrdb_file = xrdb_file or os.path.join(CACHE_DIR, "colors.Xresources")
if shutil.which("xrdb"): if shutil.which("xrdb"):
subprocess.Popen(["xrdb", "-merge", str(xrdb_file)], subprocess.Popen(["xrdb", "-merge", xrdb_file],
stdout=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL).wait() stderr=subprocess.DEVNULL).wait()
def gtk(): def gtk():
"""Move gtkrc files to the correct location.""" """Move gtkrc files to the correct location."""
theme_path = HOME / ".themes" / "Flatabulous-wal" theme_path = os.path.join(HOME, ".themes", "Flatabulous-wal")
gtk2_file = CACHE_DIR / "colors-gtk2.rc" gtk2_file = os.path.join(CACHE_DIR, "colors-gtk2.rc")
if theme_path.is_dir(): if os.path.isdir(theme_path):
if gtk2_file.is_file(): shutil.copy(gtk2_file, os.path.join(theme_path, "gtk-2.0"))
shutil.copy(str(gtk2_file), str(theme_path / "gtk-2.0"))
# Here we call a Python 2 script to reload the GTK themes. # Here we call a Python 2 script to reload the GTK themes.
# This is done because the Python 3 GTK/Gdk libraries don't # This is done because the Python 3 GTK/Gdk libraries don't
# provide a way of doing this. # provide a way of doing this.
if shutil.which("python2"): if shutil.which("python2"):
util.disown(["python2", str(MODULE_DIR / "scripts" / "gtk_reload.py")]) gtk_reload = os.path.join(MODULE_DIR, "scripts", "gtk_reload.py")
util.disown(["python2", gtk_reload])
else: else:
print("warning: GTK2 reload support requires Python 2.") print("warning: GTK2 reload support requires Python 2.")
@ -62,7 +63,7 @@ def env(xrdb_file=None):
def colors(vte, cache_dir=CACHE_DIR): def colors(vte, cache_dir=CACHE_DIR):
"""Reload the current scheme.""" """Reload the current scheme."""
sequence_file = cache_dir / "sequences" sequence_file = os.path.join(cache_dir, "sequences")
if sequence_file.is_file(): if sequence_file.is_file():
sequences = "".join(util.read_file(sequence_file)) sequences = "".join(util.read_file(sequence_file))

View File

@ -2,6 +2,7 @@
Send sequences to all open terminals. Send sequences to all open terminals.
""" """
import glob import glob
import os
from .settings import CACHE_DIR, OS from .settings import CACHE_DIR, OS
from . import util from . import util
@ -81,5 +82,5 @@ def send(colors, vte, cache_dir=CACHE_DIR):
for term in glob.glob(tty_pattern): for term in glob.glob(tty_pattern):
util.save_file(sequences, term) util.save_file(sequences, term)
util.save_file(sequences, cache_dir / "sequences") util.save_file(sequences, os.path.join(cache_dir, "sequences"))
print("colors: Set terminal colors.") print("colors: Set terminal colors.")

View File

@ -9,15 +9,15 @@
Created by Dylan Araps. Created by Dylan Araps.
""" """
import pathlib import os
import platform import platform
__version__ = "0.5.12" __version__ = "0.5.12"
HOME = pathlib.Path.home() HOME = os.environ["HOME"]
CACHE_DIR = HOME / ".cache/wal/" CACHE_DIR = os.path.join(HOME, ".cache/wal/")
MODULE_DIR = pathlib.Path(__file__).parent MODULE_DIR = os.path.dirname(__file__)
COLOR_COUNT = 16 COLOR_COUNT = 16
OS = platform.uname()[0] OS = platform.uname()[0]

View File

@ -3,7 +3,6 @@ Misc helper functions.
""" """
import json import json
import os import os
import pathlib
import subprocess import subprocess
@ -78,7 +77,7 @@ def save_file_json(data, export_file):
def create_dir(directory): def create_dir(directory):
"""Alias to create the cache dir.""" """Alias to create the cache dir."""
pathlib.Path(directory).mkdir(parents=True, exist_ok=True) os.makedirs(directory, exist_ok=True)
def hex_to_rgb(color): def hex_to_rgb(color):

View File

@ -114,9 +114,9 @@ def change(img):
def get(cache_dir=CACHE_DIR): def get(cache_dir=CACHE_DIR):
"""Get the current wallpaper.""" """Get the current wallpaper."""
current_wall = cache_dir / "wal" current_wall = os.path.join(cache_dir, "wal")
if current_wall.is_file(): if os.path.isfile(current_wall):
return util.read_file(current_wall)[0] return util.read_file(current_wall)[0]
return "None" return "None"

View File

@ -2,7 +2,7 @@
import unittest import unittest
import unittest.mock import unittest.mock
import io import io
import pathlib import os
from pywal import export from pywal import export
from pywal import util from pywal import util
@ -11,7 +11,6 @@ from pywal import util
# Import colors. # Import colors.
COLORS = util.read_file_json("tests/test_files/test_file.json") COLORS = util.read_file_json("tests/test_files/test_file.json")
COLORS["colors"].update(COLORS["special"]) COLORS["colors"].update(COLORS["special"])
OUTPUT_DIR = pathlib.Path("/tmp/wal")
util.create_dir("/tmp/wal") util.create_dir("/tmp/wal")
@ -21,25 +20,27 @@ class TestExportColors(unittest.TestCase):
def test_all_templates(self): def test_all_templates(self):
"""> Test substitutions in template file.""" """> Test substitutions in template file."""
export.every(COLORS, OUTPUT_DIR) export.every(COLORS, "/tmp/wal")
result = pathlib.Path("/tmp/wal/colors.sh").is_file() result = os.path.isfile("/tmp/wal/colors.sh")
self.assertTrue(result) self.assertTrue(result)
content = pathlib.Path("/tmp/wal/colors.sh").read_text() with open("/tmp/wal/colors.sh") as file:
content = content.split("\n")[6] content = file.read().splitlines()
self.assertEqual(content, "foreground='#F5F1F4'")
self.assertEqual(content[6], "foreground='#F5F1F4'")
def test_css_template(self): def test_css_template(self):
"""> Test substitutions in template file (css).""" """> Test substitutions in template file (css)."""
export.color(COLORS, "css", OUTPUT_DIR / "test.css") export.color(COLORS, "css", "/tmp/wal/test.css")
result = pathlib.Path("/tmp/wal/test.css").is_file() result = os.path.isfile("/tmp/wal/test.css")
self.assertTrue(result) self.assertTrue(result)
content = pathlib.Path("/tmp/wal/test.css").read_text() with open("/tmp/wal/test.css") as file:
content = content.split("\n")[6] content = file.read().splitlines()
self.assertEqual(content, " --background: #1F211E;")
self.assertEqual(content[6], " --background: #1F211E;")
def test_invalid_template(self): def test_invalid_template(self):
"""> Test template validation.""" """> Test template validation."""
@ -48,7 +49,7 @@ class TestExportColors(unittest.TestCase):
# Since this function prints a message on fail we redirect # Since this function prints a message on fail we redirect
# it's output so that we can read it. # it's output so that we can read it.
with unittest.mock.patch('sys.stdout', new=io.StringIO()) as fake_out: with unittest.mock.patch('sys.stdout', new=io.StringIO()) as fake_out:
export.color(COLORS, "dummy", OUTPUT_DIR / "test.css") export.color(COLORS, "dummy", "/tmp/wal/test.css")
self.assertEqual(fake_out.getvalue().strip(), error_msg) self.assertEqual(fake_out.getvalue().strip(), error_msg)

View File

@ -16,7 +16,8 @@ class TestMain(unittest.TestCase):
"""> Test arg parsing (-c)""" """> Test arg parsing (-c)"""
args = __main__.get_args(["-c"]) args = __main__.get_args(["-c"])
__main__.process_args(args) __main__.process_args(args)
self.assertFalse(os.path.isdir(str(CACHE_DIR / "schemes"))) scheme_dir = os.path.join(CACHE_DIR, "schemes")
self.assertFalse(os.path.isdir(scheme_dir))
def test_args_e(self): def test_args_e(self):
"""> Test arg parsing (-e)""" """> Test arg parsing (-e)"""