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

相关推荐
int WINGsssss14 小时前
Git使用
git
用户07605303543816 小时前
Git Revert:安全移除错误提交的方式
git
Good_Starry1 天前
Git介绍--github/gitee/gitlab使用
git·gitee·gitlab·github
云端奇趣1 天前
探索 3 个有趣的 GitHub 学习资源库
经验分享·git·学习·github
F_D_Z2 天前
【解决办法】git clone报错unable to access ‘xxx‘: SSL certificate problem:
网络·git·网络协议·ssl
等风来不如迎风去2 天前
【git】main|REBASE 2/6
git
艾伦~耶格尔2 天前
IDEA 配置 Git 详解
java·ide·git·后端·intellij-idea
云兮杜康2 天前
IDEA中用过git之后文件名颜色全变红
java·git·intellij-idea
睡不醒的小泽2 天前
git merge 和 git rebase
git
艾伦~耶格尔2 天前
Git 下载及安装超详教程(2024)
git·gitee·码仓