Skip to content

Commit

Permalink
added --length parameter
Browse files Browse the repository at this point in the history
  • Loading branch information
miki725 committed May 29, 2018
1 parent 0a485f8 commit e50be34
Show file tree
Hide file tree
Showing 13 changed files with 105 additions and 88 deletions.
17 changes: 8 additions & 9 deletions .travis.yml
@@ -1,20 +1,19 @@
# Config file for automatic testing at travis-ci.org

language: python

python:
- "3.6"
- "2.7"
- "pypy"
- "pypy3"

sudo: false

# command to install dependencies, e.g. pip install -r requirements.txt --use-mirrors
install:
- pip install -r requirements-dev.txt
- pip install tox-travis
- pip install coveralls

script:
make check
# command to run tests, e.g. python setup.py test
script: tox

after_success:
coveralls

sudo: false
after_success: coveralls
5 changes: 5 additions & 0 deletions HISTORY.rst
Expand Up @@ -3,6 +3,11 @@
History
-------

0.6.4 (2018-05-29)
~~~~~~~~~~~~~~~~~~

* Added support for custom line length.

0.6.3 (2018-01-27)
~~~~~~~~~~~~~~~~~~

Expand Down
66 changes: 23 additions & 43 deletions Makefile
Expand Up @@ -5,72 +5,52 @@ COVER_CONFIG_FLAGS=--with-coverage --cover-package=importanize,tests --cover-tes
COVER_REPORT_FLAGS=--cover-html --cover-html-dir=htmlcov
COVER_FLAGS=${COVER_CONFIG_FLAGS} ${COVER_REPORT_FLAGS}

