”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 使用脚本的超强大 Git 别名

使用脚本的超强大 Git 别名

发布于2024-11-08
浏览:327

Superpowered Git Aliases using Scripting

什么是 Git 别名

Git 别名的工作方式与 shell 中的常规别名类似,但它们特定于 Git 命令。它们允许您为较长的命令创建快捷方式或创建默认情况下不可用的新命令。

别名与其他 git 命令在相同的 shell 环境中运行,主要用于简化常见工作流程。

简单别名

简单别名使用一组参数调用单个 Git 命令。例如,您可以创建一个别名来显示存储库的状态,方法是使用 s 别名运行 git status:

[alias]
  s = status

然后您可以运行 git 来显示存储库的状态。因为我们在 ~/.gitconfig 中配置了别名,所以它可用于系统上的所有存储库。

更复杂的别名

您还可以创建运行任意 shell 命令的 git 别名。为此,别名需要以 ! 开头。这告诉 git 执行别名,就好像它不是 git 子命令一样。例如,如果您想依次运行两个 git 命令,您可以创建一个运行 shell 命令的别名:

[alias]
  my-alias = !git fetch && git rebase origin/master

当您运行 git my-alias 时,此别名按顺序运行 git fetch 和 git rebase origin/main。

git 别名的一个限制是它们不能设置为多行值。这意味着对于更复杂的别名,您需要缩小它们。

此外,在 INI 文件中,;字符用于注释掉该行的其余部分。这意味着您不能使用 ;在您的别名命令中。

这两个限制可能会使使用标准 git 别名语法创建更复杂的别名变得困难,但仍然可以完成。例如,使用 if 进行分支的别名可能如下所示:

[alias]
  branch-if = !bash -c "'!f() { if [ -z \"$1\" ]; then echo \"Usage: git branch-if \"; else git checkout -b $1; fi; }; f'"

这些限制使得创建和维护其中包含任何形式的控制流的别名变得更加复杂。这就是脚本的用武之地。

使用脚本设置别名

您可以使用您喜欢的任何编程语言编写 gitalias 脚本。如果您熟悉 bash 脚本并希望使用它,则可以创建一个运行所需 git 命令的 bash 脚本。事实上,我对 JavaScript 的掌握要强得多,所以我会使用 JavaScript。

另一个主要好处是,通过使用脚本语言,您的别名可以更轻松地获取和操作参数。 Git 会将您在 CLI 上传递的任何参数转发到您的别名,并将其附加到命令末尾。因此,您的脚本应该能够毫无问题地读取它们。例如,在 Node JS 中,您可以直接在 process.argv. 上访问传递给脚本的参数。

设置此功能的基本步骤不会根据所选语言而改变。您需要:

    创建一个运行所需 git 命令的脚本
  • 编写运行脚本的别名
案例研究:Rebase Main / master

近年来,新存储库的默认分支名称已从 master 更改为 main。这意味着当您克隆新存储库时,默认分支可能是 main 而不是 master。由于生态系统正在转型,不再有超级一致的名称。总的来说,这是一件好事,但这意味着我们上面的 rebase 别名并不在所有情况下都有效。

我们需要更新别名来检查分支是 main 还是 master,然后重新设置正确的分支。这是脚本的完美用例。


#!/usr/bin/env 节点 const { execSync } = require('child_process'); // 我们希望运行一些命令,并且在它们失败时不会立即失败 函数 tryExec(命令) { 尝试 { 返回 { 状态:0 标准输出:execSync(命令); } } 捕获(错误){ 返回 { 状态:错误.状态, 标准输出:错误.标准输出, stderr: 错误.stderr, } } } 函数 getOriginRemoteName() { const { stdout, 代码 } = tryExec("git Remote", true); 如果(代码!== 0){ throw new Error("无法获取远程名称。\n" stdout); } // 如果有上游遥控器,则使用它,否则使用 origin 返回 stdout.includes("upstream") ? “上游”:“起源”; } // --verify 如果分支存在则返回代码 0,如果不存在则返回代码 1 const hasMain = tryExec('git show-ref --verify refs/heads/main').status === 0; // 如果 main 存在,我们要对 main 进行变基,否则对 master 进行变基 const 分支 = hasMain ? '主要':'主'; const 远程 = getOriginRemoteName() // 使用远程的最新更改更新本地分支 execSync(`git fetch ${remote} ${branch}`, {stdio: '继承'}); // 将当前分支变基到远程分支之上 execSync(`git rebase ${remote}/${branch}`, {stdio: '继承'});
#!/usr/bin/env node

