Skip to content

Commit

Permalink
update checkoutToBranch func
Browse files Browse the repository at this point in the history
  • Loading branch information
oz-keisar-d committed Aug 21, 2024
1 parent f07c585 commit bca9c28
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 bca9c28

Please sign in to comment.