Skip to content

Commit

Permalink
Add jaraco.text.show-newlines command.
Browse files Browse the repository at this point in the history
  • Loading branch information
jaraco committed Aug 13, 2022
1 parent 71f8906 commit 6dce438
Show file tree
Hide file tree
Showing 5 changed files with 68 additions and 0 deletions.
5 changes: 5 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
v3.9.0
======

Add ``jaraco.text.show-newlines`` script.

v3.8.1
======

Expand Down
10 changes: 10 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,16 @@ layout to another::
echo "',.pyf" | python -m jaraco.text.to-qwerty
qwerty

Newline Reporting
=================

Need to know what newlines appear in a file?

::

$ python -m jaraco.text.show-newlines README.rst
newline is '\n'

For Enterprise
==============

Expand Down
19 changes: 19 additions & 0 deletions jaraco/text/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -598,3 +598,22 @@ def join_continuation(lines):
except StopIteration:
return
yield item


def read_newlines(filename, limit=1024):
r"""
>>> tmp_path = getfixture('tmp_path')
>>> filename = tmp_path / 'out.txt'
>>> _ = filename.write_text('foo\n')
>>> read_newlines(filename)
'\n'
>>> _ = filename.write_text('foo\r\n')
>>> read_newlines(filename)
'\r\n'
>>> _ = filename.write_text('foo\r\nbar\nbing\r')
>>> read_newlines(filename)
('\r', '\n', '\r\n')
"""
with open(filename) as fp:
fp.read(limit)
return fp.newlines
31 changes: 31 additions & 0 deletions jaraco/text/show-newlines.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import autocommand
import inflect

from more_itertools import always_iterable

import jaraco.text


def report_newlines(filename):
r"""
Report the newlines in the indicated file.
>>> report_newlines(__file__)
newline is '\n'
>>> tmp_path = getfixture('tmp_path')
>>> filename = tmp_path / 'out.txt'
>>> _ = filename.write_text('foo\nbar\r\n')
>>> report_newlines(filename)
newlines are ('\n', '\r\n')
"""
newlines = jaraco.text.read_newlines(filename)
count = len(tuple(always_iterable(newlines)))
engine = inflect.engine()
print(
engine.plural_noun("newline", count),
engine.plural_verb("is", count),
repr(newlines),
)


autocommand.autocommand(__name__)(report_newlines)
3 changes: 3 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ install_requires =
jaraco.functools
jaraco.context >= 4.1
importlib_resources; python_version < "3.9"
autocommand
inflect
more_itertools

[options.packages.find]
exclude =
Expand Down

0 comments on commit 6dce438

Please sign in to comment.