corrlib/corrlib/git_tools.py

44 lines
1.2 KiB
Python

import os
import datalad.api as dl
import git
GITMODULES_FILE = '.gitmodules'
def move_submodule(repo_path: str, old_path: str, new_path: str) -> None:
"""
Move a submodule to a new location.
Parameters
----------
repo_path: str
Path to the repository.
old_path: str
The old path of the module.
new_path: str
The new path of the module.
"""
os.rename(os.path.join(repo_path, old_path), os.path.join(repo_path, new_path))
gitmodules_file_path = os.path.join(repo_path, GITMODULES_FILE)
# update paths in .gitmodules
with open(gitmodules_file_path, 'r') as file:
lines = [line.strip() for line in file]
updated_lines = []
for line in lines:
if old_path in line:
line = line.replace(old_path, new_path)
updated_lines.append(line)
with open(gitmodules_file_path, 'w') as file:
file.write("\n".join(updated_lines))
# stage .gitmodules in git
repo = git.Repo(repo_path)
repo.git.add('.gitmodules')
# save new state of the dataset
dl.save(repo_path, message=f"Move module from {old_path} to {new_path}", dataset=repo_path)
return