├── eliminate_newlines ├── __init__.py ├── __main__.py ├── cli.py └── core.py ├── pytest.ini ├── tests ├── requirements.txt └── test_eliminate_whitespaces.py ├── .gitignore ├── .pre-commit-hooks.yaml ├── .github └── workflows │ ├── python-publish.yml │ └── tests.yml ├── LICENSE ├── setup.py └── README.md /eliminate_newlines/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = "1.2" 2 | -------------------------------------------------------------------------------- /eliminate_newlines/__main__.py: -------------------------------------------------------------------------------- 1 | from eliminate_newlines.cli import cli 2 | 3 | cli() 4 | -------------------------------------------------------------------------------- /pytest.ini: -------------------------------------------------------------------------------- 1 | # content of pytest.ini 2 | [pytest] 3 | addopts = -ra -v --showlocals 4 | -------------------------------------------------------------------------------- /tests/requirements.txt: -------------------------------------------------------------------------------- 1 | pytest==5.3.2 2 | pytest-check==0.3.9 3 | pytest-cov==2.8.1 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | **/venv/ 2 | **/.vscode/** 3 | *.pyc 4 | **/.cache/** 5 | **/__pycache__ 6 | **/.pytest_cache 7 | **/.coverage 8 | **/builds 9 | *.egg-info 10 | -------------------------------------------------------------------------------- /.pre-commit-hooks.yaml: -------------------------------------------------------------------------------- 1 | - id: eliminate_newlines 2 | name: eliminate_newlines 3 | description: "This CLI formats Python code in such a way that after the function definition header all newlines will be deleted." 4 | entry: eliminate_newlines 5 | language: python 6 | language_version: python3 7 | require_serial: true 8 | types: [python] 9 | -------------------------------------------------------------------------------- /.github/workflows/python-publish.yml: -------------------------------------------------------------------------------- 1 | # This workflows will upload a Python Package using Twine when a release is created 2 | # For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries 3 | 4 | name: Upload Python Package 5 | 6 | on: 7 | release: 8 | types: [created] 9 | 10 | jobs: 11 | deploy: 12 | 13 | runs-on: ubuntu-latest 14 | 15 | steps: 16 | - uses: actions/checkout@v2 17 | - name: Set up Python 18 | uses: actions/setup-python@v2 19 | with: 20 | python-version: '3.x' 21 | - name: Install dependencies 22 | run: | 23 | python -m pip install --upgrade pip 24 | pip install setuptools wheel twine 25 | - name: Build and publish 26 | env: 27 | TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }} 28 | TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }} 29 | run: | 30 | python setup.py sdist bdist_wheel 31 | twine upload dist/* 32 | -------------------------------------------------------------------------------- /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | # This workflow will install Python dependencies, run tests and lint with a variety of Python versions 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions 3 | 4 | name: Run Tests 5 | 6 | on: 7 | push: 8 | branches: [ master ] 9 | pull_request: 10 | branches: [ master ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | strategy: 17 | matrix: 18 | python-version: [3.6, 3.7, 3.8] 19 | 20 | steps: 21 | - uses: actions/checkout@v2 22 | - name: Set up Python ${{ matrix.python-version }} 23 | uses: actions/setup-python@v2 24 | with: 25 | python-version: ${{ matrix.python-version }} 26 | - name: Install dependencies 27 | run: | 28 | sudo apt-get update 29 | python -m pip install --upgrade pip 30 | pip install . 31 | pip install tests -r tests/requirements.txt 32 | - name: Test with pytest 33 | run: | 34 | pytest --cov-report term-missing --cov=eliminate_newlines tests/ 35 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Patrik Hlobil 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import setuptools 2 | from pathlib import Path 3 | from eliminate_newlines import __version__ 4 | 5 | with open(Path(__file__).parent / "README.md") as f: 6 | long_description = f.read() 7 | 8 | setuptools.setup( 9 | name="eliminate-newlines", 10 | version=__version__, 11 | author="Patrik Hlobil", 12 | author_email="patrik.hlobil@googlemail.com", 13 | description="CLI that formats Python code in such a way that after the function definition header all newlines will be deleted", 14 | long_description=long_description, 15 | long_description_content_type="text/markdown", 16 | url="https://github.com/PatrikHlobil/Eliminate-Newlines-After-Function-Definition", 17 | packages=["eliminate_newlines"], 18 | install_requires=["click>=7.1.2", "colorama>=0.4.3"], 19 | classifiers=[ 20 | "Programming Language :: Python :: 3.6", 21 | "Programming Language :: Python :: 3.7", 22 | "Programming Language :: Python :: 3.8", 23 | "License :: OSI Approved :: MIT License", 24 | "Operating System :: OS Independent", 25 | ], 26 | python_requires=">=3.6", 27 | entry_points=""" 28 | [console_scripts] 29 | eliminate_newlines=eliminate_newlines.cli:cli 30 | """, 31 | ) 32 | -------------------------------------------------------------------------------- /eliminate_newlines/cli.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | import sys 3 | import click 4 | 5 | from .core import ( 6 | eliminate_newlines_after_function_definition_in_file_or_directory, 7 | ) 8 | 9 | 10 | @click.command() 11 | @click.argument("paths", required=True, nargs=-1) 12 | @click.option( 13 | "--check", 14 | help="Don't write the files back, just return the status.", 15 | is_flag=True, 16 | ) 17 | def cli(paths, check): 18 | """This CLI formats Python code in such a way that after the function definition 19 | header all newlines will be deleted. 20 | 21 | Return code 0 means nothing would change. Return code 1 means some files would be reformatted. Return code 123 means there was an internal error."" 22 | pass. 23 | 24 | Passed PATHS can be either files or directories. In the latter case, all files in the 25 | folders will be formatted recursively. 26 | """ 27 | try: 28 | paths = [Path(path) for path in paths] 29 | changes = [] 30 | for path in paths: 31 | if path.is_file() and str(path).endswith(".py"): 32 | pass 33 | elif path.is_dir(): 34 | pass 35 | else: 36 | raise ValueError( 37 | f"PATH '{str(path)}' is neither a Python-file or directory." 38 | ) 39 | c = eliminate_newlines_after_function_definition_in_file_or_directory( 40 | path=path, check=check 41 | ) 42 | changes.append(c) 43 | sys.exit(max(changes)) 44 | except Exception as exc: 45 | click.echo(click.style(str(exc), fg="red")) 46 | sys.exit(123) 47 | 48 | 49 | if __name__ == "__main__": 50 | cli() 51 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Eliminate Newlines CLI 2 | 3 | This CLI formats Python code in such a way that after the function definition header all newlines will be deleted. 4 | 5 | 6 | **Example** 7 | 8 | ```python 9 | def foo(a): 10 | 11 | return a + 1 12 | 13 | 14 | class A: 15 | def bar(self, 16 | b, 17 | c): 18 | 19 | 20 | return b + c 21 | ``` 22 | 23 | will be formatted to: 24 | 25 | ```python 26 | def foo(a): 27 | return a + 1 28 | 29 | 30 | class A: 31 | def bar(self, 32 | b, 33 | c): 34 | return a + b + c 35 | ``` 36 | 37 | ## Example usage: 38 | 39 | **Reformat file:** 40 | 41 | eliminate_newlines testfile.py 42 | 43 | **Reformat folder (recursively):** 44 | 45 | eliminate_newlines /path/to/testfolder 46 | 47 | **Check mode:** 48 | 49 | eliminate_newlines testfile.py --check 50 | 51 | **Return Codes** 52 | 53 | Return code 0 means nothing would change. 54 | 55 | Return code 1 means some files would be reformatted. 56 | 57 | Return code 123 means there was an internal error. 58 | 59 | 60 | ## CLI Documentation: 61 | 62 | eliminate_newlines --help 63 | 64 | 65 | ``` 66 | Usage: eliminate_newlines [OPTIONS] PATH 67 | 68 | This CLI formats Python code in such a way that after the function 69 | definition header all newlines will be deleted. 70 | 71 | Return code 0 means nothing would change. Return code 1 means some files 72 | would be reformatted. Return code 123 means there was an internal error."" 73 | pass. 74 | 75 | Passed PATHS can be either filea or directories. In the latter case, all 76 | files in the folders will be formatted recursively. 77 | 78 | Options: 79 | --check Don't write the files back, just return the status. 80 | --help Show this message and exit. 81 | ``` 82 | -------------------------------------------------------------------------------- /eliminate_newlines/core.py: -------------------------------------------------------------------------------- 1 | import re 2 | from pathlib import Path 3 | from typing import Union 4 | 5 | import click 6 | 7 | 8 | def eliminate_newlines_after_function_definition_in_string(code: str) -> str: 9 | """Eliminates all newlines after the function definition in a string, e.g. 10 | 11 | def foo(a): 12 | 13 | return a + 1 14 | 15 | will become: 16 | 17 | def foo(a): 18 | return a+1""" 19 | 20 | return re.sub( 21 | pattern=r"(def \w+\([^:]*\):)(\s*)\n", 22 | repl=r"\1\n", 23 | string=code, 24 | flags=re.M | re.S, 25 | ) 26 | 27 | 28 | def eliminate_newlines_after_function_definition_in_file( 29 | path: Path, check: bool = False 30 | ) -> bool: 31 | """Eliminates all newlines after the function definition in a file, e.g. 32 | 33 | def foo(a): 34 | 35 | return a + 1 36 | 37 | will become: 38 | 39 | def foo(a): 40 | return a+1 41 | 42 | If = False, the file will not be touched and the return code indicated 43 | if the file would have to be formatted. 44 | 45 | Returns 0 if nothing has been changes and 1 otherwise.""" 46 | 47 | with open(path) as f: 48 | content = f.read() 49 | 50 | content_formatted = eliminate_newlines_after_function_definition_in_string( 51 | code=content 52 | ) 53 | 54 | if content_formatted != content: 55 | if not check: 56 | with open(path, "w") as f: 57 | f.write(content_formatted) 58 | click.echo(click.style(f"Reformatted file {str(path)}.", fg="yellow")) 59 | else: 60 | click.echo(click.style(f"Would reformat file {str(path)}.", fg="yellow")) 61 | return 1 62 | else: 63 | click.echo( 64 | click.style(f"File {str(path)} is already formatted. Skipping.", fg="green") 65 | ) 66 | return 0 67 | 68 | 69 | def eliminate_newlines_after_function_definition_in_file_or_directory( 70 | path: Path, check: bool = False 71 | ) -> bool: 72 | """Eliminates all newlines after the function definition in either a file or a 73 | directory (recursively in this case), e.g. 74 | 75 | def foo(a): 76 | 77 | return a + 1 78 | 79 | will become: 80 | 81 | def foo(a): 82 | return a+1 83 | 84 | If = False, the file(s) will not be touched and the return code indicated 85 | if the file would have to be formatted. 86 | 87 | Returns 0 if nothing has been changes and 1 otherwise.""" 88 | 89 | if path.is_file(): 90 | return eliminate_newlines_after_function_definition_in_file(path, check=check) 91 | elif path.is_dir(): 92 | formatted = [] 93 | for p in path.glob("**/*.py"): 94 | formatted.append( 95 | eliminate_newlines_after_function_definition_in_file(p, check=check) 96 | ) 97 | return max(formatted) 98 | -------------------------------------------------------------------------------- /tests/test_eliminate_whitespaces.py: -------------------------------------------------------------------------------- 1 | from _pytest.config import directory_arg 2 | import pytest 3 | from pytest_check import check 4 | 5 | from eliminate_newlines.core import ( 6 | eliminate_newlines_after_function_definition_in_file, 7 | eliminate_newlines_after_function_definition_in_file_or_directory, 8 | eliminate_newlines_after_function_definition_in_string, 9 | ) 10 | 11 | testcode0 = { 12 | "original": """ 13 | def foo(a): 14 | return a + 1 15 | 16 | a=1+1 17 | """, 18 | "formatted": """ 19 | def foo(a): 20 | return a + 1 21 | 22 | a=1+1 23 | """, 24 | } 25 | 26 | testcode1 = { 27 | "original": """ 28 | def foo(a): 29 | 30 | 31 | return a + 1 32 | 33 | a=1+1 34 | """, 35 | "formatted": """ 36 | def foo(a): 37 | return a + 1 38 | 39 | a=1+1 40 | """, 41 | } 42 | 43 | 44 | testcode2 = { 45 | "original": """ 46 | def test(a): 47 | 48 | return a + 1 49 | 50 | 51 | class A: 52 | def test_this(a, 53 | b, 54 | c): 55 | 56 | 57 | return a + b + c 58 | """, 59 | "formatted": """ 60 | def test(a): 61 | return a + 1 62 | 63 | 64 | class A: 65 | def test_this(a, 66 | b, 67 | c): 68 | return a + b + c 69 | """, 70 | } 71 | 72 | 73 | @pytest.mark.parametrize("code", [testcode1, testcode2]) 74 | def test_eliminate_newlines_after_function_definition_in_string(code): 75 | assert code["formatted"] == eliminate_newlines_after_function_definition_in_string( 76 | code=code["original"] 77 | ) 78 | 79 | 80 | class TestEliminateNewlinesAfterFunctionDefinitionInFile: 81 | @staticmethod 82 | @pytest.mark.parametrize( 83 | "code,expected_return_value", [[testcode0, 0], [testcode1, 1], [testcode2, 1]] 84 | ) 85 | def test_eliminate_newlines_after_function_definition_in_file( 86 | code, expected_return_value, tmp_path 87 | ): 88 | 89 | filepath = tmp_path / "testfile.py" 90 | filepath.write_text(code["original"]) 91 | 92 | return_value = eliminate_newlines_after_function_definition_in_file( 93 | path=filepath 94 | ) 95 | 96 | with check: 97 | assert ( 98 | filepath.read_text() == code["formatted"] 99 | ), "File not correctly formatted." 100 | with check: 101 | assert return_value == expected_return_value, "Return value is not correct" 102 | 103 | @staticmethod 104 | @pytest.mark.parametrize( 105 | "code,expected_return_value", [[testcode0, 0], [testcode1, 1], [testcode2, 1]] 106 | ) 107 | def test_eliminate_newlines_after_function_definition_in_file__checkmode( 108 | code, expected_return_value, tmp_path 109 | ): 110 | 111 | filepath = tmp_path / "testfile.py" 112 | filepath.write_text(code["original"]) 113 | 114 | return_value = eliminate_newlines_after_function_definition_in_file( 115 | path=filepath, check=True 116 | ) 117 | 118 | with check: 119 | assert ( 120 | filepath.read_text() == code["original"] 121 | ), "File should not be touched." 122 | with check: 123 | assert return_value == expected_return_value, "Return value is not correct" 124 | 125 | 126 | class TestEliminateNewlinesAfterFunctionDefinitionInFileOrDirectory: 127 | @staticmethod 128 | @pytest.mark.parametrize( 129 | "code,expected_return_value", [[testcode0, 0], [testcode1, 1], [testcode2, 1]] 130 | ) 131 | def test_eliminate_newlines_after_function_definition_in_file_or_directory__file( 132 | code, 133 | expected_return_value, 134 | tmp_path, 135 | ): 136 | filepath = tmp_path / "testfile.py" 137 | filepath.write_text(code["original"]) 138 | 139 | return_value = ( 140 | eliminate_newlines_after_function_definition_in_file_or_directory( 141 | path=filepath 142 | ) 143 | ) 144 | 145 | with check: 146 | assert ( 147 | filepath.read_text() == code["formatted"] 148 | ), "File not correctly formatted." 149 | with check: 150 | assert return_value == expected_return_value, "Return value is not correct" 151 | 152 | @staticmethod 153 | def test_eliminate_newlines_after_function_definition_in_file_or_directory__directory( 154 | tmp_path, 155 | ): 156 | directory = tmp_path 157 | config = ( 158 | [tmp_path / "testcode0.py", testcode0], 159 | [tmp_path / "testcode1.py", testcode1], 160 | [tmp_path / "testcode2.py", testcode2], 161 | ) 162 | 163 | for filepath, content in config: 164 | filepath.write_text(content["original"]) 165 | 166 | return_value = ( 167 | eliminate_newlines_after_function_definition_in_file_or_directory( 168 | path=directory 169 | ) 170 | ) 171 | 172 | for filepath, content in config: 173 | with check: 174 | filepath.read_text() == content[ 175 | "formatted" 176 | ], "File not correctly formatted." 177 | with check: 178 | assert return_value == 1, "Return value is not correct" 179 | 180 | @staticmethod 181 | def test_eliminate_newlines_after_function_definition_in_file_or_directory__checkmode( 182 | tmp_path, 183 | ): 184 | directory = tmp_path 185 | config = ( 186 | [tmp_path / "testcode0.py", testcode0], 187 | [tmp_path / "testcode1.py", testcode1], 188 | [tmp_path / "testcode2.py", testcode2], 189 | ) 190 | 191 | for filepath, content in config: 192 | filepath.write_text(content["original"]) 193 | 194 | return_value = ( 195 | eliminate_newlines_after_function_definition_in_file_or_directory( 196 | path=directory 197 | ) 198 | ) 199 | 200 | for filepath, content in config: 201 | with check: 202 | filepath.read_text() == content[ 203 | "original" 204 | ], "File not correctly formatted." 205 | with check: 206 | assert return_value == 1, "Return value is not correct" 207 | --------------------------------------------------------------------------------