blob: 278c657e04e4917cd43ebc972a3ffbd881727f74 [file] [log] [blame]
apatrick@chromium.org1218a882010-07-29 08:02:22 +09001#!/usr/bin/env python
maruel@chromium.org1f144a32011-11-24 04:13:44 +09002# Copyright (c) 2011 The Chromium Authors. All rights reserved.
apatrick@chromium.org1218a882010-07-29 08:02:22 +09003# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
maruel@chromium.org1f144a32011-11-24 04:13:44 +09006"""Extracts a single file from a CAB archive."""
apatrick@chromium.org1218a882010-07-29 08:02:22 +09007
8import os
9import subprocess
10import sys
apatrick@chromium.org38ff3d22011-12-13 09:34:15 +090011import tempfile
apatrick@chromium.org1218a882010-07-29 08:02:22 +090012
apatrick@chromium.org38ff3d22011-12-13 09:34:15 +090013lock_file = os.path.join(tempfile.gettempdir(), 'expand.lock')
14
15def acquire_lock():
16 while True:
17 try:
18 fd = os.open(lock_file, os.O_CREAT | os.O_EXCL | os.O_RDWR)
19 return fd
20 except OSError as e:
21 if e.errno != errno.EEXIST:
22 raise
23 print 'Cab extraction could not get exclusive lock. Retrying in 1 sec...'
24 time.sleep(1000)
25
26def release_lock(fd):
27 os.close(fd)
28 os.unlink(lock_file)
apatrick@chromium.org1218a882010-07-29 08:02:22 +090029
maruel@chromium.org1f144a32011-11-24 04:13:44 +090030def main():
31 if len(sys.argv) != 4:
32 print 'Usage: extract_from_cab.py cab_path archived_file output_dir'
33 return 1
apatrick@chromium.org1218a882010-07-29 08:02:22 +090034
maruel@chromium.org1f144a32011-11-24 04:13:44 +090035 [cab_path, archived_file, output_dir] = sys.argv[1:]
apatrick@chromium.org1218a882010-07-29 08:02:22 +090036
apatrick@chromium.org38ff3d22011-12-13 09:34:15 +090037 lock_fd = acquire_lock()
38 try:
39 # Invoke the Windows expand utility to extract the file.
maruel@chromium.orgc04ced42011-12-09 05:47:15 +090040 level = subprocess.call(
41 ['expand', cab_path, '-F:' + archived_file, output_dir])
42 if level != 0:
apatrick@chromium.org38ff3d22011-12-13 09:34:15 +090043 print 'Cab extraction(%s, %s, %s) failed.' % (
44 cab_path, archived_file, output_dir)
45 print 'Trying a second time.'
46 level = subprocess.call(
47 ['expand', cab_path, '-F:' + archived_file, output_dir])
48 if level != 0:
49 return level
50 finally:
51 release_lock(lock_fd)
maruel@chromium.org1f144a32011-11-24 04:13:44 +090052
53 # The expand utility preserves the modification date and time of the archived
54 # file. Touch the extracted file. This helps build systems that compare the
55 # modification times of input and output files to determine whether to do an
56 # action.
57 os.utime(os.path.join(output_dir, archived_file), None)
58 return 0
59
60
61if __name__ == '__main__':
62 sys.exit(main())