From 87d619cc1c057e39c1a534840f4889a8eb0aa6c9 Mon Sep 17 00:00:00 2001 From: Bastian Venthur Date: Thu, 1 Sep 2022 12:41:25 +0200 Subject: [PATCH] Re-formatted the code --- blag/__init__.py | 2 +- blag/blag.py | 99 +++++++++++++++++++++++------------------ blag/devserver.py | 6 ++- blag/markdown.py | 20 +++++---- blag/quickstart.py | 8 ++-- tests/conftest.py | 12 +++-- tests/test_blag.py | 52 +++++++++++----------- tests/test_devserver.py | 20 ++++++--- tests/test_markdown.py | 83 +++++++++++++++++++--------------- 9 files changed, 167 insertions(+), 135 deletions(-) diff --git a/blag/__init__.py b/blag/__init__.py index 318e4f3..189ce64 100644 --- a/blag/__init__.py +++ b/blag/__init__.py @@ -1 +1 @@ -from blag.version import __VERSION__ as __VERSION__ # noqa +from blag.version import __VERSION__ as __VERSION__ # noqa diff --git a/blag/blag.py b/blag/blag.py index 60fdb33..490348b 100644 --- a/blag/blag.py +++ b/blag/blag.py @@ -30,8 +30,8 @@ from blag.quickstart import quickstart logger = logging.getLogger(__name__) logging.basicConfig( - level=logging.INFO, - format='%(asctime)s %(levelname)s %(name)s %(message)s', + level=logging.INFO, + format='%(asctime)s %(levelname)s %(name)s %(message)s', ) @@ -72,10 +72,11 @@ def parse_args(args: list[str] | None = None) -> argparse.Namespace: parser.add_argument( '--version', action='version', - version='%(prog)s '+__VERSION__, + version='%(prog)s ' + __VERSION__, ) parser.add_argument( - '-v', '--verbose', + '-v', + '--verbose', action='store_true', help='Verbose output.', ) @@ -84,61 +85,69 @@ def parse_args(args: list[str] | None = None) -> argparse.Namespace: commands.required = True build_parser = commands.add_parser( - 'build', - help='Build website.', + 'build', + help='Build website.', ) build_parser.set_defaults(func=build) build_parser.add_argument( - '-i', '--input-dir', - default='content', - help='Input directory (default: content)', + '-i', + '--input-dir', + default='content', + help='Input directory (default: content)', ) build_parser.add_argument( - '-o', '--output-dir', - default='build', - help='Ouptut directory (default: build)', + '-o', + '--output-dir', + default='build', + help='Ouptut directory (default: build)', ) build_parser.add_argument( - '-t', '--template-dir', - default='templates', - help='Template directory (default: templates)', + '-t', + '--template-dir', + default='templates', + help='Template directory (default: templates)', ) build_parser.add_argument( - '-s', '--static-dir', - default='static', - help='Static directory (default: static)', + '-s', + '--static-dir', + default='static', + help='Static directory (default: static)', ) quickstart_parser = commands.add_parser( - 'quickstart', - help="Quickstart blag, creating necessary configuration.", + 'quickstart', + help="Quickstart blag, creating necessary configuration.", ) quickstart_parser.set_defaults(func=quickstart) serve_parser = commands.add_parser( - 'serve', - help="Start development server.", + 'serve', + help="Start development server.", ) serve_parser.set_defaults(func=serve) serve_parser.add_argument( - '-i', '--input-dir', - default='content', - help='Input directory (default: content)', + '-i', + '--input-dir', + default='content', + help='Input directory (default: content)', ) serve_parser.add_argument( - '-o', '--output-dir', - default='build', - help='Ouptut directory (default: build)', + '-o', + '--output-dir', + default='build', + help='Ouptut directory (default: build)', ) serve_parser.add_argument( - '-t', '--template-dir', - default='templates', - help='Template directory (default: templates)', + '-t', + '--template-dir', + default='templates', + help='Template directory (default: templates)', ) serve_parser.add_argument( - '-s', '--static-dir', - default='static', - help='Static directory (default: static)', + '-s', + '--static-dir', + default='static', + help='Static directory (default: static)', ) return parser.parse_args(args) @@ -224,8 +233,9 @@ def build(args: argparse.Namespace) -> None: convertibles = [] for root, dirnames, filenames in os.walk(args.input_dir): for filename in filenames: - rel_src = os.path.relpath(f'{root}/{filename}', - start=args.input_dir) + rel_src = os.path.relpath( + f'{root}/{filename}', start=args.input_dir + ) # all non-markdown files are just copied over, the markdown # files are converted to html if rel_src.endswith('.md'): @@ -233,8 +243,10 @@ def build(args: argparse.Namespace) -> None: rel_dst = rel_dst[:-3] + '.html' convertibles.append((rel_src, rel_dst)) else: - shutil.copy(f'{args.input_dir}/{rel_src}', - f'{args.output_dir}/{rel_src}') + shutil.copy( + f'{args.input_dir}/{rel_src}', + f'{args.output_dir}/{rel_src}', + ) for dirname in dirnames: # all directories are copied into the output directory path = os.path.relpath(f'{root}/{dirname}', start=args.input_dir) @@ -264,7 +276,8 @@ def build(args: argparse.Namespace) -> None: ) generate_feed( - articles, args.output_dir, + articles, + args.output_dir, base_url=config['base_url'], blog_title=config['title'], blog_description=config['description'], @@ -364,10 +377,10 @@ def generate_feed( """ logger.info('Generating Atom feed.') feed = feedgenerator.Atom1Feed( - link=base_url, - title=blog_title, - description=blog_description, - feed_url=base_url + 'atom.xml', + link=base_url, + title=blog_title, + description=blog_description, + feed_url=base_url + 'atom.xml', ) for dst, context in articles: diff --git a/blag/devserver.py b/blag/devserver.py index 42feac0..a57ad71 100644 --- a/blag/devserver.py +++ b/blag/devserver.py @@ -91,8 +91,10 @@ def serve(args: argparse.Namespace) -> None: contains the input-, template- and static dir """ - httpd = HTTPServer(('', 8000), partial(SimpleHTTPRequestHandler, - directory=args.output_dir)) + httpd = HTTPServer( + ('', 8000), + partial(SimpleHTTPRequestHandler, directory=args.output_dir), + ) proc = multiprocessing.Process(target=autoreload, args=(args,)) proc.start() logger.info("\n\n Devserver Started -- visit http://localhost:8000\n") diff --git a/blag/markdown.py b/blag/markdown.py index fa6d908..6b055ed 100644 --- a/blag/markdown.py +++ b/blag/markdown.py @@ -33,8 +33,11 @@ def markdown_factory() -> Markdown: """ md = Markdown( extensions=[ - 'meta', 'fenced_code', 'codehilite', 'smarty', - MarkdownLinkExtension() + 'meta', + 'fenced_code', + 'codehilite', + 'smarty', + MarkdownLinkExtension(), ], output_format='html', ) @@ -91,9 +94,7 @@ def convert_markdown( class MarkdownLinkTreeprocessor(Treeprocessor): - """Converts relative links to .md files to .html - - """ + """Converts relative links to .md files to .html""" def run(self, root: Element) -> Element: for element in root.iter(): @@ -112,7 +113,7 @@ class MarkdownLinkTreeprocessor(Treeprocessor): logger.debug( f'{url}: {scheme=} {netloc=} {path=} {query=} {fragment=}' ) - if (scheme or netloc or not path): + if scheme or netloc or not path: return url if path.endswith('.md'): path = path[:-3] + '.html' @@ -122,10 +123,11 @@ class MarkdownLinkTreeprocessor(Treeprocessor): class MarkdownLinkExtension(Extension): - """markdown.extension that converts relative .md- to .html-links. + """markdown.extension that converts relative .md- to .html-links.""" - """ def extendMarkdown(self, md: Markdown) -> None: md.treeprocessors.register( - MarkdownLinkTreeprocessor(md), 'mdlink', 0, + MarkdownLinkTreeprocessor(md), + 'mdlink', + 0, ) diff --git a/blag/quickstart.py b/blag/quickstart.py index 4f4678d..c27e473 100644 --- a/blag/quickstart.py +++ b/blag/quickstart.py @@ -64,10 +64,10 @@ def quickstart(args: argparse.Namespace | None) -> None: config = configparser.ConfigParser() config['main'] = { - 'base_url': base_url, - 'title': title, - 'description': description, - 'author': author, + 'base_url': base_url, + 'title': title, + 'description': description, + 'author': author, } with open('config.ini', 'w') as fh: config.write(fh) diff --git a/tests/conftest.py b/tests/conftest.py index 0b530e7..da40e05 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -50,9 +50,7 @@ def tag_template(environment: Environment) -> Iterator[Template]: @pytest.fixture def cleandir() -> Iterator[str]: - """Create a temporary workind directory and cwd. - - """ + """Create a temporary workind directory and cwd.""" config = """ [main] base_url = https://example.com/ @@ -78,9 +76,9 @@ author = a. u. thor def args(cleandir: Callable[[], Iterator[str]]) -> Iterator[Namespace]: args = Namespace( - input_dir='content', - output_dir='build', - static_dir='static', - template_dir='templates', + input_dir='content', + output_dir='build', + static_dir='static', + template_dir='templates', ) yield args diff --git a/tests/test_blag.py b/tests/test_blag.py index cb200f4..74e8512 100644 --- a/tests/test_blag.py +++ b/tests/test_blag.py @@ -28,7 +28,7 @@ def test_feed(cleandir: str) -> None: 'title': 'title1', 'date': datetime(2019, 6, 6), 'content': 'content1', - } + }, ), ( 'dest2.html', @@ -36,12 +36,18 @@ def test_feed(cleandir: str) -> None: 'title': 'title2', 'date': datetime(1980, 5, 9), 'content': 'content2', - } + }, ), ] - blag.generate_feed(articles, 'build', 'https://example.com/', - 'blog title', 'blog description', 'blog author') + blag.generate_feed( + articles, + 'build', + 'https://example.com/', + 'blog title', + 'blog description', + 'blog author', + ) with open('build/atom.xml') as fh: feed = fh.read() @@ -69,15 +75,17 @@ def test_feed(cleandir: str) -> None: def test_generate_feed_with_description(cleandir: str) -> None: # if a description is provided, it will be used as the summary in # the feed, otherwise we simply use the title of the article - articles: list[tuple[str, dict[str, Any]]] = [( - 'dest.html', - { - 'title': 'title', - 'description': 'description', - 'date': datetime(2019, 6, 6), - 'content': 'content', - } - )] + articles: list[tuple[str, dict[str, Any]]] = [ + ( + 'dest.html', + { + 'title': 'title', + 'description': 'description', + 'date': datetime(2019, 6, 6), + 'content': 'content', + }, + ) + ] blag.generate_feed(articles, 'build', ' ', ' ', ' ', ' ') with open('build/atom.xml') as fh: @@ -144,10 +152,9 @@ author = a. u. thor # a missing required config causes a sys.exit for x in 'base_url', 'title', 'description', 'author': - config2 = '\n'.join([line - for line - in config.splitlines() - if not line.startswith(x)]) + config2 = '\n'.join( + [line for line in config.splitlines() if not line.startswith(x)] + ) with TemporaryDirectory() as dir: configfile = f'{dir}/config.ini' with open(configfile, 'w') as fh: @@ -173,10 +180,7 @@ author = a. u. thor def test_environment_factory() -> None: - globals_: dict[str, object] = { - 'foo': 'bar', - 'test': 'me' - } + globals_: dict[str, object] = {'foo': 'bar', 'test': 'me'} env = blag.environment_factory(globals_=globals_) assert env.globals['foo'] == 'bar' assert env.globals['test'] == 'me' @@ -217,11 +221,7 @@ foo bar convertibles.append((str(i), str(i))) articles, pages = blag.process_markdown( - convertibles, - 'content', - 'build', - page_template, - article_template + convertibles, 'content', 'build', page_template, article_template ) assert isinstance(articles, list) diff --git a/tests/test_devserver.py b/tests/test_devserver.py index 9699f91..4b66b38 100644 --- a/tests/test_devserver.py +++ b/tests/test_devserver.py @@ -32,9 +32,11 @@ def test_autoreload_builds_immediately(args: Namespace) -> None: with open('content/test.md', 'w') as fh: fh.write('boo') - t = threading.Thread(target=devserver.autoreload, - args=(args, ), - daemon=True,) + t = threading.Thread( + target=devserver.autoreload, + args=(args,), + daemon=True, + ) t0 = devserver.get_last_modified(['build']) t.start() # try for 5 seconds... @@ -47,11 +49,15 @@ def test_autoreload_builds_immediately(args: Namespace) -> None: assert t1 > t0 -@pytest.mark.filterwarnings("ignore::pytest.PytestUnhandledThreadExceptionWarning") # noqa +@pytest.mark.filterwarnings( + "ignore::pytest.PytestUnhandledThreadExceptionWarning" +) def test_autoreload(args: Namespace) -> None: - t = threading.Thread(target=devserver.autoreload, - args=(args, ), - daemon=True,) + t = threading.Thread( + target=devserver.autoreload, + args=(args,), + daemon=True, + ) t.start() t0 = devserver.get_last_modified(['build']) diff --git a/tests/test_markdown.py b/tests/test_markdown.py index 670a4e1..816f310 100644 --- a/tests/test_markdown.py +++ b/tests/test_markdown.py @@ -9,54 +9,65 @@ import markdown from blag.markdown import convert_markdown, markdown_factory -@pytest.mark.parametrize("input_, expected", [ - # inline - ('[test](test.md)', 'test.html'), - ('[test](test.md "test")', 'test.html'), - ('[test](a/test.md)', 'a/test.html'), - ('[test](a/test.md "test")', 'a/test.html'), - ('[test](/test.md)', '/test.html'), - ('[test](/test.md "test")', '/test.html'), - ('[test](/a/test.md)', '/a/test.html'), - ('[test](/a/test.md "test")', '/a/test.html'), - # reference - ('[test][]\n[test]: test.md ''', 'test.html'), - ('[test][]\n[test]: test.md "test"', 'test.html'), - ('[test][]\n[test]: a/test.md', 'a/test.html'), - ('[test][]\n[test]: a/test.md "test"', 'a/test.html'), - ('[test][]\n[test]: /test.md', '/test.html'), - ('[test][]\n[test]: /test.md "test"', '/test.html'), - ('[test][]\n[test]: /a/test.md', '/a/test.html'), - ('[test][]\n[test]: /a/test.md "test"', '/a/test.html'), -]) +@pytest.mark.parametrize( + "input_, expected", + [ + # inline + ('[test](test.md)', 'test.html'), + ('[test](test.md "test")', 'test.html'), + ('[test](a/test.md)', 'a/test.html'), + ('[test](a/test.md "test")', 'a/test.html'), + ('[test](/test.md)', '/test.html'), + ('[test](/test.md "test")', '/test.html'), + ('[test](/a/test.md)', '/a/test.html'), + ('[test](/a/test.md "test")', '/a/test.html'), + # reference + ('[test][]\n[test]: test.md ' '', 'test.html'), + ('[test][]\n[test]: test.md "test"', 'test.html'), + ('[test][]\n[test]: a/test.md', 'a/test.html'), + ('[test][]\n[test]: a/test.md "test"', 'a/test.html'), + ('[test][]\n[test]: /test.md', '/test.html'), + ('[test][]\n[test]: /test.md "test"', '/test.html'), + ('[test][]\n[test]: /a/test.md', '/a/test.html'), + ('[test][]\n[test]: /a/test.md "test"', '/a/test.html'), + ], +) def test_convert_markdown_links(input_: str, expected: str) -> None: md = markdown_factory() html, _ = convert_markdown(md, input_) assert expected in html -@pytest.mark.parametrize("input_, expected", [ - # scheme - ('[test](https://)', 'https://'), - # netloc - ('[test](//test.md)', '//test.md'), - # no path - ('[test]()', ''), -]) +@pytest.mark.parametrize( + "input_, expected", + [ + # scheme + ('[test](https://)', 'https://'), + # netloc + ('[test](//test.md)', '//test.md'), + # no path + ('[test]()', ''), + ], +) def test_dont_convert_normal_links(input_: str, expected: str) -> None: md = markdown_factory() html, _ = convert_markdown(md, input_) assert expected in html -@pytest.mark.parametrize("input_, expected", [ - ('foo: bar', {'foo': 'bar'}), - ('foo: those are several words', {'foo': 'those are several words'}), - ('tags: this, is, a, test\n', {'tags': ['this', 'is', 'a', 'test']}), - ('tags: this, IS, a, test', {'tags': ['this', 'is', 'a', 'test']}), - ('date: 2020-01-01 12:10', {'date': - datetime(2020, 1, 1, 12, 10).astimezone()}), -]) +@pytest.mark.parametrize( + "input_, expected", + [ + ('foo: bar', {'foo': 'bar'}), + ('foo: those are several words', {'foo': 'those are several words'}), + ('tags: this, is, a, test\n', {'tags': ['this', 'is', 'a', 'test']}), + ('tags: this, IS, a, test', {'tags': ['this', 'is', 'a', 'test']}), + ( + 'date: 2020-01-01 12:10', + {'date': datetime(2020, 1, 1, 12, 10).astimezone()}, + ), + ], +) def test_convert_metadata(input_: str, expected: dict[str, Any]) -> None: md = markdown_factory() _, meta = convert_markdown(md, input_)