Skip to content

Instantly share code, notes, and snippets.

@pmeier
Created June 14, 2021 06:39
Show Gist options
  • Save pmeier/c1301ce628702e618579ef9714943fa4 to your computer and use it in GitHub Desktop.
Save pmeier/c1301ce628702e618579ef9714943fa4 to your computer and use it in GitHub Desktop.
Revert submodule commits accidentally included in the most recent commit
import os
import pathlib
import re
import shlex
import subprocess
import sys
def main():
if git("status", "--porcelain"):
exit(error=True, msg="Working directory is not clean")
submodule_commits = find_submodule_commits()
if not submodule_commits:
exit(error=False)
for submodule, commit in submodule_commits.items():
git("checkout", commit, cwd=f"third_party/{submodule}")
git("add", "third_party")
git("commit", "--amend", "--no-edit")
THIRD_PARTY_PATTERN = re.compile(r"diff --git ([ab]/third_party/(?P<submodule>[^/]+)){2}")
OLD_COMMIT_PATTERN = re.compile(r"-Subproject commit (?P<commit>[\da-f]{40})")
def find_submodule_commits():
diff = iter(git("diff", "HEAD~1").split("\n"))
submodule_commits = {}
for line in diff:
match = THIRD_PARTY_PATTERN.match(line)
if not match:
continue
submodule = match.group("submodule")
for line in diff:
match = OLD_COMMIT_PATTERN.match(line)
if not match:
continue
commit = match.group("commit")
submodule_commits[submodule] = commit
break
return submodule_commits
def git(*cmds, cwd=None) -> str:
if cwd is None:
cwd = pathlib.Path.cwd()
else:
cwd = pathlib.Path(cwd)
if not cwd.is_absolute():
cwd = pathlib.Path.cwd() / cwd
cmd = " ".join([shlex.quote(s) for s in ("git", *cmds)])
print(f"${cmd}")
return subprocess.check_output(cmd, shell=True, cwd=str(cwd)).decode()
def exit(*, error: bool, msg: str = ""):
code, file = (1, sys.stderr) if error else (0, sys.stdout)
if msg:
print(msg, file=file)
sys.exit(code)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment