Skip to content

Instantly share code, notes, and snippets.

@leptos-null
Last active Aug 29, 2019
Embed
What would you like to do?
Find tools with the with the same name in a PATH
@import Foundation;
int main(int argc, const char *argv[]) {
const char *const arg = argv[1];
if (arg) {
if (strcmp(arg, "-h") == 0 || strcmp(arg, "--help") == 0 || argc > 2) {
printf("Usage: %s [PATH]\n"
"Walk through PATH and find any repeated file names. "
"A different PATH can be provided by passing it in as the first argument.\n", argv[0]);
return 1;
}
}
const char *const path = arg ?: getenv("PATH");
if (!path) {
return 1;
}
printf("Using PATH: %s\n", path);
NSArray<NSString *> *const parts = [@(path) componentsSeparatedByString:@":"];
NSMutableDictionary<NSString *, NSMutableArray<NSString *> *> *const lookup = [NSMutableDictionary dictionary];
NSFileManager *const fileManager = [NSFileManager defaultManager];
for (NSString *part in parts) {
NSArray<NSString *> *execs = [fileManager contentsOfDirectoryAtPath:part error:NULL];
for (NSString *exec in execs) {
if (lookup[exec]) {
[lookup[exec] addObject:part];
} else {
lookup[exec] = [NSMutableArray arrayWithObject:part];
}
}
}
NSMutableString *printable = [NSMutableString string];
for (NSString *exec in lookup) {
NSArray<NSString *> *paths = lookup[exec];
if (paths.count > 1) {
[printable appendFormat:@"\n%@ found in %@, ", exec, paths.firstObject];
NSUInteger const lastInd = paths.count - 2;
for (NSUInteger ind = 1; ind < lastInd; ind++) {
[printable appendFormat:@"%@, ", paths[ind]];
}
[printable appendFormat:@"and %@", paths.lastObject];
}
}
puts(printable.UTF8String);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment