Beispiel #1
0
    def handle(self, options, global_options, *args):
        from utils import extract_dirs, pkg, extract_file
        from shutil import copy
        
        if os.path.exists('conf.py'):
            has_conf = True
        else:
            has_conf = False
        extract_dirs('parm', 'templates/env', '.', exclude=['conf.py'])
        if not os.path.exists('static'):
            os.makedirs('static')
            
        d = {}
        
        d['project'] = 'Parm'
        d['copyright'] = '2013, Limodou'
        d['version'] = '1.0'
        
        if has_conf:
            create = get_answer("Create config file", quit='q') == 'Y'
        
        if not has_conf or (has_conf and create):
            d['project'] = get_input("Project name [Parm]:", default=d['project'])
            d['copyright'] = get_input("Copyright information [%s]:" % d['copyright'], default=d['copyright'])
            d['version'] = get_input("Version [%s]:" % d['version'], default=d['version'])

            extract_file('parm', 'templates/env/conf.py', '.')
            text = template.template_file('conf.py', d).replace('\r\n', '\n')
            f = open('conf.py', 'wb')
            f.write(text)
            f.close()
Beispiel #2
0
    def template(self, filename, vars=None, env=None, dirs=None, default_template=None):
        vars = vars or {}
        dirs = dirs or self.template_dirs
        env = env or self.get_view_env()
        
        if self.debug:
            def _compile(code, filename, action, env, Loader=Loader):
                env['__loader__'] = Loader(filename, vars, env, dirs, notest=True)
                try:
                    return compile(code, filename, 'exec')
                except:
#                    file('out.html', 'w').write(code)
                    raise
            
            return template.template_file(filename, vars, env, dirs, default_template, compile=_compile)
        else:
            return template.template_file(filename, vars, env, dirs, default_template)
Beispiel #3
0
    def handle(self, options, global_options, *args):
        from utils import extract_dirs, copy_dir
        from par.bootstrap_ext import blocks
        from md_ext import new_code_comment, toc
        from functools import partial

        if not conf:
            log.error('Current directory is not a parm project')
            sys.exit(1)
            
        #make output directory
        if not os.path.exists(options.directory):
            print 'Make directories [%s]' % options.directory
            os.makedirs(options.directory)
            
        #copy static files
        print 'Copy default templates/static to %s' % options.directory
        extract_dirs('parm', 'templates/static', 
            os.path.join(options.directory, 'static'))
            
        #create source directory
        source_path = os.path.join(options.directory, 'source')
        if not os.path.exists(source_path):
            print 'Make directories [%s]' % source_path
            os.makedirs(source_path)
        
        #compile markdown files
        files = list(os.listdir('.'))
        headers = {}
        relations = {}
        
        #prepare block process handlers
        blocks['code-comment'] = new_code_comment
        blocks['toc'] = partial(toc, headers=headers, relations=relations)

        output_files = {}
        
        while 1:
            if not files:
                break
            
            path = files.pop(0)
            fname, ext = os.path.splitext(path)
            if os.path.isfile(path) and (ext in conf.source_suffix):
                if fname == conf.master_doc and len(files)>1:
                    files.append(path)
                    continue
                
                with open(path) as f:
                    
                    data = {}
                    data['conf'] = conf
                    
                    #process markdown convert
                    data['body'] = parseHtml(f.read(), 
                        '', 
                        conf.tag_class,
                        block_callback=blocks)
                    page_nav = relations.get(fname, {})
                    data['prev'] = page_nav.get('prev', {})
                    data['next'] = page_nav.get('next', {})
                    data['source'] = '<a href="source/%s">%s</a>' % (path, conf.download_source)
                    
                    #parse header from text
                    h = headers.setdefault(path, [])
                    title = self.parse_headers(path, data['body'], h)
                    if title:
                        data['title'] = unicode(title, 'utf8') + ' - ' + conf.project 
                    else:
                        print 'Error: Heading 1 not found in file %s' % path
                        continue

                    #convert conf attributes to data
                    for k in dir(conf):
                        if not k.startswith('_'):
                            data[k] = getattr(conf, k)
                       
                    #process template
                    template_file = conf.templates.get(fname, conf.templates.get('*', 'default.html'))
                    hfilename = os.path.join(options.directory, fname + '.html').replace('\\', '/')
                    with open(hfilename, 'wb') as fh:
                        print 'Convert %s to %s' % (path, hfilename)
                        fh.write(template.template_file(template_file, data, dirs=['_build']))
                
                    output_files[fname] = hfilename
                    #copy source file
                    sfilename = os.path.join(source_path, path)
                    shutil.copy(path, sfilename)
                    
            elif os.path.isdir(path) and not path.startswith('_'):
                print 'Copy %s to %s' % (path, options.directory)
                copy_dir(path, os.path.join(options.directory, path))
                
        prev_next_template_top = """{{if prev:}}<div class="chapter-prev chapter-top">
    <a prev-chapter href="{{<< prev['link']}}"><i class="icon-arrow-left"></i> {{=prev['title']}}</a>
</div>{{pass}}
{{if next:}}<div class="chapter-next chapter-top">
    <a next-chapter href="{{<< next['link']}}">{{=next['title']}} <i class="icon-arrow-right"></i></a>
</div>{{pass}}"""
        prev_next_template_down = """{{if prev:}}<div class="chapter-prev chapter-down">
    <a prev-chapter href="{{<< prev['link']}}"><i class="icon-arrow-left"></i> {{=prev['title']}}</a>
</div>{{pass}}
{{if next:}}<div class="chapter-next chapter-down">
    <a next-chapter href="{{<< next['link']}}">{{=next['title']}} <i class="icon-arrow-right"></i></a>
</div>{{pass}}"""
        
        for name, f in output_files.items():
            text = open(f, 'rb').read()
            
            x = relations.get(name, {})
            data = {}
            data['prev'] = x.get('prev', {})
            data['next'] = x.get('next', {})
            
            prev_next_text_top = template.template(prev_next_template_top, data)
            prev_next_text_down = template.template(prev_next_template_down, data)
            text = text.replace('<!-- prev_next_top -->', prev_next_text_top)
            text = text.replace('<!-- prev_next_down -->', prev_next_text_down)
            with open(f, 'wb') as fh:
                fh.write(text)
