iOS开发 - OCLint的自定义规则编写

OCLint 如何自定义规则 一 准备开发环境 二开发规则一 、准备开发环境 mac系统安装有Xcode,git,ruby(一般都会有),还有要会科学上网 在OCLint的github上clone下代码 https://github.com/oclint/oclint 。(不要下载官方网站的代码),目录如下:├── README.md ├── oclint-core ├── oclint-driver ├── oclint-me 阅读详情

通过Xcode显示Warning

方案的选择

前面已经说过如何添加自定义的规则rule以及Xcode调试:iOS开发 - OCLint自定义规则的编译与Xcode调试

一般来说,我们都有这样的需求:想在写代码的时候,就能分析出代码问题,并及时进行修改。虽然OCLint能够分析单个文件,但没有Xcode插件,像 Analyze 这样的实时分析可能并不好实现,这里我们就选择编译一次然后在项目中提示出所有的问题。

有如下方案:

  • 在主工程中添加Run Script
    这个方案并不可取,原因有:
    1.Warning容易与原工程的Warning混淆,没法区分是 Analyze 还是OCLint的Warning。
    2.每次编译都会运行代码检测,编译时间会被拉长,有时候你仅仅只需要编译,不需要代码分析。

  • 通过 Aggregate 添加脚本
    这样子能和编译分离,避免每次都进行代码分析。

OK,我们就采取 Aggregate 添加脚本的方式。

简易Rule编写

上篇文章中没有提及自定义规则的编写,这里先编写一个简单的检测rule,把流程走通,然后在进行全面的rule编写:

在定义的自定义rule文件中选取 VisitObjCMethodDecl 进行编写一个检测方法首字母的rule:

//表示这个rule的名称,叫什么
    virtual const string name() const override
    {
        return "ObjCMethodCapitalBegin";
    }
//优先级,分为P1 P2 P3,如果不进行任何设置,P1是不允许的,P2允许10次,P3允许20次,超过的话OCLint就会报错。当然这些限值可以修改
    virtual int priority() const override
    {
        return 3;
    }
//区分这个Waring种类是哪种类型,一般自行创建的会设置为custom
    virtual const string category() const override
    {
        return "growing";
    }

#ifdef DOCGEN
    virtual const std::string since() const override
    {
        return "0.15";
    }

    virtual const std::string description() const override
    {
        return ""; // TODO: fill in the description of the rule.
    }

    virtual const std::string example() const override
    {
        return R"rst(
.. code-block:: cpp

    void example()
    {
        // TODO: modify the example for this rule.
    }
        )rst";
    }
    
    bool VisitObjCMethodDecl(ObjCMethodDecl *node)
    {
        //检查名称的每部分,都不允许以大写字母开头
        Selector sel = node -> getSelector();
        string selectorName = sel.getAsString();
        int selectorPartCount = node -> getNumSelectorLocs();
        
        for (int i = 0; i < selectorPartCount; i++) {
            // 方法参数名称
            StringRef selName = sel.getNameForSlot(i);
            if (selName.size() == 0) {
                return true;
            }
            char c = selName[0];
            if (isUppercase(c)) {
                // 提示
                // 获取将要报错的位置
                SourceLocation loc = node->getSelectorLoc(i);
                string message = "方法名/方法参数: \'" + selectorName + "\' 不能以大写开头";
                addViolation(loc, loc, this, message);
            }
            if (c == '_') {
                // 提示
                // 获取将要报错的位置
                SourceLocation loc = node->getSelectorLoc(i);
                string message = "方法名/方法参数: \'" + selectorName + "\' 不要以下划线开头";
                addViolation(loc, loc, this, message);
            }
        }
        return true;
    }

将下图中的启动参数修改在这里插入图片描述
修改为:

-R=/Users/sheng/Documents/Caicai/OCLint/oclint/oclint-xcoderules/rules.dl/Debug /Users/sheng/Documents/Caicai/OCLint/oclint/demo/Test.m -- -x objective-c -isystem /Users/sheng/Documents/Caicai/OCLint/oclint/build/oclint-release/lib/clang/10.0.0/include -iframework /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/System/Library/Frameworks -isystem /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/usr/include

这会使得输入到Xcode的控制台,然后Run进行调试,输出为:

OCLint Report

Summary: TotalFiles=1 FilesWithViolations=1 P1=0 P2=0 P3=5 

/Users/sheng/Documents/Caicai/OCLint/oclint/demo/Test.m:16:28: unused method parameter [unused|P3] The parameter '_name' is unused.
/Users/sheng/Documents/Caicai/OCLint/oclint/demo/Test.m:6:5: short variable name [naming|P3] Length of variable name `i` is 1, which is shorter than the threshold of 3
/Users/sheng/Documents/Caicai/OCLint/oclint/demo/Test.m:16:14: Growing Code Warning [growing|P3] 方法名/方法参数: 'JsonFromFile:' 不能以大写开头
/Users/sheng/Documents/Caicai/OCLint/oclint/demo/Test.m:3:1: long variable name [naming|P3] Length of variable name `kGrowingNormalEventPath` is 23, which is longer than the threshold of 20
/Users/sheng/Documents/Caicai/OCLint/oclint/demo/Test.m:6:5: unused local variable [unused|P3] The local variable 'i' is unused.

