【问题标题】:Automatically track certain files自动跟踪某些文件
【发布时间】:2017-12-31 13:29:11
【问题描述】:

长话短说:我们正在使用 Jupyter 笔记本(.ipynb 文件)并设置了 Jupyter 配置以保存 .py 副本(为了更好的 git diffs 目的,this answer on SO)。

所以每次我保存.ipynb 文件时,它都会保存.py 版本,否则文件名相同。如果不存在.py 版本,则会创建一个新版本。

是否可以自动添加/跟踪这些新创建的.py 文件,也许通过在 git 配置中添加一些东西?

编辑

所以这可能使用 git pre-commit 钩子,阅读过它。但是,我真的没有足够的知识从头开始写一个钩子。

重申我想要的:我保存foo_bar.ipynb,自动创建foo_bar.py。如果我愿意,我希望 pre-commit 挂钩添加 foo_bar.py,例如 git commit -a强调一下,我不希望它添加任何旧的 .py 文件,只添加与现有 .ipynb 文件具有相同文件名的文件。

【问题讨论】:

  • 为了运行预提交钩子,你必须首先提交。 git add . 之前 git commit 应该足够了。
  • @axiac 我不想添加任何旧的.py 文件,只是那些与现有.ipynb 文件具有相同文件名的文件
  • 无论你想添加什么,Git 自己都不会做任何事情。预提交挂钩作为git commit 命令的一部分运行。必须有人(人或脚本)运行此命令。同一个人或脚本可以在运行git commit 之前git add 适当的文件。如此简单的任务不需要钩子。更重要的是,如果没有为提交准备任何内容,则没有提交(我认为钩子也不会运行)。

标签: git pre-commit-hook


【解决方案1】:

编写一个脚本,将新文件和更新文件添加到 Git 并提交它们。手动运行它或作为 cron 作业运行。更好的是,如果可能的话,将它挂接到生成文件的工具中,以便在工具每次保存文件或退出时运行。

脚本可以很简单:

# Change directory
cd /path/to/the/directory/where/the/py/files/are/saved

# Set this to 1 when a commit is needed
commit=0

# Check all the .ipynb files
for i in *.ipynb; do
    # Generate the name of the corresponding .py file
    p=${i//.ipybn}.py
    # If the .py file exists
    if [ -f $p ]; then
        # Add it to be committed; it doesn't hurt if it is not modified
        git add $p
        # Remember we have to commit at the end
        commit=1
    fi
done

# Avoid running "git commit" when nothing was staged
if [ $commit -eq 1 ]; then
    # Commit, generate an unique (not very useful) commit message.
    git commit -m "automatic commit on $(date +'%Y-%m-%d %H:%I:%S')"
fi

上面的代码假设所有.ipynb文件都存储在一个目录中(没有子目录),并且对应的.py文件存储在同一个目录中。

如果.ipynb 文件存储在多个目录中,则将for 行替换为:

for i in $(find . -name \*.ipynb); do

如果.py 文件没有与对应的.ipybn 文件存储在同一目录中,那么您必须更改p=${i//.ipybn}.py 行。

在暂存文件之前可以验证多个条件。

【讨论】:

    猜你喜欢
    • 2019-09-21
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-11
    • 1970-01-01
    • 2017-11-29
    相关资源
    最近更新 更多