const { execSync } = require('child_process');

// We want to run some commands and not immediately fail if they fail
function tryExec(command) {
  try {
    return {
      status: 0
      stdout: execSync(command);
    }
  } catch (error) {
    return {
      status: error.status,
      stdout: error.stdout,
      stderr: error.stderr,
    }
  }
}

function getOriginRemoteName() {
  const { stdout, code } = tryExec("git remote", true);
  if (code !== 0) {
    throw new Error("Failed to get remote name. \n"   stdout);
  }
  // If there is an upstream remote, use that, otherwise use origin
  return stdout.includes("upstream") ? "upstream" : "origin";
}

// --verify returns code 0 if the branch exists, 1 if it does not
const hasMain = tryExec('git show-ref --verify refs/heads/main').status === 0;

// If main is present, we want to rebase main, otherwise rebase master
const branch = hasMain ? 'main' : 'master';

const remote = getOriginRemoteName()

// Updates the local branch with the latest changes from the remote
execSync(`git fetch ${remote} ${branch}`, {stdio: 'inherit'});
// Rebases the current branch on top of the remote branch
execSync(`git rebase ${remote}/${branch}`, {stdio: 'inherit'});
目前,要运行脚本,我们需要运行node ~/gitaliases/git-rebase-main.js。这并不理想,也不是你会养成的习惯。我们可以通过创建运行脚本的 git 别名来使这变得更容易。


[别名] rebase-main = !node ~/gitaliases/git-rebase-main.js
#!/usr/bin/env node

const { execSync } = require('child_process');

// We want to run some commands and not immediately fail if they fail
function tryExec(command) {
  try {
    return {
      status: 0
      stdout: execSync(command);
    }
  } catch (error) {
    return {
      status: error.status,
      stdout: error.stdout,
      stderr: error.stderr,
    }
  }
}

function getOriginRemoteName() {
  const { stdout, code } = tryExec("git remote", true);
  if (code !== 0) {
    throw new Error("Failed to get remote name. \n"   stdout);
  }
  // If there is an upstream remote, use that, otherwise use origin
  return stdout.includes("upstream") ? "upstream" : "origin";
}

// --verify returns code 0 if the branch exists, 1 if it does not
const hasMain = tryExec('git show-ref --verify refs/heads/main').status === 0;

// If main is present, we want to rebase main, otherwise rebase master
const branch = hasMain ? 'main' : 'master';

const remote = getOriginRemoteName()

// Updates the local branch with the latest changes from the remote
execSync(`git fetch ${remote} ${branch}`, {stdio: 'inherit'});
// Rebases the current branch on top of the remote branch
execSync(`git rebase ${remote}/${branch}`, {stdio: 'inherit'});
现在您可以运行 git rebase-main 来重新设置正确的分支,无论它是 main 还是 master。

案例研究:修改

我在所有机器上设置的另一个别名是修改最后一次提交。这对我来说是一个非常常见的工作流程,我喜欢将其作为单个命令。这是脚本的一个很好的用例,因为它是一个我想经常运行的简单命令。


#!/usr/bin/env 节点 // 用法:git amend [undo] const tryExec = require('./utils/try-exec'); 异步函数 getBranchesPointingAtHead() { const { stdout, code } = wait tryExec('git 分支 --points-at HEAD', true); 如果(代码!== 0){ throw new Error('无法获取指向 HEAD 的分支。\n' stdout); } return stdout.split('\n').filter(Boolean); } (异步()=> { const 分支 = 等待 getBranchesPointingAtHead(); if (branches.length !== 1) { 控制台.log( “当前提交被其他分支依赖,避免修改它。” ); 进程.退出(1); } if (process.argv[2] === '撤消') { 等待 tryExec('git reset --soft HEAD@{1}'); } 别的 { 等待 tryExec('git commit --amend --no-edit'); } })();
#!/usr/bin/env node

const { execSync } = require('child_process');

// We want to run some commands and not immediately fail if they fail
function tryExec(command) {
  try {
    return {
      status: 0
      stdout: execSync(command);
    }
  } catch (error) {
    return {
      status: error.status,
      stdout: error.stdout,
      stderr: error.stderr,
    }
  }
}

