]> git.phdru.name Git - dotfiles.git/blob - bin/zip.py
Feat(recode-filenames-recursive): Allow to omit parameters
[dotfiles.git] / bin / zip.py
1 #! /usr/bin/env python3
2 """Zip (zip -r9) with encoded filenames
3
4    Written by Oleg Broytman. Copyright (C) 2009-2023 PhiloSoft Design.
5 """
6
7 import sys, os
8 from getopt import getopt, GetoptError
9 from zipfile import ZipFile, ZIP_DEFLATED
10 from m_lib.defenc import default_encoding
11
12 def usage():
13     sys.exit('Usage: %s file.zip file1 dir2...' % sys.argv[0])
14
15 try:
16   options, arguments = getopt(sys.argv[1:], '')
17 except GetoptError:
18     usage()
19
20 if len(arguments) < 2:
21     usage()
22
23 def addToZip(zf, path):
24     if os.path.isfile(path):
25         print(path)
26         if isinstance(path, bytes):
27             recoded_path = path.decode(default_encoding).encode('cp866')
28         else:
29             recoded_path = path
30         zf.write(path, recoded_path, ZIP_DEFLATED)
31     elif os.path.isdir(path):
32         for nm in os.listdir(path):
33             addToZip(zf, os.path.join(path, nm))
34     # else: ignore
35
36 zname = arguments[0]
37 if os.path.splitext(zname)[1] not in ('.zip', '.ZIP'):
38     zname += '.zip'
39
40 zf = ZipFile(zname, 'w', allowZip64=True)
41
42 for path in arguments[1:]:
43     addToZip(zf, path)
44
45 zf.close()