general: Added logging.

This commit is contained in:
Dylan Araps 2018-04-01 12:28:32 +10:00
parent d5f39135b2
commit cf6ac7944d
15 changed files with 64 additions and 40 deletions

View File

@ -10,6 +10,7 @@ Created by Dylan Araps.
""" """
import argparse import argparse
import logging
import os import os
import shutil import shutil
import sys import sys
@ -173,6 +174,7 @@ def process_args(args):
def main(): def main():
"""Main script function.""" """Main script function."""
util.setup_logging()
args = get_args(sys.argv[1:]) args = get_args(sys.argv[1:])
process_args(args) process_args(args)

View File

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

View File

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

View File

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

View File

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

View File

@ -1,6 +1,7 @@
""" """
Generate a colorscheme using imagemagick. Generate a colorscheme using imagemagick.
""" """
import logging
import re import re
import shutil import shutil
import subprocess import subprocess
@ -26,8 +27,8 @@ def has_im():
elif shutil.which("convert"): elif shutil.which("convert"):
return ["convert"] return ["convert"]
print("error: ImageMagick wasn't found on your system.", logging.error("Imagemagick wasn't found on your system.")
"Try another backend. (wal --backend)") logging.error("Try another backend. (wal --backend)")
sys.exit(1) sys.exit(1)
@ -43,13 +44,12 @@ def gen_colors(img):
break break
elif i == 19: elif i == 19:
print("colors: Imagemagick couldn't generate a suitable palette", logging.error("Imagemagick couldn't generate a suitable palette.")
"for the image. Exiting...")
sys.exit(1) sys.exit(1)
else: else:
print("colors: Imagemagick couldn't generate a suitable palette, " logging.warning("Imagemagick couldn't generate a palette.")
"trying a larger palette size", 16 + i) logging.warning("Trying a larger palette size %s", 16 + i)
return [re.search("#.{6}", str(col)).group(0) for col in raw_colors[1:]] 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. Generate a palette using various backends.
""" """
import logging
import os import os
import random import random
import re import re
@ -90,17 +91,17 @@ def get(img, light=False, backend="wal", cache_dir=CACHE_DIR):
if os.path.isfile(cache_file): if os.path.isfile(cache_file):
colors = theme.file(cache_file) colors = theme.file(cache_file)
util.Color.alpha_num = colors["alpha"] util.Color.alpha_num = colors["alpha"]
print("colors: Found cached colorscheme.") logging.info("Found cached colorscheme.")
else: else:
print("wal: Generating a colorscheme...") logging.info("Generating a colorscheme...")
if backend == "random": if backend == "random":
backends = list_backends() backends = list_backends()
random.shuffle(backends) random.shuffle(backends)
backend = backends[0] backend = backends[0]
print("wal: Using", backend, "backend.") logging.info("Using %s backend.", backend)
# Dynamically import the backend we want to use. # Dynamically import the backend we want to use.
# This keeps the dependencies "optional". # 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) colors = colors_to_dict(getattr(backend, "get")(img, light), img)
util.save_file_json(colors, cache_file) util.save_file_json(colors, cache_file)
print("wal: Generation complete.") logging.info("Generation complete.")
return colors return colors

View File

@ -1,6 +1,7 @@
""" """
Export colors in various formats. Export colors in various formats.
""" """
import logging
import os import os
from .settings import CACHE_DIR, MODULE_DIR, CONF_DIR 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': if file.name != '.DS_Store':
template(colors, file.path, join(output_dir, file.name)) template(colors, file.path, join(output_dir, file.name))
print("export: Exported all files.") logging.info("Exported all files.")
print("export: Exported all user files.") logging.info("Exported all user files.")
def color(colors, export_type, output_file=None): 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): 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) logging.info("Exported %s.", export_type)
else: 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. Get the image file.
""" """
import logging
import os import os
import random import random
import sys import sys
@ -24,7 +25,7 @@ def get_random_image(img_dir):
images.remove(current_wall) images.remove(current_wall)
elif not images: elif not images:
print("error: No images found in directory.") logging.error("No images found in directory.")
sys.exit(1) sys.exit(1)
random.shuffle(images) random.shuffle(images)
@ -41,7 +42,7 @@ def get(img, cache_dir=CACHE_DIR):
wal_img = get_random_image(img) wal_img = get_random_image(img)
else: else:
print("error: No valid image file found.") logging.error("No valid image file found.")
sys.exit(1) sys.exit(1)
wal_img = os.path.abspath(wal_img) wal_img = os.path.abspath(wal_img)
@ -49,5 +50,5 @@ def get(img, cache_dir=CACHE_DIR):
# Cache the image file path. # Cache the image file path.
util.save_file(wal_img, os.path.join(cache_dir, "wal")) 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 return wal_img

View File

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

View File

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

View File

@ -2,6 +2,7 @@
Send sequences to all open terminals. Send sequences to all open terminals.
""" """
import glob import glob
import logging
import os import os
from .settings import CACHE_DIR, 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, term)
util.save_file(sequences, os.path.join(cache_dir, "sequences")) 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. Theme file handling.
""" """
import logging
import os import os
import random import random
import sys import sys
@ -72,5 +73,5 @@ def file(input_file):
return parse_theme(theme_file) return parse_theme(theme_file)
else: else:
print("No colorscheme file found, exiting...") logging.error("No colorscheme file found, exiting...")
sys.exit(1) sys.exit(1)

View File

@ -3,6 +3,7 @@ Misc helper functions.
""" """
import colorsys import colorsys
import json import json
import logging
import os import os
import subprocess import subprocess
@ -75,7 +76,7 @@ def save_file(data, export_file):
with open(export_file, "w") as file: with open(export_file, "w") as file:
file.write(data) file.write(data)
except PermissionError: 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): def save_file_json(data, export_file):
@ -91,6 +92,17 @@ def create_dir(directory):
os.makedirs(directory, exist_ok=True) 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): def hex_to_rgb(color):
"""Convert a hex color to rgb.""" """Convert a hex color to rgb."""
return tuple(bytes.fromhex(color.strip("#"))) return tuple(bytes.fromhex(color.strip("#")))

View File

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