15def _zip_dir(path, zip_file, prefix):
16 path = path.rstrip(
'/\\')
17 for root, directories, files
in os.walk(path):
18 for directory
in directories:
19 if os.path.islink(os.path.join(root, directory)):
22 os.path.join(root, directory),
23 os.path.join(root.replace(path, prefix), directory),
26 if os.path.islink(os.path.join(root, file)):
28 zip_file, os.path.join(root, file), os.path.join(root.replace(path, prefix), file)
31 zip_file.write(os.path.join(root, file), os.path.join(root.replace(path, prefix), file))
35 """Adds a symlink to a zip file.
38 zip_file: The ZipFile obj where the symlink will be added.
39 source: The full path to the symlink.
40 target: The target path for the symlink within the zip file.
42 zip_info = zipfile.ZipInfo(target)
43 zip_info.create_system = 3
45 stat.S_IFLNK | stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR | stat.S_IRGRP
46 | stat.S_IWGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IWOTH | stat.S_IXOTH
48 zip_info.external_attr = unix_st_mode << 16
49 zip_file.writestr(zip_info, os.readlink(source))
53 zip_file = zipfile.ZipFile(args.output,
'w', zipfile.ZIP_DEFLATED)
55 with open(args.source_file)
as source_file:
56 file_dict_list = json.load(source_file)
57 for file_dict
in file_dict_list:
58 if os.path.islink(file_dict[
'source']):
59 add_symlink(zip_file, file_dict[
'source'], file_dict[
'destination'])
61 if os.path.isdir(file_dict[
'source']):
62 _zip_dir(file_dict[
'source'], zip_file, file_dict[
'destination'])
64 zip_file.write(file_dict[
'source'], file_dict[
'destination'])
66 for path, archive_name
in args.input_pairs:
67 if os.path.islink(path):
70 if os.path.isdir(path):
71 _zip_dir(path, zip_file, archive_name)
73 zip_file.write(path, archive_name)
77if __name__ ==
'__main__':
78 parser = argparse.ArgumentParser(description=
'This script creates zip files.')
79 parser.add_argument(
'-o', dest=
'output', action=
'store', help=
'The name of the output zip file.')
85 help=
'The input file and its destination location in the zip archive.'
88 '-f', dest=
'source_file', action=
'store', help=
'The path to the file list to zip.'
90 sys.exit(
main(parser.parse_args()))
def add_symlink(zip_file, source, target)