Conform code to pep8

This commit is contained in:
Tomas Korbar 2019-01-15 19:38:24 +01:00
parent a2e028fd19
commit 4d19505b79
5 changed files with 63 additions and 73 deletions

View File

@ -46,7 +46,6 @@ import os
if __name__ == '__main__':
# parse the command-line options
options = docopt(__doc__, version='cheat 2.3.1')

View File

@ -5,26 +5,32 @@ import json
class Configuration:
def __init__(self):
self._get_global_conf_file_path()
self._get_local_conf_file_path()
self._saved_configuration = self._get_configuration()
def _get_configuration(self):
# get options from config files and environment vairables
merged_config = {}
try:
merged_config.update(self._read_configuration_file(self.glob_config_path))
merged_config.update(
self._read_configuration_file(self.glob_config_path)
)
except Exception as e:
Utils.warn('error while parsing global configuration Reason: ' + e.message)
Utils.warn('error while parsing global configuration Reason: '
+ e.message
)
try:
merged_config.update(self._read_configuration_file(self.local_config_path))
merged_config.update(
self._read_configuration_file(self.local_config_path)
)
except Exception as e:
Utils.warn('error while parsing user configuration Reason: ' + e.message)
Utils.warn('error while parsing user configuration Reason: '
+ e.message
)
merged_config.update(self._read_env_vars_config())
@ -32,8 +38,7 @@ class Configuration:
return merged_config
def _read_configuration_file(self,path):
def _read_configuration_file(self, path):
# Reads configuration file and returns list of set variables
read_config = {}
if (os.path.isfile(path)):
@ -41,7 +46,6 @@ class Configuration:
read_config.update(json.load(config_file))
return read_config
def _read_env_vars_config(self):
read_config = {}
@ -58,10 +62,10 @@ class Configuration:
'CHEATCOLORS',
'EDITOR',
'CHEAT_HIGHLIGHT'
]
]
for k in keys:
self._read_env_var(read_config,k)
self._read_env_var(read_config, k)
return read_config
@ -70,42 +74,37 @@ class Configuration:
# validate CHEAT_HIGHLIGHT values if set
colors = [
'grey' , 'red' , 'green' , 'yellow' ,
'blue' , 'magenta' , 'cyan' , 'white' ,
'grey', 'red', 'green', 'yellow',
'blue', 'magenta', 'cyan', 'white'
]
if (
config.get('CHEAT_HIGHLIGHT') and
config.get('CHEAT_HIGHLIGHT') not in colors
):
Utils.die("%s %s" %('CHEAT_HIGHLIGHT must be one of:', colors))
Utils.die("%s %s" % ('CHEAT_HIGHLIGHT must be one of:', colors))
def _read_env_var(self,current_config,key):
def _read_env_var(self, current_config, key):
if (os.environ.get(key)):
current_config[key] = os.environ.get(key)
def _get_global_conf_file_path(self):
self.glob_config_path = os.environ.get('CHEAT_GLOBAL_CONF_PATH') \
or '/etc/cheat'
self.glob_config_path = (os.environ.get('CHEAT_GLOBAL_CONF_PATH')
or '/etc/cheat')
def _get_local_conf_file_path(self):
self.local_config_path = os.environ.get('CHEAT_LOCAL_CONF_PATH') \
or os.path.expanduser('~/.config/cheat/cheat')
path = (os.environ.get('CHEAT_LOCAL_CONF_PATH')
or os.path.expanduser('~/.config/cheat/cheat'))
self.local_config_path = path
def get_default_cheat_dir(self):
return self._saved_configuration.get('DEFAULT_CHEAT_DIR')
def get_cheatpath(self):
return self._saved_configuration.get('CHEATPATH')
def get_cheatcolors(self):
return self._saved_configuration.get('CHEATCOLORS')
def get_editor(self):
return self._saved_configuration.get('EDITOR')

View File

@ -6,26 +6,23 @@ from cheat.utils import Utils
class Sheet:
def __init__(self, sheets, utils):
self._sheets = sheets
self._utils = utils
def copy(self,current_sheet_path, new_sheet_path):
def copy(self, current_sheet_path, new_sheet_path):
""" Copies a sheet to a new path """
# attempt to copy the sheet to DEFAULT_CHEAT_DIR
try:
shutil.copy(current_sheet_path, new_sheet_path)
# fail gracefully if the cheatsheet cannot be copied. This can happen if
# DEFAULT_CHEAT_DIR does not exist
# fail gracefully if the cheatsheet cannot be copied. This can happen
# if DEFAULT_CHEAT_DIR does not exist
except IOError:
Utils.die('Could not copy cheatsheet for editing.')
def create_or_edit(self,sheet):
def create_or_edit(self, sheet):
""" Creates or edits a cheatsheet """
# if the cheatsheet does not exist
@ -35,47 +32,44 @@ class Sheet:
# if the cheatsheet exists but not in the default_path, copy it to the
# default path before editing
elif self.exists(sheet) and not self.exists_in_default_path(sheet):
self.copy(self.path(sheet), os.path.join(self._sheets.default_path(), sheet))
self.copy(self.path(sheet),
os.path.join(self._sheets.default_path(), sheet))
self.edit(sheet)
# if it exists and is in the default path, then just open it
else:
self.edit(sheet)
def create(self,sheet):
def create(self, sheet):
""" Creates a cheatsheet """
new_sheet_path = os.path.join(self._sheets.default_path(), sheet)
self._utils.open_with_editor(new_sheet_path)
def edit(self,sheet):
def edit(self, sheet):
""" Opens a cheatsheet for editing """
self._utils.open_with_editor(self.path(sheet))
def exists(self,sheet):
def exists(self, sheet):
""" Predicate that returns true if the sheet exists """
return sheet in self._sheets.get() and os.access(self.path(sheet), os.R_OK)
return (sheet in self._sheets.get() and
os.access(self.path(sheet), os.R_OK))
def exists_in_default_path(self,sheet):
def exists_in_default_path(self, sheet):
""" Predicate that returns true if the sheet exists in default_path"""
default_path_sheet = os.path.join(self._sheets.default_path(), sheet)
return sheet in self._sheets.get() and os.access(default_path_sheet, os.R_OK)
return (sheet in self._sheets.get() and
os.access(default_path_sheet, os.R_OK))
def is_writable(self,sheet):
def is_writable(self, sheet):
""" Predicate that returns true if the sheet is writeable """
return sheet in self._sheets.get() and os.access(self.path(sheet), os.W_OK)
return (sheet in self._sheets.get() and
os.access(self.path(sheet), os.W_OK))
def path(self,sheet):
def path(self, sheet):
""" Returns a sheet's filesystem path """
return self._sheets.get()[sheet]
def read(self,sheet):
def read(self, sheet):
""" Returns the contents of the cheatsheet as a String """
if not self.exists(sheet):
Utils.die('No cheatsheet found for ' + sheet)

