# 1.3 Save ROS code on GitHub

In this tutorial, we will create a ROS 2 workspace and store the project in a repository on GitHub.

{% embed url="<https://youtu.be/asKyDmM_TBY>" %}

ROS 2 has been designed with different layers. For users, the workspace is a folder that is the central location for organizing and developing your robot project. It contains all the code, data files, and configuration scripts.

<figure><img src="/files/l5m57Rg8ZKMtDRHiDxUO" alt=""><figcaption></figcaption></figure>

<details>

<summary>ROS2 workspace structure</summary>

{% code overflow="wrap" %}

```
WorkSpace --- User workspace
    |--- build：temporary files during compiling
    |--- install：every package here has a sub installation directory
    |--- log：log files
    |--- src：the source code
        |-- C++_package_1
            |-- package.xml：meta information about the package
            |-- CMakeLists.txt：how to build the code within the package
            |-- src：the source code for the package
            |-- include/<package_name>：the public headers for the package
            |-- msg：messege interface files
            |-- srv：service interface files
            |-- action：action interface files
        |-- Python_package_1
            |-- package.xml：meta information about the package
            |-- setup.py：instructions for how to install the package
            |-- setup.cfg： set it when has executables, so ros2 run can find
            |-- resource/<package_name>：marker file for the package
            |-- test：related test files
            |-- <package_name>：a directory with the same name as your package, used by ROS 2 tools to find the package, contains __init__.py
        |-- other_packages...
```

{% endcode %}

</details>

## Create a workspace

Open a terminal, and type the first two lines of command to create your workspace. The **src** folder inside the workspace is where all your code will go for your robot.

```
mkdir -p ~/ros2_ws/src
cd ~/ros2_ws/src
# git clone a repo or create a package
ros2 pkg create --build-type ament_cmake --license Apache-2.0 mec_mobile
ros2 pkg create --build-type ament_python --license Apache-2.0 <package_name>
# optional arguments --node-name and --license. 
```

We don’t need any code in our workspace now, just run the command below to build the workspace.&#x20;

```
cd ~/ros2_ws
colcon build
colcon build --packages-select package_name --symlink-install 
# --symlink-install saves rebuild every time you tweak python scripts
```

This **colcon build** command needs to be run in the **root of your workspace** whenever you make additions or changes to the code. Type following command after colcon build:

```
dir
```

You will see three folders that are automatically created when you run the colcon build:

* **build**: This is where ROS 2 temporarily stores files while it’s compiling.
* **install:** The finished, ready-to-use parts of your robot’s software are placed.
* **log: K**eeps track of what happened when you built your code.

We can run the following command to make sure this workspace will be found any time we open a new terminal window.

```
echo "source ~/ros2_ws/install/setup.bash" >> ~/.bashrc
source ~/.bashrc
```

## Git and Github

It's always a good idea to keep code backed up and version controlled. Using Git with an online service like Github is an easy way. Git is also a useful tool for multiple developers working on a project, or developing on multiple machines. Here I assume you already got a GitHub account.

<figure><img src="/files/Oexyea3x4tJy4q9rsW9h" alt=""><figcaption></figcaption></figure>

### Install Git

The first thing you need to do is install Git. Open a new terminal window, and type:

```
sudo apt-get update
sudo apt-get install git -y
```

Check the git version you have.

```
git --version
```

### Configure Git

Configure your git username and email.

```
git config --global user.name "JohnSmith"
git config --global user.email "johnsmith@example.com"
git config --global init.defaultBranch main
```

