Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor #9

Merged
merged 5 commits into from
Jan 2, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ python:
- "3.3"
- "3.4"
- "3.5"
- "3.5-dev" # 3.5 development branch
- "nightly" # currently points to 3.6-dev
# command to run tests
- "3.6"
install:
- pip install coveralls
- pip install coverage
- pip install pylint
script:
- pylint cheat
- python -m unittest discover
- coverage run -m unittest discover
- coverage report -m
Expand Down
90 changes: 53 additions & 37 deletions cheat/cheat.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,31 @@
#!/usr/bin/env python3


import os
import utils as u
"""
Main script, where all parts come together.
containers Argument Parser for commandline arguments and main function.
"""


from argparse import ArgumentParser
from configparser import ConfigParser
from configparser import Error as ConfigParserError
from os import path
from printer import PrinterFactory
from sys import exit
from utils import print_available_sheets, Colors


def commandline():
"""
Configures the Argument Parser and returns the parsed commandline args.
"""

description = "Cool Command-line Cheatsheets"
help_general = "The cheatsheet you want to see"
help_list = "List all available Cheatsheets"
help_colors = "Print output without colors"
help_inline = "One cheat per line, this is default"
help_breakline = "Break lines"
description = 'Cool Command-line Cheatsheets'
help_general = 'The cheatsheet you want to see'
help_list = 'List all available cheatsheets'
help_colors = 'Print output without colors'
help_inline = 'One cheat per line, this is the default'
help_breakline = 'Break lines'

argumentparser = ArgumentParser(description=description)
printertype = argumentparser.add_mutually_exclusive_group()
Expand All @@ -29,49 +38,56 @@ def commandline():
printertype.add_argument('-l', help=help_inline, action='store_const', dest='printer', const='InlinePrinter')
printertype.add_argument('-b', help=help_breakline, action='store_const', dest='printer', const='BreaklinePrinter')

cmd_arguments = argumentparser.parse_args()
return argumentparser

if cmd_arguments.listcheats:
u.print_available_sheets(cheats_directory)
exit(0)

if cmd_arguments.cheatsheet is None:
argumentparser.print_help()
exit(2)
def main(argparser):
"""
Where the magic happens.

return cmd_arguments
:param argparser: Configures Argument Parser
"""

cmdargs = argparser.parse_args()
filedir = path.dirname(path.abspath(__file__ + '../../'))
cheatsheetdir = path.join(filedir, 'cheatsheets/')
extension = '.ini'
filename = cheatsheetdir + str(cmdargs.cheatsheet) + extension

def main(cmd_args):
# Lists the Cheatsheats
if cmdargs.listcheats:
print_available_sheets(cheatsheetdir)
exit(0)

extension = ".ini"
filename = cheats_directory + cmd_args.cheatsheet + extension
# Print help if nothing is provided
if cmdargs.cheatsheet is None:
argparser.print_help()
exit(2)

configparser = ConfigParser()
CheatPrinterConstructor = PrinterFactory.create_printer(cmd_args.printer)
colors = u.colors
printcolored = cmd_args.nocolor
# Check if file is available
if not path.isfile(filename):
print(filename + ' is not available.')
exit(2)

cheatprinter = CheatPrinterConstructor(configparser, colors, printcolored)
# Build the Printer
configparser = ConfigParser()
printer_constructor = PrinterFactory.create_printer(cmdargs.printer)
printcolored = cmdargs.nocolor
cheatprinter = printer_constructor(configparser, Colors, printcolored)

# Read the file and exit script
try:
configparser.read(filename)
cheatprinter.printsheet()
exitcode = 0
except Exception as e:
# I know lazy handling... Sorry.
# TOOD better exception handling.
print(filename + " not available or contains errors.")
print(e)
except ConfigParserError as exception:
print(filename + ' contains error.\n')
print(exception)
exitcode = 1
finally:
exit(exitcode)

if __name__ == '__main__':

if __name__ == "__main__":

cheats_filedir = os.path.dirname(os.path.realpath(__file__))
cheats_directory = os.path.join(cheats_filedir, "sheets/")

args = commandline()
main(args)
ARGPARSER = commandline()
main(ARGPARSER)
18 changes: 5 additions & 13 deletions cheat/cheat.py2
Original file line number Diff line number Diff line change
@@ -1,19 +1,11 @@
#!/usr/bin/env python2
"""
Notice: This is the Python 2 codebase, which I don't really work on much.

Ok this whole thing is pretty straight forward I guess.

To add a new output format:
# pylint: skip-file

Add the new command-line option to the printer group, like so:
help_MyNewPrinter = "The most awesome printer to exist in the observable universe"
printertype.add_argument('-x', help=help_MyNewPrinter, action='store_const', dest='printer', const='MyNewPrinter')

And then create a new Printer Subclass based on the name you just added. It should the implement the printCheatSheet method:
class MyNewPrinter(Printer):
[...]
"""
Notice: This is the Python 2 codebase, which I don't really work on much.
"""


from ConfigParser import ConfigParser
from argparse import ArgumentParser
Expand Down Expand Up @@ -64,7 +56,7 @@ class BreaklinePrinter(Printer):

def main():
# GENERAL SETTINGS!
directory = path[0] + "/sheets/"
directory = path[0] + "/../cheatsheets/"
extention = ".ini"
description = "Cool Command-line Cheatsheets"
help_general = "The cheatsheet you want to see"
Expand Down
44 changes: 33 additions & 11 deletions cheat/printer.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
#!/usr/bin/env/python3


"""
Printer Classes.
Handle the printing of the cheatsheet files.

