Skip to content

Instantly share code, notes, and snippets.

@hxhb
Last active April 11, 2025 06:49
Show Gist options
  • Select an option

  • Save hxhb/cf598fc3ee9feeed5ae34d863e30937f to your computer and use it in GitHub Desktop.

Select an option

Save hxhb/cf598fc3ee9feeed5ae34d863e30937f to your computer and use it in GitHub Desktop.
import os
import sys
import argparse
import subprocess
g_text_exts = ["txt","lua", "ini", "json", "uproject", "uplugin"]
DEFAULT_EOL_FMT = "lf"
def git_attr_fmt(extension, fmt="crlf"):
return f"*.{extension} text eol={fmt}"
def do_system_cmd(cmd):
print(f"exec: {cmd}")
process = subprocess.Popen(
cmd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
encoding='utf-8'
)
stdout, stderr = process.communicate()
if stdout:
print("stdout:", stdout)
if stderr:
print("stderr:", stderr)
def git_eol_normalize(repo_dir, eol_format="crlf",clean_cache=False):
print(f"repo: {repo_dir}, eol: {eol_format}")
if os.path.exists(repo_dir):
os.chdir(repo_dir)
git_attr_file = os.path.join(repo_dir, ".gitattributes")
# 0. 覆盖 .gitattributes 文件,避免重复规则
with open(git_attr_file, 'a+', encoding='utf-8') as f:
for ext in g_text_exts:
f.write(f"\n{git_attr_fmt(ext, eol_format)}")
f.write("\n* text=auto eol=auto\n") # 修改为auto
# do_system_cmd("git add .gitattributes")
# do_system_cmd("git commit -m \"append .gitattributes\"")
# 1. 配置 core.autocrlf (根据需要设置)
if eol_format == "crlf":
do_system_cmd("git config core.autocrlf true") # 针对 Windows
else:
do_system_cmd("git config core.autocrlf input") # 针对 Linux/macOS
# 2. 强制重新添加和提交
do_system_cmd("git add --renormalize .")
do_system_cmd("git commit -m \"renormalize eol\"")
# 3. 添加清理缓存的选项
if clean_cache:
print("WARNING: Cleaning Git cache. This will discard uncommitted changes!")
do_system_cmd("git rm --cached -r .")
do_system_cmd("git reset --hard HEAD")
do_system_cmd("git clean -fd")
else:
print(f"Error: Repository directory '{repo_dir}' not found.")
# global
cmdline_args = argparse.ArgumentParser(description="convert git repo eol format")
cmdline_args.add_argument('--repo_dir', help='git repo dir')
cmdline_args.add_argument('--eol', default=DEFAULT_EOL_FMT, help='eol format (lf or crlf)')
def get_arg_by_name(parser_args, arg_name):
args_pairs = parser_args.__dict__
for key, value in args_pairs.items():
if key == arg_name:
return value
def main(argv):
parser_args = cmdline_args.parse_args()
repo_dir = get_arg_by_name(parser_args, "repo_dir")
eol_format = get_arg_by_name(parser_args, "eol") # 获取eol格式
git_eol_normalize(repo_dir, eol_format, True) # 传递 eol_format
if __name__ == "__main__":
main(sys.argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment