前言
在日常开发中,你是否经常遇到这样的报错?
$gitcheckout develop fatal: Unable to create'E:/project/my-app/.git/index.lock':File exists. Anothergitprocess seems to be runninginthis repository, e.g. an editor opened by'git commit'.Pleasemakesure all processes are terminatedthentry again. If it still fails, agitprocess may have crashedinthis repository earlier: remove thefilemanually to continue.每次都要手动去删除.git/index.lock文件,非常麻烦。本文将介绍如何打造一个全局命令行工具,在任何项目目录下一键解决这个问题。
问题原因分析
什么是 index.lock?
index.lock是 Git 的锁文件机制。当 Git 执行某些操作(如commit、merge、checkout等)时,会在.git目录下创建index.lock文件,防止多个 Git 进程同时修改索引文件造成数据损坏。
为什么会残留?
- Git 进程异常退出- 操作被强制中断(如 Ctrl+C)
- IDE/编辑器冲突- VSCode、WebStorm 等编辑器的 Git 插件与命令行冲突
- 系统崩溃- 电脑意外关机或蓝屏
- 并发操作- 多个终端同时执行 Git 命令
解决方案
方案一:手动删除(临时)
# Windowsdel .git\index.lock# Mac/Linuxrm-f .git/index.lock缺点:每次都要手动操作,路径还要记准。
方案二:创建全局命令行工具(推荐)
我们来创建一个可以在任何项目目录下运行的全局命令git-unlock。
实现步骤
第一步:创建全局脚本目录
在用户目录下创建一个bin文件夹,用于存放自定义的全局命令:
# Windowsmkdir%USERPROFILE%\bin# Mac/Linuxmkdir-p ~/bin第二步:编写 Node.js 脚本
创建git-unlock.js文件:
#!/usr/bin/env node/** * Git 解锁脚本 - 全局版本 * 自动清理 index.lock 文件,解决切换分支时的锁定问题 */constfs=require('fs');constpath=require('path');const{execSync}=require('child_process');// 当前工作目录constcwd=process.cwd();/** * 向上查找 .git 目录 * @param {string} startDir - 起始目录 * @returns {object|null} - 返回 gitDir 和 projectRoot */functionfindGitDir(startDir){letdir=startDir;while(dir!==path.dirname(dir)){constgitDir=path.join(dir,'.git');if(fs.existsSync(gitDir)){return{gitDir,projectRoot:dir};}dir=path.dirname(dir);}returnnull;}/** * 递归查找所有 .lock 文件 * @param {string} dir - 目录路径 * @param {number} depth - 当前递归深度 * @returns {string[]} - 锁文件路径数组 */functionfindLockFiles(dir,depth=0){constlockFiles=[];if(depth>3)returnlockFiles;// 限制递归深度try{constfiles=fs.readdirSync(dir);for(constfileoffiles)