help:
@echo "install - install all requirements including for testing"
@echo "clean - remove all artifacts"
@echo "clean-build - remove build artifacts"
@echo "clean-pyc - remove Python file artifacts"
@echo "clean-test - remove test and coverage artifacts"
@echo "clean-test-all - remove all test-related artifacts including tox"
@echo "lint - check style with flake8"
@echo "test - run tests quickly with the default Python"
@echo "test-coverage - run tests with coverage report"
@echo "test-all - run tests on every Python version with tox"
@echo "check - run all necessary steps to check validity of project"
@echo "release - package and upload a release"
@echo "dist - package"
@echo "docs - generate Sphinx HTML documentation, including API docs"
help: ## show help
@grep -E '^[a-zA-Z_\-]+:.*?## .*$$' $(MAKEFILE_LIST) | \
cut -d':' -f1- | \
sort | \
awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-15s\033[0m %s\n", $$1, $$2}'

install:
install: ## install all dependecies
pip install -U -r requirements-dev.txt

clean: clean-build clean-pyc clean-test-all
clean: clean-build clean-pyc clean-test ## clean everything except tox

clean-build:
clean-build: ## clean build and distribution artifacts
@rm -rf build/
@rm -rf dist/
@rm -rf *.egg-info

clean-pyc:
-@find . -name '*.pyc' -follow -print0 | xargs -0 rm -f
-@find . -name '*.pyo' -follow -print0 | xargs -0 rm -f
-@find . -name '__pycache__' -type d -follow -print0 | xargs -0 rm -rf
clean-pyc: ## clean pyc files
-@find . -path ./.tox -prune -o -name '*.pyc' -follow -print0 | xargs -0 rm -f
-@find . -path ./.tox -prune -o -name '*.pyo' -follow -print0 | xargs -0 rm -f
-@find . -path ./.tox -prune -o -name '__pycache__' -type d -follow -print0 | xargs -0 rm -rf

clean-test:
clean-test: ## clean test artifacts like converage
rm -rf .coverage coverage*
rm -rf htmlcov/

clean-test-all: clean-test
clean-all: clean ## clean everything including tox
rm -rf .tox/

lint:
lint: clean ## lint whole library
flake8 importanize tests
python -m importanize importanize/ tests/ --ci

test:
test: clean ## run all tests
nosetests ${NOSE_FLAGS} tests/

test-coverage:
test-coverage: clean ## run all tests with coverage
nosetests ${NOSE_FLAGS} ${COVER_FLAGS} tests/

test-all:
test-all: clean ## run all tests with tox with different python/django versions
tox

check: lint clean-build clean-pyc clean-test test-coverage
check: lint clean test-coverage ## check library which runs lint and tests

release: clean
python setup.py sdist upload
python setup.py bdist_wheel upload
release: clean ## push release to pypi
python setup.py sdist bdist_wheel upload

dist: clean
python setup.py sdist
python setup.py bdist_wheel
dist: clean ## create distribution of the library
python setup.py sdist bdist_wheel
ls -l dist

docs:
rm -f docs/importanize.rst
rm -f docs/modules.rst
sphinx-apidoc -o docs/ importanize
$(MAKE) -C docs clean
$(MAKE) -C docs html
open docs/_build/html/index.html
1 change: 1 addition & 0 deletions README.rst
Expand Up @@ -156,6 +156,7 @@ Finally, you can see all other available ``importanize`` cli options::
Not all configurations can be provided via cli.
Additional available configurations in configuration file:

* ``length`` - line length after which the formatter will split imports
* ``exclude`` - list of glob patterns of files which should be excluded from organizing.
For example::

Expand Down
2 changes: 1 addition & 1 deletion importanize/__init__.py
Expand Up @@ -4,7 +4,7 @@

__author__ = 'Miroslav Shubernetskiy'
__email__ = 'miroslav@miki725.com'
__version__ = '0.6.3'
__version__ = '0.6.4'
__description__ = (
'Utility for organizing Python imports using PEP8 or custom rules'
)
15 changes: 12 additions & 3 deletions importanize/__main__.py
Expand Up @@ -13,7 +13,7 @@
import six

from . import __description__, __version__, formatters
from .formatters import DEFAULT_FORMATTER
from .formatters import DEFAULT_FORMATTER, DEFAULT_LENGTH
from .groups import ImportGroups
from .parser import (
find_imports_from_lines,
Expand Down Expand Up @@ -93,7 +93,8 @@ def from_path(cls, path):
return cls.default()

@classmethod
def find(cls, cwd=pathlib.Path.cwd(), root=None):
def find(cls, cwd=None, root=None):
cwd = cwd or pathlib.Path.cwd()
path = cwd = cwd.resolve()

while path != pathlib.Path(root or cwd.root):
Expand Down Expand Up @@ -141,6 +142,11 @@ def __bool__(self):
choices=sorted(FORMATTERS.keys()),
help='Formatter used.'
)
parser.add_argument(
'-l', '--length',
type=int,
help='Line length when formatters will break imports.'
)
parser.add_argument(
'--print',
action='store_true',
Expand Down Expand Up @@ -216,7 +222,10 @@ def run_importanize_on_text(text, config, args):
for j in parse_statements([([i], [first_import_line_number])]):
groups.add_statement_to_group(j)

formatted_imports = groups.formatted(formatter=formatter)
formatted_imports = groups.formatted(
formatter=formatter,
length=args.length or config.get('length') or DEFAULT_LENGTH,
)

lines = text.splitlines()
for line_number in sorted(groups.all_line_numbers(), reverse=True):
Expand Down
16 changes: 10 additions & 6 deletions importanize/formatters.py
Expand Up @@ -5,6 +5,9 @@
from copy import deepcopy


DEFAULT_LENGTH = 80


def get_normalized(i):
return map(operator.attrgetter('normalized'), i)

Expand All @@ -20,8 +23,9 @@ class Formatter(object):
the import statement that must be formatted
"""

def __init__(self, statement):
def __init__(self, statement, length=DEFAULT_LENGTH):
self.statement = statement
self.length = length


class GroupedFormatter(Formatter):
Expand Down Expand Up @@ -56,7 +60,7 @@ def __init__(self, *args, **kwargs):
)

def do_grouped_formatting(self, one_liner):
return any((len(one_liner) > 80 and len(self.leafs) > 1,
return any((len(one_liner) > self.length and len(self.leafs) > 1,
len(self.all_comments) > 1))

def get_leaf_separator(self, stem=None):
Expand Down Expand Up @@ -163,7 +167,7 @@ class GroupedInlineAlignedFormatter(GroupedFormatter):
"""
name = 'inline-grouped'

def __new__(cls, statement):
def __new__(cls, statement, **kwargs):
"""
Overwrite __new__ to return GroupedFormatter formatter instance
when the statement to be formatted has both statement comment and
Expand All @@ -173,12 +177,12 @@ def __new__(cls, statement):
"""
if all([statement.comments,
statement.leafs and statement.leafs[0].comments]):
return GroupedFormatter(statement)
return GroupedFormatter(statement, **kwargs)
return super(GroupedInlineAlignedFormatter, cls).__new__(cls)

def __init__(self, statement):
def __init__(self, statement, **kwargs):
(super(GroupedInlineAlignedFormatter, self)
.__init__(self.normalize_statement(statement)))
.__init__(self.normalize_statement(statement), **kwargs))

def normalize_statement(self, statement):
if all([statement.comments,
Expand Down
12 changes: 7 additions & 5 deletions importanize/groups.py
Expand Up @@ -7,7 +7,7 @@

import six

from .formatters import DEFAULT_FORMATTER
from .formatters import DEFAULT_FORMATTER, DEFAULT_LENGTH
from .utils import is_site_package, is_std_lib


Expand Down Expand Up @@ -79,10 +79,11 @@ def as_string(self):
return sep.join(map(operator.methodcaller('as_string'),
self.unique_statements))

def formatted(self, formatter=DEFAULT_FORMATTER):
def formatted(self, formatter=DEFAULT_FORMATTER, length=DEFAULT_LENGTH):
sep = self.file_artifacts.get('sep', '\n')
return sep.join(map(operator.methodcaller('formatted',
formatter=formatter),
formatter=formatter,
length=length),
self.unique_statements))

def __str__(self):
Expand Down Expand Up @@ -184,11 +185,12 @@ def as_string(self):
self.groups)
))

