Skip to content

Instantly share code, notes, and snippets.

@NSExceptional
Last active August 28, 2015 03:18
Show Gist options
  • Save NSExceptional/87b39651d83d220bd602 to your computer and use it in GitHub Desktop.
Save NSExceptional/87b39651d83d220bd602 to your computer and use it in GitHub Desktop.
Given a path to a folder, replaces all occurrences of `snake_case` words (ignoring `ALL_CAPS` and `dispatch_foo` and `objc_foo`) with their `camelCase` equivalent.
#import <Foundation/Foundation.h>
#define kRegex @"(?<!\")\\b(?!dispatch)(?!objc)_?([A-Z]?[a-z]+_[A-Z]?[a-z]+)"
@interface NSString (Util)
- (NSArray *)matchesForRegex:(NSString *)pattern;
- (NSArray *)allCodeFilesInDirectory;
@end
@implementation NSString (Util)
- (NSArray *)allCodeFilesInDirectory {
NSArray *allItems = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:self error:nil];
if (allItems.count) {
NSMutableArray *files = [NSMutableArray array];
for (NSString *file in allItems)
if ([file hasSuffix:@".m"] || [file hasSuffix:@".h"])
[files addObject:file];
return files;
}
return @[];
}
- (NSArray *)matchesForRegex:(NSString *)pattern {
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
if (error)
return nil;
NSArray *matches = [regex matchesInString:self options:0 range:NSMakeRange(0, self.length)];
if (matches.count == 0)
return nil;
return matches;
}
@end
NSString *URStringByRemovingUnderscore(NSString *foo) {
if (![foo containsString:@"_"]) return nil;
if ([foo.uppercaseString isEqualToString:foo]) return nil;
NSRange r = [foo rangeOfString:@"_"];
foo = [foo stringByReplacingOccurrencesOfString:@"_" withString:@""];
NSString *lowercase = [foo substringWithRange:r];
foo = [foo stringByReplacingCharactersInRange:r withString:lowercase.uppercaseString];
return foo;
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSString *folder = @"/Users/you/path/too/project/folder";
NSArray *files = [folder allCodeFilesInDirectory];
for (NSString *fileName in files) {
NSData *data = [NSData dataWithContentsOfFile:[folder stringByAppendingString:fileName]];
NSMutableString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding].mutableCopy;
NSArray *matches = [string matchesForRegex:kRegex];
while (matches.count) {
NSString *replacement;
for (NSTextCheckingResult *result in matches.reverseObjectEnumerator.allObjects) {
replacement = URStringByRemovingUnderscore([string substringWithRange:[result rangeAtIndex:1]]);
if (replacement)
[string replaceCharactersInRange:[result rangeAtIndex:1] withString:replacement];
}
matches = [string matchesForRegex:kRegex];
}
data = [string dataUsingEncoding:NSUTF8StringEncoding];
[data writeToFile:[folder stringByAppendingString:fileName] atomically:YES];
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment