def construct_context_from_py(source, *args, **kwargs): if not (os.path.exists(source) and os.path.isfile(source)): return {} source_name = source.split('/')[-1][:-3] sys.path.insert(0, get_parent_path(source, 1)) try: context = __import__(source_name).construct(*args, **kwargs) finally: sys.path.remove(get_parent_path(source, 1)) return context
def ignore_rules(self): work_dir = get_parent_path(self.tpl_dir, 1) rules = parse_rules(self.IGNORE_RULRS, self.tpl_parent_dir) ignore_file = os.path.join(work_dir, 'ignores') if os.path.exists(ignore_file) and os.path.isfile(ignore_file): rules.extend(parse_rules(ignore_file, self.tpl_parent_dir)) return rules
def render(ctx, namespace, branch, template, output_dir, echo, anti_ignores): """ \b generate files or dirs to output dir according to specified template ex: render hello_world --namespace python-tpl --branch master --output_dir $HOME """ args = parse_args(ctx) kwargs = parse_kwargs(ctx) repo_dir = '{}/{}/{}'.format(TPL_STORAGE_DIR, namespace, template) tpl_dir = os.path.join(repo_dir, 'tpl') panic_if_path_not_exist(repo_dir, 'dir') panic_if_path_not_exist(tpl_dir, 'dir') panic_if_path_not_exist(output_dir, 'dir') if not (os.path.exists(tpl_dir) and os.path.isdir(tpl_dir)): panic_with_exit_code('tpl dir({}) not exist'.format(tpl_dir), 1) if branch: check_out_command = 'old_path=$(pwd -P) && cd {};git checkout {} && cd $old_path'.format( repo_dir, branch) check_out_exit_code = os.system(check_out_command) if check_out_exit_code != 0: panic_with_exit_code('failed to checkout {}'.format(branch), check_out_exit_code) constructor_script = locate_constructor_script(repo_dir) context = {} if constructor_script is not None: context = construct_context(constructor_script, *args, **kwargs) anti_ignores = [ ignore.strip() for ignore in anti_ignores.split(',') if ignore ] tpl = Template(os.path.join(repo_dir, 'tpl'), output_dir, anti_ignores=anti_ignores) rendered_dirs, rendered_files = tpl.render(context) for dir in rendered_dirs: if echo is True: click.echo('render dir: {}'.format(dir)) break mkdirs(dir) for file, file_content in rendered_files: if echo is True: click.echo('render file: {}\n{}'.format(file, file_content)) continue file_parent_dir = get_parent_path(file, 1) if not os.path.exists(file_parent_dir): mkdirs(file_parent_dir) with open(file, 'w') as fd: fd.write(file_content) click.echo('render {}/{}:{} successfully'.format(namespace, template, branch)) after_render_hook = locate_after_render_hook(repo_dir) if after_render_hook: run_hook(after_render_hook)
def test_parse_rules(): source = """ # comment *tpl ?tpl """ with TempFile() as f: f.fd.write(source) f.close() rules = ignore.parse_rules(open(f.path), get_parent_path(f.path, 1)) assert len(rules) == 2 for rule in rules: assert isinstance(rule, ignore.IgnoreRule) assert rule.rule in ['*tpl', '?tpl']
def parent_dir(self): return get_parent_path(self.abs_path, 1)
def tpl_parent_dir(self): return get_parent_path(self.tpl_dir, 1)