]> git.phdru.name Git - dotfiles.git/blob - bin/unzip.py
Feat(bin): Port scripts to Python 3
[dotfiles.git] / bin / unzip.py
1 #! /usr/bin/env python3
2 """Unzip with encoded filenames
3
4    Written by Oleg Broytman. Copyright (C) 2009-2023 PhiloSoft Design.
5 """
6
7 import sys, os, time
8 from getopt import getopt, GetoptError
9 from shutil import copyfileobj
10 from zipfile import ZipFile
11 from m_lib.defenc import default_encoding
12
13 def usage():
14     sys.exit('Usage: %s file.zip' % sys.argv[0])
15
16 try:
17     options, arguments = getopt(sys.argv[1:], '')
18 except GetoptError:
19     usage()
20
21 if len(arguments) != 1:
22     usage()
23
24 zf = ZipFile(arguments[0], 'r')
25 out = '.'
26
27 for zinfo in zf.infolist():
28     path = zinfo.filename
29     if isinstance(path, bytes):
30         path = path.decode('cp866')
31         recoded_path = path.encode(default_encoding)
32     else:
33         recoded_path = path
34     print(recoded_path)
35
36     if path.startswith('./'):
37         recoded_path = recoded_path[2:]
38     tgt = os.path.join(out, recoded_path)
39
40     tgtdir = os.path.dirname(tgt)
41     if not os.path.exists(tgtdir):
42         os.makedirs(tgtdir)
43
44     if not tgt.endswith('/'):
45         infile = zf.open(zinfo.filename)
46         fp = open(tgt, 'wb')
47         copyfileobj(infile, fp)
48         fp.close()
49         infile.close()
50     dt = time.mktime(zinfo.date_time + (0, 0, -1))
51     os.utime(tgt, (dt, dt))
52 zf.close()