Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
jupyter-naas
GitHub Repository: jupyter-naas/awesome-notebooks
Path: blob/master/GitHub/GitHub_Clone_repository_and_switch_branch.ipynb
2973 views
Kernel: Python 3

GitHub.png

GitHub - Clone repository and switch branch

Give Feedback | Bug report

Tags: #github #clone #repository #branch #switch #git

Last update: 2023-05-09 (Created: 2023-05-09)

Description: This notebook clones a branche from a GitHub repository to your local machine, rename the repository with the branch name, and switch to it to the designated branch. This approach enhances efficiency by enabling you to work on multiple branches simultaneously without the need to constantly switch, thus avoiding conflicts. Before using this on Naas, ensure your SSH is properly configured (you can use the Naas_Configure_SSH.ipynb template for this).

Input

Import libraries

import os

Setup Variables

  • repo_url: URL of the repository to clone

  • branch_name: Name of the branch to switch to

  • output_dir: Output directory to clone repo. If None, we will create a folder with the name of the branch

# Inputs repo_url = "https://github.com/jupyter-naas/awesome-notebooks" branch_name = "1743-github-clone-repository-and-switch-branch" # Outputs output_dir = None

Model

Clone repository

Clone the repository from the given URL and create a local copy of it.

def clone_branch(repo_url, output_dir, branch_name): # Get GitHub owner and repo name owner = repo_url.split("https://github.com/")[-1].split("/")[0] repo_name = repo_url.split("/")[-1] # Add repo name with .git extension if not repo_name.endswith(".git"): repo_name = f"{repo_name}.git" repo = f"{owner}/{repo_name}" # Init output dir if not output_dir: output_dir = branch_name else: output_dir = os.path.join(output_dir, branch_name) # Create output directoy if not os.path.exists(output_dir): os.makedirs(output_dir) # GitHub Action !cd '{output_dir}' !git clone git@github.com:'{repo}' '{output_dir}' print(f"✅ GitHub repo cloned: {output_dir}") return output_dir output_dir = clone_branch(repo_url, output_dir, branch_name)

Output

Switch branch

Change the current branch to the given branch name.

def switch_branch(output_dir, branch_name): # GitHub action !cd '{output_dir}' && git checkout '{branch_name}' print(f"✅ Switched to branch '{branch_name}'") switch_branch(output_dir, branch_name)