Skip to content

Commit

Permalink
Merge pull request #20 from ozkeisar/fix--bracnch-checkout
Browse files Browse the repository at this point in the history
update checkoutToBranch func
  • Loading branch information
ozkeisar authored Aug 21, 2024
2 parents f07c585 + bca9c28 commit dcf128f
Showing 1 changed file with 26 additions and 5 deletions.
31 changes: 26 additions & 5 deletions src/backend/utils/git.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,27 +116,48 @@ function formatBranchName(name: string) {

return formattedName;
}

export const checkoutToBranch = async (
projectName: string,
branchName: string,
createIfNotExist = false,
) => {
try {
const currentRepoFolderPath = await getProjectPath(projectName);

const git = simpleGit(currentRepoFolderPath);

// Check if the branch is remote
const isRemoteBranch = branchName.startsWith('remotes/origin/');
const localBranchName = isRemoteBranch
? branchName.replace('remotes/origin/', '')
: branchName;

if (createIfNotExist) {
await git.checkoutLocalBranch(formatBranchName(branchName));
if (isRemoteBranch) {
// For remote branches, we need to fetch first
await git.fetch('origin');
// Then create a new local branch tracking the remote branch
await git.checkoutBranch(localBranchName, `origin/${localBranchName}`);
} else {
await git.checkoutLocalBranch(formatBranchName(localBranchName));
}
} else if (isRemoteBranch) {
// For remote branches, we need to fetch first
await git.fetch('origin');
// Then checkout the branch, creating a local branch that tracks the remote
await git.checkout([
'-B',
localBranchName,
`origin/${localBranchName}`,
'--force',
]);
} else {
await git.checkout(branchName, ['--force']);
await git.checkout(localBranchName, ['--force']);
}
} catch (error) {
console.error(`Error checking out to branch '${branchName}':`, error);
throw error;
}
};

export const getCurrentBranch = async (projectName: string) => {
try {
const currentRepoFolderPath = await getProjectPath(projectName);
Expand Down

0 comments on commit dcf128f

Please sign in to comment.