xref: /aosp_15_r20/external/angle/build/extract_from_cab.py (revision 8975f5c5ed3d1c378011245431ada316dfb6f244)
1#!/usr/bin/env python3
2# Copyright 2012 The Chromium Authors
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""Extracts a single file from a CAB archive."""
7
8
9import os
10import shutil
11import subprocess
12import sys
13import tempfile
14
15def run_quiet(*args):
16  """Run 'expand' suppressing noisy output. Returns returncode from process."""
17  popen = subprocess.Popen(args, stdout=subprocess.PIPE)
18  out, _ = popen.communicate()
19  if popen.returncode:
20    # expand emits errors to stdout, so if we fail, then print that out.
21    print(out)
22  return popen.returncode
23
24def main():
25  if len(sys.argv) != 4:
26    print('Usage: extract_from_cab.py cab_path archived_file output_dir')
27    return 1
28
29  [cab_path, archived_file, output_dir] = sys.argv[1:]
30
31  # Expand.exe does its work in a fixed-named temporary directory created within
32  # the given output directory. This is a problem for concurrent extractions, so
33  # create a unique temp dir within the desired output directory to work around
34  # this limitation.
35  temp_dir = tempfile.mkdtemp(dir=output_dir)
36
37  try:
38    # Invoke the Windows expand utility to extract the file.
39    level = run_quiet('expand', cab_path, '-F:' + archived_file, temp_dir)
40    if level == 0:
41      # Move the output file into place, preserving expand.exe's behavior of
42      # paving over any preexisting file.
43      output_file = os.path.join(output_dir, archived_file)
44      try:
45        os.remove(output_file)
46      except OSError:
47        pass
48      os.rename(os.path.join(temp_dir, archived_file), output_file)
49  finally:
50    shutil.rmtree(temp_dir, True)
51
52  if level != 0:
53    return level
54
55  # The expand utility preserves the modification date and time of the archived
56  # file. Touch the extracted file. This helps build systems that compare the
57  # modification times of input and output files to determine whether to do an
58  # action.
59  os.utime(os.path.join(output_dir, archived_file), None)
60  return 0
61
62
63if __name__ == '__main__':
64  sys.exit(main())
65