Архив папки в tar.gz
Упаковывает папку в новый tar.gz, считает SHA-256 и не перезаписывает существующий архив.
Что делает скрипт
Скрипт создаёт архив с именем исходной папки, пропускает кеши и служебные каталоги, а результат пишет только в новый файл. Рядом сохраняется контрольная сумма. Режим --dry-run показывает количество файлов и общий размер без записи.
- Архив может содержать секреты, проверьте содержимое перед передачей.
Быстрый старт
python create_archive.py --source ~/projects/app --output /mnt/backup/app.tar.gz
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python create_archive.py --source ~/projects/app --output /mnt/backup/app.tar.gzpython create_archive.py --source ~/projects/app --output /mnt/backup/app.tar.gz --exclude .git --dry-run
Что понадобится
winget install Python.Python.3.12
brew install python
sudo apt install python3
create_archive.py
#!/usr/bin/env python3
"""Создание tar.gz архива папки с контрольной суммой."""
from __future__ import annotations
import argparse
import hashlib
import sys
import tarfile
from pathlib import Path
DEFAULT_EXCLUDES = {".cache", "node_modules", ".venv", "__pycache__", ".pytest_cache"}
def file_digest(path: Path, chunk_size: int = 1024 * 1024) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
while block := handle.read(chunk_size):
digest.update(block)
return digest.hexdigest()
def iter_source_files(source: Path, excludes: set[str]):
for path in source.rglob("*"):
if path.is_symlink() or not path.is_file():
continue
relative = path.relative_to(source)
if any(part in excludes for part in relative.parts):
continue
yield path
def main() -> int:
parser = argparse.ArgumentParser(description="Создать tar.gz архив папки")
parser.add_argument("--source", type=Path, required=True, help="Исходная папка")
parser.add_argument("--output", type=Path, required=True, help="Новый файл .tar.gz")
parser.add_argument("--exclude", action="append", default=[], help="Имя каталога для пропуска")
parser.add_argument("--dry-run", action="store_true", help="Только показать план")
args = parser.parse_args()
source = args.source.expanduser().resolve()
output = args.output.expanduser().resolve()
excludes = DEFAULT_EXCLUDES | set(args.exclude)
if not source.is_dir():
parser.error(f"Источник не найден: {source}")
if output.exists():
parser.error(f"Файл уже существует: {output}")
try:
output.relative_to(source)
except ValueError:
pass
else:
parser.error("Архив нельзя создавать внутри источника")
files = list(iter_source_files(source, excludes))
total_size = sum(path.stat().st_size for path in files)
if args.dry_run:
print(f"Файлов: {len(files)}, размер: {total_size} байт")
print(f"Будет создан: {output}")
return 0
output.parent.mkdir(parents=True, exist_ok=True)
def archive_filter(info: tarfile.TarInfo):
parts = Path(info.name).parts
if any(part in excludes for part in parts):
return None
return info
try:
with output.open("xb") as handle:
with tarfile.open(fileobj=handle, mode="w:gz", compresslevel=6) as archive:
archive.add(source, arcname=source.name, filter=archive_filter)
except Exception:
output.unlink(missing_ok=True)
raise
digest = file_digest(output)
sidecar = output.with_name(output.name + ".sha256")
if sidecar.exists():
print(f"Предупреждение: файл {sidecar} уже существует и не изменён.")
else:
sidecar.write_text(f"{digest} {output.name}\n", encoding="utf-8")
print(f"Создан архив: {output}")
print(f"Файлов: {len(files)}, исходный размер: {total_size} байт")
print(f"SHA-256: {digest}")
return 0
if __name__ == "__main__":
sys.exit(main())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.