如何写一个 git 子命令:`git open` 浏览器打开项目地址

问题

日常工作我们经常需要在工程目录下打开该工程对应的 git 仓库,每次需要复制 url 打开浏览器很麻烦,要是能有一个快捷方式直接命令行打开就太棒了,要是还能结合 git 使用体验就更自然流畅了。本文将告诉大家如何写一个 git 子命令。Make your own git subcommand。

效果

按照 TDD 或者 DDD 的开发思路,我们先想想这个命令会如何执行?

sh 复制代码
git open

对直接 git open 即可,但是目前执行会报错:

sql 复制代码
❯ git open
git: 'open' is not a git command. See 'git --help'.

The most similar commands are
	clean
	clone
	notes
	prune

本文将让其支持 open 命令,即浏览器打开工程目录。

思路

问题可以拆解成两个子问题。git 如何实现子命令,如何获取当前项目的远端地址。

实现子命令

只要可执行文件是 git- 开头,且在 path 目录下,即可以被全局 $ git-xx 唤起则可以通过 git xx 执行。

全局唤起的几种方式:

  1. npm i -g
  2. 环境变量
  3. zshrc alias git 不支持 alias 拓展子命令。
  4. zshrc plugins

第一种方即通过发布一个 npm 包,并全局安装。

sh 复制代码
npm i -g git-open

有没有不发布的方式,因为可能是自己用或者有个人隐私不方便发布到公网?有的方式都是可以的,以最简单的环境变量给大家演示下。

环境变量

新建一个目录,容纳所有的子命令

bash 复制代码
cd ~
md git-subcommands/git-open && cd -
npm init -y
touch git-open

git-open 内容:

js 复制代码
#!/usr/bin/env node
console.log('hello my first git subcommand!');

chmod u+x git-open

sh 复制代码
❯ ll git-open

-rwxr-xr-x@ 1 legend80s  staff    67B Apr 16 11:18 git-open

可以看到 git-open 已经变成了可执行文件。下一步是将其作为全局命令。

sh 复制代码
// ~/.zshrc

export PATH="$HOME/github/git-subcommands/git-open:$PATH"

让 zshrc 生效:source ~/.zshrc

以上来自 Run Node.js scripts from the command line

不必局限于 node.js 任何脚本语言都可以,比如 shell、Python、Ruby 只要设置正确的 shebang 即可。

试试 git-open 能否输出

sh 复制代码
❯ git-open
hello my first git subcommand!

说明 git-open 已经是全局可执行文件。

sh 复制代码
❯ git open
hello my first git subcommand!

说明 git 子命令已经生效 🎉!重点部分其实已经完成,下面开始完善我们的工作。

继续完善

获取远端地址:git remote get-url origin,将输出类似这种 git ssh 格式的地址,我们需要将其装换成 https 格式的。

git@github.com:legend80s/eslint-plugin-function-name.git

javascript 复制代码
function gitToHttps(git) {
  return git.replace(':', '/').replace('git@', 'https://').replace('.git', '');
}

完整代码

js 复制代码
#!/usr/bin/env node
// @ts-check
const { execSync } = require('node:child_process');

function main() {
  const gitUrl = execSync('git remote get-url origin').toString('utf8');

  const https = gitToHttps(gitUrl);

  execSync(`open ${https}`);
}

main();

/**
 * @param {string} git example "git@github.com:legend80s/eslint-plugin-function-name.git"
 * @returns {string}
 */
function gitToHttps(git) {
  return git.replace(':', '/').replace('git@', 'https://').replace('.git', '');
}

测试:去一个项目地址,试试 git open 能否在浏览器打开相应的 repo 地址。

sh 复制代码
// cd 你的项目地址
git open

总结

本文我们学会了如何增强我们的 git 命令。如果有帮助到你不妨给本文点赞,或到 GitHub 给予 star 支持,谢谢!

参考

Write Your Own Git Subcommands

相关推荐
&Sinnt&12 小时前
Git 版本控制完全指南:从入门到精通
git·后端
Tiny21415 小时前
多人协同开发时Git使用命令
git
WebGirl16 小时前
代码Revert后再次Merge会丢失的问题
git
小皮侠20 小时前
nginx的使用
java·运维·服务器·前端·git·nginx·github
HalukiSan21 小时前
如何提交PR
git·gitlab·github
爱莉希雅&&&1 天前
shell编程之awk命令详解
linux·服务器·git
baiyu331 天前
成为git砖家(12): 看懂git合并分支时冲突提示符
git
wu_aceo2 天前
将本地项目提交到Gitee
git·gitee·提交·本地提交·上传git
随便取个六字2 天前
GIT操作 学习
git·学习
星源~2 天前
tree 命令集成到 Git Bash:可视化目录结构的指南
git·单片机·物联网·嵌入式·项目开发