Appearance
Uncommitted Changes
Detect uncommitted changes and derive path-safe branch names for deployment scripts, CI pipelines, and automation tools.
When to use
Use these patterns in automation scripts that depend on repository state — guarding deployments against uncommitted work, generating version names from the current branch, or building deploy-or-abort gates.
The pattern
Detect uncommitted changes
Use git diff to check whether the working tree has modifications. A non-empty result means uncommitted changes exist.
javascript
function gitChanges() {
const { stdout } = run("git", "diff", { sync: true });
return String(stdout).trim();
}
const uncommittedChanges = gitChanges();
if (uncommittedChanges) {
console.error(
"You have uncommitted changes. Commit before deploying."
);
process.exit(1);
}Get a path-safe branch name
Branch names like feature/auth contain slashes that break file paths and URLs. Replace slashes with hyphens to produce a safe identifier.
javascript
function gitBranchName() {
const { stdout } = run(
"git", "branch --show-current", { sync: true }
);
return String(stdout).trim().replaceAll("/", "-");
}
const versionName = gitBranchName();
// "feature/user-auth" → "feature-user-auth"Combine with a timestamp to build a unique version string:
javascript
const version = `${gitBranchName()}-${Date.now()}`;
// "feature-auth-1708300000000"Combine as a deploy guard
A typical deployment script checks for uncommitted changes first, then derives a default version name from the branch:
javascript
const uncommittedChanges = gitChanges();
if (uncommittedChanges) {
const msg =
"You have uncommitted changes. Commit before deploying.";
console.error(new Error(msg));
process.exit(1);
}
const defaultName = gitBranchName();Shell variant
The same pattern in shell:
sh
changes=$(git diff)
if [ -n "$changes" ]; then
echo "Uncommitted changes. Commit before deploying." >&2
exit 1
fi
branch=$(git branch --show-current \
| tr '/' '-')
echo "Deploying version: $branch"In CI pipelines, combine with GitHub Actions error annotations:
sh
if [ -n "$(git diff)" ]; then
echo "::error::Uncommitted changes detected"
exit 1
fiTrade-offs
| Approach | Pros | Cons |
|---|---|---|
git diff | Detects all changes | Slow on large repos |
git status -s | Faster, includes staged | Needs parsing |
git diff --stat | Human-readable summary | Hard to test programmatically |
replaceAll | Simple slash replace | Misses other unsafe chars |
tr '/' '-' | POSIX-compatible | Only handles slashes |