function getOriginRemoteName() {
  const { stdout, code } = tryExec("git remote", true);
  if (code !== 0) {
    throw new Error("Failed to get remote name. \n"   stdout);
  }
  // If there is an upstream remote, use that, otherwise use origin
  return stdout.includes("upstream") ? "upstream" : "origin";
}

// --verify returns code 0 if the branch exists, 1 if it does not
const hasMain = tryExec('git show-ref --verify refs/heads/main').status === 0;

// If main is present, we want to rebase main, otherwise rebase master
const branch = hasMain ? 'main' : 'master';

const remote = getOriginRemoteName()

// Updates the local branch with the latest changes from the remote
execSync(`git fetch ${remote} ${branch}`, {stdio: 'inherit'});
// Rebases the current branch on top of the remote branch
execSync(`git rebase ${remote}/${branch}`, {stdio: 'inherit'});
这个脚本比上一个脚本稍微复杂一些,因为它有一些控制流。它将检查当前提交是否被其他分支依赖,如果是,则会错误退出。这是为了防止您修改其他分支所依赖的提交,因为这样做会在尝试合并依赖于该提交的分支时导致问题。

设置别名可以使用之前相同的方法:


[别名] 修改 = !node ~/gitaliases/git-amend.js
#!/usr/bin/env node

const { execSync } = require('child_process');

// We want to run some commands and not immediately fail if they fail
function tryExec(command) {
  try {
    return {
      status: 0
      stdout: execSync(command);
    }
  } catch (error) {
    return {
      status: error.status,
      stdout: error.stdout,
      stderr: error.stderr,
    }
  }
}

function getOriginRemoteName() {
  const { stdout, code } = tryExec("git remote", true);
  if (code !== 0) {
    throw new Error("Failed to get remote name. \n"   stdout);
  }
  // If there is an upstream remote, use that, otherwise use origin
  return stdout.includes("upstream") ? "upstream" : "origin";
}

// --verify returns code 0 if the branch exists, 1 if it does not
const hasMain = tryExec('git show-ref --verify refs/heads/main').status === 0;

// If main is present, we want to rebase main, otherwise rebase master
const branch = hasMain ? 'main' : 'master';

const remote = getOriginRemoteName()

// Updates the local branch with the latest changes from the remote
execSync(`git fetch ${remote} ${branch}`, {stdio: 'inherit'});
// Rebases the current branch on top of the remote branch
execSync(`git rebase ${remote}/${branch}`, {stdio: 'inherit'});
现在您可以运行 git amend 来修改最后一次提交,或者运行 git amend undo 来撤消最后一次修改。这是我最初在 gitconfig 中内联编写的脚本,但随着它变得越来越复杂,我将其移至脚本文件中。这是管理别名复杂性的好方法。为了比较,这里是原始别名:


[别名] amend = !bash -c "'f() { if [ $(gitbranch --points-at HEAD | wc -l) != 1 ]; then echo 当前提交被其他分支依赖,避免修改。退出 1; if [ \"$0\" = "undo" ]; 然后 git reset --soft \"HEAD@{1}\"; else git commit --amend --no-edit f; ’”
#!/usr/bin/env node

const { execSync } = require('child_process');

// We want to run some commands and not immediately fail if they fail
function tryExec(command) {
  try {
    return {
      status: 0
      stdout: execSync(command);
    }
  } catch (error) {
    return {
      status: error.status,
      stdout: error.stdout,
      stderr: error.stderr,
    }
  }
}

function getOriginRemoteName() {
  const { stdout, code } = tryExec("git remote", true);
  if (code !== 0) {
    throw new Error("Failed to get remote name. \n"   stdout);
  }
  // If there is an upstream remote, use that, otherwise use origin
  return stdout.includes("upstream") ? "upstream" : "origin";
}

// --verify returns code 0 if the branch exists, 1 if it does not
const hasMain = tryExec('git show-ref --verify refs/heads/main').status === 0;

// If main is present, we want to rebase main, otherwise rebase master
const branch = hasMain ? 'main' : 'master';

const remote = getOriginRemoteName()

