mbligh | 6231cd6 | 2008-02-02 19:18:33 +0000 | [diff] [blame] | 1 | import os, sys, re, shutil, urlparse, urllib, pickle |
| 2 | |
| 3 | |
| 4 | def 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 | |
| 17 | def 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 | |
| 24 | def 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 | |
| 43 | def 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 | |
| 63 | def 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')) |