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.
Python code
19 linesimport 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
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
- Use `subprocess.run(["git", "clean", "-n"])` to execute the real command and capture its output.
- 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
More from Git + Python
- Amend Last Commit Message in Python easy
- Bisect Good Bad Automation Script in Python easy
- Build a Simple Log Graph in Python easy
- Bump Semantic Version Git Tag in Python easy
- Count Unique Contributors from Git Shortlog in Python easy
- Create a Mock GitHub Release API in Python for Testing gh CLI easy
Keep learning
Related tutorials and quizzes for this topic.