TechEarl

How to Start Working on an Existing Git Project

Joining a team and need to start contributing to an existing Git repo? Here is the exact path: clone, install, branch off main, commit, push, and open a pull request, plus fork vs clone, syncing a fork with upstream, fixing 'remote origin already exists', and moving commits as patch files with git format-patch and git am.

Ishan KarunaratnePublished ⏱️ 21 min readUpdated
Share thisCopied
Clone a team's Git repo, branch, commit, push, and open a pull request. Plus fork vs clone, syncing a fork, and 'remote origin already exists'.

When you join a team, the path to your first contribution is the same almost everywhere: clone the repo, install its dependencies, create a branch off the main branch, make your change, push the branch, and open a pull request. You never commit straight to main, and you never start from an empty folder. The project already exists; you are joining it.

Below is that whole sequence with the reasoning behind each step, followed by the pieces you meet right after it: fork vs clone for projects you cannot push to, creating a pull request in detail, syncing a fork with upstream, the "remote origin already exists" error, and exporting and applying patches when there is no shared remote at all. If you are completely new to Git, start with Git for Beginners first.

The short version

bash
git clone git@github.com:acme/widget-api.git
cd widget-api
npm install                       # or: pip install -r requirements.txt, bundle install, etc.
git checkout -b fix-login-redirect
# ...make your change, then:
git add .
git commit -m "Fix redirect loop on expired session"
git push -u origin fix-login-redirect
# then open a pull request on GitHub

That is the entire loop. The rest of this article explains each line.

Step 1: Clone the repository

Cloning downloads the full project, including its entire history, and sets up a connection (called origin) back to the server you cloned from.

bash
git clone git@github.com:acme/widget-api.git

