Ejemplo n.º 1
0
    def test_is_python_file(self):
        self.assertTrue(autoflake.is_python_file(
            os.path.join(ROOT_DIRECTORY, 'autoflake.py')))

        with temporary_file('#!/usr/bin/env python', suffix='') as filename:
            self.assertTrue(autoflake.is_python_file(filename))

        with temporary_file('#!/usr/bin/python', suffix='') as filename:
            self.assertTrue(autoflake.is_python_file(filename))

        with temporary_file('#!/usr/bin/python3', suffix='') as filename:
            self.assertTrue(autoflake.is_python_file(filename))

        with temporary_file('#!/usr/bin/pythonic', suffix='') as filename:
            self.assertFalse(autoflake.is_python_file(filename))

        with temporary_file('###!/usr/bin/python', suffix='') as filename:
            self.assertFalse(autoflake.is_python_file(filename))

        self.assertFalse(autoflake.is_python_file(os.devnull))
        self.assertFalse(autoflake.is_python_file('/bin/bash'))
Ejemplo n.º 2
0
def _should_format(fname: str) -> bool:
    return fname.endswith((".md", ".rst")) or autoflake.is_python_file(fname)
Ejemplo n.º 3
0
def cli(
) -> None:  # pragma: no cover  # mutates things in-place, will test later.
    """Execute the `shed` CLI."""
    # TODO: make this provide useful CLI help and usage hints
    # TODO: single-file mode with optional min_version support
    parser = argparse.ArgumentParser(prog="shed", description=__doc__.strip())
    parser.add_argument(
        nargs="*",
        metavar="file",
        dest="files",
        help="File(s) to format, instead of autodetection",
    )
    args = parser.parse_args()

    if args.files:
        first_party_imports: FrozenSet[str] = frozenset()
        all_filenames = args.files
        for f in all_filenames:
            if not autoflake.is_python_file(f):
                print(f"{f!r} does not seem to be a Python file")  # noqa
                sys.exit(1)
    else:
        # Try to work out the name of the current package for first-party imports
        try:
            base = subprocess.run(
                ["git", "rev-parse", "--show-toplevel"],
                check=True,
                timeout=10,
                stdout=subprocess.PIPE,
                universal_newlines=True,
            ).stdout.strip()
        except subprocess.SubprocessError:
            print("Doesn't seem to be a git repo; pass filenames to format."
                  )  # noqa
            sys.exit(1)

        provides = {Path(base).name} | {
            init.name
            for init in Path(base).glob("**/src/*/__init__.py")
        }
        first_party_imports = frozenset(p for p in provides
                                        if p.isidentifier())

        # Get all tracked files from `git ls-files`
        all_filenames = subprocess.run(
            ["git", "ls-files"],
            check=True,
            timeout=10,
            stdout=subprocess.PIPE,
            universal_newlines=True,
        ).stdout.splitlines()
        all_filenames = [
            f for f in all_filenames if autoflake.is_python_file(f)
        ]

    for fname in all_filenames:
        with open(fname) as handle:
            on_disk = handle.read()
        result = shed(source_code=on_disk,
                      first_party_imports=first_party_imports)
        if result == on_disk:
            continue
        assert result == shed(source_code=result,
                              first_party_imports=first_party_imports)
        with open(fname, mode="w") as fh:
            fh.write(result)