Changeset 175

Show
Ignore:
Timestamp:
04/05/06 20:01:43 (3 years ago)
Author:
tim
Message:

merged mr baxters changes

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • branches/tim/pyramid/build.py

    r174 r175  
    1111import shutil 
    1212import syck 
     13import traceback 
     14from os.path import join as opjoin 
     15 
     16 
     17class OptionError(Exception): 
     18    pass 
    1319 
    1420try: 
     
    2026class Dumper(syck.Dumper): 
    2127    def represent_pyramid_path_path(self, object): 
    22         return syck.Scalar(object, tag="tag:python.yaml.org,2002:object:pyramid.path.path") 
    23     def represent_nevow_stan_xml(self,object): 
     28        return syck.Scalar(object, 
     29                    tag="tag:python.yaml.org,2002:object:pyramid.path.path") 
     30    def represent_nevow_stan_xml(self, object): 
    2431        return syck.Scalar(flat.flatten(object)) 
    2532    def allow_aliases(self, object): 
     
    2734 
    2835 
    29 def build(data,out,verbose=0,resourcedirs=[],rebuilddirs=None,partialbuild=False,constants=None,update=False,relativeurls=False,prettify=False): 
     36def build(data, out, verbose=0, resourcedirs=[], rebuilddirs=None, 
     37          partialbuild=False, constants=None, update=False, 
     38          relativeurls=False, prettify=False, createcache=False, keepgoing=False): 
    3039 
    3140    DATADIR = os.path.abspath(data) 
    3241    OUTPUTDIR = os.path.abspath(out) 
    33      
     42 
    3443    # check to see if the output directory exists 
    3544    if not os.path.exists(OUTPUTDIR): 
     
    3847            os.mkdir(OUTPUTDIR) 
    3948        except: 
    40             raise Error, 'Could not create output directory' 
     49            raise OptionError('Could not create output directory') 
    4150    else: 
    4251        if not os.path.isdir(OUTPUTDIR): 
    43             raise Error, 'OUTPUTDIR is not a directory' 
    44          
     52            raise OptionError('OUTPUTDIR is not a directory') 
     53 
    4554    # Check that the output dir is not in a subversion folder 
    46     if os.path.exists(os.path.join(OUTPUTDIR,'.svn')): 
    47         raise Error, 'the OUTPUTDIR contains .svn folders, halting operation for safety' 
    48      
     55    if os.path.exists(opjoin(OUTPUTDIR, '.svn')): 
     56        raise OptionError('the OUTPUTDIR contains .svn folders, ' 
     57                    'halting operation for safety') 
     58 
    4959    # dangerous remove directory contents function 
    5060    if partialbuild is False and rebuilddirs is None: 
    5161        utils.recursiveRemoveDirectoryContents(OUTPUTDIR) 
    52      
     62 
    5363    # copy in any resources needed 
    5464    for resourcedir in resourcedirs: 
    5565        dir, name = os.path.split(resourcedir) 
    56         utils.copytree(resourcedir,os.path.join(OUTPUTDIR,name),nocopylist=['.svn']) 
     66        utils.copytree(resourcedir, opjoin(OUTPUTDIR, name), 
     67                       nocopylist=['.svn']) 
    5768 
    5869    # change the working directory 
    5970    os.chdir(DATADIR) 
    6071    basedir = path(DATADIR) 
    61      
     72 
    6273    # initialise a context 
    6374    ctx = Context() 
    64     # set the root data key to an empty dictionary (the first level acquires from this) 
     75    # set the root data key to an empty dictionary (the first level acquires 
     76    # from this) 
    6577    ctx.data = { '': {} } 
    6678    # set the verbose option 
     
    7082    # set constants 
    7183    ctx.constants = constants 
    72     # set relative urls flag  
     84    # set relative urls flag 
    7385    ctx.relativeurls = relativeurls 
    7486    # set prettify flag 
    7587    ctx.prettify=prettify 
    76      
     88 
    7789    for root, dirs, files in os.walk('.'): 
    78      
     90 
    7991        # get the path directory 
    8092        ctx.path = path(root).abspath() 
    8193        ctx.relpath = path(basedir).relpathto(root) 
    8294        ctx.relpathparent = path(basedir).relpathto(ctx.path.parent) 
    83          
     95 
    8496        # ignore svn folders 
    8597        try: 
     
    8799        except: 
    88100            pass 
    89          
     101 
    90102        # if the target directory is not available, create it 
    91         if not os.path.isdir(os.path.join(OUTPUTDIR,root)): 
    92             os.mkdir(os.path.join(OUTPUTDIR,root)) 
     103        if not os.path.isdir(opjoin(OUTPUTDIR, root)): 
     104            os.mkdir(opjoin(OUTPUTDIR, root)) 
    93105 
    94106        for f in files: 
    95107            suffix = os.path.splitext(f)[1] 
    96108            if suffix not in PYRAMIDSUFFIXES: 
    97                 srcfile = os.path.join(ctx.path,f) 
    98                 targetfile = os.path.join(OUTPUTDIR,root,f) 
    99                 shutil.copy(srcfile,targetfile)             
    100      
     109                srcfile = opjoin(ctx.path, f) 
     110                targetfile = opjoin(OUTPUTDIR, root, f) 
     111                shutil.copy(srcfile, targetfile) 
     112 
    101113        # create the html from the index.yml fragment 
    102114        if root != '.': 
     
    106118        cachepath = outroot/'.cache.dump' 
    107119        cachepathparent = outroot.parent /'.cache.dump' 
    108          
    109          
     120 
     121 
    110122        # check to see if the current directory is in the rebuild dirs list 
    111123        matchesRebuildDir = False 
     
    115127                    matchesRebuildDir = True 
    116128                    break 
    117          
     129 
    118130        # check for nobuild 
    119131        nobuild = path(root) / 'NOBUILD' 
    120132        if nobuild.isfile(): 
    121             utils.copytree(root,os.path.join(OUTPUTDIR,root),nocopylist=['.svn']) 
     133            utils.copytree(root, opjoin(OUTPUTDIR, root), 
     134                           nocopylist=['.svn']) 
    122135            continue 
    123          
    124          
    125         if os.path.exists( cachepath ) and partialbuild: 
     136 
     137 
     138        if os.path.exists(cachepath) and partialbuild: 
    126139            ctx = pickle.load(open(cachepath)) 
    127140            ctx.partialbuild = True 
    128             html = flat.flatten( [DOCTYPE,flatten(ctx.data[ctx.relpath]['index.yml'],ctx)] ) 
    129             file(os.path.join(OUTPUTDIR,root,'index.html'),'w').write(html) 
     141            html = flat.flatten([DOCTYPE, 
     142                            flatten(ctx.data[ctx.relpath]['index.yml'], ctx)]) 
     143            file(opjoin(OUTPUTDIR, root, 'index.html'), 'w').write(html) 
    130144        else: 
    131145            if matchesRebuildDir: 
    132146                ctx.data = pickle.load(open(cachepathparent)).data 
    133                  
     147 
    134148            if matchesRebuildDir or rebuilddirs is None: 
    135149                if ctx.verbose > 0: 
     
    137151 
    138152                ctx.partialbuild = False 
    139                  
     153 
    140154                try: 
    141                     html = flat.flatten( [DOCTYPE,flatten(Y.fragmentConstructor(os.path.join(root,'index.yml')),ctx)] ) 
     155                    html = flat.flatten([DOCTYPE, 
     156                            flatten(Y.fragmentConstructor( 
     157                                    opjoin(root, 'index.yml')), ctx)]) 
    142158                except KeyError: 
    143159                    print '*'*80 
    144                     print 'An error has occured building the %s page' % path(os.path.join(OUTPUTDIR,root,'index.html')).abspath() 
    145                     print 'It is likely that an item of content is missing or malformed' 
     160                    print 'An error has occured building the %s page' % ( 
     161                        path(opjoin(OUTPUTDIR, root, 'index.html')).abspath()) 
     162                    print 'It is likely that an item of content is missing' 
     163                    print 'or malformed.' 
    146164                    print 'The current data for this page is shown above' 
    147165 
    148166                    sys.exit() 
    149                      
    150                 file(os.path.join(OUTPUTDIR,root,'index.html'),'w').write(html) 
     167                except (KeyboardInterrupt, SystemExit): # roll on Python2.5 
     168                    raise 
     169                except: 
     170                    print "While building %s:"%(opjoin(OUTPUTDIR, root)) 
     171                    if not keepgoing: 
     172                        raise 
     173                    else: 
     174                        ee, ev, et = sys.exc_info() 
     175                        traceback.print_exception(ee, ev, et, file=sys.stdout) 
     176                        print "keepgoing (-k) specified, continuing" 
     177                        continue 
     178 
     179                file(opjoin(OUTPUTDIR, root, 'index.html'), 'w').write(html) 
    151180                if createcache: 
    152                     pickle.dump(ctx,open(cachepath,'w')) 
     181                    pickle.dump(ctx, open(cachepath, 'w')) 
    153182            else: 
    154183                if ctx.verbose > 1: 
    155184                    print '.. %s Rebuilt from Cached Data' % str(ctx.relpath) 
    156             else: 
    157                 if ctx.verbose > 1: 
    158                     print '.. %s Rebuilt from Cached Data' % str(ctx.relpath) 
    159                  
    160                  
    161 def main(options,args): 
     185 
     186 
     187def main(options, args): 
    162188    if options.resources: 
    163189        resourcedirs = options.resources.split(',') 
    164190    else: 
    165191        resourcedirs = [] 
    166      
     192 
    167193    if options.rebuilddirs: 
    168194        rebuilddirs = options.rebuilddirs.strip().split(',') 
    169195    else: 
    170         rebuilddirs = None     
     196        rebuilddirs = None 
    171197 
    172198    if options.constants: 
     
    180206                constants[key]=value 
    181207    else: 
    182         constants = None   
    183          
    184  
    185     build(options.data, 
    186           options.out, 
    187           verbose=options.verbose, 
    188           resourcedirs=resourcedirs, 
    189           rebuilddirs=rebuilddirs, 
    190           constants=constants, 
    191           update=options.update, 
    192           relativeurls=options.relativeurls, 
    193           prettify=options.prettify 
    194           ) 
     208        constants = None 
     209 
     210    build(options.data, options.out, verbose=options.verbose, 
     211          resourcedirs=resourcedirs, rebuilddirs=rebuilddirs, 
     212          constants=constants, update=options.update, 
     213          createcache=options.createcache, keepgoing=options.keepgoing, 
     214          relativeurls=options.relativeurls, prettify=options.prettify) 
    195215 
    196216 
    197217def parseOptions(): 
    198218    parser = OptionParser() 
    199     parser.add_option("-d", "--data", dest="data", help="directory in which the fragment data is stored", metavar="DATA") 
    200     parser.add_option("-o", "--out", dest="out", help="directory in which to save output (will be emptied)", metavar="OUT") 
    201     parser.add_option("-r", "--resources", dest="resources", help="comma separated list of resource directories to copy", metavar="RESOURCES") 
    202     parser.add_option("-v", "--verbose", action="store_const", dest="verbose", default=0, const=1, help="print status messages to stdout")     
    203     parser.add_option("-V", "--veryverbose", action="store_const", dest="verbose", default=0, const=2, help="print all data to stdout")     
    204     parser.add_option("-W", "--veryveryverbose", action="store_const", dest="verbose", default=0, const=3, help="print all data to stdout")     
    205     parser.add_option("-R", "--rebuilddirs",dest="rebuilddirs",help="only rebuild below these comma separated directories",metavar="REBUILDDIRS") 
    206     parser.add_option("-C", "--createcache",action="store_true",dest="createcache",default=False,help="recreate the cache files",metavar="CREATECACHE") 
    207     parser.add_option("-c", "--constants", dest="constants", help="pass in the names constants (e.g. PDO=/root/pdo,PSF=/psf", metavar="CONSTANTS") 
    208     parser.add_option("-U", "--update", action="store_true", dest="update", default=False, help="NOT WORKING DO NOT USE try to build only those pages that have changed")     
    209     parser.add_option("-n", "--relativeurls", action="store_true", dest="relativeurls", default=False, help="Converts urls from absolute to relative")     
    210     parser.add_option("-P", "--prettify", action="store_true", dest="prettify", default=False, help="Prettify output - not used on live site")     
     219    parser.add_option("-d", "--data", dest="data", 
     220        help="directory in which the fragment data is stored", 
     221        metavar="DATA") 
     222    parser.add_option("-o", "--out", dest="out", 
     223        help="directory in which to save output (will be emptied)", 
     224        metavar="OUT") 
     225    parser.add_option("-r", "--resources", dest="resources", 
     226        help="comma separated list of resource directories to copy", 
     227        metavar="RESOURCES") 
     228    parser.add_option("-v", "--verbose", action="store_const", 
     229        dest="verbose", default=0, const=1, 
     230        help="print status messages to stdout") 
     231    parser.add_option("-V", "--veryverbose", action="store_const", 
     232        dest="verbose", default=0, const=2, help="print all data to stdout") 
     233    parser.add_option("-W", "--veryveryverbose", action="store_const", 
     234        dest="verbose", default=0, const=3, help="print all data to stdout") 
     235    parser.add_option("-R",  "--rebuilddirs", dest="rebuilddirs", 
     236        help="only rebuild below these comma separated directories", 
     237        metavar="REBUILDDIRS") 
     238    parser.add_option("-C",  "--createcache", action="store_true", 
     239        dest="createcache", default=False, help="recreate the cache files", 
     240        metavar="CREATECACHE") 
     241    parser.add_option("-c", "--constants", dest="constants", 
     242        help="pass in the names constants (e.g. PDO=/root/pdo,PSF=/psf", 
     243        metavar="CONSTANTS") 
     244    parser.add_option("-k", "--keepgoing", dest="keepgoing", 
     245        action="store_true", default=False, 
     246        help="keep going past errors if possible", 
     247        metavar="KEEPGOING") 
     248    parser.add_option("-U", "--update", action="store_true", dest="update", 
     249        default=False, 
     250        help="NOT WORKING DO NOT USE try to build only those pages that have changed") 
     251    parser.add_option("-n", "--relativeurls", action="store_true",  
     252        dest="relativeurls", default=False, help="Converts urls from absolute to relative") 
     253    parser.add_option("-P", "--prettify", action="store_true",  
     254        dest="prettify", default=False, help="Prettify output - not used on live site") 
    211255    (options, args) = parser.parse_args() 
    212     main(options,args) 
     256    main(options, args) 
    213257 
    214258if __name__ == "__main__": 
  • branches/tim/pyramid/core.py

    r149 r175  
    1313        self.verbose = node.get('verbose',False) 
    1414        self.root = path(node.get('root','')) 
    15          
     15 
    1616    def __eq__(self,other): 
    1717        return self.data == other.data 
    18      
     18 
    1919    def __ne__(self,other): 
    2020        return self.data != self.data 
  • branches/tim/pyramid/dictutils.py

    r96 r175  
    33import mergetrees 
    44 
    5 def merge(a,b,dir=None,partialbuild=False): 
    6      
    7     if isinstance(a,Y.sectionnav) and isinstance(b,Y.sectionnav) and dir is not None: 
    8         # special case. If b is the same as a, it has been inhereited - sectionnav's 
    9         # should not inherit in this fashion however 
    10         # TODO: this fix might cause problems in the future. e.g. if the second level nav were exactly the same as the first level nav? 
     5def merge(a, b, dir=None, partialbuild=False): 
     6 
     7    if (isinstance(a, Y.sectionnav) and 
     8        isinstance(b, Y.sectionnav) and dir is not None): 
     9        # special case. If b is the same as a, it has been inhereited - 
     10        # sectionnav's should not inherit in this fashion however 
     11        # TODO: this fix might cause problems in the future. e.g. if 
     12        # the second level nav were exactly the same as the first level nav? 
    1113        if a == b: 
    1214            b = [] 
     
    1416            a = b 
    1517        else: 
    16             mergetrees.merge(a,b,dir) 
    17      
    18     elif isinstance(b,dict) and isinstance(a,dict): 
     18            mergetrees.merge(a, b, dir) 
     19 
     20    elif isinstance(b, dict) and isinstance(a, dict): 
    1921        for bkey in b.keys(): 
    2022            if a.has_key(bkey): 
    21                 a[bkey] = merge(a[bkey],b[bkey],dir,partialbuild=partialbuild) 
     23                a[bkey] = merge(a[bkey], b[bkey], dir, 
     24                                partialbuild=partialbuild) 
    2225            else: 
    2326                a[bkey] = b[bkey] 
     
    2730 
    2831class stackdict(dict): 
    29      
     32 
    3033    parent = None 
    31      
     34 
    3235    def __init__(self, parent=None): 
    3336        if parent is not None: 
    3437            self.parent = parent 
    35             merge(self,parent) 
    36          
     38            merge(self, parent) 
     39 
    3740    def popStack(self): 
    3841        return self.parent 
     
    4043# Test code: 
    4144if __name__ == "__main__": 
    42      
     45 
    4346    def keyval(text): 
    4447        ''' Factory to convert a string into key:val pair (split on last space) 
     
    4649        t = text.split(' ') 
    4750        return { ''.join(t[:-1]) : t[-1] } 
    48          
     51 
    4952    x = ''' 
    5053a: 1 
     
    5962b: 
    6063  x: 15 
    61   z:  
     64  z: 
    6265    p: 98 
    6366    q: 99 
    6467c: 3P0 
    6568    ''' 
    66      
    6769 
    68     xd = syck.load(x,Loader=Y.Loader, implicit_typing=false) 
    69     yd = syck.load(y,Loader=Y.Loader, implicit_typing=false) 
    70      
    71     z = merge(xd,yd) 
    72      
     70 
     71    xd = syck.load(x, Loader=Y.Loader, implicit_typing=False) 
     72    yd = syck.load(y, Loader=Y.Loader, implicit_typing=False) 
     73 
     74    z = merge(xd, yd) 
     75 
    7376    print z 
    74      
     77 
    7578    print '-------------------' 
    76      
     79 
    7780    d = stackdict() 
    7881    d['a'] = 1 
    79     d['b'] = {'x':1,'y':2 } 
     82    d['b'] = {'x':1, 'y':2 } 
    8083    print d 
    81      
     84 
    8285    d = stackdict(d) 
    8386    d['a'] = 2 
    8487    print d 
    85      
     88 
    8689    d = stackdict(d) 
    87     d['b'] = {'x':2,'y': {'p':4 } } 
     90    d['b'] = {'x':2, 'y': {'p':4 } } 
    8891    d['c'] = 100 
    8992    print d 
    90      
     93 
    9194    while 1: 
    9295        d = d.popStack() 
    9396        if d is None: 
    9497            break 
    95         print d     
     98        print d 
  • branches/tim/pyramid/flatteners.py

    r174 r175  
    2121    print '--- = Page ---------------' 
    2222    pprint(data) 
    23      
     23 
    2424# 
    2525# Flatteners adaption for different item types 
     
    4949    def flatten(self, ctx, dir): 
    5050        for value in self.original: 
    51             value = flatten(value, ctx, dir)    
     51            value = flatten(value, ctx, dir) 
    5252        return self.original 
    5353 
     
    5555    def flatten(self, ctx, dir): 
    5656        return T.xml(restParser.parse(self.original)['fragment']) 
    57      
     57 
    5858class RestFileFlattener(components.Adapter): 
    59     def flatten(self, ctx, dir):     
     59    def flatten(self, ctx, dir): 
    6060        try: 
    6161            restfile = os.path.join(dir,self.original) 
    6262            fp = open(restfile) 
    6363        except IOError: 
    64             print 'IOError whilst trying to open "restfile" %s'%(restfile)   
     64            print 'IOError whilst trying to open "restfile" %s'%(restfile) 
     65            raise 
    6566 
    6667        try: 
     
    7778            fp = open(htmlfile) 
    7879        except IOError: 
    79             print 'IOError whilst trying to open "htmlfile" %s'%(htmlfile)         
    80          
     80            print 'IOError whilst trying to open "htmlfile" %s'%(htmlfile) 
     81            raise 
     82 
    8183        return T.xml(fp.read()) 
    8284 
     
    8789    if filename[0] != '/' and filename[0:4] != 'http': 
    8890        filename = os.path.join(dir,filename) 
    89     return filename     
     91    return filename 
    9092 
    9193def getFilePointer(ctx,dir,filename): 
     
    9698    except IOError: 
    9799        print 'IOError whilst trying to open "htfile" %s'%(filename) 
     100        raise 
    98101    return fp 
    99102 
     
    101104    def flatten(self, ctx, dir): 
    102105        return T.xml(self.original) 
    103      
     106 
    104107class HtFileFlattener(components.Adapter): 
    105108    def flatten(self, ctx, dir): 
     
    110113        body = message.fp.read() 
    111114        if data.get('content-type',None) == 'text/x-rst': 
    112             return T.xml(restParser.parse(body)['fragment']) 
     115            fn = os.path.join(dir, self.original) 
     116            return T.xml(restParser.parse(body, fn)['fragment']) 
    113117        else: 
    114118            return T.xml(body) 
     
    149153            contents = '<strong>MoinMoin parse failed for %s - a wiki instance needs to be installed and the wikiconfig.py directory needs to be on the $PYTHONPATH</strong>'%url 
    150154        return T.xml(contents) 
    151          
     155 
    152156class AHrefFlattener(components.Adapter): 
    153157    def flatten(self, ctx, dir): 
     
    157161    def flatten(self, ctx, dir): 
    158162        return '/%s' % str(self.original) 
    159      
     163 
    160164class BreadcrumbFlattener(components.Adapter): 
    161165    def flatten(self, ctx, dir): 
     
    174178                    hook = item['children'] 
    175179                    break 
    176                      
     180 
    177181        return flatten(breadcrumb,ctx) 
    178182 
     
    194198def acquireTemplate(ctx,template): 
    195199    """ recursively ascends the data directory looking for an appropriate template 
    196     """  
     200    """ 
    197201    searchpath = ctx.path 
    198202    #overkill checking for search path infinite recursion 
     
    202206            break 
    203207        except IOError: 
    204             searchpath = searchpath.parent    
    205     return searchpath / template     
    206      
     208            searchpath = searchpath.parent 
     209    return searchpath / template 
     210 
    207211class FragmentFileFlattener(components.Adapter): 
    208212    ''' This is the core flattener that renders fragment types (which are template/data packets) 
     
    216220        if ctx.verbose > 1: 
    217221            print '=== Current Fragment ( %s )' % name 
    218          
     222 
    219223 
    220224        # get the parent data for the current file 
     
    248252            template = acquireTemplate(ctx,self.original.template) 
    249253            flattenedData = flatten( self.original.globals, ctx, dir ) 
    250             return T.xml(fragmentGenerate(ctx,dir,template,flattenedData))     
     254            return T.xml(fragmentGenerate(ctx,dir,template,flattenedData)) 
    251255        else: 
    252256            # Get the canonical directory and filename for this file 
    253257            dir,name = os.path.split(os.path.join(dir,self.original.file)) 
    254      
     258 
    255259            if ctx.verbose > 1: 
    256260                print '=== Current Fragment ( %s )' % name 
    257              
     261 
    258262            # get the parent data for the current file 
    259263            parentdata = getParentData(self,ctx,dir,name) 
     
    261265            # inherit data from parent and merge the result with any 'local' data 
    262266            mergedData = inheritAndMergeLocals(self,ctx,dir,name,self.original,parentdata) 
    263      
     267 
    264268            # Flatten the resultant data ready for use in the template 
    265269            flattenedMergedData = flatten( mergedData, ctx, dir ) 
    266      
     270 
    267271            if ctx.verbose > 2: 
    268272                logPageData(mergedData) 
    269      
     273 
    270274            # Search for the template in this directory and above 
    271275            template = acquireTemplate(ctx,self.original.template) 
     
    274278def getFragmentData(self,ctx,dir,name,parentdata): 
    275279    ''' Get the fragment data and assign it to self.original, preserving the filename 
    276     '''  
     280    ''' 
    277281    # Try to get the data out of the current ctx first (if it is there, it 
    278282    # must have come from the cache so return it 
     
    292296    ''' get the parents data for this .yml fie (or set it as an empty fragment if not available) 
    293297        this currently only looks 'up' one directory 
    294     '''  
     298    ''' 
    295299    parentpath = str(ctx.relpathparent) 
    296300    parentdata = copy.deepcopy(ctx.data.get(parentpath,{}).get(name,Y.fragment({}))) 
     
    330334    try: 
    331335        htmlfragment = page.Fragment(ctx, dir, template, data).generate() 
    332     except KeyError
     336    except KeyError, exc
    333337        print '*'*80 
    334338        print 'problem filling slot in template %s in directory %s'% (template,dir) 
     339        print "Exception value was", exc 
    335340        print '*'*80 
    336341        print '%s %s %s'%('*'*4,'template','*'*30) 
  • branches/tim/pyramid/mergetrees.py

    r50 r175  
    66    # create a pointer to the parent tree and initialise found 
    77    hook = ptree 
    8      
     8 
    99    if path: 
    1010        pathsegments = path.split('/') 
    1111    else: 
    1212        return 
    13          
     13 
    1414    # iterate on segments in the current path 
    1515    for depth,segment in enumerate( pathsegments ): 
     
    2626        # set the pointer to the found item's child list 
    2727        hook = found.get('children',[]) 
    28      
     28 
    2929    # (**a**) now we've got a pointer to the appropriate node, make each href 
    3030    # attribue in the child tree into an absolute path by adding the path to it 
    31     makePathsAbsolute(ctree,path)         
     31    makePathsAbsolute(ctree,path) 
    3232    addBreadcrumbData(ctree,found['data']) 
    33      
     33 
    3434    # add the child tree to the found node and make the found node selected 
    3535    found['children'] = ctree 
    3636    found['selected'] = 'selected' 
    37      
    38      
     37 
     38 
    3939def findChildenForKey(treelist,key): 
    4040    for item in treelist: 
     
    4242        if str(href) == key or ( isinstance(href,Y.rhref) and '/%s'%str(href) == key ) : 
    4343            return item 
    44              
     44 
    4545    return None 
    4646 
     
    5050        if isinstance(item['data']['href'],Y.rhref): 
    5151            item['data']['href'] = '/%s/%s' % (path,item['data']['href']) 
    52      
     52 
    5353def addBreadcrumbData(children,parentdata): 
    5454    for item in children: 
    5555        item['data']['breadcrumb'] = copy.deepcopy(parentdata.get('breadcrumb',[]) ) 
    5656        item['data']['breadcrumb'].append( Y.url( '%s %s' % (item['data']['label'],item['data']['href']) ) ) 
    57   
  • branches/tim/pyramid/mkpydir.py

    r133 r175  
    11import os 
    22from optparse import OptionParser 
    3 import shutil  
     3import shutil 
    44 
    55index_yml = """--- !fragment 
     
    4343    cyml.close() 
    4444 
    45      
     45 
    4646def mkpydir(directive,prefix,path,outputdir,copy,title): 
    4747    OUTPUTDIR = os.path.abspath(outputdir) 
    4848    if os.path.isdir(outputdir) is not True: 
    4949        os.mkdir(OUTPUTDIR) 
    50      
     50 
    5151    if directive == 'htfile': 
    52          
     52 
    5353        if copy is True: 
    5454            htfile = 'content.ht' 
     
    8484    chtml.write(content_html) 
    8585    chtml.close() 
    86      
     86 
    8787def main(options,args): 
    8888    if os.path.isdir(options.outputdir) and options.replace is True: 
    8989        shutil.rmtree(options.outputdir) 
    90          
     90 
    9191    mkpydir(options.type,options.dir,options.path,options.outputdir,options.copy,options.title) 
    9292 
     
    115115    parser.add_option("-c", "--copy", action="store_true", help="copy the htfile into the directory",dest="copy", metavar="COPY",default=True) 
    116116    (options, args) = parser.parse_args() 
    117     # further checking of options  
     117    # further checking of options 
    118118    if options.copy is not False: 
    119119        options.copy=True 
  • branches/tim/pyramid/page.py

    r174 r175  
    7272        return self.data 
    7373 
     74    # TODO understand what these are for and clean up in a nevow style 
     75    def render_stringify(self, ctx, data): 
     76        '''Turns the data into a string''' 
     77        return str(data) 
     78 
     79    def render_anchorify(self, ctx, data): 
     80        '''Turn the data into something suitable for an anchor''' 
     81        import string 
     82        nulltrans = string.maketrans('', '') 
     83        data = str(data).translate(nulltrans, """ ,'"<>&+:.""") 
     84        return data 
     85 
    7486    def render_tree(self,ctx,data): 
    7587        ''' custom renderer for a tree like data structure (ie with data and children keys) 
    76         '''  
     88        ''' 
    7789        pgen = getPatterns(ctx.tag) 
    78          
     90 
    7991        html = [] 
    8092        if data: 
     
    8496                for key in item['data'].keys(): 
    8597                    ptag.fillSlots(key,item['data'][key]) 
    86                  
     98 
    8799                selected = item.get('selected','') 
    88100                ptag.fillSlots('selected',selected) 
     
    90102            if html: 
    91103                html[-1] = html[-1][0] 
    92              
     104 
    93105            ctx.tag.fillSlots('items',html) 
    94106            return ctx.tag 
     
    111123            except ValueError: 
    112124                raise 'invalid slice values' 
    113                  
     125 
    114126            tag = context.tag 
    115127            headers = tag.allPatterns('header') 
     
    117129            divider = tag.patternGenerator('divider', default=tags.invisible) 
    118130            content = [(pattern(data=element), divider(data=element)) for element in data[int(start):int(end)]] 
    119              
     131 
    120132            if not content: 
    121133                content = tag.allPatterns('empty') 
     
    124136                content[-1] = content[-1][0] 
    125137            footers = tag.allPatterns('footer') 
    126          
     138 
    127139            return tag.clear()[ headers, content, footers ] 
    128140        return render 
     
    137149        except IndexError: 
    138150            raise FragmentError, 'An error has occured whilst building the breadcrumb trail. This usually occurs when a content template has a breadcrumb trail renderer but the parent nav.yml does not include a reference to the current templates directory. Use -V to find out more information about which page cause this error.' 
    139              
     151 
    140152        return tag 
    141      
     153 
    142154    def generate(self): 
    143155        ''' render the fragment 
    144156        ''' 
    145          
    146157        html = self.renderSynchronously() 
    147158        html = html.decode('utf8') 
     
    149160        if self.ctx.relativeurls == True: 
    150161            soup = BeautifulSoup(html) 
    151             map(absoluteToRelativeFactory('href',self.dir), soup('a') )  
    152             map(absoluteToRelativeFactory('src',self.dir), soup('img') )  
    153             map(absoluteToRelativeFactory('src',self.dir), soup('script') )  
    154             map(absoluteToRelativeFactory('href',self.dir), soup('link') )  
     162            map(absoluteToRelativeFactory('href',self.dir), soup('a') ) 
     163            map(absoluteToRelativeFactory('src',self.dir), soup('img') ) 
     164            map(absoluteToRelativeFactory('src',self.dir), soup('script') ) 
     165            map(absoluteToRelativeFactory('href',self.dir), soup('link') ) 
    155166            if self.ctx.prettify == True: 
    156167                html = soup.prettify(needUnicode=True).encode('utf8') 
  • branches/tim/pyramid/path.py

    r96 r175  
    323323        d.files('*.pyc'). 
    324324        """ 
    325          
     325 
    326326        return [p for p in self.listdir(pattern) if p.isfile()] 
    327327 
     
    805805        def startfile(self): 
    806806            os.startfile(self) 
    807  
  • branches/tim/pyramid/restParser.py

    r174 r175  
    6464      string is desired, use the default value of "unicode" . 
    6565    """ 
    66      
     66 
    6767    ALLOWKEYS = ['title','subtitle','fragment'] 
    6868    try: 
     
    7070    except: 
    7171        input_string = input_string.decode('iso-8859-1') 
    72          
     72 
    7373    parts = html_parts( 
    7474        input_string=input_string, source_path=source_path, 
     
    7676        input_encoding=input_encoding, doctitle=doctitle, 
    7777        initial_header_level=initial_header_level) 
    78      
    79      
     78 
     79 
    8080    if output_encoding != 'unicode': 
    8181        data = {} 
  • branches/tim/pyramid/test/tests.py

    r174 r175  
    2222    if os.path.exists(dir): 
    2323        removeTemp(dir) 
    24     os.mkdir(dir)      
     24    os.mkdir(dir) 
    2525 
    2626def tree_from_stream(stream, 
     
    9696    fh1 = StringIO(text1) 
    9797    fh2 = StringIO(text2) 
    98      
     98 
    9999    # convert xml files to tree 
    100100    try: 
     
    175175                        print filetext2 
    176176                        print '#'*80 
    177                         print '%s\n Differences in generated output for %s\n%s' % ('='*70,relpath / file,'='*70)   
     177                        print '%s\n Differences in generated output for %s\n%s' % ('='*70,relpath / file,'='*70) 
    178178                        from pprint import pprint 
    179179                        pprint(result) 
     
    183183 
    184184class test_yamlRegistry(unittest.TestCase): 
    185      
    186     def test_url(self):                           
     185 
     186    def test_url(self): 
    187187        """ url constructor 
    188188        """ 
     
    190190        expected = {'href':Y.ahref('/link'), 'label':'My Link'} 
    191191        self.assertEqual(data,expected) 
    192   
     192 
    193193 
    194194class test_flatteners(unittest.TestCase): 
    195      
    196     def test_ahref(self):                           
     195 
     196    def test_ahref(self): 
    197197        """ absolute href 
    198198        """ 
     
    201201        self.assertEqual(flatteners.flatten(data,ctx), '/about') 
    202202 
    203     def test_rhref(self):                           
     203    def test_rhref(self): 
    204204        """ relative href 
    205205        """ 
     
    208208        self.assertEqual(flatteners.flatten(data,ctx), '/about') 
    209209 
    210              
    211     def test_url(self):                           
     210 
     211    def test_url(self): 
    212212        """ url 
    213213        """ 
     
    216216        expected = {'href':'/link', 'label':'My Link'} 
    217217        self.assertEqual(flatteners.flatten(data,ctx),expected) 
    218   
     218 
    219219 
    220220class test_build(unittest.TestCase): 
    221      
     221 
    222222    buildtestroot = 'build_tests' 
    223223    buildtestpath = path.path(os.getcwd()) / 'pyramid' / 'test' / testdatadir / buildtestroot 
    224      
     224 
    225225    def setUp(self): 
    226226        """ Create test folders 
     
    228228        makeAndCleanTemp(TEMPFOLDER) 
    229229 
    230      
     230 
    231231    def test_basic(self): 
    232232