打造一个头文件引用修复工具(修复引用文件路径为绝对路径)

2016-02-18  本文已影响104人  sma11case

前言

由于Xcode的习惯,很多OC代码中.h文件引用都是只写文件的,因为Xcode会自动查找该文件的真实位置再传递给编译器编译,但这种做法有个限制,就是必须把.h文件引用到项目中,不然会找到,笔者的问题也就源于此,出于个人习惯,我不喜欢把不需要修改的文件引用到项目中,特别是编译好的库,一般情况下都是只引用.a文件,然后包含一个头文件全部搞掂,即方便后期维护第三方库,也方便文件管理,鉴于手动修改的文件实在太多了,这种没含量的浪费时间行为,还是交给CPU吧,于是便有了此文.

(特别说明,此工具的作用是把#import "header.h",扩展为#import "../../include/header.h"的形式,如果没这个需求就不用向下看了)

正文

假设源引用是#import "header.h",然后该文件放在上两层的include目录中(也就是../../include/header.h),先整理一下思路,要找到.h文件,第一种是暴力法,枚举整个项目目录,把找到的文件填充进去,但感觉不是很好(感觉会有隐性BUG),第二种是先列举所有可用文件列表,再从列表中匹配,这种方法可自定义程度高,本文采用此法.

进行项目目录,用命令行find . -name "*.h">~/Desktop/1.txt && find . -name "*.m">>~/Desktop/1.txt把所有可能的文件生成列表(若有其它格式,继续添加,如.mm),打开.txt./替换为完整的路径,然后把文本拆解为单行的数组,也就是完整的文件路径,对每个文件进行读取,查找引用,替换引用,重新保存,过程如下:

代码如下,有什么疑问欢迎和我交流.

@interface SCCodeHelper : NSObject
+ (void)fixHeaderWithSourceFiles: (NSArray *)sourceFiles; // 参数为可用的文件列表
@end

// SCModel为一个简易模型转换对象,可在我的github找到
@interface SCCoderFixImportHeaderInfo : SCModel
@property (nonatomic, strong) NSString *codeFile;
@property (nonatomic, strong) NSMutableString *codeString;

@property (nonatomic, strong) NSArray *validHeaders;
@property (nonatomic, strong) NSString *originImportLine;

@property (nonatomic, strong, readonly) NSString *headerFileName;
@property (nonatomic, strong, readonly) NSString *codeFileDir;
@property (nonatomic, strong, readonly) NSString *codeFileName;
@end

@implementation SCCoderFixImportHeaderInfo
- (void)setValidHeaders:(NSArray *)validHeaders
{
    _validHeaders = validHeaders;
    _headerFileName = [_validHeaders.firstObject lastPathComponent];
}

- (void)setCodeFile:(NSString *)codeFile
{
    _codeFile = codeFile;
    _codeFileDir = [_codeFile regexpReplace:@"/[^/]+$" replace:@""];
    _codeFileName = [_codeFile lastPathComponent];
}
@end

@implementation SCCodeHelper
+ (void)fixHeaderWithSourceFiles: (NSArray *)sourceFiles
{
    NSArray *ebx = sourceFiles;
    
    SCCoderFixImportHeaderInfo *info = NewClass(SCCoderFixImportHeaderInfo);
    
    for (NSString *ecx in ebx)
    {
        if (0 == ecx.length) continue;
        
        NSMutableString *code = [NSMutableString stringWithContentsOfFile:ecx encoding:NSUTF8StringEncoding error:NULL];
        if (0 == code.length) continue;
        
        NSMutableDictionary *imports = [self getImports:code];
        if (0 == imports.count) continue;
        
        for (NSString *file in imports.allKeys)
        {
            NSArray *finds = [self find:file map:sourceFiles];
            if (0 == finds.count) continue;
            
            info.codeFile = ecx;
            info.codeString = code;
            info.validHeaders = finds;
            info.originImportLine = imports[file];
            
            BOOL state = [self fixCodeWithModel:info fbackLevel:0];
            if (state) [code writeToFile:ecx atomically:YES encoding:NSUTF8StringEncoding error:NULL];
            BreakPointHere;
        }
        
        BreakPointHere;
    }
}

+ (BOOL)fixCodeWithModel: (SCCoderFixImportHeaderInfo *)info fbackLevel: (NSUInteger)fbackLevel
{
    NSString *codeFileName = info.codeFileName;
    NSString *headerFileName = info.headerFileName;
    NSString *originImportLine = info.originImportLine;
    NSString *codeFileDir = info.codeFileDir;
    NSMutableString *codeString = info.codeString;
    NSArray *validHeaders = info.validHeaders;
    
    // 跳过绝对路径
    if (StringHasSubstring(originImportLine, @"/")) return NO;
    
    BOOL codeChanged = NO;
    BOOL result = NO;
    
    if (fbackLevel)
    {
        for (NSUInteger a = 0; a < fbackLevel; ++a)
        {
            codeFileDir = [codeFileDir regexpReplace:@"/[^/]+$" replace:@""];
        }
        BreakPointHere;
    }
    
    {
        // 看看同目录
        NSString *ebx = [NSString stringWithFormat:@"%@/%@", codeFileDir, headerFileName];
        for (NSString *eax in validHeaders)
        {
            if (NO == IsSameString(eax, ebx)) continue;
            
            NSString *ecx = @"";
            if (fbackLevel)
            {
                for (NSUInteger a = 0; a < fbackLevel; ++a)
                {
                    ecx = [NSString stringWithFormat:@"../%@", ecx];
                }
            }
            NSString *line = [NSString stringWithFormat:@"#import \"%@%@\"", ecx, headerFileName];
            
            if (NO == StringHasSubstring(originImportLine, line))
            {
                MLog(@"src: %@", codeFileName);
                MLog(@"fix: %@", originImportLine);
                MLog(@"to : %@", line);
                MLog(@"=========================================================");
                [codeString replaceOccurrencesOfString:originImportLine withString:line options:0 range:NSMakeRange(0, codeString.length)];
                codeChanged = YES;
            }
            
            result = YES;
            break;
        }
        
        if (result) return codeChanged;
    }
    
    // 看看子目录
    {
        for (NSString *eax in validHeaders)
        {
            if (NO == StringHasSubstring(eax, codeFileDir)) continue;
            
            NSString *buffer = [eax stringByReplacingOccurrencesOfString:codeFileDir withString:@""];
            buffer = [buffer regexpReplace:@"^/" replace:@""];
            
            NSString *ecx = @"";
            if (fbackLevel)
            {
                for (NSUInteger a = 0; a < fbackLevel; ++a)
                {
                    ecx = [NSString stringWithFormat:@"../%@", ecx];
                }
            }
            
            NSString *line = [NSString stringWithFormat:@"#import \"%@%@\"", ecx, buffer];
            
            if (NO == StringHasSubstring(originImportLine, line))
            {
                MLog(@"src: %@", codeFileName);
                MLog(@"fix: %@", originImportLine);
                MLog(@"to : %@", line);
                MLog(@"=========================================================");
                [codeString replaceOccurrencesOfString:originImportLine withString:line options:0 range:NSMakeRange(0, codeString.length)];
                codeChanged = YES;
            }
            
            result = YES;
            break;
        }
        
        if (result) return codeChanged;
    }
    
    // 看看上层目录
    {
        if (NO == [codeFileDir isEqualToString:@"/"])
        {
            codeChanged = [self fixCodeWithModel:info fbackLevel:fbackLevel+1];
            return codeChanged;
        }
    }
    
    LogAnything(codeFileDir);
    LogAnything(info.validHeaders);
    BreakPointHere;
    return NO;
}

+ (NSMutableArray *)find: (NSString *)file map: (NSArray *)map
{
    NSMutableArray *result = NewMutableArray();
    
    for (NSString *name in map)
    {
        NSString *eax = [NSString stringWithFormat:@"/%@", file];
        if ([name hasSuffix:eax])
        {
            [result addObject:name];
        }
    }
    
    if (0 == result.count) return nil;
    return result;
}

+ (NSMutableDictionary *)getImports: (NSString *)code
{
    NSArray *imps = [code regexpMatch:@"[\\r\\n]\\s*#import\\s+\\x22[^\\x22]+\\x22"];
    
    NSMutableDictionary *result = nil;
    if (imps.count) result = NewMutableDictionary();
    
    for (NSString *eax in imps)
    {
        NSString *file = [eax regexpMatch:@"\\x22[^\\x22]+\\x22"][0];
        file = [file stringByReplacingOccurrencesOfString:@"\"" withString:@""];
        
        result[file] = [eax regexpReplace:@"[\\r\\n]+" replace:@""];
    }
    
    return result;
}
@end
上一篇下一篇

猜你喜欢

热点阅读