def try_repo(args): with tmpdir() as tempdir: repo, ref = _repo_ref(tempdir, args.repo, args.ref) store = Store(tempdir) if args.hook: hooks = [{'id': args.hook}] else: repo_path = store.clone(repo, ref) manifest = load_manifest(os.path.join(repo_path, C.MANIFEST_FILE)) manifest = sorted(manifest, key=lambda hook: hook['id']) hooks = [{'id': hook['id']} for hook in manifest] items = (('repo', repo), ('rev', ref), ('hooks', hooks)) config = {'repos': [collections.OrderedDict(items)]} config_s = ordered_dump(config, **C.YAML_DUMP_KWARGS) config_filename = os.path.join(tempdir, C.CONFIG_FILE) with open(config_filename, 'w') as cfg: cfg.write(config_s) output.write_line('=' * 79) output.write_line('Using config:') output.write_line('=' * 79) output.write(config_s) output.write_line('=' * 79) return run(config_filename, store, args)
def _write_new_config_file(path, output): with open(path) as f: original_contents = f.read() output = remove_defaults(output, CONFIG_SCHEMA) new_contents = ordered_dump(output, **C.YAML_DUMP_KWARGS) lines = original_contents.splitlines(True) rev_line_indices_reversed = list( reversed([ i for i, line in enumerate(lines) if REV_LINE_RE.match(line) ]), ) for line in new_contents.splitlines(True): if REV_LINE_RE.match(line): # It's possible we didn't identify the rev lines in the original if not rev_line_indices_reversed: break line_index = rev_line_indices_reversed.pop() original_line = lines[line_index] orig_match = REV_LINE_RE.match(original_line) new_match = REV_LINE_RE.match(line) lines[line_index] = REV_LINE_FMT.format( orig_match.group(1), orig_match.group(2), new_match.group(3), orig_match.group(4), ) # If we failed to intelligently rewrite the rev lines, fall back to the # pretty-formatted yaml output to_write = ''.join(lines) if remove_defaults(ordered_load(to_write), CONFIG_SCHEMA) != output: to_write = new_contents with open(path, 'w') as f: f.write(to_write)
def modify_manifest(path): """Modify the manifest yielded by this context to write to hooks.yaml.""" manifest_path = os.path.join(path, C.MANIFEST_FILE) manifest = ordered_load(io.open(manifest_path).read()) yield manifest with io.open(manifest_path, 'w') as manifest_file: manifest_file.write(ordered_dump(manifest, **C.YAML_DUMP_KWARGS)) cmd_output('git', 'commit', '-am', 'update hooks.yaml', cwd=path)
def modify_config(path='.', commit=True): """Modify the config yielded by this context to write to .pre-commit-config.yaml """ config_path = os.path.join(path, C.CONFIG_FILE) config = ordered_load(io.open(config_path).read()) yield config with io.open(config_path, 'w', encoding='UTF-8') as config_file: config_file.write(ordered_dump(config, **C.YAML_DUMP_KWARGS)) if commit: cmd_output('git', 'commit', '-am', 'update config', cwd=path)
def autoupdate(runner): """Auto-update the pre-commit config to the latest versions of repos.""" # Set up our logging handler logger.addHandler(LoggingHandler(False)) logger.setLevel(logging.WARNING) retv = 0 output_configs = [] changed = False input_configs = load_config( runner.config_file_path, load_strategy=ordered_load, ) for repo_config in input_configs: if is_local_hooks(repo_config): output_configs.append(repo_config) continue sys.stdout.write('Updating {0}...'.format(repo_config['repo'])) sys.stdout.flush() try: new_repo_config = _update_repository(repo_config, runner) except RepositoryCannotBeUpdatedError as error: print(error.args[0]) output_configs.append(repo_config) retv = 1 continue if new_repo_config['sha'] != repo_config['sha']: changed = True print( 'updating {0} -> {1}.'.format( repo_config['sha'], new_repo_config['sha'], ) ) output_configs.append(new_repo_config) else: print('already up to date.') output_configs.append(repo_config) if changed: with open(runner.config_file_path, 'w') as config_file: config_file.write( ordered_dump( remove_defaults(output_configs, CONFIG_JSON_SCHEMA), **C.YAML_DUMP_KWARGS ) ) return retv
def autoupdate(runner): """Auto-update the pre-commit config to the latest versions of repos.""" # Set up our logging handler logger.addHandler(LoggingHandler(False)) logger.setLevel(logging.WARNING) retv = 0 output_configs = [] changed = False input_configs = load_config( runner.config_file_path, load_strategy=ordered_load, ) for repo_config in input_configs: if is_local_hooks(repo_config): output_configs.append(repo_config) continue sys.stdout.write('Updating {}...'.format(repo_config['repo'])) sys.stdout.flush() try: new_repo_config = _update_repository(repo_config, runner) except RepositoryCannotBeUpdatedError as error: print(error.args[0]) output_configs.append(repo_config) retv = 1 continue if new_repo_config['sha'] != repo_config['sha']: changed = True print( 'updating {} -> {}.'.format( repo_config['sha'], new_repo_config['sha'], ) ) output_configs.append(new_repo_config) else: print('already up to date.') output_configs.append(repo_config) if changed: with open(runner.config_file_path, 'w') as config_file: config_file.write( ordered_dump( remove_defaults(output_configs, CONFIG_JSON_SCHEMA), **C.YAML_DUMP_KWARGS ) ) return retv
def modify_config(path='.', commit=True): """Modify the config yielded by this context to write to .pre-commit-config.yaml """ config_path = os.path.join(path, C.CONFIG_FILE) with io.open(config_path) as f: config = ordered_load(f.read()) yield config with io.open(config_path, 'w', encoding='UTF-8') as config_file: config_file.write(ordered_dump(config, **C.YAML_DUMP_KWARGS)) if commit: cmd_output( 'git', 'commit', '--no-gpg-sign', '-am', 'update config', cwd=path, )
def modify_manifest(path): """Modify the manifest yielded by this context to write to .pre-commit-hooks.yaml. """ manifest_path = os.path.join(path, C.MANIFEST_FILE) with io.open(manifest_path) as f: manifest = ordered_load(f.read()) yield manifest with io.open(manifest_path, 'w') as manifest_file: manifest_file.write(ordered_dump(manifest, **C.YAML_DUMP_KWARGS)) cmd_output( 'git', 'commit', '--no-gpg-sign', '-am', 'update {}'.format(C.MANIFEST_FILE), cwd=path, )
def _original_lines(path, rev_infos, retry=False): """detect `rev:` lines or reformat the file""" with open(path) as f: original = f.read() lines = original.splitlines(True) idxs = [i for i, line in enumerate(lines) if REV_LINE_RE.match(line)] if len(idxs) == len(rev_infos): return lines, idxs elif retry: raise AssertionError('could not find rev lines') else: with open(path, 'w') as f: f.write(ordered_dump(ordered_load(original), **C.YAML_DUMP_KWARGS)) return _original_lines(path, rev_infos, retry=True)
def autoupdate(runner, tags_only): """Auto-update the pre-commit config to the latest versions of repos.""" retv = 0 output_configs = [] changed = False input_configs = load_config( runner.config_file_path, load_strategy=ordered_load, ) for repo_config in input_configs: if is_local_hooks(repo_config): output_configs.append(repo_config) continue output.write('Updating {}...'.format(repo_config['repo'])) try: new_repo_config = _update_repo(repo_config, runner, tags_only) except RepositoryCannotBeUpdatedError as error: output.write_line(error.args[0]) output_configs.append(repo_config) retv = 1 continue if new_repo_config['sha'] != repo_config['sha']: changed = True output.write_line('updating {} -> {}.'.format( repo_config['sha'], new_repo_config['sha'], )) output_configs.append(new_repo_config) else: output.write_line('already up to date.') output_configs.append(repo_config) if changed: with open(runner.config_file_path, 'w') as config_file: config_file.write( ordered_dump( remove_defaults(output_configs, CONFIG_JSON_SCHEMA), **C.YAML_DUMP_KWARGS)) return retv
def autoupdate(runner, tags_only): """Auto-update the pre-commit config to the latest versions of repos.""" retv = 0 output_configs = [] changed = False input_configs = load_config( runner.config_file_path, load_strategy=ordered_load, ) for repo_config in input_configs: if is_local_repo(repo_config): output_configs.append(repo_config) continue output.write('Updating {}...'.format(repo_config['repo'])) try: new_repo_config = _update_repo(repo_config, runner, tags_only) except RepositoryCannotBeUpdatedError as error: output.write_line(error.args[0]) output_configs.append(repo_config) retv = 1 continue if new_repo_config['sha'] != repo_config['sha']: changed = True output.write_line('updating {} -> {}.'.format( repo_config['sha'], new_repo_config['sha'], )) output_configs.append(new_repo_config) else: output.write_line('already up to date.') output_configs.append(repo_config) if changed: with open(runner.config_file_path, 'w') as config_file: config_file.write(ordered_dump( remove_defaults(output_configs, CONFIG_SCHEMA), **C.YAML_DUMP_KWARGS )) return retv
def _write_new_config(path: str, rev_infos: List[Optional[RevInfo]]) -> None: lines, idxs = _original_lines(path, rev_infos) for idx, rev_info in zip(idxs, rev_infos): if rev_info is None: continue match = REV_LINE_RE.match(lines[idx]) assert match is not None new_rev_s = ordered_dump({'rev': rev_info.rev}, **C.YAML_DUMP_KWARGS) new_rev = new_rev_s.split(':', 1)[1].strip() if rev_info.frozen is not None: comment = f' # frozen: {rev_info.frozen}' elif match[4].strip().startswith('# frozen:'): comment = '' else: comment = match[4] lines[idx] = f'{match[1]}rev:{match[2]}{new_rev}{comment}{match[5]}' with open(path, 'w') as f: f.write(''.join(lines))
def write_config(directory, config, config_file=C.CONFIG_FILE): if type(config) is not list and 'repos' not in config: assert type(config) is OrderedDict config = {'repos': [config]} with io.open(os.path.join(directory, config_file), 'w') as outfile: outfile.write(ordered_dump(config, **C.YAML_DUMP_KWARGS))
def write_config(directory, config): if type(config) is not list: assert type(config) is OrderedDict config = [config] with io.open(os.path.join(directory, C.CONFIG_FILE), 'w') as config_file: config_file.write(ordered_dump(config, **C.YAML_DUMP_KWARGS))
def write_config(directory, config, config_file=C.CONFIG_FILE): if type(config) is not list: assert type(config) is OrderedDict config = [config] with io.open(os.path.join(directory, config_file), 'w') as outfile: outfile.write(ordered_dump(config, **C.YAML_DUMP_KWARGS))
def write_config(directory, config, config_file=C.CONFIG_FILE): if type(config) is not list and 'repos' not in config: assert isinstance(config, dict), config config = {'repos': [config]} with io.open(os.path.join(directory, config_file), 'w') as outfile: outfile.write(ordered_dump(config, **C.YAML_DUMP_KWARGS))
def write_config(directory, config): assert type(config) is OrderedDict with io.open(os.path.join(directory, C.CONFIG_FILE), 'w') as config_file: config_file.write(ordered_dump([config], **C.YAML_DUMP_KWARGS))