def sort_requirements(filename: PathLike, allow_git: bool = False) -> int: """ Sort the requirements in the given file alphabetically. :param filename: The file to sort the requirements in. :param allow_git: Whether to allow lines that start with ``git+``, which are allowed by pip but not :pep:`508`. """ ret = PASS filename = PathPlus(filename) comments: List[str] requirements: Set[ComparableRequirement] git_lines: List[str] = [] requirements, comments, invalid_lines = read_requirements( req_file=filename, include_invalid=True, normalize_func=normalize_keep_dot, ) for line in invalid_lines: if line.startswith("git+") and allow_git: git_lines.append(line) else: ret |= FAIL # find and remove pkg-resources==0.0.0 # which is automatically added by broken pip package under Debian if ComparableRequirement("pkg-resources==0.0.0") in requirements: requirements.remove(ComparableRequirement("pkg-resources==0.0.0")) ret |= FAIL sorted_requirements = sorted(requirements) buf = StringList( [*comments, *git_lines, *[str(req) for req in sorted_requirements]]) buf.blankline(ensure_single=True) if (requirements != sorted_requirements and buf != filename.read_lines()) or ret: print('\n'.join(buf)) # print(coloured_diff( # filename.read_lines(), # buf, # str(filename), # str(filename), # "(original)", # "(sorted)", # lineterm='', # )) ret |= FAIL filename.write_lines(buf) return ret
def dump_to_file(self, data: Union[MutableMapping, Sequence], filename: PathLike, mode: str = 'w'): """ Dump the given data to the specified file. :param data: :param filename: :param mode: """ filename = PathPlus(filename) if 'w' in mode: filename.write_lines([ "# Configuration for 'repo_helper' (https://github.com/repo-helper/repo_helper)", self.dumps(data, explicit_start=True), ]) elif 'a' in mode: with filename.open('a') as fp: fp.write('\n') fp.write(self.dumps(data, explicit_start=False))