每一个团队都应该有统一的代码风格和规范,这带来的好处我相信不言而喻,具体我就很少说了,你们都懂的😁。如何更有效率的去作这件事呢,我此次就来讲说如何更好的自动格式化你的代码。html
大多数 iOS 开发者应该都知道 Xcode 的插件 Clang Format,它是基于 clang-format 命令行工具的一个 Xcode 插件,可是这款插件在Xcode9上已经没法使用了,由于Xcode9的插件机制已经变了。
如今可使用这一款XcodeClangFormat,具体的使用方式点击连接,你们自行去看吧。这款有个缺点,就是不能像以前那款插件能够设置在保存时自动格式化(这其实也不能怪做者,Xcode新的机制不容许)。 不过使用这种插件仍是不够方便,你还得手动选中文件或者代码再按快捷键来格式化,很容易忘,而致使把不规范的代码直接提交到仓库里了。
那么有没有一种方式,可让我在敲代码的时候为所欲为,提交时又能提醒我而后自动帮我格式化吗?git
这里我直接介绍一款神器Space Commander,它利用 Git Hooks ,在 commit 以前检查代码风格是否符合规范,只有符合规范的代码才容许提交,列出不符合规范的文件,同时提供 Shell 脚原本自动格式化。接下来我介绍下如何使用。github
git clone https://github.com/square/spacecommander.git
BasedOnStyle: Chromium
IndentWidth: 4
AlignConsecutiveAssignments: true
AlignConsecutiveDeclarations: true
ObjCSpaceAfterProperty: true
PointerAlignment: Right
BreakBeforeBraces: Attach
#import "ViewController.h"
@interface ViewController ()
@property(nonatomic, copy) NSString* p;
@property(nonatomic, strong) UITextView * textview;
@end
@implementation ViewController
-(void)formatTest:(NSString *)param{
if (param) {
NSLog(@"sss");
}
int a=0;
int b = 1;
int c= 2;
NSLog(@"%d%d%d",a,b,c);
}
-(void)viewDidLoad{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
-(void)viewDidAppear:(BOOL)animated {
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
复制代码
这一看,就很不规范吧,先让咱们提交看看shell
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, copy) NSString * p;
@property (nonatomic, strong) UITextView *textview;
@end
@implementation ViewController
- (void)formatTest:(NSString *)param {
if (param) {
NSLog(@"sss");
}
int a = 0;
int b = 1;
int c = 2;
NSLog(@"%d%d%d", a, b, c);
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidAppear:(BOOL)animated {
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
复制代码
完美!😝bash
能够看到上面的命令太长了,必需要指定shell脚本的全路径才能执行,咱们能够简化命令,若是你用的zsh,去修改 ~/.zshrc,若是是bash,则修改~/.bash_profile,工具
// 初始化
alias clangformatsetup="/你本身的路径/spacecommander/setup-repo.sh"
// 格式化对应文件
alias clangformatfile="/你本身的路径/spacecommander/format-objc-file.sh"
// 格式化全部暂存文件
alias clangformatfiles="/你本身的路径/spacecommander/format-objc-files.sh"
// 格式化整个仓库
alias clangformatall="/你本身的路径/spacecommander/format-objc-files-in-repo.sh 复制代码
若是你还想知道更多的用法,直接去spacecommander的github主页查看。ui
这是我第一次在掘金上写文章(别的地方也没写过多少😂),写的很差,你们海涵呐,多多提意见哈😁。atom