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.
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 --versionTell 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-uat2What 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 folder | Commit? | Why |
|---|---|---|
sfdx-project.json | Yes | Defines package directories and the API version. |
force-app/ | Yes | All your metadata: Apex, LWC, flows, objects, layouts. |
manifest/package.xml | Yes | The list of components you retrieve and deploy. |
config/ | Yes | Scratch org definition files. |
.gitignore, .forceignore | Yes | Everyone on the team should skip the same files. |
.sf/, .sfdx/ | No | Local org connections and source tracking. Personal to your machine. |
node_modules/ | No | Recreated with npm install. |
| Tokens, passwords, auth URL files | Never | Anyone 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
- Check whether the folder is already a repo
If it says “not a git repository”, run
git statusgit init. - 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. Rungit statusfirst so you know what that includes. - Commit locally
git commit -m "Initial commit: Salesforce metadata" - 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-ulinks your localmainto the remote one, so from now on a plaingit pushis 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.
- Start from the latest main
git switch main git pull - Create a branch for the piece of work
On Git older than 2.23, use
git switch -c feature/case-summarygit checkout -b feature/case-summary. - 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 - Review before you stage
Retrieves often pull in noise, like reordered XML or layout tweaks someone made in Setup. This is where you catch it.
git status # which files changed git diff # what changed inside them git add -p # stage changes piece by piece - Commit with a message that says what and why
git commit -m "Case summary: add LWC and Apex controller" - Push the branch and open a merge request
GitLab and GitHub both print a link to open the merge (pull) request.
git push -u origin feature/case-summary
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.
| Branch | Deploys to | Rule of thumb |
|---|---|---|
main | Production | Always matches production. Protect it; changes arrive only by merge request. |
uat | UAT sandbox | What the client is testing right now. |
develop | Dev or integration sandbox | Where finished features come together. |
feature/* | Your own sandbox | One branch per story or ticket, e.g. feature/SF-142-case-summary. |
hotfix/* | Production, after a quick test | Branch 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 manifestValidate 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_CaseSummaryControllerTestNote the job ID it prints (it starts with 0Af), then:
sf project deploy quick --job-id 0Afxxxxxxxxxxxxxxx --target-org tenet-prodDeploy 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_ThirdClassTestDeploy with the default test behaviour
sf project deploy start --manifest manifest/package.xml --target-org tenet-prodDeploy 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-uatTest levels
| Level | What runs | Use it for |
|---|---|---|
NoTestRun | No tests | Sandboxes and dev orgs only. It’s the default there. |
RunSpecifiedTests | Only the classes you name | Targeted production releases. The named tests must cover the Apex you deploy. |
RunLocalTests | All tests in the org except managed package tests | Larger releases, or when you’re not sure what’s affected. |
RunAllTestsInOrg | Every test, including managed packages | Rarely needed. Slow. |
Long deployments
sf project deploy report --job-id 0Afxxxxxxxxxxxxxxx --target-org tenet-prod
sf project deploy resume --job-id 0AfxxxxxxxxxxxxxxxRun tests without deploying
sf apex run test \
--class-names TE_CaseSummaryControllerTest \
--code-coverage \
--result-format human \
--wait 10 \
--target-org tenet-uatDeploy 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-uatDelete 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-uatUse --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-currentCheck 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_repositoryandwrite_repositoryscopes. - “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.gitGit 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.gitBut 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 happened | Fix |
|---|---|
| Staged a file by mistake | git restore --staged path/to/file |
| Want to throw away local edits to a file | git restore path/to/file (can’t be undone) |
| Wrong commit message, not pushed yet | git commit --amend -m "Better message" |
| Undo the last commit but keep the changes, not pushed yet | git reset --soft HEAD~1 |
| Undo a commit that’s already pushed | git 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 work | git stash, switch, come back, git stash pop |
| Pushed a file that should be ignored | git 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 mainPushed 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 KnowledgeAppDevAdd --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
| Task | Command |
|---|---|
| What changed locally? | git status |
| Which branch am I on? | git branch --show-current |
| Get latest | git pull |
| New branch | git switch -c feature/name |
| Recent history | git log --oneline -10 |
| Stage, commit, push | git add . → git commit -m "..." → git push |
| Where am I pushing? | git remote -v |
| Change remote URL | git remote set-url origin <url> |
| Check repo access | git ls-remote <url> |
| Connected orgs | sf org list |
| Set default org | sf config set target-org <alias> |
| Pull from org | sf project retrieve start --manifest manifest/package.xml |
| Validate for prod | sf project deploy validate --manifest manifest/package.xml --target-org <alias> |
| Quick deploy | sf project deploy quick --job-id <id> --target-org <alias> |
| Open an org | sf org open --target-org <alias> |