【问题标题】:Detect changes to a file in Git检测 Git 中文件的更改
【发布时间】:2015-04-12 13:20:39
【问题描述】:

我查看了here,但我的问题没有得到解答。 我有一个脚本可以使许多文件保持最新。该存储库由许多 bash 和 python 脚本组成。其中一个脚本在每小时 cronjob 上运行,如下所示:

#! /bin/bash

git fetch origin && git reset --hard origin/dev && git clean -f -d

python -m compileall .
# Set permissions
chmod -R 744 *

基本上它会将所有脚本更新为 GitHub 的当前内容。其中一个脚本是守护程序的代码。当 that 发生变化时,我想重新启动守护程序。 git 命令的输出中没有关于哪些文件被更改的线索。那么,我该怎么做呢?

更复杂的是,我认为python -m compileall 使git 认为所有文件都已更改。但我发现this question 似乎可行。

[编辑] 添加了额外的奖励问题: 根据@behzad.nouri 下面给出的答案,我修改了代码:

#! /bin/bash

branch=$(cat ~/bin/gitbin.branch)
git fetch origin && \
DIFFdmn=$(git --no-pager diff --name-only $branch..origin/$branch -- ./testdaemon/daemon.py) && \
DIFFlib=$(git --no-pager diff --name-only $branch..origin/$branch -- ./testdaemon/libdaemon.py) && \
git reset --hard origin/dev && git clean -f -d

python -m compileall .
# Set permissions
chmod -R 744 *

if [[ -n "$DIFFdmn" ]]; then
    logger -t 02-update-scripts "daemon has changed"
    ./testdaemon/daemon.py restart
fi

if [[ -n "$DIFFlib" ]]; then
    logger -t 02-update-scripts "daemonlib has changed"
    ./testdaemon/daemon.py restart
fi

~/bin/gitbin.branch 应包含要与之同步的分支的名称。这适用于名为 dev 的分支,但对于 master-branch(尝试定义 DIFFdmn 变量时)失败并显示以下消息:

fatal: bad revision 'master..origin/master'

非常欢迎任何建议。

【问题讨论】:

    标签: python git


    【解决方案1】:
    git diff --name-only
    

    给出已更改文件的名称。为避免python -m compileall 问题,您需要比较本地分支,而不是工作目录,如:

    git diff --name-only dev..origin/dev
    

    如果您只关心一个文件,请将其传递给diff 命令:

    git diff --name-only dev..origin/dev -- path/to/daemon.file
    

    在 bash 方面,您可以通过 -n 检查输出:

    DIFF=$(git --no-pager diff --name-only dev..origin/dev -- path/to/daemon.file)
    
    if [[ -n "$DIFF" ]]
    then 
        echo "daemon has changed"
    fi
    

    【讨论】:

    • 谢谢。这似乎行得通。我将在git reset 之前插入DIFF=...。这样我就可以检测到文件更改并在编译后重新启动守护进程。
    • 但是,这似乎不适用于主分支(将dev..origin/dev 替换为master..origin/master。对这种情况有什么建议吗?
    【解决方案2】:

    在接受@behzad.nouri 给出的答案时,我想自己回答奖金问题。因此,至少可以关闭问题,并且对所提出问题的答案希望对其他人有所帮助。

    在附加问题中,代码失败是因为git diff 显然无法在当前分支之外进行比较。首先您需要使用git checkout $branch 切换分支,然后执行git diff

    所以,是这样的:

    branch=$(cat ~/bin/gitbin.branch)
    git checkout $branch
    git fetch origin && \
    DIFFdmn=$(git --no-pager diff --name-only $branch..origin/$branch -- ./testdaemon/daemon.py) && \
    DIFFlib=$(git --no-pager diff --name-only $branch..origin/$branch -- ./testdaemon/libdaemon.py) && \
    git reset --hard origin/$branch && git clean -f -d
    

    应该可以的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-05
      • 1970-01-01
      • 1970-01-01
      • 2012-07-19
      • 2016-03-23
      • 2022-09-23
      • 1970-01-01
      相关资源
      最近更新 更多