iOS- Xcode配置OCLint
一、OCLint介紹,為什麼要使用OCLint
OCLint 是基於 Clang 的靜態分析工具,支援對 C、C++ 和 Objective-C 程式碼進行靜態分析,它基於 Clang 輸出的抽象語法樹對程式碼進行靜態分析,支援與現有的 CI 整合,部署之後基本不需要維護,簡單方便,實現code review自動化,檢查程式碼中的缺陷:
- 可能出現的bug,空的if/else/try/catch/finally的引數
- 沒有使用的變數或者引數
- 複雜的程式碼邏輯,多個if/else的判斷
- 不需要的程式碼
- 過長的方法或者引數
- 錯誤的分配方式
- ....
二、環境配置
1、通過Homebrew安裝OCLint:
brew tap oclint/formulae
brew install Clint
如果已安裝過OCLint可執行升級的指令:
brew update
brew upgrade oclint
2、用gem安裝xcpretty
sudo gem install xcpretty
3、執行oclint確認OClint是否安裝成功
oclint
如果展示以下內容即為安裝成功:
TF013550:~ name$ oclint
oclint: Not enough positional command line arguments specified!
Must specify at least 1 positional argument: See: oclint -help
1、首先在targets點新增按鈕,在Cross-platform選項中,選“Aggregate”,然後命名為"OCLint":
2、選中OCLint Target,進入Build Phases選項,點左上角的加號,選擇“New Run Script Phase”
新增指令碼
在指令碼輸入框內輸入指令碼程式碼:
chmod -R 777 $SRCROOT/oclint
$SRCROOT/oclint/oclint.sh
3、在主工程目錄下新建oclint資料夾,新建oclint.sh指令碼檔案,編輯內容如下:
cd到工程目錄下,執行命令:
touch oclint.sh
4、xcode工程中選中scheme選擇OCLint,command+B編譯source ~/.bash_profile #獲取專案路徑 PROJECT_DIR=$(cd `dirname $0`;cd ..;pwd) cd ${PROJECT_DIR} buildPath="${PROJECT_DIR}/oclint/build" compilecommandsJsonFolderPath="${PROJECT_DIR}/oclint" compilecommandsJsonFilePath="${PROJECT_DIR}/oclint/compile_commands.json" rm -rf "$compilecommandsJsonFolderPath/build" xcodebuild SYMROOT=$buildPath | xcpretty -r json-compilation-database -o $compilecommandsJsonFilePath cd $compilecommandsJsonFolderPath oclint-json-compilation-database -- -report-type xcode \ -rc CYCLOMATIC_COMPLEXITY=10 \ -rc LONG_CLASS=1000 \ -rc LONG_METHOD=50 \ -rc LONG_LINE=140 \ -rc LONG_VARIABLE_NAME=30 \ -rc SHORT_VARIABLE_NAME=1 \ -rc MAXIMUM_IF_LENGTH=5 \ -rc MINIMUM_CASES_IN_SWITCH=2 \ -rc NCSS_METHOD=30 \ -rc NESTED_BLOCK_DEPTH=5 \ -rc TOO_MANY_METHOD=30 \ -rc TOO_MANY_PARAMETERS=5 \ -max-priority-1 0 \ -max-priority-2 5 \ -max-priority-3 10
Error:編譯工程,一般會出現錯誤找不到complie_commands.json檔案
Error: compile_commands.json not found at /Users/yuge/Desktop/LJTransfar/LJAPPS/TFParty/Trunk/oclint.
Command /bin/sh failed with exit code 98
解決辦法:
1>、執行命令,使用xcpretty生成的檔名是:compilation_db.json
xcodebuild |xcpretty -r json-compilation-database
▸Copying YGInfo.h
▸Touching YGModle.framework
▸Build Succeeded
出現Build Success後表示執行完成,生成目錄在build/reports中
2>、
把xcpretty生成的檔案compilation_db.json複製到當前目錄即oclint資料夾下下,重新命名為compile_commands.json。
3>、command+B重新編譯,編譯完成之後xcode則出現各種警告,證明成功了
1、多餘的Else語句 Unnecessary else statement
當一個IF語句有返回語句,那麼else 語句就不是必要的。剩下的語句可以不再程式碼塊中執行。
if (response.error == nil) {
return YES;
}
else {
if (error != NULL) {
*error = [[NSError alloc] initWithDomain:USER_DOMAIN
code:response.error.code
userInfo:response.error.userInfo];
}
}
2、Useless parentheses 無用的括號五、禁止OCLint的檢查
使用語法
未完待續...