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

相关推荐
sulikey1 天前
从零配置一个规范的 Python Git 仓库(适用于 Gitee / GitHub)
git·python·pycharm·gitee·github
学渣676561 天前
【面向小白】git rebase全面总结,什么时候用rebase
git
小龙报1 天前
《算法每日一题(1)--- 第31场蓝桥算法挑战赛》
c语言·开发语言·c++·git·算法·学习方法
222you1 天前
idea整合Git
git
今禾1 天前
Git完全指南(下篇):Git高级技巧与问题解决
前端·git·github
Molesidy1 天前
【Git】【TortoiseGit】TortoiseGit安装与基础使用
git
lichong9512 天前
Git 检出到HEAD 再修改提交commit 会消失解决方案
java·前端·git·python·github·大前端·大前端++
222you2 天前
Git仓库推送到GitHub
git·github
你的人类朋友2 天前
hotfix分支的使用
git·gitlab·github
小蜜蜂爱编程2 天前
gerrit的部署与配置关联到不同服务器上的git仓库
运维·服务器·git·gerrit