Last active
August 29, 2019 23:28
-
-
Save leptos-null/a492a8035aef988ead5f7bcc42eafc91 to your computer and use it in GitHub Desktop.
Find tools with the with the same name in a PATH
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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