PythonIntermediate · Windows, macOS, or Linux; Python 3.12+

Export pending tracked edits

Write either staged or unstaged tracked changes to a new patch file.

Before you begin

  • Python 3.12 or later.
  • Git must be installed on PATH. --repo must be an existing non-bare repository.
What this script changesCreates one new patch file and refuses overwrite. Patches may contain private data or binary content. The patch is not applied or uploaded.

Set up your example

  1. Save as git-export-working-patch.py.
  2. Open a terminal in its folder.
  3. Run python "git-export-working-patch.py" --help and prepare the listed input files.

This recipe uses your own local input or creates its own example output. Follow the setup steps below.

Download the ZIP, extract it, and open a terminal inside the extracted folder. The source file is git-export-working-patch.py.

Run the script

Run command
python "git-export-working-patch.py" --output "working.patch"

If your system uses python3 instead of python, use that command for Python examples. Keep paths containing spaces in quotes. Required inputs and optional settings are described in the code and setup steps.

What to expect

A new patch captures unstaged tracked changes; --staged captures index changes instead.

The complete script

git-export-working-patch.py
#!/usr/bin/env python3
"""Write either staged or unstaged tracked changes to a new patch file."""
import argparse
import sys
import json
from pathlib import Path
import os
import subprocess
from collections import Counter
from datetime import datetime, timezone

def git(repo,*arguments,allow=(0,)):
    env=dict(os.environ,GIT_OPTIONAL_LOCKS='0',GIT_PAGER='cat',GIT_TERMINAL_PROMPT='0')
    result=subprocess.run(['git','--no-pager','--no-optional-locks','-C',str(repo),*arguments],capture_output=True,timeout=60,env=env)
    if result.returncode not in allow:
        raise RuntimeError(result.stderr.decode('utf-8','replace').strip() or f'git exited {result.returncode}')
    return result.stdout

def text(repo,*arguments,allow=(0,)):
    return git(repo,*arguments,allow=allow).decode('utf-8','replace')

def main():
    parser = argparse.ArgumentParser(description='Write either staged or unstaged tracked changes to a new patch file.')
    parser.add_argument("--repo",type=Path,default=Path("."))
    parser.add_argument('--output',type=Path,default=Path('working.patch'))
    parser.add_argument('--staged',action='store_true')
    args = parser.parse_args()
    repo=Path(text(args.repo,"rev-parse","--show-toplevel").strip())
    
    flags=['--cached'] if args.staged else []
    patch=git(repo,'diff',*flags,'--binary','--no-ext-diff','--no-textconv')
    with args.output.open('xb') as stream:stream.write(patch)
    print(f'Created {args.output} ({len(patch)} bytes); untracked files excluded.')

if __name__ == '__main__':
    try:
        main()
    except (OSError, ValueError, RuntimeError) as exc:
        print(f'Error: {exc}', file=sys.stderr)
        sys.exit(1)

Open source as plain text · Download source and sample files

How it works

  1. Write either staged or unstaged tracked changes to a new patch file.
  2. Arguments are explicit and expected input errors produce a message with a nonzero exit code.
  3. Results reflect your selected local data or the specific endpoint you choose; the example illustrates the result shape.

Make it your own

Adapt the task

Add --staged for index changes; choose a different --output each time.

Adjust presentation

Edit final print statements or json.dumps indentation to adjust the report layout. Keep input validation and exclusive-create file modes intact.

Change one setting at a time, run it again on sample data, and compare the output. The customization guide walks through this process.

If something goes wrong

An input or dependency is unavailable.

Git must be installed on PATH. --repo must be an existing non-bare repository.

Actual results differ from the example.

Inputs and system state determine values. Review each finding in context; a report is not proof of system health or a complete security assessment.

Reference & next steps

These official references explain the underlying tools. The Scriptage example and guide are original instructional content. See verification notes for what has been checked and the limits of those checks.

Copies a template for your own notes. It does not send anything.