aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authoruser <user@node5.net>2024-01-24 17:33:33 +0100
committeruser <user@node5.net>2024-01-24 17:33:33 +0100
commit59ef46fb2d44a7c212a0846028a2bda78de5c146 (patch)
treef5a216bb65412e29a9b4cdbe0afb3bc802225f92
parent22eb37030133b1bee7e90756090e328d56399568 (diff)
replace custom command line arguments parsing with argparse, use exception message
-rwxr-xr-xblog_generator.py76
1 files changed, 31 insertions, 45 deletions
diff --git a/blog_generator.py b/blog_generator.py
index 4dceb45..b1ffb86 100755
--- a/blog_generator.py
+++ b/blog_generator.py
@@ -9,9 +9,9 @@ import datetime # Created, modified date
import jinja2 # HTML Templates
import shutil # Copy files and directories
import time # Sleep
-import sys # Command line arguments
import livereload # Generate on content source file change and reload browser
import datetime # Read article dates metadata
+import argparse # Command line arguments
logging.basicConfig()
logger = logging.getLogger('blog_generator')
@@ -20,9 +20,6 @@ logger.setLevel(level=logging.INFO)
class BlogGeneratorException(Exception):
pass
-class WrongCLIArgsPassedException(BlogGeneratorException):
- pass
-
class FoundMoreThanOneSourceFileException(BlogGeneratorException):
pass
@@ -66,11 +63,9 @@ def generate_article(jinja_env: jinja2.environment.Environment, paths: dict, art
article_dir_path = os.path.join(paths['articles'], article_name)
sources = glob.glob(os.path.join(article_dir_path, '*.md'))
if len(sources) > 1:
- logger.error(f'Found more than one source file for article: {article_name}')
- raise FoundMoreThanOneSourceFileException()
+ raise FoundMoreThanOneSourceFileException(f'Found more than one source file for article: {article_name}')
if len(sources) == 0:
- logger.error(f'No source file found for article: {article_name}')
- raise ArticleSourceFileNotFoundException()
+ raise ArticleSourceFileNotFoundException(f'No source file found for article: {article_name}')
article_source_path = sources[0]
article_source_file_name = os.path.basename(article_source_path)
@@ -183,51 +178,42 @@ def main():
source_content_root = None
paths = {}
+ parser = argparse.ArgumentParser(description='Static blog site generator')
+ parser.add_argument('--action', choices=['live_reload', 'generate'], default='live_reload', nargs='?',
+ help='serve the page to live preview changes, or just generate once')
+ parser.add_argument('--directory', default=".", nargs='?',
+ help='the directory containing the site source files, defaults to current working directory')
# Parse arguments
- try:
- if len(sys.argv) < 3:
- logger.error('Too few arguments passed')
- raise WrongCLIArgsPassedException()
- paths['source_content_root'] = sys.argv[1]
- if not os.path.exists(paths['source_content_root']):
- logger.error(f'Source directory not found: {paths["source_content_root"]}')
- raise SourceDirectoryNotFoundException()
+ args = parser.parse_args()
- if os.path.isdir(paths['source_content_root']):
- for directory in ['articles', 'templates', 'static']:
- path = os.path.join(paths['source_content_root'], directory)
- if not os.path.exists(path):
- logger.error(f'Source directory not found: {path}')
- raise SourceDirectoryNotFoundException()
- paths[directory] = path
- paths['output'] = os.path.join(paths['source_content_root'], 'output')
- if sys.argv[2] not in ['generate', 'live_reload']:
- logger.error('Action not found')
- raise WrongCLIArgsPassedException()
+ paths['source_content_root'] = args.directory
+ if not os.path.exists(paths['source_content_root']):
+ raise SourceDirectoryNotFoundException(f'Source directory not found: {paths["source_content_root"]}')
- # Setup jinja enviroment
- # Dict values globally accesible in templates e.g. root title
- # Get name of directory, in case it's relative
- jinja_global = {'title': os.path.basename(os.path.realpath(sys.argv[1]))}
- jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(paths['templates']))
- jinja_env.globals.update(jinja_global)
+ if os.path.isdir(paths['source_content_root']):
+ for directory in ['articles', 'templates', 'static']:
+ path = os.path.join(paths['source_content_root'], directory)
+ if not os.path.exists(path):
+ raise SourceDirectoryNotFoundException(f'Source directory not found: {path}')
+ paths[directory] = path
+ paths['output'] = os.path.join(paths['source_content_root'], 'output')
- match sys.argv[2]: # Switch statement
+ # Setup jinja enviroment
+ # Dict values globally accesible in templates e.g. root title
+ # Get name of directory, in case it's relative
+ jinja_global = {'title': os.path.basename(os.path.realpath(args.directory))}
+ jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(paths['templates']))
+ jinja_env.globals.update(jinja_global)
+
+ try:
+ match args.action: # Switch statement
case 'generate':
generate_all(jinja_env, paths)
case 'live_reload':
live_reload(jinja_env, paths)
- case _: # Default
- logger.error('No action specified')
- raise WrongCLIArgsPassedException()
-
- except WrongCLIArgsPassedException:
- # Wrong CLI args passed
- print("\nUsage: generate_blog [CONTENT ROOT] [ACTION]\n"
- " [CONTENT ROOT] being the root of your content e.g. default_page\n"
- " [ACTION] being either generate or live_reload")
- exit(2) # Exit code 2: Incorrect command (or argument) usage
- except BlogGeneratorException: # Other known custom error
+ # Known custom error, avoid stack trace, merely print the pretty exception message
+ except BlogGeneratorException as exception:
+ logger.error(exception)
exit(1) # Exit code 1: Code for generic errors
if __name__ == "__main__":