That creates a widget-api folder containing the code. Use the SSH URL (git@github.com:...) if you have an SSH key set up, or the HTTPS URL (https://github.com/...) if you do not. If you have not set up a key yet, see adding an SSH key to GitHub; if you are unsure which to pick, I compared SSH vs HTTPS remotes separately.

Cloning is not the same as forking. On a team where you have write access to the shared repo, you clone. Forking makes your own server-side copy first and is the norm for open-source contributions where you do not have write access. I cover the distinction in fork vs clone below.

After cloning, move into the folder:

bash
cd widget-api

Step 2: Install dependencies and read the README

The code is on your machine, but it will not run yet. Almost every project depends on packages that are not committed to the repo. The README tells you which command installs them and how to run the project locally.

bash
npm install          # Node.js
# pip install -r requirements.txt   # Python
# bundle install                    # Ruby
# composer install                  # PHP

Why are these packages not in the repo? Because they are listed in a manifest (package.json, requirements.txt) and reinstalled on demand, and the actual files are excluded by .gitignore. Open the .gitignore early; it tells you a lot about what the project considers generated or local-only. If a node_modules folder or a .env file shows up as untracked, that is expected: those are ignored on purpose.

Run whatever the README lists as the test or dev command to confirm the project actually works on your machine before you change anything. Diagnosing a failing build is much easier when you know it failed because of your change, not because the project never ran in the first place.

Step 3: Make sure your main branch is current

Before you branch, make sure your local copy of the main branch matches the server. A fresh clone is current by definition, but if you cloned days ago, sync first:

bash
git checkout main
git pull

git pull fetches the latest commits from origin and merges them into your local main. On a recent Git, that first pull can throw the divergent-branches reconcile prompt if your local and remote histories have diverged, so do not be alarmed when it asks you to pick a strategy. If you want to inspect what changed before merging, fetch first and look; I explain the difference in git pull vs git fetch.

If you already made edits before syncing, the pull can also stop with a complaint that your local edits would be overwritten. The cleanest fix is to stash them out of the way, pull to get main current, then continue.

Some teams call the main branch master instead of main. Check with git branch -a, which lists every local and remote branch.

Step 4: Create a branch for your work

You do your work on a branch, never directly on main. A branch is a cheap, isolated line of development. It lets you commit freely without touching the shared branch, and it is what a pull request is built on.

bash
git checkout -b fix-login-redirect

git checkout -b creates a new branch and switches to it in one step. The name should describe the work: fix-login-redirect, add-csv-export. Many teams have a naming convention (feature/..., fix/...); the README or a CONTRIBUTING file will say. If branching itself is still fuzzy, I walk through it in Git branching explained.

Newer Git also offers git switch -c fix-login-redirect, which does the same thing with a clearer name. Both work; use whichever your team uses.

Step 5: Make your change, then stage and commit

Edit the files. When you are ready to record a snapshot, you stage the changes and then commit them. Staging is the step where you choose exactly what goes into the next commit, and it trips up a lot of newcomers, so it is worth understanding the staging area properly.

bash
git status                # see what changed
git add src/auth.js       # stage specific files
git commit -m "Fix redirect loop on expired session"

git add . stages everything that changed, which is fine for a focused branch. For a clean history, prefer staging only the files that belong to this change so unrelated edits do not sneak in. Run git status first, every time, so you know what you are about to commit.

Write a real commit message. "Fix redirect loop on expired session" tells a reviewer what happened; "stuff" and "fix" do not. A good message has a short summary line in the imperative mood. There is more nuance to it, which I cover in commit message conventions.

Made a typo in the message or staged the wrong file? It is recoverable. You can undo the last commit before you push, and if you have already deleted work, the reflog can recover lost commits.

Step 6: Push your branch

Your commits live only on your machine until you push them. The first push of a new branch needs -u to link your local branch to a new branch on origin:

bash
git push -u origin fix-login-redirect

The -u (short for --set-upstream) tells Git that this local branch tracks origin/fix-login-redirect. After that first push, every later push and pull on this branch is just git push and git pull with no arguments. If you skip the -u, Git stops with:

text
fatal: The current branch fix-login-redirect has no upstream branch.

That exact situation is covered in the current branch has no upstream branch.

Step 7: Open a pull request

Pushing the branch does not merge it. It just makes the branch visible on the server. To get your change into main, you open a pull request (PR): a request to merge your branch, which your teammates review before it lands. Right after a push, GitHub usually prints a URL in the terminal that opens the PR form directly. The full flow, from the compare view to merging, is in create a pull request below.

Fork vs clone

A fork is a copy of someone else's repository in your own account on the hosting platform, so you can change it without push access to the original. A clone is a local copy on your own machine. They are not alternatives: for a project you cannot push to, you fork on GitHub, then clone your fork.

ForkClone
Where the copy livesOn the hosting platform (GitHub, GitLab), in your accountOn your local machine
What it isA server-side copy of the whole repo under your namespaceA working copy with the full history and a .git folder
Is it a Git command?No (a GitHub/GitLab feature, done in the web UI)Yes (git clone)
When you need itYou want to contribute but lack push access to the originalYou want to work with the files locally (any repo)
Do you get push access?Yes, you own the fork, so you can push to itOnly if you had push access to the cloned repo already
Knows about the original?Yes, GitHub tracks the upstream parentNot automatically (you add a remote yourself)

Cloning never grants permission; it only copies. A clone records the original URL as a push target, but if you lack write access the server rejects the push:

text
remote: Permission to some-org/some-project.git denied to your-username.
fatal: unable to access 'https://github.com/some-org/some-project.git/': The requested URL returned error: 403

That is why forks exist. The decision is one question: do you have push access?

SituationWhat you doWhy
You are on the team with write accessClone the shared repo, push branches to itYou can push branches and open PRs directly on origin
Open-source project, no write accessFork first, then clone your forkYou cannot push to a repo you do not own; the fork is your writable copy
You want a local copy to read, not contributeClone (read-only)Nothing to push; you just want the code and history

The fork-and-pull-request workflow

  1. Fork the project on GitHub. some-org/the-project becomes your-username/the-project.
  2. Clone your fork (not the original) and move into it: git clone https://github.com/your-username/the-project.git, then cd the-project.
  3. Add the original as upstream so you can pull in its changes later:
bash
git remote add upstream https://github.com/some-org/the-project.git
git remote -v
text
origin    https://github.com/your-username/the-project.git (fetch)
origin    https://github.com/your-username/the-project.git (push)
upstream  https://github.com/some-org/the-project.git (fetch)
upstream  https://github.com/some-org/the-project.git (push)
  1. Branch, commit, and push to your fork (origin, which you own): git checkout -b fix-typo-in-readme, commit, then git push origin fix-typo-in-readme.
  2. Open a pull request from your fork's branch into the original project's main. The maintainers review and merge it; you never needed push access to the original.

Common confusions: forking does not put anything on your computer (you still clone); you do not need a fork for repos you own or collaborate on; and once your PR is merged, you can safely delete the fork, because the merged commits now live in the original.

Create a pull request

A pull request is a request to merge the commits on one branch into another, paused so a teammate can review them first. On GitLab the same thing is called a merge request (MR); the mechanics are identical. The loop: branch off an up-to-date main, commit, push with -u, open the PR, request review, address feedback, merge. Never open a PR from main itself.

Open it and pick base and compare

There are three ways to reach the form: the "Create a pull request" link GitHub prints after your push, the yellow "Compare & pull request" banner on the repo page, or the "Pull requests" tab, then "New pull request". Either way you land on the compare view:

text
base: main  <-  compare: add-login-page

base is where your work will merge into (usually main); compare is your branch. Getting these backwards is the single most common beginner mistake: if the diff looks empty or shows the wrong commits, you have them swapped. On GitLab it is "Merge requests", then "New merge request", with "source" (yours) and "target" (main).

Write a description that respects the reviewer

A good description answers three questions before the reviewer has to ask: what changes, why (link the issue; Closes #142 auto-closes it on merge), and how to check it.

text
## What
Adds the login page and client-side form validation.

## Why
Closes #142. Users had no way to sign in from the marketing site.

## How to test
1. Run the app, visit /login
2. Submit empty form -> see inline errors
3. Submit valid creds -> redirect to /dashboard

Keep the PR small. A 60-line PR gets a careful review in ten minutes; a 2,000-line PR gets a rubber-stamp "LGTM" because nobody can hold that much in their head.

Review, drafts, and feedback

Add reviewers from the sidebar. With branch protection on main, a required-review rule means the PR cannot merge until someone approves, and CI checks show up as pass/fail status on the PR. A draft pull request (the dropdown next to "Create pull request", or a Draft: title prefix on GitLab) is visible and runs CI but cannot be merged and does not ping reviewers; click "Ready for review" when it is.

To address feedback, push more commits to the same branch; they appear on the open PR automatically, and since the upstream is set, it is just git push. If main moved on while the PR was open, merge or rebase it into your branch (the trade-offs are in git merge vs git rebase) and resolve any merge conflicts.

Merge and clean up

StrategyWhat it doesWhen I reach for it
Create a merge commitKeeps every commit plus a merge commitLong-lived feature branches where the history matters
Squash and mergeCollapses all branch commits into oneThe default for most feature PRs; keeps main linear and readable
Rebase and mergeReplays each commit onto main, no merge commitWhen each commit is already clean and you want them preserved

For most day-to-day work I use squash and merge. Afterwards, delete the branch on GitHub and locally:

bash
git switch main
git pull
git branch -d add-login-page
GitHubGitLab
Feature namePull request (PR)Merge request (MR)
Branch dropdownsbase / comparetarget / source
Draft mode"Create draft pull request"Draft: title prefix
Auto-close issueCloses #142Closes #142

Plain Git cannot open a pull request; it is a hosting-platform feature. From the terminal, GitHub's CLI has gh pr create and GitLab has glab.

Sync a fork with upstream

A fork is frozen at the moment you made it, and the original project keeps moving. Your clone's origin points at your fork, so git pull only pulls from your own copy. To catch up, fetch from the upstream remote you added in the fork workflow and bring its commits into your branch:

bash
git remote -v                     # check upstream is already there
# only if it is missing:
# git remote add upstream https://github.com/original-owner/project.git
git fetch upstream
git checkout main
git merge upstream/main
git push origin main

git fetch upstream downloads the original project's commits into remote-tracking branches like upstream/main without touching your files. If main has no commits of your own (the common case, since you work on feature branches), the merge is a fast-forward. You only ever fetch from upstream; you never push to it. If Git says remote upstream already exists, reuse it or fix its URL with git remote set-url upstream <url>.

You can rebase instead of merging (git rebase upstream/main), which replays any commits you have on main on top of upstream's latest for a linear history:

MergeRebase
HistoryKeeps a merge commit when branches divergedLinear, no merge commit
SafetySafer; never rewrites existing commitsRewrites your local commits
Already-pushed commitsFineAvoid if those commits are already public
Best forA shared main others have pulledKeeping a personal fork tidy before a PR

The pattern I follow: sync main, then branch off the freshly synced main, do the work, and push the branch with -u. Right before opening the PR, sync once more and rebase the feature branch onto the latest upstream so the PR sits on current code:

bash
git fetch upstream
git checkout fix-typo-in-readme
git rebase upstream/main
git push --force-with-lease origin fix-typo-in-readme

--force-with-lease refuses to overwrite the remote branch if it no longer matches what your last fetch recorded, so a push someone made since then is not silently clobbered. The check relies on your remote-tracking ref, so a background git fetch (some editors run one) can update it and defeat the protection; when that matters, pass the expected tip explicitly (--force-with-lease=fix-typo-in-readme:<sha>) or add --force-if-includes. Use it instead of a bare --force after any rebase. If a PR shows changes you did not make, your branch is based on stale upstream history, and this rebase narrows the diff back to your own work. If the merge errors with refusing to merge unrelated histories, the fork was re-initialized at some point and no longer shares a common ancestor with upstream. And if uncommitted edits block the sync, git stash, merge, then git stash pop.

Fix "remote origin already exists"

fatal: remote origin already exists. means you ran git remote add origin <url> but a remote named origin is already configured. You do not need to add it again. The usual causes: you cloned the repo (which sets origin for you) and then followed GitHub's "push an existing repository" snippet, you ran the same git remote add twice, or a folder you set up with git init still has an origin pointing at an old URL.

Check what is set first:

bash
git remote -v
text
origin  https://github.com/you/your-repo.git (fetch)
origin  https://github.com/you/your-repo.git (push)

If that is already the URL you want, there is nothing to fix. If not, update it in place:

bash
git remote set-url origin https://github.com/you/your-repo.git
# or switch to SSH (add an SSH key to your account first):
git remote set-url origin git@github.com:you/your-repo.git

set-url changes only the URL and keeps branch tracking and fetch refspecs. When the remote's config is broken beyond its URL, remove and re-add it instead (git remote rm origin is the older spelling of remove):

bash
git remote remove origin
git remote add origin https://github.com/you/your-repo.git
SituationUseWhy
origin exists, you just want a different URLgit remote set-url origin <url>Surgical: changes only the URL, keeps tracking config
Switching HTTPS to SSH (or back) for the same repogit remote set-url origin <url>Same remote, different transport, no need to recreate
Remote config is broken or you want a clean slategit remote remove then git remote addWipes the old definition entirely and rebuilds it
You want a second remote alongside origin (e.g. a fork)git remote add upstream <url>Add under a new name, do not touch origin

To confirm everything lines up, run git remote -v (the URL), git remote show origin (contacts the remote and lists its branches), and git branch -vv (which remote branch each local branch tracks).

Export and apply Git patches

Pull requests cover everyday team work, but sometimes there is no shared remote in the middle: moving a change between two repos that share no remote, sending a fix to a project you have no push access to, attaching a diff to a bug tracker, or the mailing-list workflow (git send-email) that the Linux kernel and other large projects still run on. For those, a patch file does the job, and there are two flavors. Picking the right one is the whole game.

You wantExportApplyAuthorship and history
A quick change moved overgit diff > my.patchgit apply my.patchNone preserved, no commit created
The commits recreated faithfullygit format-patch <range>git am *.patchAuthor, date, and message kept

git diff plus git apply: a quick change transfer

git diff > my.patch captures your unstaged changes (the working tree compared with the index) into a plain unified diff. Anything you already ran git add on is left out, so if the patch must carry both staged and unstaged edits, use git diff HEAD > my.patch, which compares the working tree with the last commit. git apply my.patch in another checkout replays those line edits. No commit is created, nothing is staged, and the patch has no notion of who wrote it or why. It suits a one-off fix, a config tweak, or moving an experiment between two clones.

bash
# In the source repo: write the unstaged changes to a file
git diff > my.patch

# Staged and unstaged changes together (everything since the last commit)
git diff HEAD > my.patch

# Only what is already staged (--staged is the same flag)
git diff --cached > staged.patch

# In the target repo: apply to the working tree only
git apply my.patch

# Or apply and stage in one step
git apply --index my.patch

git format-patch plus git am: preserve authorship

git format-patch writes one file per commit, each formatted as an mbox-style email complete with the author, date, subject (the commit summary), and full commit body. You pick the range of commits to export:

bash
# The last N commits, numbered 0001-, 0002-, ...
git format-patch -3

# Every commit on feature that is not on main
git format-patch main..feature

# Just the most recent commit
git format-patch -1 HEAD

# Everything on this branch that is not on origin/main
git format-patch origin/main..HEAD

# Drop the files into a directory instead of the current folder
git format-patch -3 -o patches/

# A single combined file on stdout instead of one-per-commit
git format-patch main --stdout > feature.patch

On the receiving end, git am ("apply mailbox") reads those files, splits each back into its metadata and diff, and creates a commit per patch. Because the author and date rode along in the file, the replayed commits keep the original authorship rather than being attributed to whoever ran the command:

bash
# Apply every patch file in order, recreating the commits
git am *.patch

# Add a Signed-off-by trailer if the project expects one
git am --signoff *.patch

If git am stops on a conflict, git am --abort rewinds you to where you started, git am --skip drops the current patch, and git am --continue resumes after you have resolved the conflict and staged the fix.

The short rule: git apply for a change transfer you will throw away after one apply, git format-patch plus git am when the work is real commits you want to land intact in another tree.

Check a patch first, and fall back to --3way

git apply --check tells you whether a patch will apply cleanly without changing anything. Run it first whenever you did not generate the patch yourself:

bash
# Will it apply? No changes made, just success or an error.
git apply --check my.patch

# What files and how many lines would it touch?
git apply --stat my.patch

A clean --check exits silently with status 0. A "patch does not apply" or a hunk error means the target tree has drifted from where the patch was cut. When that happens because the surrounding lines have moved, --3way falls back to Git's real merge machinery instead of failing outright:

bash
git apply --3way my.patch
git am --3way *.patch

It needs the patch to record the blob identities it expects (the index lines that git format-patch and git diff include by default) and those blobs to exist locally. Instead of rejecting a hunk, Git does a three-way merge and leaves you ordinary conflict markers to resolve, exactly like a branch merge. If the commits you are about to export are noisy, squashing them first gives you cleaner patch files to hand over.

Common things that go wrong on your first day

A few errors are near-universal for newcomers. None of them mean you broke anything.

  • Please tell me who you are on your first commit means Git does not have your name and email configured yet. The fix is two git config commands, covered in fixing "Please tell me who you are".
  • Permission denied (publickey) when cloning over SSH means your SSH key is not set up or not added to GitHub. See Permission denied (publickey).
  • Support for password authentication was removed over HTTPS means GitHub wants a personal access token, not your account password. The fix is in password authentication was removed.
  • failed to push some refs usually means the remote has commits you do not, so you need to pull first. See failed to push some refs.

When your branch falls behind main while your PR is open, you will eventually have to integrate the latest changes, which can produce a merge conflict. Conflicts are normal and resolvable; they are not a sign you did something wrong.

Where to go next

That loop, clone to PR, is the daily rhythm of working on a team. Once it is muscle memory, the next things worth learning are how your team integrates branches (merge vs rebase) and which overall branching model you are following (GitHub Flow vs Git Flow vs trunk-based). The full map of beginner Git topics lives on the Git for Beginners hub.

If you are on the team and have write access to the repository, clone it and push your branches directly. If it is an open-source project where you do not have write access, fork it first, then clone your fork. The deciding factor is whether you can push to the original repo.

On a team, the main branch is the shared, deployable line of work, and most teams protect it so direct pushes are blocked. You do your work on a separate branch and open a pull request so a teammate can review the change before it merges. This keeps main stable and gives every change a second pair of eyes.

The -u flag, short for set-upstream, links your local branch to a matching branch on the server the first time you push it. After that, plain git push and git pull on that branch work with no extra arguments because Git already knows which remote branch to talk to.

Almost always, yes. Dependency files like node_modules or installed Python packages are excluded from the repository by .gitignore and rebuilt from a manifest such as package.json or requirements.txt. Run the install command the project's README lists before trying to run or test the code.

After you clone your fork, origin points at your fork, which you push to. Upstream is a second remote you add by hand that points at the original project. You fetch from upstream to stay current and push to origin to publish your work. You never push to upstream, which is why contributions go through pull requests.

Nothing functional. GitHub and Bitbucket call it a pull request, GitLab calls it a merge request, but both propose merging one branch into another with review in between.

No. It only means a remote named origin is already configured, so Git refuses to add a second one under the same name. Run git remote -v to see what is set, then update it with git remote set-url if the URL is wrong.

git apply applies the line changes from a patch to your working tree and creates no commit, so the author, date, and message are lost. git am reads a patch made by git format-patch (which embeds that metadata) and recreates the original commit, authorship and all. Use apply for a quick change transfer, am when you need history preserved.

Run git format-patch -1 HEAD for the most recent commit as a standalone .patch file, or git format-patch -1 followed by a commit SHA for a specific one. The -N flag exports the last N commits, one file each, numbered in order.

Sources

Authoritative references this article was fact-checked against.

TagsGit onboardingGitVersion Controlclonepull requestbranchingfork vs clonesync fork with upstreamgit remotegit format-patch

Found this useful? Pass it on.

Copied

Ishan Karunaratne

Systems and Network Architect · Chief Technology Officer

Systems and network architect and Chief Technology Officer with more than two decades designing, building, and running production software, cloud and network architecture, Linux systems, and the bare metal underneath them, and lately working AI into the stack. A US Army veteran who served in Operation Iraqi Freedom. What I write here is drawn from the full arc of that work, across architecture, engineering, and operations, not any single job.

Keep reading

Related posts

Discard local changes in Git with restore and clean, then undo the last commit, pick reset or revert, untrack a file, and recover commits with reflog.

How to Discard Local Changes in Git

Discard local changes in Git with restore, checkout, and clean. Throw away edits to tracked files, delete untracked files, reset to the last commit, then undo a commit, choose reset or revert, untrack a file, and recover lost commits with reflog.

Write an effective system prompt in five parts: role, capabilities, constraints, output, refusal. Plus anti-hallucination tactics and evals for regressions.

How to Write an Effective System Prompt

Write an effective system prompt for an LLM with five parts: role, capabilities, constraints, output format, refusal policy. With before/after examples, the structure that maximises cache hits, six techniques that stop an LLM from hallucinating, and the evals that catch prompt regressions in CI.