Changeset 175
- Timestamp:
- 04/05/06 20:01:43 (3 years ago)
- Files:
-
- branches/tim/pyramid/build.py (modified) (10 diffs)
- branches/tim/pyramid/core.py (modified) (1 diff)
- branches/tim/pyramid/dictutils.py (modified) (6 diffs)
- branches/tim/pyramid/flatteners.py (modified) (19 diffs)
- branches/tim/pyramid/mergetrees.py (modified) (4 diffs)
- branches/tim/pyramid/mkpydir.py (modified) (4 diffs)
- branches/tim/pyramid/page.py (modified) (8 diffs)
- branches/tim/pyramid/path.py (modified) (2 diffs)
- branches/tim/pyramid/restParser.py (modified) (3 diffs)
- branches/tim/pyramid/test/tests.py (modified) (11 diffs)
- branches/tim/pyramid/utils.py (modified) (9 diffs)
- branches/tim/pyramid/yamlRegistry.py (modified) (13 diffs)
Legend:
- Unmodified
- Added
- Removed
- Modified
- Copied
- Moved
branches/tim/pyramid/build.py
r174 r175 11 11 import shutil 12 12 import syck 13 import traceback 14 from os.path import join as opjoin 15 16 17 class OptionError(Exception): 18 pass 13 19 14 20 try: … … 20 26 class Dumper(syck.Dumper): 21 27 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): 24 31 return syck.Scalar(flat.flatten(object)) 25 32 def allow_aliases(self, object): … … 27 34 28 35 29 def build(data,out,verbose=0,resourcedirs=[],rebuilddirs=None,partialbuild=False,constants=None,update=False,relativeurls=False,prettify=False): 36 def build(data, out, verbose=0, resourcedirs=[], rebuilddirs=None, 37 partialbuild=False, constants=None, update=False, 38 relativeurls=False, prettify=False, createcache=False, keepgoing=False): 30 39 31 40 DATADIR = os.path.abspath(data) 32 41 OUTPUTDIR = os.path.abspath(out) 33 42 34 43 # check to see if the output directory exists 35 44 if not os.path.exists(OUTPUTDIR): … … 38 47 os.mkdir(OUTPUTDIR) 39 48 except: 40 raise Error, 'Could not create output directory'49 raise OptionError('Could not create output directory') 41 50 else: 42 51 if not os.path.isdir(OUTPUTDIR): 43 raise Error, 'OUTPUTDIR is not a directory'44 52 raise OptionError('OUTPUTDIR is not a directory') 53 45 54 # 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 49 59 # dangerous remove directory contents function 50 60 if partialbuild is False and rebuilddirs is None: 51 61 utils.recursiveRemoveDirectoryContents(OUTPUTDIR) 52 62 53 63 # copy in any resources needed 54 64 for resourcedir in resourcedirs: 55 65 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']) 57 68 58 69 # change the working directory 59 70 os.chdir(DATADIR) 60 71 basedir = path(DATADIR) 61 72 62 73 # initialise a context 63 74 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) 65 77 ctx.data = { '': {} } 66 78 # set the verbose option … … 70 82 # set constants 71 83 ctx.constants = constants 72 # set relative urls flag 84 # set relative urls flag 73 85 ctx.relativeurls = relativeurls 74 86 # set prettify flag 75 87 ctx.prettify=prettify 76 88 77 89 for root, dirs, files in os.walk('.'): 78 90 79 91 # get the path directory 80 92 ctx.path = path(root).abspath() 81 93 ctx.relpath = path(basedir).relpathto(root) 82 94 ctx.relpathparent = path(basedir).relpathto(ctx.path.parent) 83 95 84 96 # ignore svn folders 85 97 try: … … 87 99 except: 88 100 pass 89 101 90 102 # if the target directory is not available, create it 91 if not os.path.isdir(o s.path.join(OUTPUTDIR,root)):92 os.mkdir(o s.path.join(OUTPUTDIR,root))103 if not os.path.isdir(opjoin(OUTPUTDIR, root)): 104 os.mkdir(opjoin(OUTPUTDIR, root)) 93 105 94 106 for f in files: 95 107 suffix = os.path.splitext(f)[1] 96 108 if suffix not in PYRAMIDSUFFIXES: 97 srcfile = o s.path.join(ctx.path,f)98 targetfile = o s.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 101 113 # create the html from the index.yml fragment 102 114 if root != '.': … … 106 118 cachepath = outroot/'.cache.dump' 107 119 cachepathparent = outroot.parent /'.cache.dump' 108 109 120 121 110 122 # check to see if the current directory is in the rebuild dirs list 111 123 matchesRebuildDir = False … … 115 127 matchesRebuildDir = True 116 128 break 117 129 118 130 # check for nobuild 119 131 nobuild = path(root) / 'NOBUILD' 120 132 if nobuild.isfile(): 121 utils.copytree(root,os.path.join(OUTPUTDIR,root),nocopylist=['.svn']) 133 utils.copytree(root, opjoin(OUTPUTDIR, root), 134 nocopylist=['.svn']) 122 135 continue 123 124 125 if os.path.exists( cachepath) and partialbuild:136 137 138 if os.path.exists(cachepath) and partialbuild: 126 139 ctx = pickle.load(open(cachepath)) 127 140 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) 130 144 else: 131 145 if matchesRebuildDir: 132 146 ctx.data = pickle.load(open(cachepathparent)).data 133 147 134 148 if matchesRebuildDir or rebuilddirs is None: 135 149 if ctx.verbose > 0: … … 137 151 138 152 ctx.partialbuild = False 139 153 140 154 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)]) 142 158 except KeyError: 143 159 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.' 146 164 print 'The current data for this page is shown above' 147 165 148 166 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) 151 180 if createcache: 152 pickle.dump(ctx, open(cachepath,'w'))181 pickle.dump(ctx, open(cachepath, 'w')) 153 182 else: 154 183 if ctx.verbose > 1: 155 184 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 187 def main(options, args): 162 188 if options.resources: 163 189 resourcedirs = options.resources.split(',') 164 190 else: 165 191 resourcedirs = [] 166 192 167 193 if options.rebuilddirs: 168 194 rebuilddirs = options.rebuilddirs.strip().split(',') 169 195 else: 170 rebuilddirs = None 196 rebuilddirs = None 171 197 172 198 if options.constants: … … 180 206 constants[key]=value 181 207 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) 195 215 196 216 197 217 def parseOptions(): 198 218 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") 211 255 (options, args) = parser.parse_args() 212 main(options, args)256 main(options, args) 213 257 214 258 if __name__ == "__main__": branches/tim/pyramid/core.py
r149 r175 13 13 self.verbose = node.get('verbose',False) 14 14 self.root = path(node.get('root','')) 15 15 16 16 def __eq__(self,other): 17 17 return self.data == other.data 18 18 19 19 def __ne__(self,other): 20 20 return self.data != self.data branches/tim/pyramid/dictutils.py
r96 r175 3 3 import mergetrees 4 4 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? 5 def 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? 11 13 if a == b: 12 14 b = [] … … 14 16 a = b 15 17 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): 19 21 for bkey in b.keys(): 20 22 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) 22 25 else: 23 26 a[bkey] = b[bkey] … … 27 30 28 31 class stackdict(dict): 29 32 30 33 parent = None 31 34 32 35 def __init__(self, parent=None): 33 36 if parent is not None: 34 37 self.parent = parent 35 merge(self, parent)36 38 merge(self, parent) 39 37 40 def popStack(self): 38 41 return self.parent … … 40 43 # Test code: 41 44 if __name__ == "__main__": 42 45 43 46 def keyval(text): 44 47 ''' Factory to convert a string into key:val pair (split on last space) … … 46 49 t = text.split(' ') 47 50 return { ''.join(t[:-1]) : t[-1] } 48 51 49 52 x = ''' 50 53 a: 1 … … 59 62 b: 60 63 x: 15 61 z: 64 z: 62 65 p: 98 63 66 q: 99 64 67 c: 3P0 65 68 ''' 66 67 69 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 73 76 print z 74 77 75 78 print '-------------------' 76 79 77 80 d = stackdict() 78 81 d['a'] = 1 79 d['b'] = {'x':1, 'y':2 }82 d['b'] = {'x':1, 'y':2 } 80 83 print d 81 84 82 85 d = stackdict(d) 83 86 d['a'] = 2 84 87 print d 85 88 86 89 d = stackdict(d) 87 d['b'] = {'x':2, 'y': {'p':4 } }90 d['b'] = {'x':2, 'y': {'p':4 } } 88 91 d['c'] = 100 89 92 print d 90 93 91 94 while 1: 92 95 d = d.popStack() 93 96 if d is None: 94 97 break 95 print d 98 print d branches/tim/pyramid/flatteners.py
r174 r175 21 21 print '--- = Page ---------------' 22 22 pprint(data) 23 23 24 24 # 25 25 # Flatteners adaption for different item types … … 49 49 def flatten(self, ctx, dir): 50 50 for value in self.original: 51 value = flatten(value, ctx, dir) 51 value = flatten(value, ctx, dir) 52 52 return self.original 53 53 … … 55 55 def flatten(self, ctx, dir): 56 56 return T.xml(restParser.parse(self.original)['fragment']) 57 57 58 58 class RestFileFlattener(components.Adapter): 59 def flatten(self, ctx, dir): 59 def flatten(self, ctx, dir): 60 60 try: 61 61 restfile = os.path.join(dir,self.original) 62 62 fp = open(restfile) 63 63 except IOError: 64 print 'IOError whilst trying to open "restfile" %s'%(restfile) 64 print 'IOError whilst trying to open "restfile" %s'%(restfile) 65 raise 65 66 66 67 try: … … 77 78 fp = open(htmlfile) 78 79 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 81 83 return T.xml(fp.read()) 82 84 … … 87 89 if filename[0] != '/' and filename[0:4] != 'http': 88 90 filename = os.path.join(dir,filename) 89 return filename 91 return filename 90 92 91 93 def getFilePointer(ctx,dir,filename): … … 96 98 except IOError: 97 99 print 'IOError whilst trying to open "htfile" %s'%(filename) 100 raise 98 101 return fp 99 102 … … 101 104 def flatten(self, ctx, dir): 102 105 return T.xml(self.original) 103 106 104 107 class HtFileFlattener(components.Adapter): 105 108 def flatten(self, ctx, dir): … … 110 113 body = message.fp.read() 111 114 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']) 113 117 else: 114 118 return T.xml(body) … … 149 153 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 150 154 return T.xml(contents) 151 155 152 156 class AHrefFlattener(components.Adapter): 153 157 def flatten(self, ctx, dir): … … 157 161 def flatten(self, ctx, dir): 158 162 return '/%s' % str(self.original) 159 163 160 164 class BreadcrumbFlattener(components.Adapter): 161 165 def flatten(self, ctx, dir): … … 174 178 hook = item['children'] 175 179 break 176 180 177 181 return flatten(breadcrumb,ctx) 178 182 … … 194 198 def acquireTemplate(ctx,template): 195 199 """ recursively ascends the data directory looking for an appropriate template 196 """ 200 """ 197 201 searchpath = ctx.path 198 202 #overkill checking for search path infinite recursion … … 202 206 break 203 207 except IOError: 204 searchpath = searchpath.parent 205 return searchpath / template 206 208 searchpath = searchpath.parent 209 return searchpath / template 210 207 211 class FragmentFileFlattener(components.Adapter): 208 212 ''' This is the core flattener that renders fragment types (which are template/data packets) … … 216 220 if ctx.verbose > 1: 217 221 print '=== Current Fragment ( %s )' % name 218 222 219 223 220 224 # get the parent data for the current file … … 248 252 template = acquireTemplate(ctx,self.original.template) 249 253 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)) 251 255 else: 252 256 # Get the canonical directory and filename for this file 253 257 dir,name = os.path.split(os.path.join(dir,self.original.file)) 254 258 255 259 if ctx.verbose > 1: 256 260 print '=== Current Fragment ( %s )' % name 257 261 258 262 # get the parent data for the current file 259 263 parentdata = getParentData(self,ctx,dir,name) … … 261 265 # inherit data from parent and merge the result with any 'local' data 262 266 mergedData = inheritAndMergeLocals(self,ctx,dir,name,self.original,parentdata) 263 267 264 268 # Flatten the resultant data ready for use in the template 265 269 flattenedMergedData = flatten( mergedData, ctx, dir ) 266 270 267 271 if ctx.verbose > 2: 268 272 logPageData(mergedData) 269 273 270 274 # Search for the template in this directory and above 271 275 template = acquireTemplate(ctx,self.original.template) … … 274 278 def getFragmentData(self,ctx,dir,name,parentdata): 275 279 ''' Get the fragment data and assign it to self.original, preserving the filename 276 ''' 280 ''' 277 281 # Try to get the data out of the current ctx first (if it is there, it 278 282 # must have come from the cache so return it … … 292 296 ''' get the parents data for this .yml fie (or set it as an empty fragment if not available) 293 297 this currently only looks 'up' one directory 294 ''' 298 ''' 295 299 parentpath = str(ctx.relpathparent) 296 300 parentdata = copy.deepcopy(ctx.data.get(parentpath,{}).get(name,Y.fragment({}))) … … 330 334 try: 331 335 htmlfragment = page.Fragment(ctx, dir, template, data).generate() 332 except KeyError :336 except KeyError, exc: 333 337 print '*'*80 334 338 print 'problem filling slot in template %s in directory %s'% (template,dir) 339 print "Exception value was", exc 335 340 print '*'*80 336 341 print '%s %s %s'%('*'*4,'template','*'*30) branches/tim/pyramid/mergetrees.py
r50 r175 6 6 # create a pointer to the parent tree and initialise found 7 7 hook = ptree 8 8 9 9 if path: 10 10 pathsegments = path.split('/') 11 11 else: 12 12 return 13 13 14 14 # iterate on segments in the current path 15 15 for depth,segment in enumerate( pathsegments ): … … 26 26 # set the pointer to the found item's child list 27 27 hook = found.get('children',[]) 28 28 29 29 # (**a**) now we've got a pointer to the appropriate node, make each href 30 30 # attribue in the child tree into an absolute path by adding the path to it 31 makePathsAbsolute(ctree,path) 31 makePathsAbsolute(ctree,path) 32 32 addBreadcrumbData(ctree,found['data']) 33 33 34 34 # add the child tree to the found node and make the found node selected 35 35 found['children'] = ctree 36 36 found['selected'] = 'selected' 37 38 37 38 39 39 def findChildenForKey(treelist,key): 40 40 for item in treelist: … … 42 42 if str(href) == key or ( isinstance(href,Y.rhref) and '/%s'%str(href) == key ) : 43 43 return item 44 44 45 45 return None 46 46 … … 50 50 if isinstance(item['data']['href'],Y.rhref): 51 51 item['data']['href'] = '/%s/%s' % (path,item['data']['href']) 52 52 53 53 def addBreadcrumbData(children,parentdata): 54 54 for item in children: 55 55 item['data']['breadcrumb'] = copy.deepcopy(parentdata.get('breadcrumb',[]) ) 56 56 item['data']['breadcrumb'].append( Y.url( '%s %s' % (item['data']['label'],item['data']['href']) ) ) 57 branches/tim/pyramid/mkpydir.py
r133 r175 1 1 import os 2 2 from optparse import OptionParser 3 import shutil 3 import shutil 4 4 5 5 index_yml = """--- !fragment … … 43 43 cyml.close() 44 44 45 45 46 46 def mkpydir(directive,prefix,path,outputdir,copy,title): 47 47 OUTPUTDIR = os.path.abspath(outputdir) 48 48 if os.path.isdir(outputdir) is not True: 49 49 os.mkdir(OUTPUTDIR) 50 50 51 51 if directive == 'htfile': 52 52 53 53 if copy is True: 54 54 htfile = 'content.ht' … … 84 84 chtml.write(content_html) 85 85 chtml.close() 86 86 87 87 def main(options,args): 88 88 if os.path.isdir(options.outputdir) and options.replace is True: 89 89 shutil.rmtree(options.outputdir) 90 90 91 91 mkpydir(options.type,options.dir,options.path,options.outputdir,options.copy,options.title) 92 92 … … 115 115 parser.add_option("-c", "--copy", action="store_true", help="copy the htfile into the directory",dest="copy", metavar="COPY",default=True) 116 116 (options, args) = parser.parse_args() 117 # further checking of options 117 # further checking of options 118 118 if options.copy is not False: 119 119 options.copy=True branches/tim/pyramid/page.py
r174 r175 72 72 return self.data 73 73 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 74 86 def render_tree(self,ctx,data): 75 87 ''' custom renderer for a tree like data structure (ie with data and children keys) 76 ''' 88 ''' 77 89 pgen = getPatterns(ctx.tag) 78 90 79 91 html = [] 80 92 if data: … … 84 96 for key in item['data'].keys(): 85 97 ptag.fillSlots(key,item['data'][key]) 86 98 87 99 selected = item.get('selected','') 88 100 ptag.fillSlots('selected',selected) … … 90 102 if html: 91 103 html[-1] = html[-1][0] 92 104 93 105 ctx.tag.fillSlots('items',html) 94 106 return ctx.tag … … 111 123 except ValueError: 112 124 raise 'invalid slice values' 113 125 114 126 tag = context.tag 115 127 headers = tag.allPatterns('header') … … 117 129 divider = tag.patternGenerator('divider', default=tags.invisible) 118 130 content = [(pattern(data=element), divider(data=element)) for element in data[int(start):int(end)]] 119 131 120 132 if not content: 121 133 content = tag.allPatterns('empty') … … 124 136 content[-1] = content[-1][0] 125 137 footers = tag.allPatterns('footer') 126 138 127 139 return tag.clear()[ headers, content, footers ] 128 140 return render … … 137 149 except IndexError: 138 150 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 140 152 return tag 141 153 142 154 def generate(self): 143 155 ''' render the fragment 144 156 ''' 145 146 157 html = self.renderSynchronously() 147 158 html = html.decode('utf8') … … 149 160 if self.ctx.relativeurls == True: 150 161 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') ) 155 166 if self.ctx.prettify == True: 156 167 html = soup.prettify(needUnicode=True).encode('utf8') branches/tim/pyramid/path.py
r96 r175 323 323 d.files('*.pyc'). 324 324 """ 325 325 326 326 return [p for p in self.listdir(pattern) if p.isfile()] 327 327 … … 805 805 def startfile(self): 806 806 os.startfile(self) 807 branches/tim/pyramid/restParser.py
r174 r175 64 64 string is desired, use the default value of "unicode" . 65 65 """ 66 66 67 67 ALLOWKEYS = ['title','subtitle','fragment'] 68 68 try: … … 70 70 except: 71 71 input_string = input_string.decode('iso-8859-1') 72 72 73 73 parts = html_parts( 74 74 input_string=input_string, source_path=source_path, … … 76 76 input_encoding=input_encoding, doctitle=doctitle, 77 77 initial_header_level=initial_header_level) 78 79 78 79 80 80 if output_encoding != 'unicode': 81 81 data = {} branches/tim/pyramid/test/tests.py
r174 r175 22 22 if os.path.exists(dir): 23 23 removeTemp(dir) 24 os.mkdir(dir) 24 os.mkdir(dir) 25 25 26 26 def tree_from_stream(stream, … … 96 96 fh1 = StringIO(text1) 97 97 fh2 = StringIO(text2) 98 98 99 99 # convert xml files to tree 100 100 try: … … 175 175 print filetext2 176 176 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) 178 178 from pprint import pprint 179 179 pprint(result) … … 183 183 184 184 class test_yamlRegistry(unittest.TestCase): 185 186 def test_url(self): 185 186 def test_url(self): 187 187 """ url constructor 188 188 """ … … 190 190 expected = {'href':Y.ahref('/link'), 'label':'My Link'} 191 191 self.assertEqual(data,expected) 192 192 193 193 194 194 class test_flatteners(unittest.TestCase): 195 196 def test_ahref(self): 195 196 def test_ahref(self): 197 197 """ absolute href 198 198 """ … … 201 201 self.assertEqual(flatteners.flatten(data,ctx), '/about') 202 202 203 def test_rhref(self): 203 def test_rhref(self): 204 204 """ relative href 205 205 """ … … 208 208 self.assertEqual(flatteners.flatten(data,ctx), '/about') 209 209 210 211 def test_url(self): 210 211 def test_url(self): 212 212 """ url 213 213 """ … … 216 216 expected = {'href':'/link', 'label':'My Link'} 217 217 self.assertEqual(flatteners.flatten(data,ctx),expected) 218 218 219 219 220 220 class test_build(unittest.TestCase): 221 221 222 222 buildtestroot = 'build_tests' 223 223 buildtestpath = path.path(os.getcwd()) / 'pyramid' / 'test' / testdatadir / buildtestroot 224 224 225 225 def setUp(self): 226 226 """ Create test folders … … 228 228 makeAndCleanTemp(TEMPFOLDER) 229 229 230 230 231 231 def test_basic(self): 232 232
