1
#!/usr/bin/env python
2
3
import sys, os
4
from distutils.core import setup
5
from distutils.command.install_scripts import install_scripts
6
from distutils.command.build import build
7
from distutils.core import Command
8
from distutils.util import change_root, newer
9
10
# Try to run 2to3 automaticaly when building in Python 3.x
11
try:
12
    from distutils.command.build_py import build_py_2to3 as build_py
13
except ImportError:
14
    if sys.version_info >= (3, 0):
15
        raise ImportError("build_py_2to3 is required to build in Python 3.x.")
16
    from distutils.command.build_py import build_py
17
18
version = '2.1.0.Dev'
19
20
# The command line script name.  Currently set to "markdown_py" so as not to 
21
# conflict with the perl implimentation (which uses "markdown").  We can't use
22
# "markdown.py" as the default config on some systems will cause the script to
23
# try to import itself rather than the library which will raise an error. 
24
SCRIPT_NAME = 'markdown_py'
25
26
class md_install_scripts(install_scripts):
27
    """ Customized install_scripts. Create markdown_py.bat for win32. """
28
    def run(self):
29
        install_scripts.run(self)
30
31
        if sys.platform == 'win32':
32
            try:
33
                script_dir = os.path.join(sys.prefix, 'Scripts')
34
                script_path = os.path.join(script_dir, SCRIPT_NAME)
35
                bat_str = '@"%s" "%s" %%*' % (sys.executable, script_path)
36
                bat_path = os.path.join(self.install_dir, '%s.bat' %SCRIPT_NAME)
37
                f = open(bat_path, 'w')
38
                f.write(bat_str)
39
                f.close()
40
                print ('Created: %s' % bat_path)
41
            except Exception:
42
                _, err, _ = sys.exc_info() # for both 2.x & 3.x compatability
43
                print ('ERROR: Unable to create %s: %s' % (bat_path, err))
44
45
46
doc_header = """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
47
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
48
<html xmlns="http://www.w3.org/1999/xhtml">
49
<head>
50
<title>%(title)s</title>
51
<style type="text/css">
52
.nav { float:right; margin:1em;}
53
</style>
54
</head>
55
<body>
56
<div id="nav">
57
%(menu)s
58
</div>
59
<div id="content">
60
"""
61
62
doc_footer = """
63
</div>
64
<p id="foot">&copy; 2010 Python Markdown Project<p>
65
</body>
66
</html>
67
"""
68
69
class build_docs(Command):
70
    """ Build markdown documentation into html."""
71
72
    description = '"build" documentation (convert markdown text to html)'
73
74
    user_options = [
75
        ('build-base=', 'd', 'directory to "build" to'),
76
        ('force', 'f', 'forcibly build everything (ignore file timestamps)'),
77
        ]
78
79
    boolean_options = ['force']
80
81
    def initialize_options(self):
82
        self.build_base = None
83
        self.force = None
84
        self.docs = None
85
        self.sitemap = ''
86
87
    def finalize_options(self):
88
        self.set_undefined_options('build', 
89
                                    ('build_base', 'build_base'), 
90
                                    ('force', 'force'))
91
        self.docs = self._get_docs()
92
        try:
93
            sm = open('docs/sitemap.txt')
94
            self.sitemap = sm.read()
95
            sm.close()
96
        except:
97
            pass
98
99
    def _get_docs(self):
100
        for root, dirs, files in os.walk('docs'):
101
            for file in files:
102
                path = os.path.join(root, file)
103
                yield (path, self._get_page_title(path))
104
105
    def _get_page_title(self, path):
106
        """ Get page title from file name (and path). """
107
        root, ext = os.path.splitext(path)
108
        path, name = os.path.split(root)
109
        parts = path.split(os.sep)
110
        parts = [x.replace('_', ' ').capitalize() for x in parts[1:]]
111
        if name.lower() != 'index':