def formatted(self, formatter=DEFAULT_FORMATTER):
def formatted(self, formatter=DEFAULT_FORMATTER, length=DEFAULT_LENGTH):
sep = self.file_artifacts.get('sep', '\n') * 2
return sep.join(filter(
None, map(operator.methodcaller('formatted',
formatter=formatter),
formatter=formatter,
length=length),
self.groups)
))

Expand Down
2 changes: 1 addition & 1 deletion importanize/parser.py
Expand Up @@ -131,7 +131,7 @@ def read_line(paren_count):
def tokenize_import_lines(import_lines):
tokens = []

for n, line in enumerate(import_lines):
for line in import_lines:
_tokens = []
words = filter(None, TOKEN_REGEX.split(line))

Expand Down
6 changes: 3 additions & 3 deletions importanize/statements.py
Expand Up @@ -5,7 +5,7 @@

import six

from .formatters import DEFAULT_FORMATTER
from .formatters import DEFAULT_FORMATTER, DEFAULT_LENGTH
from .mixin import ComparatorMixin
from .utils import list_strip

Expand Down Expand Up @@ -154,8 +154,8 @@ def as_string(self):
self.unique_leafs)))
)

def formatted(self, formatter=DEFAULT_FORMATTER):
return formatter(self).format()
def formatted(self, formatter=DEFAULT_FORMATTER, length=DEFAULT_LENGTH):
return formatter(self, length=length).format()

def __hash__(self):
return hash(self.as_string())
Expand Down
1 change: 1 addition & 0 deletions requirements-dev.txt
@@ -1,6 +1,7 @@
-r requirements.txt
coverage
flake8
flake8-bugbear; python_version >= '3'
mock
nose
pdbpp
Expand Down

0 comments on commit e50be34

Please sign in to comment.