Skip to content

Commit 502dd2d

Browse files
🔀 Merge pull request #211 from retigra/git-faulty-base-branches
🐛 Using non-default branches results in conflicts as branches are frequently based of default branch
2 parents 936a4fe + f8319cd commit 502dd2d

File tree

2 files changed

+25
-8
lines changed

2 files changed

+25
-8
lines changed

zabbixci/git/git.py

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,6 @@ def switch_branch(self, branch: str):
110110
Switch to a branch, if the branch does not exist, create it
111111
"""
112112
if not self._repository.branches.local.get(branch):
113-
logger.debug("Branch %s does not exist, creating", branch)
114113
self.create_branch(branch)
115114

116115
local_branch = self._repository.branches.local[branch]
@@ -124,7 +123,25 @@ def create_branch(self, branch: str):
124123
Create a branch
125124
"""
126125
try:
127-
peel = self._repository.head.peel(None)
126+
peel = None
127+
try:
128+
# Check for remote branch and base the new branch on it
129+
remote_branch = self._repository.branches.remote.get(f"origin/{branch}")
130+
131+
if remote_branch:
132+
logger.debug(
133+
"Found remote branch %s, basing local branch off it", branch
134+
)
135+
peel = remote_branch.peel(None)
136+
except GitError:
137+
logger.exception("Fetching remote branch %s failed", branch)
138+
139+
if not peel:
140+
peel = self._repository.head.peel(None)
141+
logger.debug(
142+
"Remote branch %s does not exist, basing local branch off HEAD",
143+
branch,
144+
)
128145

129146
if not isinstance(peel, Commit):
130147
raise GitError("Cannot create branch, HEAD is not a commit")

zabbixci/zabbixci.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,11 @@ async def push(self) -> bool:
107107
if not self._git.is_empty:
108108
# If the repository is empty, new branches can't be created. But it is
109109
# safe to push to the default branch
110+
111+
# Switch to the pull branch, as we base our push branch on it
112+
self._git.switch_branch(self.settings.PULL_BRANCH)
113+
114+
# Switch or create the push branch
110115
self._git.switch_branch(self.settings.PUSH_BRANCH)
111116

112117
# Pull the latest remote state
@@ -117,12 +122,7 @@ async def push(self) -> bool:
117122
"Remote branch does not exist, using state from branch: %s",
118123
self.settings.PULL_BRANCH,
119124
)
120-
# Remote branch does not exist, we pull the default branch and create a new branch
121-
self._git.switch_branch(self.settings.PULL_BRANCH)
122-
self._git.pull(self.settings.REMOTE)
123-
124-
# Create a new branch
125-
self._git.switch_branch(self.settings.PUSH_BRANCH)
125+
self._git.pull(self.settings.REMOTE, branch=self.settings.PULL_BRANCH)
126126

127127
# Reflect current Zabbix state in the cache
128128
Cleanup.cleanup_cache(self.settings)

0 commit comments

Comments
 (0)