[OCLint (http://oclint.org) v0.15]
Program ended with exit code: 0

然后生成dylib库,这里选择 ALL_BUILD 生成所有release格式的dylib。

如果无法生成所有的,去ALL_BUILD的Build Phases->Dependencies添加所有的dylib即可。

然后获取到输出路径 /Volumes/CaiCai/OCLint/oclint/oclint-xcoderules/rules.dl/Release

brew安装

由于给公司小伙伴使用,当然是最简单最好,拉源码拷贝配置的方式太LOW了,也太麻烦,小伙伴当然想着步骤越少越好。我们使用brew安装OCLint,然后进行添加dylib,这样的工作量比较少了。

尝试了一下发现brew上oclint版本为0.13,我在0.15上编译的dylib通过0.13编译报错,可能是Clang版本不一致的原因,考虑到需要修改其内容,不如自己做一套。

https://blog.csdn.net/shengpeng3344/article/details/107378382

Aggregate 添加脚本

添加 Aggregate ,并添加脚本

source ~/.bash_profile

cd ${SRCROOT}
 
xcodebuild clean
 
#build xcodebuild.log
xcodebuild | xcpretty -r json-compilation-database -o compile_commands.json

oclint-json-compilation-database -e Pods -v -- -report-type xcode   -rc LONG_LINE=1000 -rc LONG_VARIABLE_NAME=100 -max-priority-1=9999 -max-priority-2=9999 -max-priority-3=9999 -R=/Volumes/CaiCai/OCLint/oclint/oclint-xcoderules/rules.dl/Release 
  • -e Pods 过滤Pods
  • -report-type xcode 输出到Xcode IDE
  • -rc LONG_LINE=1000 行长度设置为1000,原OCLint设置为100,太容易报Warning了
  • -rc LONG_VARIABLE_NAME=100 变量名长度设置100
  • -max-priority 优先级允许错误个数,这里 P1 P2 P3 都设置为9999
  • -R= 设置调试的dylib文件夹路径,我们上面已经生成了一个了

更多设置参考官网 http://docs.oclint.org/en/stable/manual/oclint.html

配置好之后Run,项目中就可以看到提示。
在这里插入图片描述
说明自定义库检测成功了,我们需要去掉-R,将我们编译的自定义的 libCCRuleTestRule.dylib 拷贝到默认引用的那个OCLint 的lib库中去。

注意要拷贝Release版本,因为Debug版本dylib库太大了

我这里路径是:/Users/sheng/Documents/Caicai/OCLint/oclint/build/oclint-release/lib/oclint/rules

去掉 -R,再进行 Run,成功。

好了,我们将-R加上,进行编写各种规则。

规则编写

我们要使用

clang -fmodules -fsyntax-only -Xclang -ast-dump test.m

来分析文件抽象语法树组成,先将有问题的代码输入,然后查找关键字。

关于OC的编译过程,抽象语法树在何时生成,可以 查看此文

例如我们需要编写分类前缀和static NSString前缀的规则,就加入如下代码:

#import <Foundation/Foundation.h>
static NSString * const kGrowingNormalEventPath = @"/v2/%@/ios/events?stm=%llu";
int main(void) {
    int i=9;
    return 0;
}
@interface AppGroupManager : NSObject

@end

@implementation AppGroupManager
- (NSString*)JsonFromFile:(NSString*)_name {
    return @"";
}
@end

@implementation AppGroupManager (Growing_node)
@end

然后转成AST进行查看

TranslationUnitDecl 0x7ff69001ce08 <<invalid sloc>> <invalid sloc> <undeserialized declarations>
|-TypedefDecl 0x7ff69001d6a0 <<invalid sloc>> <invalid sloc> implicit __int128_t '__int128'
| `-BuiltinType 0x7ff69001d3a0 '__int128'
|-TypedefDecl 0x7ff69001d710 <<invalid sloc>> <invalid sloc> implicit __uint128_t 'unsigned __int128'
| `-BuiltinType 0x7ff69001d3c0 'unsigned __int128'
|-TypedefDecl 0x7ff69001d7b0 <<invalid sloc>> <invalid sloc> implicit SEL 'SEL *'
| `-PointerType 0x7ff69001d770 'SEL *' imported
|   `-BuiltinType 0x7ff69001d600 'SEL'
|-TypedefDecl 0x7ff69001d898 <<invalid sloc>> <invalid sloc> implicit id 'id'
| `-ObjCObjectPointerType 0x7ff69001d840 'id' imported
|   `-ObjCObjectType 0x7ff69001d810 'id' imported
|-TypedefDecl 0x7ff69001d978 <<invalid sloc>> <invalid sloc> implicit Class 'Class'
| `-ObjCObjectPointerType 0x7ff69001d920 'Class' imported
|   `-ObjCObjectType 0x7ff69001d8f0 'Class' imported
|-ObjCInterfaceDecl 0x7ff69001d9d0 <<invalid sloc>> <invalid sloc> implicit Protocol
|-TypedefDecl 0x7ff69001dd48 <<invalid sloc>> <invalid sloc> implicit __NSConstantString 'struct __NSConstantString_tag'
| `-RecordType 0x7ff69001db40 'struct __NSConstantString_tag'
|   `-Record 0x7ff69001daa0 '__NSConstantString_tag'
|-TypedefDecl 0x7ff69005a400 <<invalid sloc>> <invalid sloc> implicit __builtin_ms_va_list 'char *'
| `-PointerType 0x7ff69001dda0 'char *'
|   `-BuiltinType 0x7ff69001cea0 'char'
|-TypedefDecl 0x7ff69005a6e8 <<invalid sloc>> <invalid sloc> implicit __builtin_va_list 'struct __va_list_tag [1]'
| `-ConstantArrayType 0x7ff69005a690 'struct __va_list_tag [1]' 1
|   `-RecordType 0x7ff69005a4f0 'struct __va_list_tag'
|     `-Record 0x7ff69005a458 '__va_list_tag'
|-ImportDecl 0x7ff68f868d78 </Users/sheng/Documents/Caicai/OCLint/oclint/demo/test.m:1:1> col:1 implicit Foundation
|-VarDecl 0x7ff68f86a320 <line:2:1, col:52> col:25 kGrowingNormalEventPath 'NSString *const' static cinit
| `-ObjCStringLiteral 0x7ff68f86a440 <col:51, col:52> 'NSString *'
|   `-StringLiteral 0x7ff68f86a408 <col:52> 'char [27]' lvalue "/v2/%@/ios/events?stm=%llu"
|-FunctionDecl 0x7ff68f86a540 <line:3:1, line:6:1> line:3:5 main 'int (void)'
| `-CompoundStmt 0x7ff68f86a708 <col:16, line:6:1>
|   |-DeclStmt 0x7ff68f86a6c0 <line:4:5, col:12>
|   | `-VarDecl 0x7ff68f86a638 <col:5, col:11> col:9 i 'int' cinit
|   |   `-IntegerLiteral 0x7ff68f86a6a0 <col:11> 'int' 9
|   `-ReturnStmt 0x7ff68f86a6f8 <line:5:5, col:12>
|     `-IntegerLiteral 0x7ff68f86a6d8 <col:12> 'int' 0
|-ObjCInterfaceDecl 0x7ff68f86a740 <line:7:1, line:9:2> line:7:12 AppGroupManager
| |-super ObjCInterface 0x7ff68f869488 'NSObject'
| `-ObjCImplementation 0x7ff68f86a870 'AppGroupManager'
|-ObjCImplementationDecl 0x7ff68f86a870 <line:11:1, line:15:1> line:11:17 AppGroupManager
| |-ObjCInterface 0x7ff68f86a740 'AppGroupManager'
| `-ObjCMethodDecl 0x7ff68f86a9e0 <line:12:1, line:14:1> line:12:1 - JsonFromFile: 'NSString *'
|   |-ImplicitParamDecl 0x7ff68f87d618 <<invalid sloc>> <invalid sloc> implicit self 'AppGroupManager *'
|   |-ImplicitParamDecl 0x7ff68f87d680 <<invalid sloc>> <invalid sloc> implicit _cmd 'SEL':'SEL *'
|   |-ParmVarDecl 0x7ff68f86aa68 <col:28, col:38> col:38 _name 'NSString *'
|   `-CompoundStmt 0x7ff68f87d770 <col:44, line:14:1>
|     `-ReturnStmt 0x7ff68f87d760 <line:13:5, col:13>
|       `-ObjCStringLiteral 0x7ff68f87d740 <col:12, col:13> 'NSString *'
|         `-StringLiteral 0x7ff68f87d728 <col:13> 'char [1]' lvalue ""
`-ObjCCategoryImplDecl 0x7ff68f8c9978 <line:17:1, line:18:1> line:17:17 Growing_node
  |-ObjCInterface 0x7ff68f86a740 'AppGroupManager'
  `-ObjCCategory 0x7ff68f8c98e0 'Growing_node'

ObjCCategoryImplDecl 明显就是分类的,然后搜索代码,找到

    /* Visit ObjCCategoryImplDecl
    bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *node)
    {
        return true;
    }
     */

去掉注释,然后观察类型里面的值,进行判断,最终通过addViolation添加waring错误,这里举例几个示例。

Static常量和Extern常量

对于static修饰的常量,我们应该以k开头,并附带Growing字段,并附加该常量说明,尽可能简洁详细,不应该带下划线

从AST中分析到VarDecl表示变量类型

|-VarDecl 0x7fd2f9aed320 <line:3:1, col:52> col:25 kGrowingNormalEventPath 'NSString *const' static cinit
| `-ObjCStringLiteral 0x7fd2f9aed440 <col:51, col:52> 'NSString *'
|   `-StringLiteral 0x7fd2f9aed408 <col:52> 'char [27]' lvalue "/v2/%@/ios/events?stm=%llu"
  1. 通过 getType 获取类型,类型为 NSString *const
  2. 通过 getInitStyle 获取初始化类型,类型为 cinit
  3. 判断是否 Static
  4. 是否 NSString * 类型
  5. 获取配置的前缀名,默认为 kGrowing,并判断
  6. 获取 location 添加 addViolation
	/// 检测到变量声明
    /// 1. static以及Extern修饰的NSString类型,以kGrowing开头
    bool VisitVarDecl(VarDecl *node)
    {
        string varname = node->getNameAsString();
        //通过 `getType` 获取类型,类型为 `NSString *const`
        QualType type = node->getType();
        //通过 `getInitStyle`  获取初始化类型,类型为 `cinit` 
        clang::VarDecl::InitializationStyle initType = node->getInitStyle();
        if (initType == clang::VarDecl::CInit) {
        	//判断是否 `Static` 
            StorageClass stclass = node->getStorageClass();
            bool isStatic = (stclass == SC_Static || stclass == SC_Extern);
            string typeName = type.getAsString();
            //是否 `NSString *` 类型
            if (isPrefixOf("NSString *", typeName) && isStatic) {
            //获取配置的前缀名,默认为 `kGrowing`,并判断
                string prefix = RuleConfiguration::stringForKey("GIO_STATIC_NSSTRING_PREFIX","kGrowing");
                if (!isPrefixOf("kGrowing", varname)) {
                //获取 `location` 添加 `addViolation`
                    SourceLocation loc = node->getLocation();
                    string message = "static NSString*的变量: \'" + varname + "\' 前缀应使用" + prefix;
                    addViolation(loc, loc, this, message);
                }
            }
        }
        
        return true;
    }

最终输出就为:

/Users/sheng/Documents/Caicai/OCLint/oclint/demo/Test.m:3:25: growing rule [custom|P3] static NSString*的变量: 'XXXNormalEventPath' 前缀应使用kGrowing

BOOL类型的规则判断

Objective-C使用YES和NO。因此true和false只能用于CoreFoundation、C或c++代码。因为nil解析为NO,所以没有必要在条件下对它进行比较。永远不要直接将某个值与YES进行比较,因为YES被定义为1,一个BOOL最多可以是8位。

    bool VisitIfStmt(IfStmt *node)
    {
        //获得操作符号
        Expr* condExpr = node->getCond();
        BinaryOperator *binaryOperator = dyn_cast_or_null<BinaryOperator>(condExpr);
        ///如果是 == 和 !=
        if ((binaryOperator && binaryOperator->getOpcode() == BO_NE) || (binaryOperator && binaryOperator->getOpcode() == BO_EQ)) {
            //获得左右两侧 expr
            ImplicitCastExpr *lhs = dyn_cast<ImplicitCastExpr>(binaryOperator->getLHS());
            ImplicitCastExpr *rhs = dyn_cast<ImplicitCastExpr>(binaryOperator->getRHS());
            //当expr为BOOL类型时,强转ObjCBoolLiteralExpr并判断是否为true,然后加入violation
            if (GrowingCheckImplicitCastExpr(lhs) || GrowingCheckImplicitCastExpr(rhs)) {
                SourceLocation loc = node->getIfLoc();
                string message = "不能与YES的BOOL值进行直接比较";
                addViolation(loc, loc, this, message);
            }
        }
        return true;
    }
    
    bool GrowingCheckImplicitCastExpr(ImplicitCastExpr *expr) {
        Expr *subExpr = expr->getSubExpr();
        string operatorStr = subExpr->getType().getAsString();
        if (operatorStr == "BOOL") {
            ObjCBoolLiteralExpr *trueObjCBOOL =
            dyn_cast_or_null<ObjCBoolLiteralExpr>(subExpr);
            if (trueObjCBOOL && trueObjCBOOL->getValue()) {
               return true;
            }
        }
        return false;
    }

枚举 Enum

在使用枚举时,建议使用新的类型规范,因为它具有更强的类型检查和代码完成功能。SDK现在包含一个宏来促进和鼓励使用固定的底层类型:NS_ENUM()

代码中加入两种枚举类型

typedef enum : NSUInteger {
    GrowingTypeA,
    GrowingTypeB,
    GrowingTypeC,
} GrowingType;

typedef NS_ENUM(NSUInteger, GrowingKind) {
    GrowingKindA,
    GrowingKindB,
    GrowingKindC,
};

发现NS_ENUM()的枚举有EnumExtensibilityAttr和prev,通过这两个值来过滤

|-EnumDecl 0x7fc2a4075c78 <line:4:9, line:8:1> line:4:9 'NSUInteger':'unsigned long'
| |-EnumConstantDecl 0x7fc2a4075d50 <line:5:5> col:5 GrowingTypeA 'NSUInteger':'unsigned long'
| |-EnumConstantDecl 0x7fc2a4075da0 <line:6:5> col:5 GrowingTypeB 'NSUInteger':'unsigned long'
| `-EnumConstantDecl 0x7fc2a4075df0 <line:7:5> col:5 GrowingTypeC 'NSUInteger':'unsigned long'
|-TypedefDecl 0x7fc2a4075e98 <line:4:1, line:8:3> col:3 GrowingType 'enum GrowingType':'GrowingType'
| `-ElaboratedType 0x7fc2a4075e40 'enum GrowingType' sugar
|   `-EnumType 0x7fc2a4075d30 'GrowingType'
|     `-Enum 0x7fc2a4075c78 ''
|-EnumDecl 0x7fc2a4076208 </Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/CoreFoundation.framework/Headers/CFAvailability.h:138:43, /Users/sheng/Documents/Caicai/OCLint/oclint/demo/test.m:10:29> col:29 GrowingKind 'NSUInteger':'unsigned long'
| `-EnumExtensibilityAttr 0x7fc2a40762e0 </Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/CoreFoundation.framework/Headers/CFAvailability.h:127:45, col:68> Open
|-TypedefDecl 0x7fc2a4076378 </Users/sheng/Documents/Caicai/OCLint/oclint/demo/test.m:10:1, col:29> col:29 GrowingKind 'enum GrowingKind':'enum GrowingKind'
| `-ElaboratedType 0x7fc2a4076320 'enum GrowingKind' sugar
|   `-EnumType 0x7fc2a40762c0 'enum GrowingKind'
|     `-Enum 0x7fc2a40763f8 'GrowingKind'
|-EnumDecl 0x7fc2a40763f8 prev 0x7fc2a4076208 </Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/CoreFoundation.framework/Headers/CFAvailability.h:138:90, /Users/sheng/Documents/Caicai/OCLint/oclint/demo/test.m:14:1> line:10:29 GrowingKind 'NSUInteger':'unsigned long'
| |-EnumExtensibilityAttr 0x7fc2a40764c8 </Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/CoreFoundation.framework/Headers/CFAvailability.h:127:45> Inherited Open
| |-EnumConstantDecl 0x7fc2a40764d8 </Users/sheng/Documents/Caicai/OCLint/oclint/demo/test.m:11:5> col:5 GrowingKindA 'NSUInteger':'unsigned long'
| |-EnumConstantDecl 0x7fc2a4076528 <line:12:5> col:5 GrowingKindB 'NSUInteger':'unsigned long'
| `-EnumConstantDecl 0x7fc2a4076578 <line:13:5> col:5 GrowingKindC 'NSUInteger':'unsigned long'

同时,我们可以遍历 EnumConstantDecl 判断值是否与枚举类型对应

    bool VisitEnumDecl(EnumDecl *node)
    {
        string nodename = node->getNameAsString();
        if (nodename.length() > 0) {
            for (clang::CapturedDecl::specific_decl_iterator<EnumConstantDecl> decllt = node->enumerator_begin(); decllt != node->enumerator_end(); decllt++) {
                EnumConstantDecl *tmp = *decllt;
                string tmpname = tmp->getNameAsString();
                if (!isPrefixOf(tmpname, nodename)) {
                    SourceLocation loc = tmp->getLocation();
                    string message = "枚举值\'" + tmpname + "\'与声明的类型不对应,应该以\'" + nodename + "\'为前缀";
                    addViolation(loc, loc, this, message);
                }
            }
        }
        
        Decl *decl = node->getPreviousDecl();
        bool hasattr = node->hasAttrs();
        if (hasattr || decl) {
            return true;
        }
        SourceLocation loc = node->getLocation();
        string message = "请使用\'typedef NS_ENUM\'类型枚举";
        addViolation(loc, loc, this, message);
        return true;
    }

检测NSString的copy属性以及集合类型泛型判断

    ///检测到属性,不管是谁的属性
    bool VisitObjCPropertyDecl(ObjCPropertyDecl *node)
    {
        string propertyname = node->getNameAsString();
        QualType type = node->getType();
        string ivarname = type.getAsString();
        if (isPrefixOf("NSString", ivarname)) {
            int kind = node->getPropertyAttributes();
            if (kind & 0x20) {
                //nothing
            } else {
                SourceLocation loc = node->getLocation();
                string message = "\'NSString\'类型的属性: \'" + propertyname + "\' 应该以copy修饰";
                addViolation(loc, loc, this, message);
            }
        }
        string str[] = {"NSArray", "NSDictionary", "NSSet"};
        vector<string> v(str,str+sizeof(str)/sizeof(str[0]));
        
        
        string templateStr[] = {"NSArray<NSNumber *>*", "NSDictionary<NSString *, NSDate *>*", "NSSet<NSNumber *>*"};
        vector<string> templateV(templateStr,templateStr+sizeof(templateStr)/sizeof(templateStr[0]));
        
        for (vector<string>::size_type i = 0; i != v.size(); ++i) {
            string classname = v[i];
            if (isPrefixOf(classname, ivarname)) {
                if (ivarname.find("<") == ivarname.npos && ivarname.find(">") == ivarname.npos) {
                    SourceLocation loc = node->getLocation();
                    string message = classname + " 集合的属性: \'" + propertyname + "\' 应该以指定泛型. eg:" + templateV[i];
                    addViolation(loc, loc, this, message);
                }
            }
        }
        
        
        StringRef nameref = node->getName();
        if (isUppercase(nameref[0])) {
            SourceLocation loc = node->getLocation();
            string message = "属性: \'" + propertyname + "\' 不能以大写开头";
            addViolation(loc, loc, this, message);
        }
        
        return true;
    }

Report的修改

由于OCLint默认设置提示的是Warning,我希望它提示Error,了解其构成之后,发现可以从Reporter中下手脚。

  1. 按照 https://blog.csdn.net/shengpeng3344/article/details/106926671 所述,同理创建Reporter的工程
  2. 找到Xcode Reporter,修改其代码为 Error
    void writeViolation(std::ostream &out, const Violation &violation)
    {
        out << violation.path << ":" << violation.startLine << ":" << violation.startColumn;
        const RuleBase *rule = violation.rule;
//        out << ": warning: " << rule->name();
        out << ": error: " << rule->name();
        out << " [" << rule->category() << "|P" << rule->priority() << "]";
        out << " " << violation.message;
    }
  1. 编译后,替换 /oclint/build/oclint-growing/lib/oclint/reporters 中的 libXcodeReporter.dylib
  2. 重新运行检测,OK,现在提示错误了。

demo链接

我将修改后的rule源码以及使用demo放在了github上 https://github.com/growingio/oclint-growing

代码格式化

关于项目中的空格,对齐等问题,想使用工具解决,这里找到Clang-format,能够方便的解决我的问题,而且使用clang-format google标准。

安装

  1. 使用brew
brew install clang-format
  1. 直接安装
sudo apt install clang-format

使用

  • 预览规范后的代码,输出到控制台
clang-format main.cc
  • 直接在原文件上规范代码
clang-format -i main.cc
  • 显示指明代码规范,默认为 LLVM
clang-format -style=google main.cc
  • 将代码规范配置信息写入文件 .clang-format
clang-format -dump-config > .clang-format

使用自定义代码规范,规范位于当前目录或任一父目录的文件 .clang-format 或 _clang-format 中(如果未找到文件,使用默认代码规范)

clang-format -style=file main.cc

这里-style=file 就是对的,不要将file替换为.clang-format

根据文件变动调用clang-format

我想根据git的文件变动,仅对变动的文件进行clang-format,无论我有没有进行add和commit操作,撰写脚本如下:

#获取现在shell的目录
cur_dir=$(dirname $0)
echo "[LOG] current path is :$cur_dir"

gio_dirname=$(echo $cur_dir | grep "Growing")

if [[ "$gio_dirname" == "" ]]; then
	echo "该shell脚本目录不为Growing,exit"
	exit 0;
fi

cd "$cur_dir"
# 获得变动文件
git status | grep -Eo '([A-Za-z0-9_-]+/){1,}[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+' > $cur_dir/git_changed.txt
# 路径去重
sort -k2n $cur_dir/git_changed.txt | uniq > $cur_dir/git_changed_output.txt


find_code_file() {
	m_name=$1
	if [[ "${m_name##*.}"x = "m"x || "${m_name##*.}"x = "mm"x|| "${m_name##*.}"x = "cpp"x||"${m_name##*.}"x = "c"x|| "${m_name##*.}"x = "h"x|| "${m_name##*.}"x = "hpp"x ]];then
    	
    	if [[ -f $m_name ]]; then
    		#statements
    		echo "clang-format Code :$m_name"
    		clang-format -style=google -i $m_name
    	else
    		echo "clang-format Not Exist:$m_name"
    	fi
    	
	fi
}

format_code() {
	# 获取文件列表
	filelist=$1

	while read line
	do
		if [[ "$line" != "" ]]; then
			find_code_file "$cur_dir/$line"
		fi
	done < $1
}

echo "[LOG] 格式化文件 $cur_dir/git_changed_output.txt"
format_code $cur_dir/git_changed_output.txt


rm $cur_dir/git_changed.txt
rm $cur_dir/git_changed_output.txt

Demo链接: https://github.com/growingio/oclint-growing


参考链接:
https://www.cnblogs.com/liuyunbin/p/11538267.html
http://clang.llvm.org/docs/ClangFormat.html
https://blog.csdn.net/shengpeng3344/article/details/106926671
http://clang.llvm.org/docs/ClangFormatStyleOptions.html

OCLint+Xcode实现Code Review Code Review是开发过程中保证代码质量不可或缺的一部分,但是呢,要么是懒,要么是真没时间,在我们公司code review已从原来的流于形式到彻底废弃了。最近看了看项目代码,咋写的都有,看着确实难受,于是就动了“code review自动化”的念头。xcode里有内置的Analyser,但由于默认的规则太少导致功能实在很有限。找了半天,就盯上OCLint了。OCLint是啥我就不多说啦,具 阅读详情

相关推荐

Xilinx的DDR4 IP

Xilinx的DDR4 IP

weixin_39896700的博客 4471

关于OCLint自定义规则

###2017.9.25 升级Xcode9GM版本后是无法用Xcode9的命令行工具的,建议切换到Xcode8的命令行工具,或者等到OCLint新版本适配Xcode9 ###静态编译分析 这段时间公司要求添加静态扫描的功能,还要能自定义规则,所以就花了两天进行研究。 1.Xcode内部自带的Clang Static Analyzer(简称CSA) 2.OCLint 两者都是基于clang的前端编译...

weixin_34414650的博客 389

【Unity】ABB CRB 15000 外部引导运动实战:从配置到实时控制

本文详细介绍了ABB CRB 15000协作机器人的外部引导运动(EGM)功能在Unity环境中的实战应用。从RobotStudio配置到Unity实时通信架构,再到EGM运动控制技巧和问题排查,全面解析如何实现机器人的高精度实时控制。通过实际案例展示EGM技术在精密装配等场景中的显著效果,帮助开发者快速掌握这一先进技术。

weixin_29057695的博客 448

OCLint的使用

OCLint的使用与集成 1,通过Homebrew安装 使用命令行 brew tap oclint/formulae brew install oclint 2,下载安装包安装 1,进入OCLint在Github的地址,选择release,选择最新版本的安装包 2,解压下载文件。将文件存放到一个合适的位置。(比如我选择将这些需要的源代码存放到 Document 目录下) 3,在终端编辑当前环境的配置文件,将 bin 目录添加到 PATH 下,编辑 .bashrc 或 vim .bash_profile OC

qq_30252465的博客 1557

Microsoft Dynamics 365软件二次开发:Dynamics365部署与版本控制策略

在Microsoft Dynamics 365中,自定义实体允许开发者扩展系统以满足特定业务需求。自定义实体可以包含字段、选项集、关系和其他属性,与标准实体类似,但完全由用户定义。1. 登录到Dynamics 365环境。2. 转到“解决方案”区域,选择“自定义”。3. 在“自定义”菜单中,选择“实体”。4. 点击“新建”,输入实体名称,例如“客户反馈”。5. 添加字段,如“反馈类型”、“反馈日期”、“描述”等。6. 设置主键和唯一标识符。7. 定义关系,如与“客户”实体的关联。

kkchenjj的博客 2216

实时系统vxWorks - 虚拟机环境搭建

概述VxWorks 操作系统是美国WindRiver公司于1983年设计开发的一种嵌入式实时操作系统(RTOS),是嵌入式开发环境的关键组成部分。良好的持续发展能力、高性能的内核以及友好的...

不只会拍照的程序猿 7869

iOS开发 - OCLint自定义规则的编译与Xcode调试

OCLint的编译 基于版本 oclint version 0.15 OCLint 需要自定义规则的话需要自己编译

CaicaiNo.1 2245

RK3568笔记六十一:MIPI摄像头应用程序编写

V4L2设备驱动框架向应用层提供了一套统一、标准的接口规范,应用程序按照该接口规范来进行应用编程,从而使用摄像头。对于摄像头设备来说,其编程模式如下所示:1.首先是打开摄像头设备;2.查询设备的属性或功能;3.设置设备的参数,譬如像素格式、帧大小、帧率;4.申请帧缓冲、内存映射;5.帧缓冲入队;6.开启视频采集;7.帧缓冲出队、对采集的数据进行处理;8.处理完后,再次将帧缓冲入队,往复;9.结束采集。

1010

rcp 创建自定义project_使用 OCLint 自定义 MVVM 规则

作者 |杨萧玉来源 |玉令天下的博客http://yulingtianxia.com/最近在搞 iOS MVVM 框架,虽说是 N 年前就老生常谈的知识了,但设计模式毕竟是只一种规范,无法约束项目中所有程序员都去遵循。我做了个 OCLint 的自定义规则,对 ViewModel 运行静态检查。然而过程中踩了不少坑,OCLint 的官方 Repo 早已失效,可以使用我修改后基于 LL...

weixin_39873177的博客 207

【AUTOSAR-COM】-10.5-APP CAN Frame/PDU“发送周期不准“的影响因素

一个Tx PDU在COM模块中的数据流; Tx APP CAN Frame/PDU"发送周期不准"的影响因素;

「汽车电子助手」的博客 2391

PCL 从LAS文件中获取点云的颜色【2027最新版】

PCL从LAS文件中获取点云的RGB信息(pcl::PointXYZRGB)并进行可视化。博客长期更新,本文最新更新时间为:2026年12月1日。

点云侠的博客 1730

OCLint从安装到使用

OCLint是什么,引用官方对于OCLint的介绍:OCLint is a static code analysis tool for improving quality and reducing defects by inspecting C, C++ and Objective-C code and looking for potential problems. 通俗的讲,就是一个静态代码分析...

TuGeLe的博客 3811

把 Claude Code 接进 ABAP 世界,vibing-steampunk 到底能做什么

《Vibing Steampunk:AI Agent 与 ABAP 开发的工程化桥梁》摘要 Vibing Steampunk(vsp)是一个连接 AI Agent 与 SAP ABAP 开发环境的开源工具,通过 Model Context Protocol(MCP)将 ABAP 开发能力标准化。它解决了传统 ABAP 开发中 AI 辅助工具的局限性,使 Claude Code 等 AI 编程助手能够直接访问 ADT API,实现代码读写、调试、测试等完整开发流程。该工具采用 Go 语言开发,提供 147 个

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 1938

OCLint自定义规则的调试方法

上一篇说到的如何自己写一个OCLint规则,但是没有提到调试的方法。用C++写程序如果没有调试方法那简直是噩梦,所以这里说一下如何调试。 其实如何在Xcode上调试OClint自定义规则,就是如何在Xcode上调试dylib的问题。 这个问题Google一下就知道了,比如搜索“How to debug dylib with Xcode?”这里有一个靠谱的回答“点击这里” I faced ...

hdwhappy的专栏 2626

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

使用规则_使用 OCLint 自定义 MVVM 规则

作者 |杨萧玉来源 |玉令天下的博客http://yulingtianxia.com/最近在搞 iOS MVVM 框架,虽说是 N 年前就老生常谈的知识了,但设计模式毕竟是只一种规范,无法约束项目中所有程序员都去遵循。我做了个 OCLint 的自定义规则,对 ViewModel 运行静态检查。然而过程中踩了不少坑,OCLint 的官方 Repo 早已失效,可以使用我修改后基于 LL...

weixin_30896727的博客 188

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

用OCLint给iOS代码做静态分析

对iOS代码做代码静态分析的工具有OCLint, 这篇帖子说的就是如何使用这个工具. 转载请注明出处,晓月的博客:(http://blog.csdn.net/uxyheaven/article/details/50818107) 什么是OCLint 最好的介绍当然首选官方文档, 以下的说明摘选自官方文档:OCLint是一个代码静态分析描工具

晓月的专栏 1万+

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

iOS使用OCLint做静态代码分析

iOS使用OCLint做静态代码分析 为什么要做代码检查? 检查代码是否误写或者错写,导致一些问题的产生,不能及时发现 减少工程的警告,防止后续系统版本更新的不兼容问题 规范代码风格,变量和方法的命名、空格和空白行,提高代码的可读性 减少代码冗余 初识OCLint OCLint是一种静态代码分析工具,用于通过检查C,C ++和Objective-C代码并查找潜在问题来提高质量并减少缺陷。...

weixin_44836266的博客 801

【测试左移】基于oclint的IOS静态代码扫描实战

测试左移,基于oclint的IOS静态代码扫描实战

weixin_45589713的博客 1319

iOS 工程自动化 - OCLint

前言 最近一直在做 iOS 工程自动化方向的事情,所以把自己研究和实践的内容进行记录并分享,希望能给大家一些帮助。 为什么要使用 OCLint 做为一个静态代码分析工具,我们引入 OCLint 的目的主要是为了提高我们的代码质量。通常我们提高代码质量的方式是通过 CodeReview,但是这个过程耗费的人工和时间往往较大,所以我们想通过 OCLint 的一些规则,让机器帮我们完成一部分代码质量的检测,从而提高我们的工作效率。 安装 OCLint OCLint 的安装方式有很多中,这里我们选择最简单的方式:通

ADreamClusive的博客 849

iOS开发-OCLint如何自定义静态扫描代码规则

一、开发准备 1、MacOS一般默认都有Xcode,Git和Ruby 2、下载OCLint代码 OCLint-Github地址 下载到本地的目录如下: 3、cd进入oclint-scripts文件加,执行./make 如果没有报错的话,大约30分钟后编译完成,大概过程是下载LLVM、clang的源代码,编译LLVM、clang与OCLint的默认规则。 不过一般都会遇到一些问题: 1、如果没...

weixin_34326429的博客 401

Jenkins+OCLINT+SONAR+搭建IOS静态代码扫描平台

@[TOC]Jenkins+OCLINT+SONAR搭建IOS静态代码扫描平台 Jenkins+OCLINT+SONAR+sonar-objective-c-plugin搭建IOS静态代码扫描平台 本文记录了我搭建公司IOS静态代码扫描环境的操作过程,差不多一步一坑吧,但好歹是成功运行了。 环境说明 Jenkins 2.176.3 oclint 0.13 SONARqube:6.2 sonar-objective-c-plugin: 0.6.3 找到跟自己soanrqube版本匹配的objc插件,真是个苦差

freflying1119的博客 1121

OCLint的使用与集成

OCLint的使用与集成 1,通过Homebrew安装 使用命令行 brew tap oclint/formulae brew install oclint 2,下载安装包安装 1,进入OCLint在Github的地址,选择release,选择最新版本的安装包 2,解压下载文件。将文件存放到一个合适的位置。(比如我选择将这些需要的源代码存放到 Document 目录下) 3,在终端编辑当前环境的配置文件,将 bin 目录添加到 PATH 下,编辑 .bashrc 或 vim .bash_profile OC

qq_30252465的博客 879

iOS项目的静态代码扫描之OClint使用

上文介绍了如何安装OClint,这次简单介绍下如何使用OClint。 先确定要扫描的项目(本文使用了一个很久很久用来学习的demo)

程序鹅 1212

iOS开发-OCLint的安装和使用(命令行)

关于OCLintOCLint是一个静态代码分析工具,提高质量和减少缺陷通过检查C 、C++ 和Objective-C 代码和寻找潜在的问题可能的缺陷 - 空的if / else / try / catch / finally语句 未使用的代码 - 未使用的局部变量和参数 复杂的代码 - 很高的圈复杂度,NPath复杂性和太高的NCSS 代码异味 - 长方法和参数列表 长方法和参数列表不好的实践——倒

Pandakingli的博客 1152

iOS开发 - 创建自定义的brew仓库oclint-0.15

文章目录背景创建仓库brew create创建tap使用参考文档 背景 项目需要使用 oclint 0.15 版本,并添加一定的规则 rule ,这里oclint 0.13版本之后就没有再更新了,两个版本由于clang版本不同,不能共用,如果让每个人去拉包,然后替换,太繁琐了,这里创建一个brew库用于快速集成。 在 Homebrew 的架构下,至少有 4 层概念 Keg(酒桶):安装好的脚本、软件等; Cellar(酒窖):所有用 Homebrew 安装在本地的脚本、软件组成的集合; Formula(配

CaicaiNo.1 751
上一篇: iOS开发 - 创建自定义的brew仓库oclint-0.15
下一篇: iOS开发-关于iOS13.4的UITextMultiTapRecognizer问题记录
CaicaiNo.1
博客等级 码龄11年 572粉丝 154原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值