We'll use SSH to authenticate. So if you haven't got that set up already, [take a look here](https://docs.github.com/en/authentication/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent?platform=linux).

<details>

<summary>Connecting to GitHub with SSH</summary>

If you want to not have to use a username and password every time you run “git push”, you can use SSH keys. Here is the process:

1. Generate an SSH key pair (if you don’t already have one) by running:

```
ssh-keygen -t ed25519 -C "your_email@example.com"
# This creates a new SSH key, using the provided email as a label.
```

When you get prompted for a password or saving location, just keep pressing Enter, which will accept the default.

2. Start the ssh-agent in the background.

```
eval "$(ssh-agent -s)"
```

3. Add your SSH private key to the ssh-agent:

```
ssh-add ~/.ssh/id_ed25519
```

4. Copy the SSH public key to your clipboard.

```
cat ~/.ssh/id_ed25519.pub
# Then select and copy the contents of the id_ed25519.pub file
```

5. Go to your GitHub account **“Settings”** by clicking your profile icon in the upper right.
6. In the "Access" section of the sidebar, click **SSH and GPG keys**. Then click **New SSH key** or **Add SSH key**.
7. In the "Key" field, paste the copied key as an “Authentication Key”. Also add a title such as *laptop*.
8. Click **Add SSH key**.

#### Test the SSH:

1. Go back to the main page of your repository on GitHub. Copy the SSH URL of the repo.\
   ![](/files/n2GjYqIlXmQ23EzrN4ea)
2. Back to your Ubuntu Linux terminal window, and moving to the directory of your repository, then run *git clone + ssh*. For example:

```
cd  ~/ros2_ws/src/my_package1/
git clone COPYED_SSH
```

#### Switch your repository’s remote URL to SSH&#x20;

Go to your Ubuntu Linux terminal window, and moving to the directory of your repository. For example:

```
cd  ~/ros2_ws/src/mec_mobile/
git remote set-url origin git@github.com:rbtlabs/mec_mobile.git
```

To confirm everything is setup properly, type:

```
git pull
```

If you get asked about the authenticity of the host, just type <mark style="color:red;">**yes**</mark> and press Enter.

</details>

### Create the Remote Repository on GitHub

[Go to GitHub](https://github.com/) and log in. Click on the “+” icon in the upper right corner and select “New repository.”&#x20;

Give the package a name (usually same as in ROS), choose to make it public or private, and then we  **skip** the "Initialize" options and hit "Create Repository".

### Push the package to the remote repo[​](https://articulatedrobotics.xyz/tutorials/ready-for-ros/packages/#push-the-package-to-a-repo) <a href="#push-the-package-to-a-repo" id="push-the-package-to-a-repo"></a>

Now we need to push our local content to this repo. Open a terminal in your ros project directory:&#x20;

```
cd ~/ros2_ws/src/mec_mobile/
```

We can run the following commands with our `username` and `repository` name substituted. If you've never used Git on this computer before, you may also need to set a username and email address (it will tell you how).

```
git init
git add .
git commit -m "First Commit"
git branch -M main
git remote add origin git@github.com:<GITHUB_USERNAME>/<REPO_NAME>.git
git push -u origin main
```

These commands:

* Initialize git for the directory
* Stage the whole directory (ready to be committed)
* Create a commit with a message
* Create a `main` branch
* Set the URL link for the cloud repo to push to, and give it the name `origin`
* Push the `main` branch to the `origin` repo

Origin refers to your GitHub repository, and main is the name of your branch. The terminal will respond to let us know it has been pushed.

Now if you go back to GitHub, you can see your repository.

## Git Command Overview

When you make changes to your code on your computer, and want to get these code changes saved to GitHub, here is how you do it:

```
git add . 
# This command picks up all your new code changes and gets them ready to be saved.
```

```
git commit -m "description of changes" 
# This command saves the changes on your computer with a message for what you did.
```

```
git push 
# This command sends all your saved changes to GitHub.
```

You’ll repeat these three steps each time you want to update your code on GitHub.&#x20;

And if you’re working with other people, you should always download their changes first using **git fetch**, **git status**, and then **git pull** (one command right after the other) before you start working.

**git fetch** checks GitHub to see <mark style="color:red;">what changes exist</mark> – it’s like looking at a list of updates available but not downloading them yet. It tells you what’s different between your code and GitHub’s code.

**git status** shows you <mark style="color:red;">exactly what’s different</mark> between your local code and the code on GitHub after you’ve fetched. It’s like comparing your version with GitHub’s version to see what’s changed.

**git pull** actually <mark style="color:red;">downloads those changes</mark> from GitHub to your computer, bringing your local code up to date. It’s like clicking “download” on those updates you found with fetch and status.

These three commands help you safely check for and get any updates before you start working, which helps avoid conflicts with other people’s code changes.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://robotlabs.gitbook.io/docs/ros/ros2-jazzy/1.3-save-ros-code-on-github.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
