概述
代码格式化预提交工作流是一个初级难度的工作流。设置预提交钩子在每次提交前自动格式化代码,保持团队代码风格一致。该工作流的目标是:Enforce consistent code formatting automatically before any commit is created.
环境准备
执行本工作流需要以下环境:A project with a code formatter installed;Git repository with hooks directory;Team agreement on formatting rules。请确保在开始前准备好所有必需的工具和资源,以避免中途因环境问题中断。
执行步骤
本工作流包含3个步骤。步骤1:Install hook——Create a .git/hooks/pre-commit script that runs the formatter on staged files. 步骤2:Test the hook——Make a formatting violation, stage the file, and attempt to commit. 步骤3:Verify formatting——Check that staged files are formatted correctly after the hook runs.
验证与清理
预期结果:All commits automatically have formatted code, preventing style inconsistencies from entering the repository.。验证方法:Make a commit with unformatted code and confirm the hook reformats it or blocks the commit.。清理操作:Remove the pre-commit hook if needed with rm .git/hooks/pre-commit.。estimatedMinutes 为 15 分钟。
代码示例
#!/bin/sh
prettier --write $(git diff --cached --name-only --diff-filter=ACM | grep "\.js$")