Use GIT in Salesforce Implementation Project

This is the working reference I use to keep Salesforce metadata in Git on client projects: setting up a repo, moving changes between the org and the repo, deploying with the Salesforce CLI, and getting out of trouble when something goes wrong.

VS CodeSalesforce CLI (sf)GitLab or GitHubGit 2.23+

Windows users: the VS Code terminal opens PowerShell by default. Multi-line commands on this page end lines with \, which works in Git Bash, macOS and Linux. In PowerShell, replace \ with a backtick `, or put the whole command on one line.

1Set up your machine

Install Git, the Salesforce CLI and VS Code with the Salesforce Extension Pack. Then confirm everything is on your path:

git --version
sf --version

Tell Git who you are (once per machine)

Use the same email as your GitLab or GitHub account so commits show up against your name.

git config --global user.name "Your Name"
git config --global user.email "you@company.com"

Create a project (skip if you already have one)

sf project generate --name client-salesforce --manifest

--manifest adds an empty manifest/package.xml you can fill in later.

Connect your orgs

# Production or Developer Edition
sf org login web --alias tenet-prod --instance-url https://login.salesforce.com

# Sandbox
sf org login web --alias tenet-uat --instance-url https://test.salesforce.com

# Org that only allows My Domain login
sf org login web --alias client-dev --instance-url https://yourdomain.my.salesforce.com

# See every connected org, then pick the default for this project
sf org list
sf config set target-org tenet-uat

2What goes in the repo

Commit the source and the project files. Keep local CLI state, dependencies and anything that looks like a credential out.

File or folderCommit?Why
sfdx-project.jsonYesDefines package directories and the API version.
force-app/YesAll your metadata: Apex, LWC, flows, objects, layouts.
manifest/package.xmlYesThe list of components you retrieve and deploy.
config/YesScratch org definition files.
.gitignore, .forceignoreYesEveryone on the team should skip the same files.
.sf/, .sfdx/NoLocal org connections and source tracking. Personal to your machine.
node_modules/NoRecreated with npm install.
Tokens, passwords, auth URL filesNeverAnyone with repo access could log in to the org.

A starter .gitignore

# Salesforce CLI local state
.sf/
.sfdx/
.localdevserver/
deploy-options.json

# Node and tooling
node_modules/
coverage/
*.log

# OS files
.DS_Store
Thumbs.db

.gitignore and .forceignore do different jobs.

.gitignore controls what Git tracks. .forceignore controls what the Salesforce CLI deploys and retrieves. A file can be in Git but still be skipped on deploy, which is handy for things like admin profiles you don’t want to push.

3Push a project for the first time

  1. Check whether the folder is already a repo
    git status
    If it says “not a git repository”, run git init.
  2. Stage only what you want to push
    # Core project files
    git add sfdx-project.json .gitignore .forceignore config/ manifest/
    
    # Everything under force-app
    git add force-app/
    
    # Or only selected metadata folders
    git add force-app/main/default/classes/
    git add force-app/main/default/flows/
    git add force-app/main/default/objects/
    git add . stages everything that isn’t ignored. Run git status first so you know what that includes.
  3. Commit locally
    git commit -m "Initial commit: Salesforce metadata"
  4. Connect to the remote and push
    git remote add origin https://gitlab.com/your-group/your-project.git
    git branch -M main
    git push -u origin main
    -u links your local main to the remote one, so from now on a plain git push is enough.

4The everyday loop

On most Salesforce projects a lot of work happens in Setup, not in VS Code. So the loop is: get the latest code, retrieve what changed in the org, review it, commit, push.

  1. Start from the latest main
    git switch main
    git pull
  2. Create a branch for the piece of work
    git switch -c feature/case-summary
    On Git older than 2.23, use git checkout -b feature/case-summary.
  3. Retrieve changes from the org
    # Everything in the manifest
    sf project retrieve start --manifest manifest/package.xml --target-org tenet-dev
    
    # Or just the components you touched
    sf project retrieve start \
      --metadata ApexClass:TE_CaseSummaryController \
      --metadata LightningComponentBundle:caseSummary \
      --metadata Flow:Case_Auto_Assign \
      --target-org tenet-dev
  4. Review before you stage
    git status        # which files changed
    git diff          # what changed inside them
    git add -p        # stage changes piece by piece
    Retrieves often pull in noise, like reordered XML or layout tweaks someone made in Setup. This is where you catch it.
  5. Commit with a message that says what and why
    git commit -m "Case summary: add LWC and Apex controller"
  6. Push the branch and open a merge request
    git push -u origin feature/case-summary
    GitLab and GitHub both print a link to open the merge (pull) request.

5Branches and orgs

A setup that works well for small and mid-size teams: each long-lived branch maps to one org, and code only moves forward through merge requests. Adjust the names to match your sandboxes.

BranchDeploys toRule of thumb
mainProductionAlways matches production. Protect it; changes arrive only by merge request.
uatUAT sandboxWhat the client is testing right now.
developDev or integration sandboxWhere finished features come together.
feature/*Your own sandboxOne branch per story or ticket, e.g. feature/SF-142-case-summary.
hotfix/*Production, after a quick testBranch from main, merge back into main and develop.

6Deploy with the Salesforce CLI

Build or refresh the manifest

# From what's in your local project
sf project generate manifest --source-dir force-app --output-dir manifest

# From what's in an org
sf project generate manifest --from-org tenet-prod --output-dir manifest

Validate first, then quick deploy (recommended for production)

Validation runs the full deployment and the tests without saving anything. If it passes, you can quick deploy the same job later without running the tests again, which is useful when you have a short release window.

sf project deploy validate \
  --manifest manifest/package.xml \
  --target-org tenet-prod \
  --test-level RunSpecifiedTests \
  --tests TE_CaseSummaryControllerTest

Note the job ID it prints (it starts with 0Af), then:

sf project deploy quick --job-id 0Afxxxxxxxxxxxxxxx --target-org tenet-prod

Deploy directly with specific tests

sf project deploy start \
  --manifest manifest/package.xml \
  --target-org tenet-prod \
  --test-level RunSpecifiedTests \
  --tests TE_CaseSummaryControllerTest \
  --tests TE_AnotherControllerTest \
  --tests TE_ThirdClassTest

Deploy with the default test behaviour

sf project deploy start --manifest manifest/package.xml --target-org tenet-prod

Deploy one component or one folder

sf project deploy start --metadata ApexClass:TE_CaseSummaryController --target-org tenet-uat
sf project deploy start --source-dir force-app/main/default/lwc/caseSummary --target-org tenet-uat

Test levels

LevelWhat runsUse it for
NoTestRunNo testsSandboxes and dev orgs only. It’s the default there.
RunSpecifiedTestsOnly the classes you nameTargeted production releases. The named tests must cover the Apex you deploy.
RunLocalTestsAll tests in the org except managed package testsLarger releases, or when you’re not sure what’s affected.
RunAllTestsInOrgEvery test, including managed packagesRarely needed. Slow.

Long deployments

sf project deploy report --job-id 0Afxxxxxxxxxxxxxxx --target-org tenet-prod
sf project deploy resume --job-id 0Afxxxxxxxxxxxxxxx

Run tests without deploying

sf apex run test \
  --class-names TE_CaseSummaryControllerTest \
  --code-coverage \
  --result-format human \
  --wait 10 \
  --target-org tenet-uat

Deploy only what changed between two commits

The free sfdx-git-delta plugin reads your Git history and builds a package.xml of changed components, plus a destructiveChanges.xml for anything deleted.

sf plugins install sfdx-git-delta

# Compare the latest commit with the one before it
sf sgd source delta --to "HEAD" --from "HEAD~1" --output-dir .

# Or compare a feature branch with main
sf sgd source delta --to "HEAD" --from "origin/main" --output-dir .

sf project deploy start \
  --manifest package/package.xml \
  --post-destructive-changes destructiveChanges/destructiveChanges.xml \
  --target-org tenet-uat

Delete components from an org

Put the components to delete in a destructiveChanges.xml. The deploy still needs a package.xml, which can be empty apart from the version.

<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
  <types>
    <members>Old_Helper_Class</members>
    <name>ApexClass</name>
  </types>
  <version>66.0</version>
</Package>
sf project deploy start \
  --manifest manifest/package.xml \
  --post-destructive-changes manifest/destructiveChanges.xml \
  --target-org tenet-uat

Use --pre-destructive-changes when the deletion has to happen before the new components land, and --post-destructive-changes when it should happen after. Match <version> to the API version in your sfdx-project.json.

7Remotes, access and tokens

See and change where you push

# Show current remote
git remote -v

# Point origin at a different repo (wrong URL, or project moved)
git remote set-url origin https://gitlab.com/new-group/new-project.git

# Show the branch you're on
git branch --show-current

Check a URL works and you have access

git ls-remote https://gitlab.com/group/project.git
  • A list of commit hashes and branch names means the repo exists and you can reach it.
  • A login prompt means the repo is private. Enter your username, and paste a personal access token as the password. In GitLab, create one under your avatar → Edit profile → Access tokens, with read_repository and write_repository scopes.
  • “Not found” can mean a wrong URL or a private repo you haven’t been added to. Ask the client to check your access before assuming the URL is wrong.

Working with more than one GitLab or GitHub account

Your credential manager remembers the first account you logged in with. To make Git ask for a different account on one repo, put that username in the URL:

git remote set-url origin https://other-username@gitlab.com/client-group/salesforce.git

Git will prompt for that user’s token. On Windows, you can also clear the saved login in Windows Credential Manager under the git:https://gitlab.com entry.

About putting the token in the URL

This works, and is quick for a one-off:

git remote set-url origin https://<username>:<token>@gitlab.com/client-group/salesforce.git

But the token is stored in plain text in .git/config and shows up in git remote -v, screen shares and terminal history. Remove it once you’re done by setting the URL back without the token. If a token has been exposed, revoke it in GitLab and create a new one.

“You are not allowed to push to a protected branch”

The target branch is protected, usually main. Push to a feature branch and open a merge request instead. If you really need direct push, a Maintainer can change it in GitLab under Settings → Repository → Protected branches.

8Fixing mistakes

What happenedFix
Staged a file by mistakegit restore --staged path/to/file
Want to throw away local edits to a filegit restore path/to/file (can’t be undone)
Wrong commit message, not pushed yetgit commit --amend -m "Better message"
Undo the last commit but keep the changes, not pushed yetgit reset --soft HEAD~1
Undo a commit that’s already pushedgit revert <commit-sha> then git push. This adds a new commit that reverses the old one, so nobody’s history breaks.
Need to switch branch with unfinished workgit stash, switch, come back, git stash pop
Pushed a file that should be ignoredgit rm --cached path/to/file (use -r for a folder), add it to .gitignore, commit, push. The local file stays.

Clear everything from the remote and start clean

Useful when the first push included things it shouldn’t have. Your local files are not touched.

# Untrack everything
git rm -r --cached .
git commit -m "Clear repository"
git push origin main

# Add back only what you want
git add sfdx-project.json .gitignore .forceignore config/ manifest/ force-app/
git commit -m "Add Salesforce project files"
git push origin main

Pushed a password, token or auth file? Revoke or rotate it first. Deleting the file, or even rewriting history, doesn’t help anyone who already cloned or forked the repo.

9Scratch orgs

Scratch orgs are short-lived orgs built from your source. You need a Dev Hub enabled in your production or Developer Edition org.

# Connect the Dev Hub once
sf org login web --alias DevHub --set-default-dev-hub

# Create a scratch org from config/project-scratch-def.json
sf org create scratch \
  --definition-file config/project-scratch-def.json \
  --alias KnowledgeAppDev \
  --duration-days 30 \
  --set-default \
  --target-dev-hub DevHub

# Push your source, open the org, pull back changes made in Setup
sf project deploy start --target-org KnowledgeAppDev
sf org open --target-org KnowledgeAppDev
sf project retrieve start --target-org KnowledgeAppDev

# Clean up when done
sf org delete scratch --target-org KnowledgeAppDev

Add --no-namespace if your project has a namespace but you want this scratch org without it. Scratch orgs last at most 30 days.

10Cheat sheet

TaskCommand
What changed locally?git status
Which branch am I on?git branch --show-current
Get latestgit pull
New branchgit switch -c feature/name
Recent historygit log --oneline -10
Stage, commit, pushgit add . → git commit -m "..." → git push
Where am I pushing?git remote -v
Change remote URLgit remote set-url origin <url>
Check repo accessgit ls-remote <url>
Connected orgssf org list
Set default orgsf config set target-org <alias>
Pull from orgsf project retrieve start --manifest manifest/package.xml
Validate for prodsf project deploy validate --manifest manifest/package.xml --target-org <alias>
Quick deploysf project deploy quick --job-id <id> --target-org <alias>
Open an orgsf org open --target-org <alias>

References