View File

@ -2,8 +2,8 @@ import os
from cheat.utils import Utils
class Sheets:
class Sheets:
def __init__(self, config):
self._default_cheat_dir = config.get_default_cheat_dir()
@ -14,8 +14,10 @@ class Sheets:
""" Returns the default cheatsheet path """
# determine the default cheatsheet dir
default_sheets_dir = self._default_cheat_dir or os.path.join('~', '.cheat')
default_sheets_dir = os.path.expanduser(os.path.expandvars(default_sheets_dir))
default_sheets_dir = (self._default_cheat_dir or
os.path.join('~', '.cheat'))
default_sheets_dir = os.path.expanduser(
os.path.expandvars(default_sheets_dir))
# create the DEFAULT_CHEAT_DIR if it does not exist
if not os.path.isdir(default_sheets_dir):
@ -29,14 +31,17 @@ class Sheets:
# assert that the DEFAULT_CHEAT_DIR is readable and writable
if not os.access(default_sheets_dir, os.R_OK):
Utils.die('The DEFAULT_CHEAT_DIR (' + default_sheets_dir +') is not readable.')
Utils.die('The DEFAULT_CHEAT_DIR ('
+ default_sheets_dir
+ ') is not readable.')
if not os.access(default_sheets_dir, os.W_OK):
Utils.die('The DEFAULT_CHEAT_DIR (' + default_sheets_dir +') is not writable.')
Utils.die('The DEFAULT_CHEAT_DIR ('
+ default_sheets_dir
+ ') is not writable.')
# return the default dir
return default_sheets_dir
def get(self):
""" Assembles a dictionary of cheatsheets as name => file-path """
cheats = {}
@ -54,7 +59,6 @@ class Sheets:
return cheats
def paths(self):
""" Assembles a list of directories containing cheatsheets """
sheet_paths = [
@ -69,11 +73,11 @@ class Sheets:
sheet_paths.append(path)
if not sheet_paths:
Utils.die('The DEFAULT_CHEAT_DIR dir does not exist or the CHEATPATH is not set.')
Utils.die('The DEFAULT_CHEAT_DIR dir does not exist '
+ 'or the CHEATPATH is not set.')
return sheet_paths
def list(self):
""" Lists the available cheatsheets """
sheet_list = ''
@ -82,8 +86,7 @@ class Sheets:
sheet_list += sheet[0].ljust(pad_length) + sheet[1] + "\n"
return sheet_list
def search(self,term):
def search(self, term):
""" Searches all cheatsheets for the specified term """
result = ''

View File

@ -3,10 +3,10 @@ import os
import subprocess
import sys
class Utils:
def __init__(self,config):
def __init__(self, config):
self._displaycolors = config.get_cheatcolors()
self._editor_executable = config.get_editor()
self._highlight_color = config.get_highlight()
@ -29,8 +29,7 @@ class Utils:
# if the import succeeds, colorize the needle in haystack
return haystack.replace(needle, colored(needle, self._highlight_color))
def colorize(self,sheet_content):
def colorize(self, sheet_content):
""" Colorizes cheatsheet content if so configured """
# only colorize if configured to do so, and if stdout is a tty
@ -53,7 +52,7 @@ class Utils:
# otherwise, attempt to colorize
first_line = sheet_content.splitlines()[0]
lexer = get_lexer_by_name('bash')
lexer = get_lexer_by_name('bash')
# apply syntax-highlighting if the first line is a code-fence
if first_line.startswith('```'):
@ -65,14 +64,12 @@ class Utils:
return highlight(sheet_content, lexer, TerminalFormatter())
@staticmethod
def die(message):
""" Prints a message to stderr and then terminates """
Utils.warn(message)
exit(1)
def editor(self):
""" Determines the user's preferred editor """
@ -85,16 +82,14 @@ class Utils:
return self._editor_executable
def open_with_editor(self,filepath):
""" Open `filepath` using the EDITOR specified by the environment variables """
def open_with_editor(self, filepath):
""" Open `filepath` using the EDITOR specified by the env variables """
editor_cmd = self.editor().split()
try:
subprocess.call(editor_cmd + [filepath])
except OSError:
Utils.die('Could not launch ' + self.editor())
@staticmethod
def warn(message):
""" Prints a message to stderr """