Permalink
Browse files

Make slice work like [:]

  • Loading branch information...
1 parent ea13709 commit 9ce5dc081585ce1c75ab60fc580590ae1544a18f @robertkrimen robertkrimen committed Aug 25, 2011
Showing with 15 additions and 5 deletions.
  1. +13 −2 gist_it.py
  2. +2 −3 test/test_slice.py
View
@@ -9,21 +9,32 @@ def parse( location, **arguments ):
return Gist.parse( location, **arguments )
def parse_slice( slice_ ):
+ match = re.match( r'^(-?\d+)$', slice_ )
+ if match:
+ return ( int( match.group(1) ), None )
+
match = re.match( r'^(-?\d+)?:?(-?\d+)?$', slice_ )
if match is None:
return ( 0, 0 )
- return map( lambda _: int(_) if _ is not None else 0, match.groups(0) )
+
+ return map( lambda _: int(_) if _ is not None else 0, match.groups() )
'''
Take a (line) slice of content, based on a start/end index
'''
-def take_slice( content, start_line = 0, end_line = 0 ):
+def take_slice( content, start_line = None, end_line = None ):
+ if (start_line is None and end_line is None):
+ return content
+
if (start_line == 0 and end_line == 0):
return content
if (end_line == 0):
return '\n'.join(content.splitlines()[start_line:])
+ if (end_line is None):
+ return content.splitlines()[start_line]
+
return '\n'.join(content.splitlines()[start_line:end_line])
class Gist:
View
@@ -18,7 +18,7 @@ def runTest( self ):
slice_ = gist_it.parse_slice( '1' )
self.assertEqual( len( slice_ ), 2 )
self.assertEqual( slice_[0], 1 )
- self.assertEqual( slice_[1], 0 )
+ self.assertEqual( slice_[1], None )
slice_ = gist_it.parse_slice( '1:' )
self.assertEqual( len( slice_ ), 2 )
@@ -71,6 +71,7 @@ def runTest( self ):
"""
self.assertEqual( gist_it.take_slice( content, 0, 0 ), content )
self.assertEqual( gist_it.take_slice( content, 1, 2 ), "Line 2" )
+ self.assertEqual( gist_it.take_slice( content, 1, None ), "Line 2" )
self.assertEqual( gist_it.take_slice( content, 0, 2 ), "\nLine 2" )
self.assertEqual( gist_it.take_slice( content, 0, -1 ), """
Line 2
@@ -81,7 +82,5 @@ def runTest( self ):
""" )
self.assertEqual( gist_it.take_slice( content, -1, 0 ), "Line 8" )
-
-
if __name__ == '__main__':
unittest2.main()

0 comments on commit 9ce5dc0

Please sign in to comment.