公司的项目已经迭代了近两年,在两年的时间里不断的有新人参加到项目里,每个人都有自己的代码风格,随着项目越来越大,没有统一代码规范带来的维护问题也越来越多,所以和小组的同事商量了下制定了iOS的编码规范。
规范总是要执行才能生效,不过几千字的编码规范总不能每次写代码前都熟读一遍吧,翻了下Package Manager,发现CLangFormat可以根据代码规范格式化代码。具体的使用方式已经有大神非常详尽地介绍,感兴趣的同学请移步《iOS 代码格式化管理》—Bannings的专栏。
看了《iOS 代码格式化管理》后发现我们当前还需要解决两个问题:一个是自定义符合我们团队的代码规范;另外一个是根据规范整理以前写的代码。
第一个问题 在《iOS 代码格式化管理》中已经介绍过,主要是配置.clang-format文件,让CLangFormat根据自定义的配置格式化代码,这里贴出我们团队使用的.clang-format配置。因为.clang-format的配置选项非常多、有些选项的解释非常模糊,所以我们只测试了常用的选项,没用到的都注释了。
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
- 175
- 176
- 177
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
- 175
- 176
- 177
第二个问题 其实也很简单,CLangFormat就是把clang-format进行了wrap,clang-format本身其实是一个命令行工具,所以嘛,写个shell脚本就能把以前代码都格式化了。具体的命令如下:
find . -regex “.*.[hm]” | xargs clang-format -i -style=file
把上面的命令解释下,这行命令分为3部分:
1 find . -regex ".*\.[hm]"
是找出当前目录所在的所有以h和m结尾的文件
2 | xargs
把文件导入到xargs中,逐个调用clang-format命令
3 clang-format -i -style=file
这里就是对文件进行格式化了,-i
的意思是把格式化好的代码直接写入源文件,-sytle=file
指从当前目录或者当前父目录搜索文件名为.clang-format的格式配置文件
当然,这行命令需要你根据你自己的clang-format的路径做一下调整。