Merge pull request #216 from dylanaraps/logging

general: Added logging.
This commit is contained in:
Dylan Araps 2018-04-01 13:11:07 +10:00 committed by GitHub
commit 50de3cf270
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
16 changed files with 63 additions and 56 deletions

View File

@ -173,6 +173,7 @@ def process_args(args):
def main():
"""Main script function."""
util.setup_logging()
args = get_args(sys.argv[1:])
process_args(args)

View File

@ -1,14 +1,15 @@
"""
Generate a colorscheme using ColorThief.
"""
import logging
import sys
try:
from colorthief import ColorThief
except ImportError:
print("error: ColorThief wasn't found on your system.",
"Try another backend. (wal --backend)")
logging.error("ColorThief wasn't found on your system.")
logging.error("Try another backend. (wal --backend)")
sys.exit(1)
from .. import util
@ -25,13 +26,12 @@ def gen_colors(img):
break
elif i == 19:
print("colors: ColorThief couldn't generate a suitable palette",
"for the image. Exiting...")
logging.error("ColorThief couldn't generate a suitable palette.")
sys.exit(1)
else:
print("colors: ColorThief couldn't create a suitable palette, "
"trying a larger palette size", 8 + i)
logging.warning("ColorThief couldn't generate a palette.")
logging.warning("Trying a larger palette size %s", 8 + i)
return [util.rgb_to_hex(color) for color in raw_colors]

View File

@ -1,6 +1,7 @@
"""
Generate a colorscheme using Colorz.
"""
import logging
import shutil
import subprocess
import sys
@ -28,8 +29,8 @@ def adjust(cols, light):
def get(img, light=False):
"""Get colorscheme."""
if not shutil.which("colorz"):
print("error: Colorz wasn't found on your system.",
"Try another backend. (wal --backend)")
logging.error("Colorz wasn't found on your system.")
logging.error("Try another backend. (wal --backend)")
sys.exit(1)
cols = [col.decode('UTF-8').split()[0] for col in gen_colors(img)]

View File

@ -1,14 +1,15 @@
"""
Generate a colorscheme using Haishoku.
"""
import logging
import sys
try:
from haishoku.haishoku import Haishoku
except ImportError:
print("error: Haishoku wasn't found on your system.",
"Try another backend. (wal --backend)")
logging.error("Haishoku wasn't found on your system.")
logging.error("Try another backend. (wal --backend)")
sys.exit(1)
from .. import colors

View File

@ -1,6 +1,7 @@
"""
Generate a colorscheme using Schemer2.
"""
import logging
import shutil
import subprocess
import sys
@ -26,8 +27,8 @@ def adjust(cols, light):
def get(img, light=False):
"""Get colorscheme."""
if not shutil.which("schemer2"):
print("error: Schemer2 wasn't found on your system.",
"Try another backend. (wal --backend)")
logging.error("Schemer2 wasn't found on your system.")
logging.error("Try another backend. (wal --backend)")
sys.exit(1)
cols = [col.decode('UTF-8') for col in gen_colors(img)]

View File

@ -1,6 +1,7 @@
"""
Generate a colorscheme using imagemagick.
"""
import logging
import re
import shutil
import subprocess
@ -26,8 +27,8 @@ def has_im():
elif shutil.which("convert"):
return ["convert"]
print("error: ImageMagick wasn't found on your system.",
"Try another backend. (wal --backend)")
logging.error("Imagemagick wasn't found on your system.")
logging.error("Try another backend. (wal --backend)")
sys.exit(1)
@ -43,13 +44,12 @@ def gen_colors(img):
break
elif i == 19:
print("colors: Imagemagick couldn't generate a suitable palette",
"for the image. Exiting...")
logging.error("Imagemagick couldn't generate a suitable palette.")
sys.exit(1)
else:
print("colors: Imagemagick couldn't generate a suitable palette, "
"trying a larger palette size", 16 + i)
logging.warning("Imagemagick couldn't generate a palette.")
logging.warning("Trying a larger palette size %s", 16 + i)
return [re.search("#.{6}", str(col)).group(0) for col in raw_colors[1:]]

