blob: 7f586e0916404409de503649da51ed5865ef2203 [file] [log] [blame]
mbligh462c0152008-03-13 15:37:10 +00001import os, sys, re, shutil, urlparse, urllib, pickle, random
mbligh15b2a112008-02-27 16:46:56 +00002from error import *
mbligh6231cd62008-02-02 19:18:33 +00003
4def write_keyval(path, dictionary):
5 if os.path.isdir(path):
6 path = os.path.join(path, 'keyval')
7 keyval = open(path, 'a')
8 try:
9 for key, value in dictionary.iteritems():
10 if re.search(r'\W', key):
11 raise ValueError('Invalid key: %s' % key)
12 keyval.write('%s=%s\n' % (key, value))
13 finally:
14 keyval.close()
15
16
17def is_url(path):
18 """Return true if path looks like a URL"""
19 # for now, just handle http and ftp
20 url_parts = urlparse.urlparse(path)
21 return (url_parts[0] in ('http', 'ftp'))
22
23
24def get_file(src, dest, permissions=None):
25 """Get a file from src, which can be local or a remote URL"""
26 if (src == dest):
27 return
28 if (is_url(src)):
29 print 'PWD: ' + os.getcwd()
30 print 'Fetching \n\t', src, '\n\t->', dest
31 try:
32 urllib.urlretrieve(src, dest)
33 except IOError, e:
34 raise AutotestError('Unable to retrieve %s (to %s)'
35 % (src, dest), e)
36 else:
37 shutil.copyfile(src, dest)
38 if permissions:
39 os.chmod(dest, permissions)
40 return dest
41
42
43def unmap_url(srcdir, src, destdir='.'):
44 """
45 Receives either a path to a local file or a URL.
46 returns either the path to the local file, or the fetched URL
47
48 unmap_url('/usr/src', 'foo.tar', '/tmp')
49 = '/usr/src/foo.tar'
50 unmap_url('/usr/src', 'http://site/file', '/tmp')
51 = '/tmp/file'
52 (after retrieving it)
53 """
54 if is_url(src):
55 url_parts = urlparse.urlparse(src)
56 filename = os.path.basename(url_parts[2])
57 dest = os.path.join(destdir, filename)
58 return get_file(src, dest)
59 else:
60 return os.path.join(srcdir, src)
61
62
63def update_version(srcdir, preserve_srcdir, new_version, install,
64 *args, **dargs):
65 """
66 Make sure srcdir is version new_version
67
68 If not, delete it and install() the new version.
69
70 In the preserve_srcdir case, we just check it's up to date,
71 and if not, we rerun install, without removing srcdir
72 """
73 versionfile = os.path.join(srcdir, '.version')
74 install_needed = True
75
76 if os.path.exists(versionfile):
77 old_version = pickle.load(open(versionfile))
78 if old_version == new_version:
79 install_needed = False
80
81 if install_needed:
82 if not preserve_srcdir and os.path.exists(srcdir):
83 shutil.rmtree(srcdir)
84 install(*args, **dargs)
85 if os.path.exists(srcdir):
86 pickle.dump(new_version, open(versionfile, 'w'))
mbligh462c0152008-03-13 15:37:10 +000087
88
89class run_randomly:
90 def __init__(self):
91 self.test_list = []
92
93
94 def add(self, *args, **dargs):
95 test = (args, dargs)
96 self.test_list.append(test)
97
98
99 def run(self, fn):
100 while self.test_list:
101 test_index = random.randint(0, len(self.test_list)-1)
102 (args, dargs) = self.test_list.pop(test_index)
103 fn(*args, **dargs)