-
Notifications
You must be signed in to change notification settings - Fork 15
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add management that allows creating an archive from the contents of a…
… folder (#23)
- Loading branch information
1 parent
1ae3f3e
commit fbff39d
Showing
3 changed files
with
78 additions
and
0 deletions.
There are no files selected for viewing
Empty file.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
import random | ||
import string | ||
from pathlib import Path | ||
from zipfile import ZIP_DEFLATED, ZipFile | ||
|
||
from cabinet.models import Folder | ||
from django.core.management import BaseCommand | ||
|
||
|
||
def _get_random_suffix(): | ||
return random.choices(string.ascii_lowercase, k=4) | ||
|
||
|
||
class Command(BaseCommand): | ||
help = "Create archive with contents of a cabinet folder, using the data structure of the db instead of the disk." | ||
|
||
def add_arguments(self, parser): | ||
parser.add_argument("--folder-id", type=int, required=True) | ||
parser.add_argument("--output", type=Path, required=True) | ||
|
||
def handle(self, **options): | ||
folder = Folder.objects.get(id=options["folder_id"]) | ||
output = options["output"] | ||
|
||
arc_paths = set() | ||
with ZipFile(output, "w", ZIP_DEFLATED) as zip_file: | ||
for file, path in self._walk(folder, path=()): | ||
arc_path = Path(*path) / file.file_name | ||
|
||
if arc_path in arc_paths: | ||
filename = Path(file.file_name) | ||
arc_path = Path(*path) / "".join([ | ||
filename.stem, | ||
"_", | ||
*_get_random_suffix(), | ||
*filename.suffixes, | ||
]) | ||
|
||
zip_file.write(file.file.path, arc_path) | ||
arc_paths.add(arc_path) | ||
|
||
def _walk(self, folder, *, path): | ||
path = (*tuple(path), folder.name) | ||
for file_ in folder.files.all(): | ||
yield (file_, path) | ||
|
||
for child in folder.children.all(): | ||
yield from self._walk(child, path=path) |
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