View File

@ -1,6 +1,7 @@
"""
Generate a palette using various backends.
"""
import logging
import os
import random
import re
@ -90,17 +91,17 @@ def get(img, light=False, backend="wal", cache_dir=CACHE_DIR):
if os.path.isfile(cache_file):
colors = theme.file(cache_file)
util.Color.alpha_num = colors["alpha"]
print("colors: Found cached colorscheme.")
logging.info("Found cached colorscheme.")
else:
print("wal: Generating a colorscheme...")
logging.info("Generating a colorscheme...")
if backend == "random":
backends = list_backends()
random.shuffle(backends)
backend = backends[0]
print("wal: Using", backend, "backend.")
logging.info("Using %s backend.", backend)
# Dynamically import the backend we want to use.
# This keeps the dependencies "optional".
@ -113,7 +114,7 @@ def get(img, light=False, backend="wal", cache_dir=CACHE_DIR):
colors = colors_to_dict(getattr(backend, "get")(img, light), img)
util.save_file_json(colors, cache_file)
print("wal: Generation complete.")
logging.info("Generation complete.")
return colors

View File

@ -1,6 +1,7 @@
"""
Export colors in various formats.
"""
import logging
import os
from .settings import CACHE_DIR, MODULE_DIR, CONF_DIR
@ -65,8 +66,8 @@ def every(colors, output_dir=CACHE_DIR):
if file.name != '.DS_Store':
template(colors, file.path, join(output_dir, file.name))
print("export: Exported all files.")
print("export: Exported all user files.")
logging.info("Exported all files.")
logging.info("Exported all user files.")
def color(colors, export_type, output_file=None):
@ -79,6 +80,6 @@ def color(colors, export_type, output_file=None):
if os.path.isfile(template_file):
template(all_colors, template_file, output_file)
print("export: Exported %s." % export_type)
logging.info("Exported %s.", export_type)
else:
print("warning: template '%s' doesn't exist." % export_type)
logging.warning("Template '%s' doesn't exist.", export_type)

View File

@ -1,6 +1,7 @@
"""
Get the image file.
"""
import logging
import os
import random
import sys
@ -24,7 +25,7 @@ def get_random_image(img_dir):
images.remove(current_wall)
elif not images:
print("error: No images found in directory.")
logging.error("No images found in directory.")
sys.exit(1)
random.shuffle(images)
@ -41,7 +42,7 @@ def get(img, cache_dir=CACHE_DIR):
wal_img = get_random_image(img)
else:
print("error: No valid image file found.")
logging.error("No valid image file found.")
sys.exit(1)
wal_img = os.path.abspath(wal_img)
@ -49,5 +50,5 @@ def get(img, cache_dir=CACHE_DIR):
# Cache the image file path.
util.save_file(wal_img, os.path.join(cache_dir, "wal"))
print("image: Using image", wal_img)
logging.info("Using image %s.", wal_img)
return wal_img

View File

@ -1,6 +1,7 @@
"""
Reload programs.
"""
import logging
import os
import shutil
import subprocess
@ -32,17 +33,17 @@ def oomox(gen_theme):
"""Call oomox to generate a theme."""
if gen_theme:
if not shutil.which("oomox-cli"):
print("gtk: oomox not found, skipping...")
logging.warning("Oomox not found, skipping...")
return
oomox_file = os.path.join(CACHE_DIR, "colors-oomox")
print("reload: Waiting for oomox...")
logging.info("Waiting for oomox...")
subprocess.run(["oomox-cli", "-o", "wal", oomox_file],
stdout=subprocess.DEVNULL)
else:
print("gtk: Use -g to generate an oomox theme.")
logging.info("Use -g to generate an oomox theme.")
def gtk():
@ -55,7 +56,7 @@ def gtk():
util.disown(["python2", gtk_reload])
else:
print("warning: GTK2 reload support requires Python 2.")
logging.warning("GTK2 reload support requires Python 2.")
def i3():
@ -93,5 +94,5 @@ def env(xrdb_file=None, tty_reload=True):
i3()
sway()
polybar()
print("reload: Reloaded environment.")
logging.info("Reloaded environment.")
tty(tty_reload)

