summaryrefslogtreecommitdiff
path: root/creole/cmdline.py
blob: 82a156e66effa057eac69abbe26c795667984ac6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/usr/bin/env python
# coding: utf-8

"""
    python-creole commandline interface
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    :copyleft: 2013 by the python-creole team, see AUTHORS for more details.
    :license: GNU GPL v3 or above, see LICENSE for more details.
"""

from __future__ import division, absolute_import, print_function, unicode_literals
import argparse
import codecs

from creole import creole2html, html2creole, html2rest, html2textile
from creole import VERSION_STRING


class CreoleCLI(object):
    def __init__(self, convert_func):
        self.convert_func = convert_func
        self.parser = argparse.ArgumentParser(
            description=(
                "python-creole is an open-source (GPL) markup converter"
                " in pure Python for:"
                " creole2html, html2creole, html2ReSt, html2textile"
            ),
        )
        self.parser.add_argument('--version', action='version',
            version='%%(prog)s from python-creole v%s' % VERSION_STRING
        )
        self.parser.add_argument("sourcefile", help="source file to convert")
        self.parser.add_argument("destination", help="Output filename")
        self.parser.add_argument("--encoding",
            default="utf-8",
            help="Codec for read/write file (default encoding: utf-8)"
        )
        
        args = self.parser.parse_args()

        sourcefile = args.sourcefile
        destination = args.destination
        encoding = args.encoding

        self.convert(sourcefile, destination, encoding)

    def convert(self, sourcefile, destination, encoding):
        print("Convert %r to %r with %s (codec: %s)" % (
            sourcefile, destination, self.convert_func.__name__, encoding
        ))
        
        with codecs.open(sourcefile, "r", encoding=encoding) as infile:
            with codecs.open(destination, "w", encoding=encoding) as outfile:
                content = infile.read()
                converted = self.convert_func(content)
                outfile.write(converted)
        print("done. %r created." % destination)


def cli_creole2html():
    CreoleCLI(creole2html)

def cli_html2creole():
    CreoleCLI(html2creole)
    
def cli_html2rest():
    CreoleCLI(html2rest)
    
def cli_html2textile():
    CreoleCLI(html2textile)


if __name__ == "__main__":
    import sys
    sys.argv += ["../README.creole", "../test.html"]
    print(sys.argv)
    cli_creole2html()