def apply_directive(self, directive, bk, code=None, s=None, repl_records=None): """Apply directives. The value in directive[2] depends on the command: 'replace': the argument is the string to use as a replacement 'push': the argument is the filepath to save into """ snip_id = directive[0] cmd = directive[1] if cmd == 'push': # Perform replacements on the directive argument if necessary arg = directive[2] if repl_records is not None: for rec in repl_records: # rec[0] = snippet id, rec[1] = array of replacement values if rec[0] == snip_id: arg = replace_values(arg, rec[1]) break # Save the current (code, filepath) on the stack bk.code_stack.append((code + s, arg)) code = s = '' elif cmd == 'pop': # Finalize code being generated code += s # Pop up one stack level and resume that level's code generation prev_code, filepath = bk.code_stack.pop() print(f'{self.id}: apply_directive: writing "{filepath}"') # Write out to file chrooted = self.id.startswith('6.') or self.id.startswith('9.') with open(filepath, 'w') as f: f.write( file_header(filepath, bk, chrooted=chrooted) + code + file_footer(filepath)) # Reset code generation for this stack level code = prev_code s = '' elif cmd == 'add': arg = directive[2] t = Snippet('userinput', arg) # Replace placeholders with actual values if repl_records is not None: for rec in repl_records: # rec[0] = snippet id, rec[1] = array of replacement values if rec[0] == snip_id: t.text = t.replace_values(rec[1]) break s += t.generate(f'{self.id}_{snip_id} [add]') else: print(f'Sect: {self.id}, snippet directive: {snip_id}' + f', unknown command "{cmd}"') return code, s