def get_code_spline(d, k=1, vector_valued=False, vectorized=False, allocate=False, grid_types=None, extrap_mode=None, orders=None): if orders is None: orders = (0,)*d # bases function to compute for each dimension if isinstance(orders, tuple): oo = [orders] else: oo = orders bases_orders = [sorted(list(set(e))) for e in zip(*oo)] if grid_types is None: grid_types = ['uniform']*d if set(grid_types) != set(['uniform']) and k>1: raise Exception("Nonuniform grids are only supported for linear splines.") templ = tempita.Template(template_linear) templ_vec = tempita.Template(template_linear_vectorized) if vectorized: template = templ_vec else: template = templ code = ( template.substitute(d=d, vector_valued=vector_valued, get_values=get_values, allocate=allocate, grid_types=grid_types, extrap_mode=extrap_mode, orders=orders, bases_orders=bases_orders, blending_formula=blending_formula, indent=indent, k=k) ) return (code)[1:]
def generate(switch, model_id): model = config.models[model_id] mgmt, vlanid = parse_metadata(switch) if mgmt is None: raise Exception("The switch " + switch + " was not found in ipplan") if radius is None: raise Exception("Radius key not set") if username is None: raise Exception("Username not set") if password is None: raise Exception("User-password not set") if enable is None: raise Exception("Enable password not set") if snmp_ro is None: raise Exception("SNMP ro not set") if snmp_salt is None: raise Exception("SNMP salt not set") # # Template function definition # cfg = tempita.Template(open(model.template).read()) cfg_subbed = cfg.substitute( hostname=switch, model=model, mgmt_ip=mgmt['ip'], mgmt_mask=mgmt['mask'], mgmt_mask_cidr=mgmt['mask_cidr'], mgmt_gw=mgmt['gw'], mgmt_vlanid=mgmt['vlanid'], vlanid=vlanid, wifi_switches=config.wifi_switches, wifi_vlanid=config.wifi_vlanid, password=config.password, password_sha512=sha512_crypt.hash(config.password), enable=config.enable, enable_sha512=sha512_crypt.hash(config.enable), radius=config.radius, snmp_ro=config.snmp_ro, snmp_rw=hashlib.sha1((config.snmp_salt + mgmt['ip']).encode()).hexdigest(), ipplan_host=lambda h: ipplan_host(h), ipplan_pkg=lambda p: ipplan_package(p), # snmp_user=config.snmp_user, # snmp_auth=config.snmp_auth, # snmp_priv=config.snmp_priv ) # We make the Juniper config a script, to be able to add the crontab. if "Juniper" in model_id: jcfg = tempita.Template(open(os.path.join(os.path.dirname(sys.argv[0]), 'juniper.sh.template')).read()) cfg_subbed = jcfg.substitute(config=cfg_subbed) return cfg_subbed
def make_course_rdf(taught_data): """ Given taught_data, generate the RDF for a course, a teacher role and links between course, teacher role and instructor """ import tempita from vivofoundation import get_vivo_uri from datetime import datetime course_rdf_template = tempita.Template(""" <rdf:Description rdf:about="{{course_uri}}"> <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Thing"/> <rdf:type rdf:resource="http://vivo.ufl.edu/ontology/vivo-ufl/Course"/> <rdf:type rdf:resource="http://vivo.ufl.edu/ontology/vivo-ufl/UFEntity"/> <rdfs:label>{{course_name}}</rdfs:label> <ufVivo:courseNum>{{course_number}}</ufVivo:courseNum> <ufVivo:harvestedBy>Python Courses version 0.5</ufVivo:harvestedBy> <ufVivo:dateHarvested>{{harvest_datetime}}</ufVivo:dateHarvested> </rdf:Description>""") course_uri = get_vivo_uri() rdf = course_rdf_template.substitute( course_uri=course_uri, course_name=taught_data['course_name'], course_number=taught_data['course_number'], harvest_datetime=datetime.now().isoformat(), person_uri=taught_data['person_uri']) return [rdf, course_uri]
def get_reader(self, backend, kernel_params, mac=None, **extra): """Render a configuration file as a unicode string. :param backend: requesting backend :param kernel_params: An instance of `KernelParameters`. :param mac: Optional MAC address discovered by `match_path`. :param extra: Allow for other arguments. This is a safety valve; parameters generated in another component (for example, see `TFTPBackend.get_boot_method_reader`) won't cause this to break. """ template = self.get_template( kernel_params.purpose, kernel_params.arch, kernel_params.subarch ) namespace = self.compose_template_namespace(kernel_params) def kernel_command(params): cmd_line = compose_kernel_command_line(params) # Modify the kernel_command to inject the BOOTIF. S390X doesn't # support the IPAPPEND pxelinux flag. if mac is not None: return "%s BOOTIF=%s" % (cmd_line, format_bootif(mac)) return cmd_line namespace["kernel_command"] = kernel_command # We are going to do 2 passes of tempita substitution because there # may be things like kernel params which include variables that can # only be populated at run time and thus contain variables themselves. # For example, an OS may need a kernel parameter that points back to # fs_host and the kernel parameter comes through as part of the simple # stream. step1 = template.substitute(namespace) return BytesReader( tempita.Template(step1).substitute(namespace).encode("utf-8") )
def generate(switch, model_id): model = config.models[model_id] mgmt, vlanid = parse_metadata(switch) if mgmt is None: raise Exception("The switch " + switch + " was not found in ipplan") cfg = tempita.Template(file(model.template).read()) return \ cfg.substitute( hostname=switch, model=model, mgmt_ip=mgmt['ip'], mgmt_mask=mgmt['mask'], mgmt_gw=mgmt['gw'], mgmt_vlanid=mgmt['vlanid'], vlanid=vlanid, wifi_switches=config.wifi_switches, wifi_vlanid=config.wifi_vlanid, password=config.password, enable=config.enable, radius=config.radius, snmp_ro=config.snmp_ro, snmp_rw=hashlib.sha1(config.snmp_salt + mgmt['ip']).hexdigest(), # snmp_user=config.snmp_user, # snmp_auth=config.snmp_auth, # snmp_priv=config.snmp_priv )
def __init__(self, stream, **kw): self._output = stream self.data = tempita.bunch( filename=self._output.name, today=datetime.date.today(), **kw ) try: import pkg_resources template_txt = pkg_resources.resource_string('fatghol', 'template.tex') except ImportError: # try to open in current directory if os.path.exists('template.tex') and os.path.isfile('template.tex'): with open('template.tex', 'r') as template_file: template_txt = template_file.read() else: raise self._template = tempita.Template( template_txt, delimeters=('<<', '>>'), name='fatghol/template.tex', namespace=self.data, ) self._total_graphs = 0 self._total_marked_graphs = 0 # document appendices self._appendix_graph_markings = None
def __call__(self, entries, args, size=50): """Generates items.""" filename = args[0] link = args[1] title = args[2] description = ' '.join(args[3:]) entries = entries[:size] data = { 'entries': entries, 'channel': { 'title': title, 'description': description, 'link': link } } template = tempita.Template(unicode(open(tmpl).read())) content = template.substitute(**data) f = open(filename, 'w') try: f.write(content.encode('utf-8')) finally: f.close()
def get_reader(self, backend, kernel_params, **extra): """Render a configuration file as a unicode string. :param backend: requesting backend :param kernel_params: An instance of `KernelParameters`. :param extra: Allow for other arguments. This is a safety valve; parameters generated in another component (for example, see `TFTPBackend.get_boot_method_reader`) won't cause this to break. """ template = self.get_template( kernel_params.purpose, kernel_params.arch, kernel_params.subarch ) kernel_params.mac = extra.get("mac", "") namespace = self.compose_template_namespace(kernel_params) # We are going to do 2 passes of tempita substitution because there # may be things like kernel params which include variables that can # only be populated at run time and thus contain variables themselves. # For example, an OS may need a kernel parameter that points back to # fs_host and the kernel parameter comes through as part of # the simplestream. step1 = template.substitute(namespace) return BytesReader( tempita.Template(step1).substitute(namespace).encode("utf-8") )
def renderTemplate(templateFile,data,outputFile): '''Renders a template from a templateFile with data to an outputFile''' # read template file into a string. some engines requires this. if not os.path.isfile( templateFile ): raise IOError( "file '"+templateFile+"' does not exist") templateText = "" with open( templateFile ) as f: templateText = f.read() # make sure we are not going to overwrite template file if outputFile == templateFile: raise IOError( "Output file (%s) would overwrite template file (%s)" % (outputFile,templateFile) ) # check if we are going to overwrite existing file if outputFile != '/dev/stdout' and not args.overwrite and os.path.isfile( outputFile ): print "output file '"+outputFile+"' exists, please delete, move, or rerun with --overwrite option" sys.exit(1) # render with open( outputFile, "w" ) as f: if args.engine == 'ctemplate': f.write( _ctemplate.compile_template( templateText, data ) ) if args.engine == 'mako': t = mako.template.Template(filename=templateFile) f.write( t.render( **data ) ) if args.engine == 'jinja': t = jinja2.Template(templateText) f.write( t.render( **data ) ) if args.engine == 'Tempita': t = tempita.Template(templateText) f.write( t.substitute( **data ) )
def setUp(self): self.destination_file = tempfile.NamedTemporaryFile() self.addCleanup(self.destination_file.close) self.template = tempita.Template('{{foo}}, {{bar}}') with tempfile.NamedTemporaryFile(delete=False) as template_file: template_file.write(self.template.content) self.template_path = template_file.name self.addCleanup(os.remove, self.template_path)
def generate(args, invocations): header_title = "API" if args.libsel4: header_title = "LIBSEL4" if args.arch: template = tempita.Template(ARCH_INVOCATION_TEMPLATE) else: template = tempita.Template(INVOCATION_TEMPLATE) args.dest.write( template.substitute(header_title=header_title, libsel4=args.libsel4, invocations=invocations)) args.dest.close()
def blending_formula(k=1, l=0, i=0): """ k: spline order l: diff order i: current dimension """ if k == 1: if l == 0: s = f"""\ Φ_{i}_{0} = 1.0 - λ_{i} Φ_{i}_{1} = λ_{i}""" elif l == 1: s = f"""\ d_Φ_{i}_{0} = -1.0*δ_{i} d_Φ_{i}_{1} = 1.0*δ_{i}""" else: s = f""" d_{l}_Φ_{i}_{0} = 0.0 d_{l}_Φ_{i}_{1} = 0.0""" elif k == 3: import tempita if l == 0: template_0 = """ μ_{{i}}_0 = λ_{{i}}*λ_{{i}}*λ_{{i}}; μ_{{i}}_1 = λ_{{i}}*λ_{{i}}; μ_{{i}}_2 = λ_{{i}}; μ_{{i}}_3 = 1.0; """ phi = lambda i, j: "Φ_{}_{}".format(i, j) elif l == 1: template_0 = """ μ_{{i}}_0 = 3*λ_{{i}}*λ_{{i}}*δ_{{i}}; μ_{{i}}_1 = 2*λ_{{i}}*δ_{{i}}; μ_{{i}}_2 = δ_{{i}}; μ_{{i}}_3 = 0.0; """ phi = lambda i, j: "d_Φ_{}_{}".format(i, j) else: raise Exception("Not implemented") template = tempita.Template(template_0 + """ {{for j in range(4)}} {{phi(i,j)}}= 0.0 {{endfor}} if λ_{{i}} < 0: {{for j in range(4)}} {{phi(i,j)}} = dCd[{{j}},3]*μ_{{i}}_2 + Cd[{{j}},3]*μ_{{i}}_3 {{endfor}} elif λ_{{i}} > 1: {{for j in range(4)}} {{phi(i,j)}} = (3*Cd[{{j}},0] + 2*Cd[{{j}},1] + Cd[{{j}},2])*(μ_{{i}}_2-μ_{{i}}_3) + (Cd[{{j}},0]+Cd[{{j}},1]+Cd[{{j}},2]+Cd[{{j}},3])*μ_{{i}}_3 {{endfor}} else: {{for j in range(4)}} {{phi(i,j)}} = (Cd[{{j}},0]*μ_{{i}}_0 + Cd[{{j}},1]*μ_{{i}}_1 + Cd[{{j}},2]*μ_{{i}}_2 + Cd[{{j}},3]*μ_{{i}}_3) {{endfor}} """) s = template.substitute(i=i, phi=phi) else: raise Exception(f"Spline order {k} not implemented.") return s
def get_code_spline( d, k=1, vector_valued=False, vectorized=False, allocate=False, grid_types=None, extrap_mode=None, orders=None, ): if orders is None: bases_orders = [(0, )] * d else: bases_orders = [sorted(list(set(e))) for e in zip(*orders)] if grid_types is None: grid_types = ["uniform"] * d if set(grid_types) != set(["uniform"]) and k > 1: raise Exception( "Nonuniform grids are only supported for linear splines.") templ = tempita.Template(eval_template) templ_vec = tempita.Template(eval_template_vectorized) if vectorized: template = templ_vec else: template = templ code = template.substitute( d=d, vector_valued=vector_valued, get_values=get_values, allocate=allocate, grid_types=grid_types, extrap_mode=extrap_mode, orders=orders, bases_orders=bases_orders, blending_formula=blending_formula, indent=indent, k=k, ) return (code)[1:]
def generate(args, invocations): header_title = "LIBRUSTSEL4" template = tempita.Template(INVOCATION_TEMPLATE) args.dest.write( template.substitute(header_title=header_title, invocations=invocations)) args.dest.close()
def make_section_rdf(taught_data): """ Given teaching data, make a section and a teaching role. Link the section to its teaching role, to its course and term. Link the role to the instructor. """ from vivofoundation import get_vivo_uri import tempita from datetime import datetime section_rdf_template = tempita.Template(""" <rdf:Description rdf:about="{{section_uri}}"> <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Thing"/> <rdf:type rdf:resource="http://vivo.ufl.edu/ontology/vivo-ufl/CourseSection"/> <rdf:type rdf:resource="http://vivo.ufl.edu/ontology/vivo-ufl/UFEntity"/> <rdfs:label>{{section_name}}</rdfs:label> <ufVivo:sectionNum>{{section_number}}</ufVivo:sectionNum> <vivo:dateTimeInterval rdf:resource="{{term_uri}}"/> <ufVivo:sectionForCourse rdf:resource="{{course_uri}}"/> <ufVivo:harvestedBy>Python Courses version 0.5</ufVivo:harvestedBy> <ufVivo:dateHarvested>{{harvest_datetime}}</ufVivo:dateHarvested> </rdf:Description> <rdf:Description rdf:about="{{term_uri}}"> <ufVivo:dateTimeIntervalFor rdf:resource="{{section_uri}}"/> </rdf:Description> {{if course_new}} <rdf:Description rdf:about="{{course_role_uri}}"> <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Thing"/> <rdf:type rdf:resource="http://vivoweb.org/ontology/core#TeacherRole"/> <rdfs:label>{{course_name}}</rdfs:label> <ufVivo:courseRoleOf rdf:resource="{{person_uri}}"/> <vivo:roleRealizedIn rdf:resource="{{course_uri}}"/> </rdf:Description> {{endif}} <rdf:Description rdf:about="{{teacher_role_uri}}"> <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Thing"/> <rdf:type rdf:resource="http://vivoweb.org/ontology/core#TeacherRole"/> <vivo:teacherRoleOf rdf:resource="{{person_uri}}"/> <vivo:roleRealizedIn rdf:resource="{{section_uri}}"/> </rdf:Description>""") section_uri = get_vivo_uri() rdf = section_rdf_template.substitute( section_uri=section_uri, section_name=taught_data['section_name'], section_number=taught_data['section_number'], term_uri=taught_data['term_uri'], course_uri=taught_data['course_uri'], course_name=taught_data['course_name'], course_new=taught_data['course_new'], teacher_role_uri=get_vivo_uri(), course_role_uri=get_vivo_uri(), person_uri=taught_data['person_uri'], harvest_datetime=datetime.now().isoformat()) return [rdf, section_uri]
def do_pdf(self, selector, generate): """Generate and view a PDF invoice. This requires Tempita 0.5. """ import tempita invoice = self.db.invoices[selector] tmp_path = self.tmp_path.format(year=self.year) output_path = self.output_path.format(year=self.year) log.debug("tmp_path={0}".format(tmp_path)) tex_template = os.path.join(self.template_path, "invoice.tex") tex_file = os.path.join(tmp_path, "{0}.tex".format(invoice._name)) tmp_pdf_file = os.path.join(tmp_path, "{0}.pdf".format(invoice._name)) pdf_file = os.path.join(output_path, "{0}.pdf".format(invoice._name)) if generate: #if(not os.path.exists(pdf_file) or # os.path.getmtime(invoice._path) > os.path.getmtime(pdf_file)): issuer = self.db.companies[self.my_company] customer = self.db.companies[invoice.company_name] invoice_data = invoice.data() issuer_data = issuer.data() customer_data = customer.data() log.debug("Invoice: {0}".format(invoice_data._data)) log.debug("Issuer: {0}".format(issuer_data._data)) log.debug("Customer: {0}".format(customer_data._data)) log.debug("Creating TeX invoice...") self._check_path(self.tmp_path) result = tempita.Template(open(tex_template).read()).substitute( invoice=invoice_data, issuer=issuer_data, customer=customer_data) open(tex_file, "w").write(str(result)) assert (os.path.exists(tex_file)) log.debug("Creating PDF invoice...") if subprocess.call( (self.tex_program, "{0}.tex".format(invoice._name)), cwd=tmp_path) != 0: raise GenerationError("PDF generation failed.") assert (os.path.exists(tmp_pdf_file)) log.debug("Moving PDF file to the output directory...") self._check_path(output_path) os.rename(tmp_pdf_file, pdf_file) assert (os.path.exists(pdf_file)) log.debug("Running PDF viewer...") subprocess.call((self.pdf_program, pdf_file))
def build_html(self, req, json): def add_path(*path): path_info = req.path_info.rstrip("/") path_info += '/'.join(str(i) for i in path) + '/' return req.script_name + "/" + path_info + '?' + req.query_string if 'results' in json: ctx = {} ctx['add_path'] = add_path ctx['records'] = json['records'] ctx['allowed_columns'] = json['columns'] ctx['columns'] = json['results'][0].keys() if len( json['results']) else [] ctx['results'] = json['results'] _req = req.copy() _req.GET['page'] = str( int(_req.GET['page']) + 1 if 'page' in _req.GET else 1) qs = "?" + '&'.join('='.join(x) for x in _req.GET.items()) ctx['nextpage'] = qs page = req.GET.get('page', '0') _req = req.copy() _req.GET['page'] = str( int(_req.GET['page']) - 1 if 'page' in _req.GET else -1) if int(_req.GET['page']) > -1 and _req.GET['page'] != page: qs = "?" + '&'.join('='.join(x) for x in _req.GET.items()) ctx['prevpage'] = qs else: ctx['prevpage'] = None return tempita.Template(self.results_template).substitute(**ctx) else: ctx = {} ctx['column'] = json['name'] ctx['type'] = json['type'] ctx['operators'] = json['operators'] ctx['examples'] = operator_examples return tempita.Template(self.column_template).substitute(**ctx)
def patch_template(self, template_content=sample_template): """Patch the DHCP config template with the given contents. Returns a `tempita.Template` of the given template, so that a test can make its own substitutions and compare to those made by the code being tested. """ fake_etc_maas = self.make_dir() self.useFixture( EnvironmentVariableFixture('MAAS_CONFIG_DIR', fake_etc_maas)) template_dir = path.join(fake_etc_maas, 'templates', 'dhcp') makedirs(template_dir) template = factory.make_file(template_dir, 'dhcpd.conf.template', contents=template_content) return tempita.Template(template_content, name=template)
def interpolate(args): vars = os.environ.copy() if args.file: vars.update( dict( file=args.file, file_dir=os.path.dirname(os.path.abspath(args.file)), file_basename=os.path.basename(args.file), file_name=os.path.splitext(os.path.basename(args.file))[0], )) for var in ['row_python', 'row_pyfile']: value = getattr(args, var) if value: value = tempita.Template(value) value = value.substitute(vars) setattr(args, var, value)
def generate(switch, model_id): model = config.models[model_id] mgmt, vlanid = parse_metadata(switch) if mgmt is None: raise Exception("The switch " + switch + " was not found in ipplan") if radius is None: raise Exception("Radius key not set") if username is None: raise Exception("Username not set") if password is None: raise Exception("User-password not set") if enable is None: raise Exception("Enable password not set") if snmp_ro is None: raise Exception("SNMP ro not set") if snmp_salt is None: raise Exception("SNMP salt not set") # # Template function definition # cfg = tempita.Template(file(model.template).read()) return \ cfg.substitute( hostname=switch, model=model, mgmt_ip=mgmt['ip'], mgmt_mask=mgmt['mask'], mgmt_gw=mgmt['gw'], mgmt_vlanid=mgmt['vlanid'], vlanid=vlanid, wifi_switches=config.wifi_switches, wifi_vlanid=config.wifi_vlanid, password=config.password, enable=config.enable, radius=config.radius, snmp_ro=config.snmp_ro, snmp_rw=hashlib.sha1(config.snmp_salt + mgmt['ip']).hexdigest(), ipplan_host=lambda h: ipplan_host(h), ipplan_pkg=lambda p: ipplan_package(p), # snmp_user=config.snmp_user, # snmp_auth=config.snmp_auth, # snmp_priv=config.snmp_priv )
def render(self): ''' Renders the template data to the template Returns: the result ''' if self.template_name and not self.Template: self.debug('Instantiating template from filename: %s' % self.template_name) self.Template = tempita.Template.from_filename(self.template_name) if self.template_body and not self.Template: self.debug('Instantiating template from body...') self.Template = tempita.Template(self.template_body) self.debug('Using template data: %s' % self.template_data, False) return self.Template.substitute(self.template_data)
def blending_formula(k=1, l=0, i=0): """ k: spline order l: diff order i: current dimension """ if k==1: if l==0: s = f"""\ Φ_{i}_{0} = 1.0 - λ_{i} Φ_{i}_{1} = λ_{i}""" elif l==1: s = f"""\ d_Φ_{i}_{0} = -1.0/δ_{i} d_Φ_{i}_{1} = 1.0/δ_{i}""" else: s = f""" d_{{l}}_Φ_{i}_{0} = 0.0 d_{{l}}_Φ_{i}_{1} = 0.0""" elif k==3: if l>1: raise Exception("Not implemented") import tempita template = tempita.Template(""" μ_{{i}}_0 = λ_{{i}}*λ_{{i}}*λ_{{i}}; μ_{{i}}_1 = λ_{{i}}*λ_{{i}}; μ_{{i}}_2 = λ_{{i}}; μ_{{i}}_3 = 1.0; {{for j in range(4)}} Φ_{{i}}_{{j}} = 0.0 {{endfor}} if λ_{{i}} < 0: {{for j in range(4)}} Φ_{{i}}_{{j}} = dCd[{{j}},3]*λ_{{i}} + Cd[{{j}},3] {{endfor}} elif λ_{{i}} > 1: {{for j in range(4)}} Φ_{{i}}_{{j}} = (3*Cd[{{j}},0] + 2*Cd[{{j}},1] + Cd[{{j}},2])*(λ_{{i}}-1) + (Cd[{{j}},0]+Cd[{{j}},1]+Cd[{{j}},2]+Cd[{{j}},3]) {{endfor}} else: {{for j in range(4)}} Φ_{{i}}_{{j}} = (Cd[{{j}},0]*μ_{{i}}_0 + Cd[{{j}},1]*μ_{{i}}_1 + Cd[{{j}},2]*μ_{{i}}_2 + Cd[{{j}},3]*μ_{{i}}_3) {{endfor}} """) s = template.substitute(i=i) return s
def process(src, dst, defines): with open(src, 'r') as f: text = f.read() tmpl = tempita.Template(text) out = tmpl.substitute(defines) src = os.path.basename(src) with open(dst, 'w') as f: if dst.endswith('.f95'): f.write( "!! NOTE: this file is autogenerated from {}: do not edit manually\n" .format(src)) else: f.write( "/* NOTE: this file is autogenerated from {}: do not edit manually */\n" .format(src)) f.write(out) sys.exit(0)
def make_vars(self): if not self._defaults: return self.vars new_vars = dict(self.vars) for name, value, filename, pos in self._defaults: if name not in self.vars: tmpl = tempita.Template(value, name='%s:default %s=...' % (filename, name), line_offset=pos - 1) sub_value = tmpl.substitute(globals=self['global'], config=self, __file__=filename, environ=os.environ, here=os.path.dirname( os.path.abspath(filename)), **new_vars) new_vars[name] = sub_value return new_vars
def __getitem__(self, name, **vars): value = self.config._config.get((self.name, name)) if value is None: raise KeyError value, filename, pos = value if '{{' not in value: return value tmpl = tempita.Template(value, name='%s:%s=...' % (filename, name), line_offset=pos - 1) vars.update(self.config.make_vars()) return tmpl.substitute(section=self, globals=self.config['global'], config=self.config, __file__=filename, __section__=self.name, environ=os.environ, here=os.path.dirname(os.path.abspath(filename)), **vars)
def preparse(template_text, lookup=None): """ Do any special processing of a template, including recognizing the templating language and resolving file: references, then return an appropriate wrapper object. Currently Tempita and Python string interpolation are supported. `lookup` is an optional callable that resolves any ambiguous template path. """ # First, try to resolve file: references to their contents template_path = None try: is_file = template_text.startswith("file:") except (AttributeError, TypeError): pass # not a string else: if is_file: template_path = template_text[5:] if template_path.startswith('/'): template_path = '/' + template_path.lstrip('/') elif template_path.startswith('~'): template_path = os.path.expanduser(template_path) elif lookup: template_path = lookup(template_path) with closing(open(template_path, "r")) as handle: template_text = handle.read().rstrip() if hasattr(template_text, "__engine__"): # Already preparsed template = template_text else: if template_text.startswith("{{"): import tempita # only on demand template = tempita.Template(template_text, name=template_path) template.__engine__ = "tempita" else: template = InterpolationTemplate(template_text) template.__file__ = template_path template.__text__ = template_text return template
def to_php(self, filename="test_installed_map.php", composer_location=None): if composer_location is None: bootstrap_path = "__DIR__.'/src/bootstrap.php'" else: bootstrap_path = "'%s'" % op.join(composer_location, "src", "bootstrap.php") template = tempita.Template(TEMPLATE) remote_packages = self.remote_repository.list_packages() installed_packages = self.installed_repository.list_packages() variables = { "bootstrap_path": bootstrap_path, "remote_repo_json_string": packages_list_to_php_json(remote_packages), "installed_repo_json_string": packages_list_to_php_json(installed_packages), "request": [(job.job_type, job.requirement.name, job_to_php_constraints(job)) \ for job in self.request.jobs], "common_imports": COMMON_IMPORTS, } with open(filename, "wt") as fp: fp.write(template.substitute(variables))
def generate_libsel4_file(libsel4_header, syscalls): tmpl = tempita.Template(libsel4_header_template) libsel4_header.write(tmpl.substitute(enum=syscalls))
def generate_kernel_file(kernel_header, api, debug): tmpl = tempita.Template(kernel_header_template) kernel_header.write(tmpl.substitute(assembler=api, enum=api + debug, upper=convert_to_assembler_format))
class BINDServerResources(fixtures.Fixture): """Allocate the resources a BIND server needs. :ivar port: A port that was free at the time setUp() was called. :ivar rndc_port: A port that was free at the time setUp() was called (used for rndc communication). :ivar homedir: A directory where to put all the files the BIND server needs (configuration files and executable). :ivar log_file: The log file allocated for the server. :ivar include_in_options: Name of a file under homedir to include inside the options block. """ # The full path where the 'named' executable can be # found. # Note that it will be copied over to a temporary # location in order to by-pass the limitations imposed by # apparmor if the executable is in /usr/sbin/named. NAMED_PATH = "/usr/sbin/named" # The configuration template for the BIND server. The goal here # is to override the defaults (default configuration files location, # default port) to avoid clashing with the system's BIND (if # running). NAMED_CONF_TEMPLATE = tempita.Template( dedent( """ options { directory "{hotexamples_com}"; listen-on port {{port}} {127.0.0.1;}; listen-on-v6 port {{port}} {::1;}; pid-file "{hotexamples_com}/named.pid"; session-keyfile "{hotexamples_com}/session.key"; {{if include_in_options}} include "{hotexamples_com}/{{include_in_options}}"; {{endif}} }; logging{ channel simple_log { file "{{log_file}}"; severity debug; print-severity yes; print-time yes; }; category default{ simple_log; }; }; {{extra}} """ ) ) def __init__( self, port=None, rndc_port=None, homedir=None, log_file=None, include_in_options=None, ): super(BINDServerResources, self).__init__() self._defaults = dict( port=port, rndc_port=rndc_port, homedir=homedir, log_file=log_file, include_in_options=include_in_options, ) def setUp(self, overwrite_config=False): super(BINDServerResources, self).setUp() self.__dict__.update(self._defaults) self.set_up_config() self.set_up_named(overwrite_config=overwrite_config) def set_up_named(self, overwrite_config=True): """Setup an environment to run 'named'. - Creates the default configuration for 'named' and sets up rndc. - Copies the 'named' executable inside homedir. AppArmor won't let us run the installed version the way we want. """ # Generate rndc configuration (rndc config and named snippet). # Disable remote administration for init scripts by suppressing the # "controls" statement. rndcconf, namedrndcconf = generate_rndc( port=self.rndc_port, key_name="dnsfixture-rndc-key", include_default_controls=False, ) # Write main BIND config file. if should_write(self.conf_file, overwrite_config): named_conf = self.NAMED_CONF_TEMPLATE.substitute( homedir=self.homedir, port=self.port, log_file=self.log_file, include_in_options=self.include_in_options, extra=namedrndcconf, ) atomic_write( (GENERATED_HEADER + named_conf).encode("ascii"), self.conf_file ) # Write rndc config file. if should_write(self.rndcconf_file, overwrite_config): atomic_write( (GENERATED_HEADER + rndcconf).encode("ascii"), self.rndcconf_file, ) # Copy named executable to home dir. This is done to avoid # the limitations imposed by apparmor if the executable # is in /usr/sbin/named. # named's apparmor profile prevents loading of zone and # configuration files from outside of a restricted set, # none of which an ordinary user has write access to. if should_write(self.named_file, overwrite_config): named_path = self.NAMED_PATH assert os.path.exists(named_path), ( "'%s' executable not found. Install the package " "'bind9' or define an environment variable named " "NAMED_PATH with the path where the 'named' " "executable can be found." % named_path ) copy(named_path, self.named_file) def set_up_config(self): if self.port is None: [self.port] = allocate_ports("localhost") if self.rndc_port is None: [self.rndc_port] = allocate_ports("localhost") if self.homedir is None: self.homedir = self.useFixture(TempDirectory()).path if self.log_file is None: self.log_file = os.path.join(self.homedir, "named.log") self.named_file = os.path.join( self.homedir, os.path.basename(self.NAMED_PATH) ) self.conf_file = os.path.join(self.homedir, "named.conf") self.rndcconf_file = os.path.join(self.homedir, "rndc.conf")