-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathfsutils.py
More file actions
246 lines (211 loc) · 6.75 KB
/
fsutils.py
File metadata and controls
246 lines (211 loc) · 6.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
import os
import os.path
import re
import glob
from os import sep
from itertools import takewhile
# http://vimdoc.sourceforge.net/htmldoc/options.html#'isfname'
FNAME_CHARS = ('/','\\','.','-','_','"',"'",'+','#','$','%','{','}','[',']',':','@','!','~','=')
WIN32_FNAME_CHARS = FNAME_CHARS + (',',)
WIN32_ROOTS = re.compile('^[a-zA-Z]:[/\\\\]')
MAX_FILE_LENGTH = 255
def iglob(pattern):
def either(c):
return '[%s%s]'%(c.lower(),c.upper()) if c.isalpha() else c
# escape glob pattern
pattern = pattern.replace('?','\?')
pattern = pattern.replace('[','\[')
pattern = pattern.replace(']','\]')
icase_pattern = ''.join(map(either,pattern))
return glob.iglob(icase_pattern)
def isfnamespec(ch):
chars = WIN32_FNAME_CHARS if os.name == 'nt' else FNAME_CHARS
return ch in chars
def isfname(ch):
return ch.isalnum() or isfnamespec(ch)
def hasnext(itr):
"""
>>> hasnext(iter([1,2,3]))
True
>>> hasnext(iter([]))
False
"""
try:
next(itr)
return True
except StopIteration:
return False
def hasroot(rpath):
"""
>>> hasroot('/somepath')
True
>>> hasroot('C:/somepath')
True
>>> hasroot('C:\somepath')
True
>>> hasroot('~/somepath')
False
>>> hasroot('somepath')
False
"""
return rpath.startswith('/') or \
WIN32_ROOTS.match(rpath) != None
def isexplicitpath(rpath):
"""
>>> isexplicitpath('/somepath')
True
>>> isexplicitpath('./somepath')
True
>>> isexplicitpath('~/somepath')
True
>>> isexplicitpath('C:/somepath')
True
>>> isexplicitpath('C:\somepath')
True
>>> isexplicitpath('somepath')
False
"""
return hasroot(rpath) or \
rpath.startswith('~/') or \
rpath.startswith('./')
def ispathescaped(path):
"""
Returns true if all spaces in the path are escaped.
>>> ispathescaped(r'\\\\ catch')
False
>>> ispathescaped(r'\\\\\ nocatch')
True
>>> ispathescaped(r'\\ \\ \\ space\\ \\ escaped')
True
>>> ispathescaped('')
False
>>> ispathescaped('string')
False
>>> ispathescaped(r'simple\\ escape')
True
>>> ispathescaped('simple nonescape')
False
>>> ispathescaped(r'almost\\ all\\ spaces escaped')
False
"""
has_spaces = False
i = 0
while i < len(path):
ch = path[i]
nch = path[i+1] if i+1 < len(path) else None
# print i,ch,nch
if ch == '\\' and nch == '\\':
i += 2
elif ch == '\\' and nch == ' ':
has_spaces = True
i += 2
elif ch == ' ':
return False
else:
i += 1
return has_spaces
def scanpath(string):
"""
Return the longest sibstring of str that could be considered as a rpath.
>>> scanpath(r'with spaces\\\\ home')
'with spaces\\\\\\\\ home'
>>> scanpath(r'with spaces\\\\\\ home')
'spaces\\\\\\\\\\\\ home'
>>> scanpath('/home')
'/home'
>>> scanpath('some text with /home')
'/home'
>>> scanpath(r'some text with filename\\ with\\ spaces')
'filename\\\\ with\\\\ spaces'
>>> scanpath(r'some text with filename with\\ spaces')
'with\\\\ spaces'
>>> scanpath(r'some\\ text with spaces')
'some\\\\ text with spaces'
>>> scanpath('some text with ./filename')
'./filename'
>>> scanpath('some text with ./filename with spaces')
'./filename with spaces'
>>> scanpath('some text with wrong filename')
'some text with wrong filename'
>>> scanpath('some text ~/Documents')
'~/Documents'
>>> scanpath('some text C:\Documents')
'C:\\\\Documents'
>>> scanpath('some text C:/Documents')
'C:/Documents'
>>> scanpath(r'some text C:/Documents\\ and\\ Settings/Directory')
'C:/Documents\\\\ and\\\\ Settings/Directory'
>>> scanpath('some text C:/Documents and Settings/Directory')
'C:/Documents and Settings/Directory'
"""
rpath = ''
rstring = string[::-1]
lastsep = 0
escaped_path = False
for i,ch in enumerate(rstring):
if ch == sep: lastsep = i
if isfname(ch):
rpath += ch
elif (ch == ' ' and i-lastsep <= MAX_FILE_LENGTH):
if isexplicitpath(rpath[::-1]):
break
nch = rstring[i+1] if i+1 < len(rstring) else ''
if nch == '\\':
# the number of following \ must be even in order for the current \
# to be the escape for the space
next = ''.join([r for r in rstring[i+2:] if r == '\\'])
if (next.count('\\') & 1) != 1:
escaped_path = True
elif escaped_path:
# the current space is not escaped while others were
break
elif escaped_path:
break
rpath += ch
else:
break
return rpath[::-1]
def remove_escape_spaces(path):
return path.replace('\\ ',' ')
def escape_scapes(path):
return path.replace(' ', '\\ ')
def fuzzypath(path, cwd, aglob=iglob):
"""
Tries to find the longest possible path that actually contains some elements
@param path to be checked. All space escapes must be removed
>>> fuzzypath('some precceding test[[[[test', lambda f: iter(['testing']) if f == 'test*' else iter([]))
'test'
>>> fuzzypath('[test', lambda f: iter(['testing']) if f == 'test*' else iter([]))
'test'
>>> fuzzypath('[ttest', lambda f: iter(['testing']) if f == 'test' else iter([]))
>>> fuzzypath('[some text ttest', lambda f: iter(['testing']) if f == 'test*' else iter([]))
>>> fuzzypath('[some text test', lambda f: iter(['testing']) if f == 'test*' else iter([]))
'test'
>>> fuzzypath('[/', lambda f: iter(['testing']) if f == '/*' else iter([]))
'/'
>>> fuzzypath('/', lambda f: iter(['testing']) if f == '/*' else iter([]))
'/'
>>> fuzzypath('/file', lambda f: iter(['testing']) if f == '/file*' else iter([]))
'/file'
"""
# add current directory if it is missing
if not hasroot(path):
path = os.path.join(cwd, path)
# start with what we get
bpath = remove_escape_spaces(path)
if hasnext(aglob(bpath+'*')):
return path
for i in range(len(path)):
ch = path[i]
if (isfnamespec(ch) and ch != sep) or ch == ' ':
apath = path[i+1:] if i+1 < len(path) else path[i:]
apath = os.path.join(cwd, apath)
# path without escapes - the one we want to check
bpath = remove_escape_spaces(apath)
# print bpath, list(aglob(bpath+'*'))
if len(bpath) and hasnext(aglob(bpath+'*')):
return apath
return None
if __name__ == "__main__":
import doctest
doctest.testmod()