summaryrefslogtreecommitdiff
path: root/tests/archive.py
blob: a0967fcf4ab9070c7393e27fdd2e4dc37c7720a3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import os.path
import sys
import tarfile
import zipfile
import StringIO

def read_file(path, use_crlf):
	with open(path, 'rb') as file:
		data = file.read()

	if '\0' not in data:
		data = data.replace('\r', '')
		if use_crlf:
			data = data.replace('\n', '\r\n')

	return data

def write_zip(target, arcprefix, sources):
	with zipfile.ZipFile(target, 'w', zipfile.ZIP_DEFLATED) as archive:
		for source in sorted(sources):
			data = read_file(source, use_crlf = True)
			path = os.path.join(arcprefix, source)
			archive.writestr(path, data)

def write_tar(target, arcprefix, sources, compression):
	with tarfile.open(target, 'w:' + compression) as archive:
		for source in sorted(sources):
			data = read_file(source, use_crlf = False)
			path = os.path.join(arcprefix, source)
			info = tarfile.TarInfo(path)
			info.size = len(data)
			archive.addfile(info, StringIO.StringIO(data))

if len(sys.argv) < 4:
	raise RuntimeError('Usage: python archive.py <target> <archive prefix> <source files>')

target = sys.argv[1]
arcprefix = sys.argv[2]
sources = sys.argv[3:]

if target.endswith('.zip'):
	write_zip(target, arcprefix, sources)
elif target.endswith('.tar.gz') or target.endswith('.tar.bz2'):
	write_tar(target, arcprefix, sources, compression = os.path.splitext(target)[1][1:])
else:
	raise NotImplementedError('File type not supported: ' + target)