【问题标题】:Prepending git commit message without making a new line在不换行的情况下添加 git commit 消息
【发布时间】:2020-03-04 20:49:52
【问题描述】:

我在prepare-commit-msg 钩子中使用这个衬线在提交消息前添加自定义字符串:

echo "text " | cat - $COMMIT_MSG_FILE > /tmp/out && mv /tmp/out $COMMIT_MSG_FILE

不幸的是,每条提交消息都包含“文本”,后跟 CRLF,其余的提交消息在下一行。例如,如果提交消息是:"Commit 123",则新的提交消息将是

"text
Commit 123"

而不是"textCommit 123",这是我想要的。

知道我错过了什么吗?

【问题讨论】:

    标签: git githooks


    【解决方案1】:

    不要将您的 echo 语句通过管道传递给 cat。而是在 echo 字符串中使用 cat 语句的命令替换:

    echo "text $(cat $COMMIT_MSG_FILE)" > /tmp/out && mv /tmp/out $COMMIT_MSG_FILE
    

    【讨论】:

      【解决方案2】:

      echo 打印一个换行符。使用不支持的命令:这可能是 echo -n,取决于您的 echo 年份,或者 printf,如果您有的话,会这样做:

      echo -n "text " | cat - $COMMIT_MSG_FILE > /tmp/out && mv /tmp/out $COMMIT_MSG_FILE
      

      dGot14U's method using command substitution 也可以。也可以考虑使用就地sed

      sed -i '' '1s/^/text /' $COMMIT_MSG_FILE
      

      -i 是否以及何时需要一个单独的空字符串参数'',如此处所示,取决于操作系统:MacOS sed 需要一个,Linux sed 禁止一个。我在脚本中使用过这个:

      if sed --version >/dev/null 2>&1; then
          # apparently this is gnu sed, so -i requires the extension attached
          sedinplace="-i"
      else
          # apparently this is BSD/MacOS sed, so -i requires a separate argument
          sedinplace="-i ''"
      fi
      # ...
      sed $sedinplace -e cmd1 -e cmd2 $file
      

      $sedinplace 然后扩展为正确的东西。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-28
        • 2021-11-23
        • 2014-03-04
        相关资源
        最近更新 更多