// Updates the local branch with the latest changes from the remote
execSync(`git fetch ${remote} ${branch}`, {stdio: 'inherit'});
// Rebases the current branch on top of the remote branch
execSync(`git rebase ${remote}/${branch}`, {stdio: 'inherit'});
这个脚本也可以提取到 .sh 文件中,但是将内容保留在节点中可以减轻我个人的维护负担。过去,每当我需要更新此别名时,我都必须将其粘贴到 bash linter 中,进行更改,缩小它,然后将其粘贴回我的 gitconfig 中。这很痛苦,因此我经常避免更新别名。现在它位于脚本文件中,我可以像任何其他脚本一样更新它。

一些注意事项

将别名设置为脚本可以解锁 git 别名的全新功能。不过,执行此操作时需要注意一些事项。

像这样设置别名时,请务必记住脚本的 cwd 将是运行脚本的 shell 的当前工作目录。脚本中的任何相对文件路径都将被视为相对于 shell 的 cwd,而不是脚本的位置。这有时非常有用,但有时却非常痛苦。对于我们的 rebase-main 脚本来说,这不是问题,发生这种情况的唯一迹象是我们在文件路径中使用 ~ 将脚本位置引用为绝对路径。

将脚本引入您的 git 别名也可以让您向别名添加越来越多的逻辑。这会使它们更难维护和理解,但也更难记住。不值得维护一个超级复杂的别名,因为无论如何你都不太可能使用它。此外,您应该小心,不要引入任何可能需要很长时间才能遇到别名的内容。如果您正在运行一个需要很长时间才能运行的脚本,您可能需要考虑它是否适合它。

结论

我希望这篇文章向您展示了在 git 别名中编写脚本的强大功能。通过使用脚本,您可以创建更复杂、更易于维护和理解的别名。这可以使您的 git 工作流程更加高效和愉快。有关 git 别名的更多示例,您可以查看我的 dotfiles 项目。它包含我在所有计算机上保留的大量配置,包括我的 git 别名。

