How to Mock Git Clean Dry Run in Python

Simulate the output of `git clean -n` in Python to preview which untracked files would be removed without actually deleting them.

Easy Python 3.9+ Aug 9, 2026 Git + Python 14 views 0 copies

Python code

19 lines
Python 3.9+
import subprocess
import sys

def mock_git_clean_dry_run(untracked_files):
    """Simulate `git clean -n` for a given list of untracked files."""
    if not untracked_files:
        print("No untracked files to remove.")
        return

    print("Would remove:")
    for file in untracked_files:
        print(f"  {file}")

    # Simulate the command output for educational purposes
    print("\n[DRY RUN] No files were actually deleted.")

if __name__ == "__main__":
    files = ["temp.log", "cache/", "notes.txt~"]
    mock_git_clean_dry_run(files)

Output

stdout
Would remove:
  temp.log
  cache/
  notes.txt~

[DRY RUN] No files were actually deleted.

How it works

This function mimics the behavior of git clean -n by printing each untracked file that would be removed. It uses a simple loop to iterate over the list of files and prints them with indentation, similar to real Git output. The dry-run message clarifies that nothing has been deleted, reinforcing the safety of the operation. The if __name__ == '__main__' guard allows the function to be imported and reused elsewhere without executing the demo.

Common mistakes

  • Forgetting to add a trailing slash to directory names in the output, unlike Git's actual display.
  • Not handling an empty file list, which would otherwise produce confusing output.
  • Actually calling `git clean` without `-n` in a real script, which could delete files permanently.

Variations

  1. Use `subprocess.run(["git", "clean", "-n"])` to execute the real command and capture its output.
  2. Return a list of file names instead of printing, to allow programmatic use.

Real-world use cases

  • In a CI pipeline, you can run a dry run to list files that will be cleaned before a build, preventing accidental deletion of needed assets.
  • A developer tool that previews which temporary or cache files would be removed by a cleanup script, safely showing the user what would happen.
  • A testing mock for a function that wraps `git clean -n`, allowing you to verify the logic without touching the real repository.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Git + Python

Related tutorials and quizzes for this topic.