-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathiTermPathFinder.m
271 lines (244 loc) · 10.9 KB
/
iTermPathFinder.m
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
//
// iTermPathFinder.m
// iTerm2SharedARC
//
// Created by George Nachman on 4/15/19.
//
#import "iTermPathFinder.h"
#import "DebugLogging.h"
#import "iTermPathCleaner.h"
#import "NSArray+CommonAdditions.h"
#import "NSFileManager+CommonAdditions.h"
#import "NSStringITerm.h"
#import "RegexKitLite.h"
static dispatch_queue_t iTermPathFinderQueue(void) {
static dispatch_queue_t queue;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
queue = dispatch_queue_create("com.iterm2.path-finder", DISPATCH_QUEUE_SERIAL);
});
return queue;
}
@interface iTermPathFinder()
@property (atomic, readwrite) BOOL canceled;
@end
@implementation iTermPathFinder {
NSString *_beforeStringIn;
NSString *_afterStringIn;
NSString *_workingDirectory;
BOOL _trimWhitespace;
}
- (instancetype)initWithPrefix:(NSString *)beforeStringIn
suffix:(NSString *)afterStringIn
workingDirectory:(NSString *)workingDirectory
trimWhitespace:(BOOL)trimWhitespace
ignore:(NSString *)pathsToIgnore
allowNetworkMounts:(BOOL)allowNetworkMounts {
self = [super init];
if (self) {
_beforeStringIn = [beforeStringIn copy];
_afterStringIn = [afterStringIn copy];
_workingDirectory = [workingDirectory copy];
_trimWhitespace = trimWhitespace;
_fileManager = [NSFileManager defaultManager];
_pathsToIgnore = [pathsToIgnore copy];
_allowNetworkMounts = allowNetworkMounts;
}
return self;
}
- (void)cancel {
self.canceled = YES;
}
- (void)searchWithCompletion:(void (^)(void))completion {
dispatch_async(iTermPathFinderQueue(), ^{
[self searchSynchronously];
dispatch_async(dispatch_get_main_queue(), ^{
completion();
});
});
}
- (void)searchSynchronously {
BOOL workingDirectoryIsOk = [self fileExistsAtPathLocally:_workingDirectory];
if (!workingDirectoryIsOk) {
DLog(@"Working directory %@ is a network share or doesn't exist. Not using it for context.",
_workingDirectory);
}
DLog(@"Brute force path from prefix <<%@>>, suffix <<%@>> directory=%@",
_beforeStringIn, _afterStringIn, _workingDirectory);
// Split "Foo Bar" to ["Foo", " ", "Bar"]
NSArray *beforeChunks = [self splitString:_beforeStringIn];
NSArray *afterChunks = [self splitString:_afterStringIn];
NSMutableString *left = [NSMutableString string];
int iterationsBeforeQuitting = 100; // Bail after 100 iterations if nothing is still found.
NSMutableSet *paths = [NSMutableSet set];
NSCharacterSet *whitespaceCharset = [NSCharacterSet whitespaceAndNewlineCharacterSet];
for (NSInteger i = [beforeChunks count]; i >= 0; i--) {
if (self.canceled) {
_path = nil;
return;
}
NSString *beforeChunk = @"";
if (i < [beforeChunks count]) {
beforeChunk = beforeChunks[i];
}
[left insertString:beforeChunk atIndex:0];
NSMutableString *right = [NSMutableString string];
// Do not search more than 10 chunks forward to avoid starving leftward search.
for (int j = 0; j < MAX(1, afterChunks.count) && j < 10; j++) {
if (self.canceled) {
_path = nil;
return;
}
NSString *rightChunk = @"";
if (j < afterChunks.count) {
rightChunk = afterChunks[j];
}
[right appendString:rightChunk];
NSString *possiblePath = [left stringByAppendingString:right];
NSString *trimmedPath = possiblePath;
if (_trimWhitespace) {
trimmedPath = [trimmedPath stringByTrimmingCharactersInSet:whitespaceCharset];
}
if ([paths containsObject:[NSString stringWithString:trimmedPath]]) {
continue;
}
[paths addObject:[trimmedPath copy]];
// Replace \x with x for x in: space, (, [, ], \, ).
NSString *removeEscapingSlashes = @"\\\\([ \\(\\[\\]\\\\)])";
trimmedPath = [trimmedPath stringByReplacingOccurrencesOfRegex:removeEscapingSlashes withString:@"$1"];
// Some programs will thoughtlessly print a filename followed by some silly suffix.
// We'll try versions with and without a questionable suffix. The version
// with the suffix is always preferred if it exists.
static NSArray *questionableSuffixes;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
questionableSuffixes = @[ @"!", @"?", @".", @",", @";", @":", @"...", @"…" ];
});
for (NSString *modifiedPossiblePath in [self pathsFromPath:trimmedPath byRemovingBadSuffixes:questionableSuffixes]) {
if (self.canceled) {
_path = nil;
return;
}
BOOL exists = NO;
if (workingDirectoryIsOk || [modifiedPossiblePath hasPrefix:@"/"]) {
iTermPathCleaner *cleaner = [[iTermPathCleaner alloc] initWithPath:modifiedPossiblePath
suffix:nil
workingDirectory:_workingDirectory
ignore:_pathsToIgnore
allowNetworkMounts:_allowNetworkMounts];
cleaner.reqid = self.reqid;
cleaner.fileManager = self.fileManager;
[cleaner cleanSynchronously];
exists = (cleaner.cleanPath != nil);
}
if (exists) {
NSString *extra = @"";
if (j + 1 < afterChunks.count) {
extra = [self columnAndLineNumberFromChunks:[afterChunks subarrayFromIndex:j + 1]];
}
NSString *extendedPath = [modifiedPossiblePath stringByAppendingString:extra];
[right appendString:extra];
if (_trimWhitespace &&
[[right stringByTrimmingTrailingCharactersFromCharacterSet:whitespaceCharset] length] == 0) {
// trimmedPath is trim(left + right). If trim(right) is empty
// then we don't want to count trailing whitespace from left in the chars
// taken from prefix.
_prefixChars = (int)[[left stringByTrimmingTrailingCharactersFromCharacterSet:whitespaceCharset] length];
} else {
_prefixChars = (int)left.length;
}
NSInteger lengthOfBadSuffix = extra.length ? 0 : trimmedPath.length - modifiedPossiblePath.length;
int n;
if (_trimWhitespace) {
n = (int)([[right stringByTrimmingTrailingCharactersFromCharacterSet:whitespaceCharset] length] - lengthOfBadSuffix);
} else {
n = (int)(right.length - lengthOfBadSuffix);
}
_suffixChars = MAX(0, n);
DLog(@"Using path %@", extendedPath);
_path = [extendedPath copy];
return;
}
}
if (--iterationsBeforeQuitting == 0) {
_path = nil;
return;
}
}
}
_path = nil;
return;
}
#pragma mark - Private
#pragma mark Filesystem
- (BOOL)fileExistsAtPathLocally:(NSString *)path {
_workingDirectoryIsLocal = [self.fileManager fileIsLocal:path
additionalNetworkPaths:[_pathsToIgnore componentsSeparatedByString:@","]
allowNetworkMounts:_allowNetworkMounts];
if (!_workingDirectoryIsLocal) {
return NO;
}
return [self.fileManager fileExistsAtPath:path];
}
- (BOOL)fileHasForbiddenPrefix:(NSString *)path {
return [self.fileManager fileHasForbiddenPrefix:path
additionalNetworkPaths:[_pathsToIgnore componentsSeparatedByString:@","]];
}
#pragma mark String Manipulation
- (NSArray<NSString *> *)splitString:(NSString *)string {
NSMutableArray<NSString *> *parts = [NSMutableArray array];
__block NSRange lastRange = NSMakeRange(0, 0);
[string enumerateStringsMatchedByRegex:@"([^\t ():\",]*)([\t ():\",])"
options:0
inRange:NSMakeRange(0, string.length)
error:nil
enumerationOptions:0
usingBlock:^(NSInteger captureCount,
NSString *const __unsafe_unretained *capturedStrings,
const NSRange *capturedRanges,
volatile BOOL *const stop) {
[parts addObject:capturedStrings[1]];
[parts addObject:capturedStrings[2]];
lastRange = capturedRanges[2];
}];
const NSInteger suffixStartIndex = NSMaxRange(lastRange);
if (suffixStartIndex < string.length) {
[parts addObject:[string substringFromIndex:suffixStartIndex]];
}
return parts;
}
- (NSArray *)pathsFromPath:(NSString *)source byRemovingBadSuffixes:(NSArray *)badSuffixes {
NSMutableArray *result = [NSMutableArray array];
[result addObject:source];
for (NSString *badSuffix in badSuffixes) {
if ([source hasSuffix:badSuffix]) {
NSString *stripped = [source substringToIndex:source.length - badSuffix.length];
if (stripped.length) {
[result addObject:stripped];
}
}
}
return result;
}
#pragma mark - Line Numbers
// Note that this can only see stuff *after* the filename.
- (NSString *)columnAndLineNumberFromChunks:(NSArray<NSString *> *)afterChunks {
NSString *suffix = [afterChunks componentsJoinedByString:@""];
NSArray<NSString *> *regexes = @[ @"^(:\\d+:\\d+)",
@"^(:\\d+)",
@"^(\\[\\d+, ?\\d+])",
@"^(\", line \\d+, column \\d+)",
@"^(\", line \\d+, in)",
@"^(\\(\\d+, ?\\d+\\))",
@"^(\\(\\d+\\))",
@"^( line \\d+:$)"];
// NOTE: If you change this also update regexes in iTermPathCleaner.
for (NSString *regex in regexes) {
NSString *value = [suffix stringByMatching:regex capture:1];
if (value) {
return value;
}
}
return @"";
}
@end