Created
December 20, 2019 22:11
-
-
Save jsbueno/f223a008d971bcc04ebebdd8d134754b to your computer and use it in GitHub Desktop.
Gist to enable filtering out file-name-patterns when creating an Archive (zipfile, tarball) with Python code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# WARNING: this implementation depends on the internal implementation of shutil.makefile as it is up to Python 3.8.0 | |
# it might change without notice to use pathlib internally, and this will break | |
import shutil | |
import re | |
from unittest.mock import patch | |
def create_archive_with_filter(*args, filter_out_pattern="", **kwargs): | |
import os | |
original_listdir = os.listdir | |
original_walk = os.walk | |
def new_listdir(path): | |
results = original_listdir(path) | |
return [result for result in results if not re.search(filter_out_pattern)] | |
def new_walk(path): | |
for current, dirs, files in original_walk(path): | |
files = [file for file in files if not re.search(filter_out_pattern)] | |
yield (current, dirs, files) | |
with patch("os.listdir", new_lisdir), patch("os.walk", new_walk): | |
shutil.create_archive(*args, **kwargs) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment