如何写一个 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

相关推荐
猫腻余腥13 分钟前
Git 命令使用教程
git
lanhuazui1017 分钟前
git常见操作
git
未名编程1 小时前
本地项目上传 GitHub 私有库:GitHub CLI 与 Git 原生双方案详解
git·github
我是一只代码狗2 小时前
git和master分支进行对比差异
git
弘毅 失败的 mian2 小时前
Git 标签管理
经验分享·笔记·git
TPBoreas2 小时前
前端项目 Git 仓库管理策略选择
git
钦拆大仁2 小时前
Git提交代码报错fatal: detected dubious ownership ...
git
C_心欲无痕3 小时前
git - git push同时推送GitHub和Gitee两个远程仓库
git·gitee·github
骁悦彬子3 小时前
IntelliJ IDEA2025 版本控制(svn、git) 修改文件后,所属目录的颜色也变化
git·svn·intellij-idea
一只旭宝3 小时前
Linux专题十四:git代码管理库
git