112
            parts.append(name.replace('_', ' ').capitalize())
113
        if parts:
114
            return ' | '.join(parts) + ' &#8212; Python Markdown'
115
        else:
116
            return 'Python Markdown'
117
118
    def run(self):
119
        # Before importing markdown, tweak sys.path to import from the 
120
        # build directory (2to3 might have run on the library).
121
        bld_cmd = self.get_finalized_command("build")
122
        sys.path.insert(0, bld_cmd.build_lib)
123
        try:
124
            import markdown
125
        except ImportError:
126
            print ('skipping build_docs: Markdown "import" failed!')
127
        else:
128
            md = markdown.Markdown()
129
            menu = md.convert(self.sitemap)
130
            md.reset()
131
            for infile, title in self.docs:
132
                outfile, ext = os.path.splitext(infile)
133
                if ext == '.txt':
134
                    outfile += '.html'
135
                    outfile = change_root(self.build_base, outfile)
136
                    self.mkpath(os.path.split(outfile)[0])
137
                    if self.force or newer(infile, outfile):
138
                        if self.verbose:
139
                            print ('Converting %s -> %s' % (infile, outfile))
140
                        if not self.dry_run:
141
                            doc = open(outfile, 'wb')
142
                            header = doc_header % {'title': title, 'menu': menu}
143
                            doc.write(header.encode('utf-8'))
144
                            md.convertFile(infile, doc)
145
                            md.reset()
146
                            doc.write(doc_footer.encode('utf-8'))
147
                            doc.close()
148
149
150
class md_build(build):
151
    """ Run "build_docs" command from "build" command. """
152
    def has_docs(self):
153
        return True
154
155
    sub_commands = build.sub_commands + [('build_docs', has_docs)]
156
157
158
data = dict(
159
    name =          'Markdown',
160
    version =       version,
161
    url =           'http://www.freewisdom.org/projects/python-markdown',
162
    download_url =  'http://pypi.python.org/packages/source/M/Markdown/Markdown-%s.tar.gz' % version,
163
    description =   'Python implementation of Markdown.',
164
    author =        'Manfred Stienstra and Yuri takhteyev',
165
    author_email =  'yuri [at] freewisdom.org',
166
    maintainer =    'Waylan Limberg',
167
    maintainer_email = 'waylan [at] gmail.com',
168
    license =       'BSD License',
169
    packages =      ['markdown', 'markdown.extensions'],
170
    scripts =       ['bin/%s' % SCRIPT_NAME],
171
    cmdclass =      {'install_scripts': md_install_scripts, 
172
                     'build_py': build_py,
173
                     'build_docs': build_docs,
174
                     'build': md_build},
175
    classifiers =   ['Development Status :: 5 - Production/Stable',
176
                     'License :: OSI Approved :: BSD License',
177
                     'Operating System :: OS Independent',
178
                     'Programming Language :: Python',
179
                     'Programming Language :: Python :: 2',
180
                     'Programming Language :: Python :: 2.4',
181
                     'Programming Language :: Python :: 2.5',
182
                     'Programming Language :: Python :: 2.6',
183
                     'Programming Language :: Python :: 2.7',
184
                     'Programming Language :: Python :: 3',
185
                     'Programming Language :: Python :: 3.1',
186
                     'Topic :: Communications :: Email :: Filters',
187
                     'Topic :: Internet :: WWW/HTTP :: Dynamic Content :: CGI Tools/Libraries',
188
                     'Topic :: Internet :: WWW/HTTP :: Site Management',
189
                     'Topic :: Software Development :: Documentation',
190
                     'Topic :: Software Development :: Libraries :: Python Modules',
191
                     'Topic :: Text Processing :: Filters',
192
                     'Topic :: Text Processing :: Markup :: HTML',
193
                    ],
194
    ) 
195
196
if sys.version[:3] < '2.5':
197
    data['install_requires'] = ['elementtree']
198
199
setup(**data)