boop.py 2.53 KB
Newer Older
1
2
3
#!/bin/env python3

import os
4
import sys
5
6
import shutil

7
8
import markdown

9

10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class ProgramError(Exception):
    """Exception raised during the program execution.

    Examples:

    >>> try:
    ...     raise ProgramError("Oops")
    ... except ProgramError as e:
    ...     print(e.args[0])
    Oops
    """

    pass


25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
def dir_tree(path):
    """List all the tree directory under the given path.
    """
    for filename in os.listdir(path):
        full_path = os.path.join(path, filename)
        if os.path.isdir(full_path):
            for sub_filename in dir_tree(full_path):
                yield os.path.join(filename, sub_filename)
        else:
            yield filename


def mkdirs_for_file(filepath):
    """Create parent directories for a given file.
    """
    path = os.path.dirname(filepath)
    os.makedirs(path, exist_ok=True)


44
def main():
45
46
47
48
49
    # Check that content directory exists on the filesystem
    content_path = os.path.join(os.curdir, "content")
    if not os.path.isdir(content_path):
        raise ProgramError("./content directory does not exist")

50
    # Make sure output dir doesn't exist
51
52
    output_path = os.path.join(os.curdir, "output")
    if os.path.isdir(output_path):
53
        # it should be a directory...
54
        shutil.rmtree(output_path)
55
56
57
    elif os.path.exists(output_path):
        # ... but it also can be a simple file if user created it manually!
        os.remove(output_path)
58

59
60
    md = markdown.Markdown()

61
    # And copy the files from ./content to ./output
62
    for filepath in dir_tree(content_path):
63
        base, ext = os.path.splitext(filepath)
64
65
        content_filepath = os.path.join(content_path, filepath)
        output_filepath = os.path.join(output_path, filepath)
66
67
        if ext == ".md":
            output_filepath = os.path.join(output_path, f"{base}.html")
68
69
70
71

        # First we need to create all the parent directories for our file
        mkdirs_for_file(output_filepath)

72
73
74
75
76
77
78
79
80
81
82
        if ext == ".md":
            # Then, if it is a Markdown file, we convert it
            with open(content_filepath, "r") as content_file:
                html = md.convert(content_file.read())

            # And we write it as a HTML file
            with open(output_filepath, "w") as output_file:
                output_file.write(html)
        else:
            # ... else, we simply copy the file to the output directory
            shutil.copyfile(content_filepath, output_filepath)
83
84
85


if __name__ == "__main__":
86
87
88
89
90
    try:
        main()
        print("Boop!")
    except ProgramError as e:
        print(e.args[0], file=sys.stderr)