Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

accept strings in constructor #45

Merged
merged 3 commits into from
Jun 8, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions tests/test_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,16 @@ def test_patchset_from_bytes_string(self):

self.assertEqual(ps1, ps2)

def test_patchset_string_input(self):
with codecs.open(self.sample_file, 'r', encoding='utf-8') as diff_file:
diff_data = diff_file.read()
ps1 = PatchSet(diff_data)

with codecs.open(self.sample_file, 'r', encoding='utf-8') as diff_file:
ps2 = PatchSet(diff_file)

self.assertEqual(ps1, ps2)

def test_parse_malformed_diff(self):
"""Parse malformed file."""
with open(self.sample_bad_file) as diff_file:
Expand Down
18 changes: 14 additions & 4 deletions unidiff/patch.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@ def implements_to_string(cls):
make_str = str
implements_to_string = lambda x: x
unicode = str

basestring = str


@implements_to_string
class Line(object):
Expand Down Expand Up @@ -294,6 +295,11 @@ class PatchSet(list):

def __init__(self, f, encoding=None):
super(PatchSet, self).__init__()

# convert string inputs to StringIO objects
if isinstance(f, basestring):
f = self._convert_string(f, encoding)

# make sure we pass an iterator object to parse
data = iter(f)
# if encoding is None, assume we are reading unicode data
Expand Down Expand Up @@ -355,13 +361,17 @@ def from_filename(cls, filename, encoding=DEFAULT_ENCODING, errors=None):
instance = cls(f)
return instance

@classmethod
def from_string(cls, data, encoding=None, errors='strict'):
@staticmethod
def _convert_string(data, encoding=None, errors='strict'):
"""Return a PatchSet instance given a diff string."""
if encoding is not None:
# if encoding is given, assume bytes and decode
data = unicode(data, encoding=encoding, errors=errors)
return cls(StringIO(data))
return StringIO(data)

@classmethod
def from_string(cls, data, encoding=None, errors='strict'):
return cls(cls._convert_string(data, encoding, errors))

@property
def added_files(self):
Expand Down