git.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # Licensed to the Apache Software Foundation (ASF) under one
  2. # or more contributor license agreements. See the NOTICE file
  3. # distributed with this work for additional information
  4. # regarding copyright ownership. The ASF licenses this file
  5. # to you under the Apache License, Version 2.0 (the
  6. # "License"); you may not use this file except in compliance
  7. # with the License. You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing,
  12. # software distributed under the License is distributed on an
  13. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. # KIND, either express or implied. See the License for the
  15. # specific language governing permissions and limitations
  16. # under the License.
  17. """Github utils for git operations."""
  18. from pathlib import Path
  19. from typing import Dict, Optional
  20. from git import Repo
  21. git_dir_path: Path = Path(__file__).parent.parent.parent.parent.joinpath(".git")
  22. class Git:
  23. """Operator to handle git object.
  24. :param path: git repository path
  25. :param branch: branch you want to query
  26. """
  27. def __init__(
  28. self, path: Optional[str] = git_dir_path, branch: Optional[str] = None
  29. ):
  30. self.path = path
  31. self.branch = branch
  32. @property
  33. def repo(self) -> Repo:
  34. """Get git repo object."""
  35. return Repo(self.path)
  36. def has_commit_current(self, sha: str) -> bool:
  37. """Whether SHA in current branch."""
  38. branches = self.repo.git.branch("--contains", sha)
  39. return f"* {self.repo.active_branch.name}" in branches
  40. def has_commit_global(self, sha: str) -> bool:
  41. """Whether SHA in all branches."""
  42. try:
  43. self.repo.commit(sha)
  44. return True
  45. except ValueError:
  46. return False
  47. def cherry_pick_pr(self, pr: Dict) -> None:
  48. """Run command `git cherry-pick -x <SHA>`."""
  49. sha = pr["merge_commit_sha"]
  50. if not self.has_commit_global(sha):
  51. raise RuntimeError(
  52. "Cherry-pick SHA %s error because SHA not exists,"
  53. "please make sure you local default branch is up-to-date",
  54. sha,
  55. )
  56. if self.has_commit_current(sha):
  57. print("SHA %s already in current active branch, skip it.", sha)
  58. self.repo.git.cherry_pick("-x", sha)