update_rules.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import argparse
  2. import configparser
  3. import glob
  4. import logging
  5. import os
  6. import shutil
  7. import stat
  8. from git import InvalidGitRepositoryError, Repo
  9. def del_rw(action, name: str, exc):
  10. os.chmod(name, stat.S_IWRITE)
  11. os.remove(name)
  12. def open_repo(path: str):
  13. if not os.path.exists(path):
  14. return None
  15. try:
  16. return Repo(path)
  17. except InvalidGitRepositoryError:
  18. return None
  19. def update_rules(repo_path, save_path, commit, matches, keep_tree):
  20. os.makedirs(save_path, exist_ok=True)
  21. for pattern in matches:
  22. files = glob.glob(os.path.join(repo_path, pattern), recursive=True)
  23. for file in files:
  24. if os.path.isdir(file):
  25. continue
  26. file_rel_path, file_name = os.path.split(os.path.relpath(file, repo_path))
  27. if keep_tree:
  28. file_dest_dir = os.path.join(save_path, file_rel_path)
  29. os.makedirs(file_dest_dir, exist_ok=True)
  30. file_dest_path = os.path.join(file_dest_dir, file_name)
  31. else:
  32. file_dest_path = os.path.join(save_path, file_name)
  33. shutil.copy2(file, file_dest_path)
  34. logging.info(f"copied {file} to {file_dest_path}")
  35. def main():
  36. parser = argparse.ArgumentParser()
  37. parser.add_argument("-c", "--config", default="rules_config.conf")
  38. args = parser.parse_args()
  39. config = configparser.ConfigParser()
  40. config.read(args.config)
  41. logging.basicConfig(format="%(asctime)s %(message)s", level=logging.DEBUG)
  42. for section in config.sections():
  43. repo = config.get(section, "name", fallback=section)
  44. url = config.get(section, "url")
  45. commit = config.get(section, "checkout")
  46. matches = config.get(section, "match").split("|")
  47. save_path = config.get(section, "dest", fallback=f"base/rules/{repo}")
  48. keep_tree = config.getboolean(section, "keep_tree", fallback=True)
  49. logging.info(f"reading files from url {url} with commit {commit} and matches {matches}, save to {save_path} keep_tree {keep_tree}")
  50. repo_path = os.path.join("./tmp/repo/", repo)
  51. r = open_repo(repo_path)
  52. if r is None:
  53. logging.info(f"cloning repo {url} to {repo_path}")
  54. r = Repo.clone_from(url, repo_path)
  55. else:
  56. logging.info(f"repo {repo_path} exists")
  57. r.git.checkout(commit)
  58. update_rules(repo_path, save_path, commit, matches, keep_tree)
  59. shutil.rmtree("./tmp", ignore_errors=True)
  60. if __name__ == "__main__":
  61. main()