View File

@ -10,7 +10,7 @@ Original source: https://crunchbang.org/forums/viewtopic.php?id=39646
try:
import gtk
except ImportError:
print("error: GTK reload requires PyGTK.")
print("[ERROR] gtk_reload: GTK reload requires PyGTK.")
exit(1)

View File

@ -2,6 +2,7 @@
Send sequences to all open terminals.
"""
import glob
import logging
import os
from .settings import CACHE_DIR, OS
@ -89,4 +90,4 @@ def send(colors, cache_dir=CACHE_DIR, to_send=True):
util.save_file(sequences, term)
util.save_file(sequences, os.path.join(cache_dir, "sequences"))
print("colors: Set terminal colors.")
logging.info("Set terminal colors.")

View File

@ -1,6 +1,7 @@
"""
Theme file handling.
"""
import logging
import os
import random
import sys
@ -72,5 +73,5 @@ def file(input_file):
return parse_theme(theme_file)
else:
print("No colorscheme file found, exiting...")
logging.error("No colorscheme file found, exiting...")
sys.exit(1)

View File

@ -3,6 +3,7 @@ Misc helper functions.
"""
import colorsys
import json
import logging
import os
import subprocess
@ -75,7 +76,7 @@ def save_file(data, export_file):
with open(export_file, "w") as file:
file.write(data)
except PermissionError:
print("warning: Couldn't write to %s." % export_file)
logging.warning("Couldn't write to %s.", export_file)
def save_file_json(data, export_file):
@ -91,6 +92,17 @@ def create_dir(directory):
os.makedirs(directory, exist_ok=True)
def setup_logging():
"""Logging config."""
logging.basicConfig(format=("[%(levelname)s\033[0m] "
"\033[1;31m%(module)s\033[0m: "
"%(message)s"),
level=logging.INFO)
logging.addLevelName(logging.ERROR, '\033[1;31mE')
logging.addLevelName(logging.INFO, '\033[1;32mI')
logging.addLevelName(logging.WARNING, '\033[1;33mW')
def hex_to_rgb(color):
"""Convert a hex color to rgb."""
return tuple(bytes.fromhex(color.strip("#")))

View File

@ -1,5 +1,6 @@
"""Set the wallpaper."""
import ctypes
import logging
import os
import shutil
import subprocess
@ -61,7 +62,7 @@ def set_wm_wallpaper(img):
util.disown(["display", "-backdrop", "-window", "root", img])
else:
print("error: No wallpaper setter found.")
logging.error("No wallpaper setter found.")
return
@ -135,7 +136,7 @@ def change(img):
else:
set_desktop_wallpaper(desktop, img)
print("wallpaper: Set the new wallpaper.")
logging.info("Set the new wallpaper.")
def get(cache_dir=CACHE_DIR):

View File

@ -1,7 +1,6 @@
"""Test export functions."""
import unittest
import unittest.mock
import io
import shutil
import os
@ -53,20 +52,5 @@ class TestExportColors(unittest.TestCase):
self.is_file_contents(tmp_file, " --background: #1F211E;")
class TestInvalidExport(unittest.TestCase):
"""Test export function error handling."""
def test_invalid_template(self):
"""> Test template validation."""
error_msg = "warning: template 'dummy' doesn't exist."
tmp_file = os.path.join(TMP_DIR, "test.css")
# Since this function prints a message on fail we redirect
# it's output so that we can read it.
with unittest.mock.patch('sys.stdout', new=io.StringIO()) as fake_out:
export.color(COLORS, "dummy", tmp_file)
self.assertEqual(fake_out.getvalue().strip(), error_msg)
if __name__ == "__main__":
unittest.main()