【问题标题】:Can I replace message in my commit message(git)?我可以在我的提交消息(git)中替换消息吗?
【发布时间】:2021-06-18 09:34:44
【问题描述】:

我在 git 中使用了 commit-msg 钩子来检查我的提交是否正确,并希望自动将 BugID 替换为 Bug 地址。但似乎它只能在提交消息的底部再添加一行,而不是替换原来的行。有什么办法可以让它工作吗? 我的提交模板是

Branch:
BugId:
Description:

这是我的代码:

with open(sys.argv[1],r+) as fp:
    lines=fp.readlines()
    for line in lines:
        if line[0]=="#":
            continue
        line=line.strip()
        for l in l.split('/n'):
            if not l.split(":")[-1]:
                print(l,"is empty")
                sys.exit(1)
            if l.startswith("Bug"):
                fp.write(l.replace(l.split(":")[-1],"http:bugs.xxxxxxxxx")
sys.exit(0)

【问题讨论】:

  • 表达式l.split('/n')中的l是什么?
  • 恐怕你的 Python 代码在这里很糟糕而且错误。 :-) 首先打开文件并读取它(就像你做的那样),然后在尝试写入文件之前回到开头,并确保你写了你想要出现的每一行在文件中。修复@mkrieger1 指出的错误和其他明显的错误(还没有什么可拆分的,您已经按行拆分了)等。这似乎更好地表述为一个关于如何用您想要的任何语言编写您想要的代码的问题写吧……
  • 这让我觉得它可能是一个两行可读的 bash 脚本。

标签: git git-commit githooks re


【解决方案1】:

这是一个来自 Gerrit 的示例,如果它不存在,则在每个提交中添加“Change-Id: ....”行

当然,它不是 Python,但我认为你可以从那里借用一个想法


#!/bin/sh
# From Gerrit Code Review 2.16.2
#
# Part of Gerrit Code Review (https://www.gerritcodereview.com/)
#
# Copyright (C) 2009 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# avoid [[ which is not POSIX sh.
if test "$#" != 1 ; then
  echo "$0 requires an argument."
  exit 1
fi

if test ! -f "$1" ; then
  echo "file does not exist: $1"
  exit 1
fi

if test ! -s "$1" ; then
  echo "file is empty: $1"
  exit 1
fi

# $RANDOM will be undefined if not using bash, so don't use set -u
random=$( (whoami ; hostname ; date; cat $1 ; echo $RANDOM) | git hash-object --stdin)
dest="$1.tmp.${random}"

# Avoid the --in-place option which only appeared in Git 2.8
# Avoid the --if-exists option which only appeared in Git 2.15
cat "$1" \
  | git -c trailer.ifexists=doNothing interpret-trailers --trailer "Change-Id: I${random}" > "${dest}" \
  && mv "${dest}" "$1"

注意脚本的最后几行:它创建一个dest,然后打印消息并添加“Change-Id”(如果不存在)。然后它移动 temp dest 以实际成为一条消息。任务完成。

我不是真正精通 git 钩子,但这个应该在名为 .git/hooks/commit-msg 的文件中,所以我相信这是你需要的

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-08
    • 2021-03-06
    • 2017-11-01
    • 2012-05-04
    • 2020-08-11
    相关资源
    最近更新 更多