版本声明 本文转载于:https://dev.to/agentender/superpowered-git-aliases-using-scripting-4odf?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • PHP与C++函数重载处理的区别
    PHP与C++函数重载处理的区别
    作为经验丰富的C开发人员脱离谜题,您可能会遇到功能超载的概念。这个概念虽然在C中普遍,但在PHP中构成了独特的挑战。让我们深入研究PHP功能过载的复杂性,并探索其提供的可能性。在PHP中理解php的方法在PHP中,函数超载的概念(如C等语言)不存在。函数签名仅由其名称定义,而与他们的参数列表无关。...
    编程 发布于2025-07-06
  • 图片在Chrome中为何仍有边框?`border: none;`无效解决方案
    图片在Chrome中为何仍有边框?`border: none;`无效解决方案
    在chrome 中删除一个频繁的问题时,在与Chrome and IE9中的图像一起工作时,遇到了一个频繁的问题。和“边境:无;”在CSS中。要解决此问题,请考虑以下方法: Chrome具有忽略“ border:none; none;”的已知错误,风格。要解决此问题,请使用以下CSS ID块创建带...
    编程 发布于2025-07-06
  • 哪种方法更有效地用于点 - 填点检测:射线跟踪或matplotlib \的路径contains_points?
    哪种方法更有效地用于点 - 填点检测:射线跟踪或matplotlib \的路径contains_points?
    在Python Matplotlib's path.contains_points FunctionMatplotlib's path.contains_points function employs a path object to represent the polygon.它...
    编程 发布于2025-07-06
  • 在Ubuntu/linux上安装mysql-python时,如何修复\“ mysql_config \”错误?
    在Ubuntu/linux上安装mysql-python时,如何修复\“ mysql_config \”错误?
    mysql-python安装错误:“ mysql_config找不到”“ 由于缺少MySQL开发库而出现此错误。解决此问题,建议在Ubuntu上使用该分发的存储库。使用以下命令安装Python-MysqldB: sudo apt-get安装python-mysqldb sudo pip in...
    编程 发布于2025-07-06
  • 您如何在Laravel Blade模板中定义变量?
    您如何在Laravel Blade模板中定义变量?
    在Laravel Blade模板中使用Elegance 在blade模板中如何分配变量对于存储以后使用的数据至关重要。在使用“ {{}}”分配变量的同时,它可能并不总是最优雅的解决方案。幸运的是,Blade通过@php Directive提供了更优雅的方法: $ old_section =“...
    编程 发布于2025-07-06
  • 如何使用Depimal.parse()中的指数表示法中的数字?
    如何使用Depimal.parse()中的指数表示法中的数字?
    在尝试使用Decimal.parse(“ 1.2345e-02”中的指数符号表示法时,您可能会出现错误。这是因为默认解析方法无法识别指数符号。 成功解析这样的字符串,您需要明确指定它代表浮点数。您可以使用numbersTyles.Float样式进行此操作,如下所示:[&& && && &&华氏度D...
    编程 发布于2025-07-06
  • HTML格式标签
    HTML格式标签
    HTML 格式化元素 **HTML Formatting is a process of formatting text for better look and feel. HTML provides us ability to format text without us...
    编程 发布于2025-07-06
  • PHP SimpleXML解析带命名空间冒号的XML方法
    PHP SimpleXML解析带命名空间冒号的XML方法
    在php 很少,请使用该限制很大,很少有很高。例如:这种技术可确保可以通过遍历XML树和使用儿童()方法()方法的XML树和切换名称空间来访问名称空间内的元素。
    编程 发布于2025-07-06
  • 用户本地时间格式及时区偏移显示指南
    用户本地时间格式及时区偏移显示指南
    在用户的语言环境格式中显示日期/时间,并使用时间偏移在向最终用户展示日期和时间时,以其localzone and格式显示它们至关重要。这确保了不同地理位置的清晰度和无缝用户体验。以下是使用JavaScript实现此目的的方法。方法:推荐方法是处理客户端的Javascript中的日期/时间格式化和时...
    编程 发布于2025-07-06
  • 为什么在我的Linux服务器上安装Archive_Zip后,我找不到“ class \” class \'ziparchive \'错误?
    为什么在我的Linux服务器上安装Archive_Zip后,我找不到“ class \” class \'ziparchive \'错误?
    Class 'ZipArchive' Not Found Error While Installing Archive_Zip on Linux ServerSymptom:When attempting to run a script that utilizes the ZipAr...
    编程 发布于2025-07-06
  • 如何在其容器中为DIV创建平滑的左右CSS动画?
    如何在其容器中为DIV创建平滑的左右CSS动画?
    通用CSS动画,用于左右运动 ,我们将探索创建一个通用的CSS动画,以向左和右移动DIV,从而到达其容器的边缘。该动画可以应用于具有绝对定位的任何div,无论其未知长度如何。问题:使用左直接导致瞬时消失 更加流畅的解决方案:混合转换和左 [并实现平稳的,线性的运动,我们介绍了线性的转换。这...
    编程 发布于2025-07-06
  • 如何正确使用与PDO参数的查询一样?
    如何正确使用与PDO参数的查询一样?
    在pdo 中使用类似QUERIES在PDO中的Queries时,您可能会遇到类似疑问中描述的问题:此查询也可能不会返回结果,即使$ var1和$ var2包含有效的搜索词。错误在于不正确包含%符号。通过将变量包含在$ params数组中的%符号中,您确保将%字符正确替换到查询中。没有此修改,PDO...
    编程 发布于2025-07-06
  • 为什么使用Firefox后退按钮时JavaScript执行停止?
    为什么使用Firefox后退按钮时JavaScript执行停止?
    导航历史记录问题:JavaScript使用Firefox Back Back 此行为是由浏览器缓存JavaScript资源引起的。要解决此问题并确保在后续页面访问中执行脚本,Firefox用户应设置一个空功能。 警报'); }; alert('inline Alert')...
    编程 发布于2025-07-06
  • 如何有效地选择熊猫数据框中的列?
    如何有效地选择熊猫数据框中的列?
    在处理数据操作任务时,在Pandas DataFrames 中选择列时,选择特定列的必要条件是必要的。在Pandas中,选择列的各种选项。选项1:使用列名 如果已知列索引,请使用ILOC函数选择它们。请注意,python索引基于零。 df1 = df.iloc [:,0:2]#使用索引0和1 c...
    编程 发布于2025-07-06
  • 为什么Microsoft Visual C ++无法正确实现两台模板的实例?
    为什么Microsoft Visual C ++无法正确实现两台模板的实例?
    The Mystery of "Broken" Two-Phase Template Instantiation in Microsoft Visual C Problem Statement:Users commonly express concerns that Micro...
    编程 发布于2025-07-06

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3