Beispiel #4
0
    def handle(self, options, global_options, *args):
        from utils import extract_dirs, pkg, extract_file
        from shutil import copy
        
        if os.path.exists('conf.py'):
            has_conf = True
        else:
            has_conf = False
            
        d = {}
        
        d['project'] = getattr('conf', 'project', 'Parm')
        d['copyright'] = getattr('conf', 'copyright', '2013, Limodou')
        d['version'] = getattr('conf', 'version', __version__)
        d['theme'] = getattr(conf, 'theme', 'semantic')
        d['template_dirs'] = getattr(conf, 'template_dirs', 'templates')
        d['disqus'] = getattr(conf, 'disqus', '')
        
        if has_conf:
            create = get_answer("Create config file", quit='q') == 'Y'
        
        if not has_conf or (has_conf and create):
            d['project'] = get_input("Project name [%s]:"%d['project'], default=d['project'])
            d['copyright'] = get_input("Copyright information [%s]:" % d['copyright'], default=d['copyright'])
            d['version'] = get_input("Version [%s]:" % d['version'], default=d['version'])
            d['theme'] = get_input("Choice theme (bootstrap, semantic) [%s]:" % d['theme'], choices=['bootstrap', 'semantic'], default=d['theme'])
            d['disqus'] = get_input("Disqus account name:", d['disqus'])
            
            if d['theme'] == 'bootstrap':
                d['tag_class'] = """
'table':'table table-bordered',
'pre':'prettyprint linenums',
"""
            elif d['theme'] == 'semantic':
                d['tag_class'] = """
'table':'ui collapsing celled table segment',
'pre':'prettyprint',
"""
            
            conf_file = pkg.resource_filename('parm', 'templates/env/conf.py.txt')
            text = template.template_file(conf_file, d).replace('\r\n', '\n')
            f = open('conf.py', 'wb')
            f.write(text)
            f.close()
        
        run = False
        if os.path.exists(d['template_dirs']):
            print "Template directory [%s] is already existed! If you've changed them, please deal with manually, otherwise the content will be overwritten." % d['template_dirs']
            if get_answer("Overwrite template files") == 'Y':
                run = True
        else:
            run = True
        
        if run:
            print 'Copy %s to ./%s' % ('theme/%s/templates' % d['theme'], d['template_dirs'])
            extract_dirs('parm', 'templates/theme/%s/templates' % d['theme'], 
                d['template_dirs'])
                
        if get_answer("Copy init files [index.md*]") == 'Y':
            for f in ['index.md', 'introduction.md', 'exclude.txt']:
                if os.path.exists(f):
                    print '%s is already existed, so just skip it' % f
                else:
                    print 'Copy templates/env/%s to ./%s' % (f, f)
                    extract_file('parm', 'templates/env/%s' % f, '.')
