美文网首页
swift项目用SwiftFormat自动格式代码

swift项目用SwiftFormat自动格式代码

作者: CCloud | 来源:发表于2023-07-19 13:24 被阅读0次
1. 安装 swiftformat
brew install swiftformat
2. 安装 swiftformat Xcode插件
brew install --cask swiftformat-for-xcode
3. 打开swiftformat

在程序坞中直接打开

open "/Applications/SwiftFormat For Xcode.app"

会看到 About, 介绍了 How do I install it?

4. 开启权限

设置->隐私与安全性->扩展
选择Xcode Source Editor,勾选SwiftFormat

5. 重启Xcode

点击 顶部 Editor目录可以看到 SwiftFormat, 可以手动格式化单个文件或选中内容

6. 配置快捷键

参考 https://www.jianshu.com/p/69883f2a16e1

7. 格式化代码

在项目目录批量格式化可以执行

swiftformat .

单个文件

swiftformat path/file.swift
8. 自动格式化代码

8.1 创建钩子目录

mkdir -p .git/hooks

8.2 创建 pre-commit 钩子脚本

cd .git/hooks
touch pre-commit

8.3 编辑 pre-commit 脚本

#!/bin/bash

# Get the staged Swift files
files=$(git diff --cached --name-only --diff-filter=ACM | grep '\.swift$')

# Check if any Swift files are staged
if [[ -n $files ]]; then
  # Format the staged Swift files using swiftformat
  swiftformat $files --swiftversion 5

  # Add the formatted files to the staging area
  git add $files
fi

8.4 赋予执行权限

chmod +x pre-commit

完成以上步骤,提交代码的时候会自动format

相关文章

网友评论

      本文标题:swift项目用SwiftFormat自动格式代码

      本文链接:https://www.haomeiwen.com/subject/ntgoudtx.html