blob: d04bcfd14aa6c25ec2a56d3d4527ff6de58b08b2 [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
apatrick@chromium.org3faf3c82011-12-13 12:32:12 +090015
apatrick@chromium.org38ff3d22011-12-13 09:34:15 +090016def acquire_lock():
17 while True:
18 try:
19 fd = os.open(lock_file, os.O_CREAT | os.O_EXCL | os.O_RDWR)
20 return fd
21 except OSError as e:
22 if e.errno != errno.EEXIST:
23 raise
apatrick@chromium.org3faf3c82011-12-13 12:32:12 +090024 print 'Cab extraction could not get exclusive lock. Retrying in 100ms...'
25 time.sleep(0.1)
26
apatrick@chromium.org38ff3d22011-12-13 09:34:15 +090027
28def release_lock(fd):
29 os.close(fd)
30 os.unlink(lock_file)
apatrick@chromium.org1218a882010-07-29 08:02:22 +090031
apatrick@chromium.org3faf3c82011-12-13 12:32:12 +090032
maruel@chromium.org1f144a32011-11-24 04:13:44 +090033def main():
34 if len(sys.argv) != 4:
35 print 'Usage: extract_from_cab.py cab_path archived_file output_dir'
36 return 1
apatrick@chromium.org1218a882010-07-29 08:02:22 +090037
maruel@chromium.org1f144a32011-11-24 04:13:44 +090038 [cab_path, archived_file, output_dir] = sys.argv[1:]
apatrick@chromium.org1218a882010-07-29 08:02:22 +090039
apatrick@chromium.org38ff3d22011-12-13 09:34:15 +090040 lock_fd = acquire_lock()
41 try:
42 # Invoke the Windows expand utility to extract the file.
maruel@chromium.orgc04ced42011-12-09 05:47:15 +090043 level = subprocess.call(
44 ['expand', cab_path, '-F:' + archived_file, output_dir])
45 if level != 0:
apatrick@chromium.org3faf3c82011-12-13 12:32:12 +090046 return level
apatrick@chromium.org38ff3d22011-12-13 09:34:15 +090047 finally:
48 release_lock(lock_fd)
maruel@chromium.org1f144a32011-11-24 04:13:44 +090049
50 # The expand utility preserves the modification date and time of the archived
51 # file. Touch the extracted file. This helps build systems that compare the
52 # modification times of input and output files to determine whether to do an
53 # action.
54 os.utime(os.path.join(output_dir, archived_file), None)
55 return 0
56
57
58if __name__ == '__main__':
59 sys.exit(main())