comparison cmd2.py @ 305:f84e8be8a792

new History.span()
author catherine@dellzilla
date Wed, 27 Jan 2010 16:28:10 -0500
parents 8c96f829ba1b
children 1802f8c75265
comparison
equal deleted inserted replaced
304:8c96f829ba1b 305:f84e8be8a792
948 arg is integer -> list one history item, by index 948 arg is integer -> list one history item, by index
949 - arg, arg - (integer) -> list up to or after #arg 949 - arg, arg - (integer) -> list up to or after #arg
950 arg is string -> list last command matching string search 950 arg is string -> list last command matching string search
951 arg is /enclosed in forward-slashes/ -> regular expression search 951 arg is /enclosed in forward-slashes/ -> regular expression search
952 """ 952 """
953 try: 953 #TODO: totally failing to recognize args
954 self.stdout.write(self.last_matching(arg).pr()) 954 try:
955 #self.stdout.write(self.last_matching(arg).pr())
956 for hi in self.history.get(arg or -1):
957 self.poutput(hi.pr())
955 except: 958 except:
956 pass 959 pass
957 do_hi = do_history 960 do_hi = do_history
958 do_l = do_list 961 do_l = do_list
959 do_li = do_list 962 do_li = do_list
1097 data = f.read() 1100 data = f.read()
1098 f.close() 1101 f.close()
1099 return data 1102 return data
1100 1103
1101 class HistoryItem(str): 1104 class HistoryItem(str):
1105 listformat = '-------------------------[%d]\n%s\n'
1102 def __init__(self, instr): 1106 def __init__(self, instr):
1103 str.__init__(self) 1107 str.__init__(self)
1104 self.lowercase = self.lower() 1108 self.lowercase = self.lower()
1105 self.idx = None 1109 self.idx = None
1106 def pr(self): 1110 def pr(self):
1107 return '-------------------------[%d]\n%s\n' % (self.idx, str(self)) 1111 return listformat % (self.idx, str(self))
1108 1112
1109 class History(list): 1113 class History(list):
1110 rangeFrom = re.compile(r'^([\d])+\s*\-$') 1114 '''A list of HistoryItems that knows how to respond to user requests.
1115 >>> h = History([HistoryItem('first'), HistoryItem('second'), HistoryItem('third'), HistoryItem('fourth')])
1116 >>> h.span('-2..')
1117 ['third', 'fourth']
1118 >>> h.span('2..3')
1119 ['second', 'third']
1120 >>> h.span('3')
1121 ['third']
1122 >>> h.span(':')
1123 ['first', 'second', 'third', 'fourth']
1124 >>> h.span('2..')
1125 ['second', 'third', 'fourth']
1126 >>> h.span('-1')
1127 ['fourth']
1128 >>> h.span('-2..-3')
1129 ['third', 'second']
1130 '''
1131 def zero_based_index(self, onebased):
1132 result = onebased
1133 if result > 0:
1134 result -= 1
1135 return result
1136 def to_index(self, raw):
1137 if raw:
1138 result = self.zero_based_index(int(raw))
1139 else:
1140 result = None
1141 return result
1142 spanpattern = re.compile(r'^\s*(?P<start>\-?\d+)?\s*(?P<separator>:|(\.{2,}))?\s*(?P<end>\-?\d+)?\s*$')
1143 def span(self, raw):
1144 results = self.spanpattern.search(raw)
1145 if not results.group('separator'):
1146 return [self[self.to_index(results.group('start'))]]
1147 start = self.to_index(results.group('start'))
1148 end = self.to_index(results.group('end'))
1149 reverse = False
1150 if end is not None:
1151 if end < start:
1152 (start, end) = (end, start)
1153 reverse = True
1154 end += 1
1155 result = self[start:end]
1156 if reverse:
1157 result.reverse()
1158 return result
1159
1160 rangePattern = re.compile(r'^\s*(?P<start>[\d]+)?\s*\-\s*(?P<end>[\d]+)?\s*$')
1111 def append(self, new): 1161 def append(self, new):
1112 new = HistoryItem(new) 1162 new = HistoryItem(new)
1113 list.append(self, new) 1163 list.append(self, new)
1114 new.idx = len(self) 1164 new.idx = len(self)
1115 def extend(self, new): 1165 def extend(self, new):
1116 for n in new: 1166 for n in new:
1117 self.append(n) 1167 self.append(n)
1118 def get(self, getme): 1168
1169
1170 def get(self, getme=None, fromEnd=False):
1171 if not getme:
1172 return self
1119 try: 1173 try:
1120 getme = int(getme) 1174 getme = int(getme)
1121 if getme < 0: 1175 if getme < 0:
1122 return self[:(-1 * getme)] 1176 return self[:(-1 * getme)]
1123 else: 1177 else:
1124 return [self[getme-1]] 1178 return [self[getme-1]]
1125 except IndexError: 1179 except IndexError:
1126 return [] 1180 return []
1127 except (ValueError, TypeError): 1181 except ValueError:
1182 rangeResult = self.rangePattern.search(getme)
1183 if rangeResult:
1184 start = rangeResult.group('start') or None
1185 end = rangeResult.group('start') or None
1186 if start:
1187 start = int(start) - 1
1188 if end:
1189 end = int(end)
1190 return self[start:end]
1191
1128 getme = getme.strip() 1192 getme = getme.strip()
1129 mtch = self.rangeFrom.search(getme) 1193
1130 if mtch:
1131 return self[(int(mtch.group(1))-1):]
1132 if getme.startswith(r'/') and getme.endswith(r'/'): 1194 if getme.startswith(r'/') and getme.endswith(r'/'):
1133 finder = re.compile(getme[1:-1], re.DOTALL | re.MULTILINE | re.IGNORECASE) 1195 finder = re.compile(getme[1:-1], re.DOTALL | re.MULTILINE | re.IGNORECASE)
1134 def isin(hi): 1196 def isin(hi):
1135 return finder.search(hi) 1197 return finder.search(hi)
1136 else: 1198 else:
1244 command = [line[len(self.cmdapp.prompt):]] 1306 command = [line[len(self.cmdapp.prompt):]]
1245 line = transcript.next() 1307 line = transcript.next()
1246 while line.startswith(self.cmdapp.continuation_prompt): 1308 while line.startswith(self.cmdapp.continuation_prompt):
1247 command.append(line[len(self.cmdapp.continuation_prompt):]) 1309 command.append(line[len(self.cmdapp.continuation_prompt):])
1248 line = transcript.next() 1310 line = transcript.next()
1249 command = ''.join(command) 1311 command = ''.join(command).strip()
1250 self.cmdapp.onecmd(command.strip()) 1312 self.cmdapp.onecmd(command)
1251 result = self.outputTrap.read().strip() 1313 result = self.outputTrap.read().strip()
1252 if line.startswith(self.cmdapp.prompt): 1314 if line.startswith(self.cmdapp.prompt):
1253 message = '\nFile %s, line %d\nCommand was:\n%s\nExpected: (nothing)\nGot:\n%s\n'%\ 1315 message = '\nFile %s, line %d\nCommand was:\n%s\nExpected: (nothing)\nGot:\n%s\n'%\
1254 (fname, lineNum, command, result) 1316 (fname, lineNum, command, result)
1255 self.assert_(not(result.strip()), message) 1317 self.assert_(not(result.strip()), message)