Skip to main content

revert-unstaged.py

revert-unstaged.py reverts working directory changes back to what's in the staging area (INDEX), preserving any staged changes.

What It Does​

The script:

  1. Parses the arguments, so --help and bad arguments never reach git
  2. Verifies the file exists
  3. Verifies the file is tracked by git (an untracked file has no staged version)
  4. Stops with "Nothing to revert" if the file already matches the staged version
  5. Runs git restore --worktree -- <file> to revert unstaged changes
  6. Preserves any staged changes

Usage​

python3 scripts/revert-unstaged.py <file_path>

To restore a file whose name starts with -, put -- before it:

python3 scripts/revert-unstaged.py -- -notes.txt

Options​

  • file_path - the file to restore (required, exactly one)
  • -h, --help - print the usage text and exit without calling git

Example​

python3 scripts/revert-unstaged.py juneau-core/juneau-marshall/src/main/java/org/apache/juneau/ClassMeta.java

Use Case​

This is useful when you have:

  • Staged changes that you've tested and want to keep
  • Unstaged changes that you want to discard

The script will revert the working directory to match the staged version, effectively discarding only the unstaged changes.

Exit Codes​

  • 0 - Success, or nothing to revert (the file already matches the staged version)
  • 1 - Error (file not found, file not tracked by git, git restore failed)
  • 2 - Bad arguments (usage text printed to stderr)

Requirements​

  • Python 3.6 or higher
  • Git (git command must be in PATH)
  • No external Python dependencies (uses only standard library)

Notes​

  • This only affects unstaged changes - staged changes are preserved
  • Use revert-staged.py if you want to revert both staged and unstaged changes
  • The file must exist and be tracked by git (the script verifies both)