Beispiel #5
0
    def handle(self, options, global_options, *args):
        from utils import extract_dirs, copy_dir, walk_dirs, import_attr
        from md_ext import new_code_comment, toc
        from functools import partial
        from shutil import copy2

        if not conf:
            log.error('Current directory is not a parm project')
            sys.exit(1)
            
        #make output directory
        if not os.path.exists(options.directory):
            print 'Make directories [%s]' % options.directory
            os.makedirs(options.directory)
            
        #get theme config
        theme = getattr(conf, 'theme', 'semantic')
        print 'Using theme [%s]' % theme
        
        #copy static files
        print 'Copy %s to %s' % ('theme/%s/static' % theme, os.path.join(options.directory, 'static'))
        extract_dirs('parm', 'templates/theme/%s/static' % theme, 
            os.path.join(options.directory, 'static'))
            
        dst_dir = os.path.normpath(os.path.abspath(options.directory)).replace('\\', '/') + '/'
        
        #process exclude
        if os.path.exists('exclude.txt'):
            _exclude = open('exclude.txt').read().splitlines()
        else:
            _exclude = []
        _exclude.extend([options.directory, conf.template_dirs])
        files = list(walk_dirs('.', exclude=_exclude))
        headers = {}
        relations = {}
        
        #prepare block process handlers
        blocks = {}
        blocks['code-comment'] = new_code_comment
        blocks['toc'] = partial(toc, headers=headers, relations=relations)

        #according theme import different blocks
        mod_path = 'par.%s_ext.blocks' % theme
        b = import_attr(mod_path)
        blocks.update(b)
        
        output_files = {}
        template_dirs = conf.template_dirs
        
        while 1:
            if not files:
                break
            
            path = files.pop(0)
            fname, ext = os.path.splitext(path)
            if os.path.isfile(path) and (ext in conf.source_suffix):
                if fname == conf.master_doc and len(files)>0:
                    files.append(path)
                    continue
                
                with open(path) as f:
                    
                    data = {}
                    data['conf'] = conf
                    
                    #process markdown convert
                    data['body'] = parseHtml(f.read(), 
                        '', 
                        conf.tag_class,
                        block_callback=blocks)
                    page_nav = relations.get(fname, {})
                    data['prev'] = page_nav.get('prev', {})
                    data['next'] = page_nav.get('next', {})
                    data['relpath'] = '.' * (path.count('/')+1)
                    data['source'] = '<a href="%s/%s">%s</a>' % (data['relpath'], path, conf.download_source)
                    
                    #parse header from text
                    h = headers.setdefault(path, [])
                    title = self.parse_headers(path, data['body'], h)
                    if title:
                        data['title'] = unicode(title, 'utf8') + ' - ' + conf.project 
                    else:
                        if fname != conf.master_doc:
                            print 'Error: Heading 1 not found in file %s' % path
                            continue
                        else:
                            data['title'] = conf.project

                    #convert conf attributes to data
                    for k in dir(conf):
                        if not k.startswith('_'):
                            data[k] = getattr(conf, k)
                       
                    #process template
                    template_file = conf.templates.get(fname, conf.templates.get('*', 'default.html'))
                    hfilename = os.path.join(options.directory, fname + '.html').replace('\\', '/')
                    fix_dir(hfilename)
                    with open(hfilename, 'wb') as fh:
                        print 'Convert %s to %s' % (path, hfilename)
                        fh.write(template.template_file(template_file, data, dirs=[template_dirs]))
                        copy2(path, os.path.join(options.directory, path))
                    output_files[fname] = hfilename
                    
            else:
                if os.path.isdir(path):
                    dpath = os.path.join(dst_dir, path)
                    if not os.path.exists(dpath):
                        print 'Makedir %s' % os.path.join(dst_dir, path)
                        os.makedirs(dpath)
                else:
                    print 'Copy %s to %s' % (path, os.path.join(dst_dir, path))
                    shutil.copy(path, os.path.join(dst_dir, path))
                
        prev_next_template_top = """{{if prev:}}<div class="chapter-prev chapter-top">
    <a prev-chapter href="{{<< prev['link']}}"><i class="icon-arrow-left"></i> {{=prev['title']}}</a>
</div>{{pass}}
{{if next:}}<div class="chapter-next chapter-top">
    <a next-chapter href="{{<< next['link']}}">{{=next['title']}} <i class="icon-arrow-right"></i></a>
</div>{{pass}}"""
        prev_next_template_down = """{{if prev:}}<div class="chapter-prev chapter-down">
    <a prev-chapter href="{{<< prev['link']}}"><i class="icon-arrow-left"></i> {{=prev['title']}}</a>
</div>{{pass}}
{{if next:}}<div class="chapter-next chapter-down">
    <a next-chapter href="{{<< next['link']}}">{{=next['title']}} <i class="icon-arrow-right"></i></a>
</div>{{pass}}"""
        
        for name, f in output_files.items():
            text = open(f, 'rb').read()
            
            x = relations.get(name, {})
            data = {}
            data['prev'] = x.get('prev', {})
            if data['prev']:
                relpath = '.' * (data['prev']['link'].count('/')+1)
                data['prev']['link'] = relpath + '/' + data['prev']['link']
            data['next'] = x.get('next', {})
            if data['next']:
                relpath = '.' * (data['next']['link'].count('/')+1)
                data['next']['link'] = relpath + '/' + data['next']['link']
            
            prev_next_text_top = template.template(prev_next_template_top, data)
            prev_next_text_down = template.template(prev_next_template_down, data)
            text = text.replace('<!-- prev_next_top -->', prev_next_text_top)
            text = text.replace('<!-- prev_next_down -->', prev_next_text_down)
            with open(f, 'wb') as fh:
                fh.write(text)