如何通过删除历史记录中所有 Jupyter 笔记本的所有输出来缩小 git 存储库

Min*_*ark 2 git jupyter

我想通过删除存储库历史记录中每个 Jupyter 笔记本的所有输出来缩小 git 存储库。这可能吗?

Min*_*ark 5

是的,可以使用git filter-repo.

  1. 安装git 过滤器仓库
  2. 获取存储库的干净克隆,并确保保留备份以防出现问题。
  3. 进入存储库的根目录,然后运行以下命令:
git filter-repo --blob-callback '
import json
try:
    notebook = json.loads(blob.data)
    if "cells" in notebook:
        for cell in notebook["cells"]:
            if "outputs" in cell:
                cell["outputs"] = []
        blob.data = (json.dumps(notebook, ensure_ascii=False, indent=1,
                                sort_keys=True) + "\n").encode("utf-8")
except json.JSONDecodeError as ex:
    pass
except UnicodeDecodeError as ex:
    pass
'
Run Code Online (Sandbox Code Playgroud)

此命令将为历史记录中的每个 blob 调用 Python 代码,并尝试将其解析为 JSON。如果它有效并返回带有键的字典"cells",那么我们(几乎肯定)正在处理 Jupyter 笔记本,我们可以遍历单元格并将输出替换为空数组。然后,代码json.dumps()将笔记本转储回文件,替换 blob 以前的数据。

我在一个有很多笔记本的存储库上尝试了这个,大约 200MB 大,然后它缩小到 20MB。我发现这很好所以我想我会分享。