The factory pattern creates a Printer Object from the commandline arguments.
Meaning that there's no need for an elaborate if-else condition.
"""


class Printer:
"""
Base class for the cheatsheet printers. Takes care of the actuall printing.
Expand All @@ -20,6 +30,8 @@ def __init__(self, configparser, colors, print_colored=True):
def add_color(self, string):
"""
Adds color to the console output.

:param string: The string to add color to.
"""

default_color = self.colors.DEFAULT
Expand All @@ -33,19 +45,23 @@ def add_color(self, string):

return colored

def printsheet(self, template):
def printcheats(self, template):
"""
Loops over the entries in the ConfigParser and prints them with a specific template.

:param template: Template to use with the format() function.
"""

for description in self.configparser['cheats']:
value = self.configparser['cheats'][description]
value = self.add_color(value) if self.print_colored else value
output = template.format(description, value)
sections = self.configparser.sections()
sections.remove('main')

print(output)
for section in sections:
print(section.upper())
for description in self.configparser[section]:
value = self.configparser[section][description]
value = self.add_color(value) if self.print_colored else value
output = template.format(description.capitalize(), value)
print(output)


class InlinePrinter(Printer):
Expand All @@ -59,7 +75,13 @@ def width(self):
Width of the longest ConfigParser entry.
"""

width = len(max(self.configparser['cheats'], key=len))
width = 1

# Calculate new width
for section in self.configparser.sections():
longest_width = len(max(self.configparser[section], key=len))
if longest_width > width:
width = longest_width

return str(width)

Expand All @@ -69,7 +91,7 @@ def printsheet(self):
"""

print_format = "{0:<" + self.width + "} {1}"
super().printsheet(print_format)
super().printcheats(print_format)


class BreaklinePrinter(Printer):
Expand All @@ -83,7 +105,7 @@ def printsheet(self):
"""

print_format = "{0} \n {1}"
super().printsheet(print_format)
super().printcheats(print_format)


class PrinterFactory:
Expand All @@ -92,8 +114,8 @@ class PrinterFactory:
"""

printer_classes = {
"InlinePrinter": InlinePrinter,
"BreaklinePrinter": BreaklinePrinter
'InlinePrinter': InlinePrinter,
'BreaklinePrinter': BreaklinePrinter
}

@staticmethod
Expand Down
33 changes: 23 additions & 10 deletions cheat/utils.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,39 @@
#!/usr/bin/env python3


import os
"""
Utility functions and classes for common tasks.
"""


from configparser import ConfigParser
from configparser import Error as ConfigParserError
from os import listdir, path


def print_available_sheets(directory):
"""
Prints all available cheatsheets in the sheet folder to the stdout.
:param directory: The directory where the cheatsheets are located

:param directory: The directory where the cheatsheets are located.
"""

cp = ConfigParser()
parser = ConfigParser()
files = listdir(directory)

for root, dirs, files in os.walk(directory):
for name in files:
if name.endswith('ini'):
cp.read(os.path.join(root, name))
output = " {0}".format(cp['main']['name'])
print(output)
for name in sorted(files):
try:
parser.read(path.join(directory, name))
print('{0}'.format(parser['main']['name']))
except ConfigParserError:
# TOOD: What to do here?
pass

class colors:

class Colors:
"""
Wrapper class for colored output
"""

DEFAULT = '\033[94m'
PARAM = '\033[93m'
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
8 changes: 8 additions & 0 deletions cheatsheets/example.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[main]
name=example
desc=An example for start your own
[common]
Simple Example = example foobar
Example with Parameter = example foo <PARAMETER>
[workflow]
Example in another section = example barfoo
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
3 changes: 3 additions & 0 deletions pylintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# pylint config
[MESSAGES CONTROL]
disable=too-few-public-methods, line-too-long, no-name-in-module, import-error
2 changes: 1 addition & 1 deletion tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def test_main_failure_no_cheatsheet(self):
command = '/usr/bin/env python3 cheat/cheat.py not_available > /dev/null 2>&1'
result = os.system(command)

self.assertEqual(result, self.exit_1)
self.assertEqual(result, self.exit_2)

def test_main_failure_no_argument(self):
"""
Expand Down
Loading