Skip to content

Commit 4dd9b50

Browse files
author
techtonik
committed
Make all from* functions return False if patch parsing is not successful.
Only one argument for not doing this with exceptions: - checking if a file is a valid patch should be a one-liner >>> patch.fromfile('not-a-patch') False
1 parent 1472b75 commit 4dd9b50

File tree

2 files changed

+30
-9
lines changed

2 files changed

+30
-9
lines changed

patch.py

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -109,26 +109,38 @@ def xstrip(filename):
109109
# Main API functions
110110

111111
def fromfile(filename):
112-
""" Parse patch file and return PatchSet() object
113-
XXX error reporting
112+
""" Parse patch file. If successful, returns
113+
PatchSet() object. Otherwise returns False.
114114
"""
115+
patchset = PatchSet()
115116
debug("reading %s" % filename)
116117
fp = open(filename, "rb")
117-
patchset = PatchSet(fp)
118+
res = patchset.parse(fp)
118119
fp.close()
119-
return patchset
120+
if res == True:
121+
return patchset
122+
return False
120123

121124

122125
def fromstring(s):
123-
""" Parse text string and return PatchSet() object
126+
""" Parse text string and return PatchSet()
127+
object (or False if parsing fails)
124128
"""
125-
return PatchSet( StringIO(s) )
129+
ps = PatchSet( StringIO(s) )
130+
if ps.errors == 0:
131+
return ps
132+
return False
126133

127134

128135
def fromurl(url):
129-
""" Read patch from URL
136+
""" Parse patch from an URL, return False
137+
if an error occured. Note that this also
138+
can throw urlopen() exceptions.
130139
"""
131-
return PatchSet( urllib2.urlopen(url) )
140+
ps = PatchSet( urllib2.urlopen(url) )
141+
if ps.errors == 0:
142+
return ps
143+
return False
132144

133145

134146
# --- Utility functions ---

tests/run_tests.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,10 @@
3737
verbose = True
3838

3939

40-
#: full path for directory with tests
40+
# full path for directory with tests
4141
tests_dir = dirname(abspath(__file__))
42+
def testfile(name):
43+
return join(tests_dir, 'data', name)
4244

4345

4446
# import patch.py from parent directory
@@ -226,6 +228,13 @@ def test_fromstring(self):
226228
pst = patch.fromstring(readstr)
227229
self.assertEqual(len(pst), 5)
228230

231+
def test_fromfile(self):
232+
pst = patch.fromfile(join(tests_dir, "01uni_multi.patch"))
233+
self.assertNotEqual(pst, False)
234+
self.assertEqual(len(pst), 5)
235+
ps2 = patch.fromfile(testfile("failing/not-a-patch.log"))
236+
self.assertFalse(ps2)
237+
229238
def test_no_header_for_plain_diff_with_single_file(self):
230239
pto = patch.fromfile(join(tests_dir, "03trail_fname.patch"))
231240
self.assertEqual(pto.items[0].header, [])

0 commit comments

Comments
 (0)