blob: c2b299bf837d1fdb60bc9174913b1878e493de27 [file] [log] [blame]
Benjamin Gordon1f4537f2019-12-06 09:10:56 -07001# -*- coding: utf-8 -*-
2# Copyright 2020 The Chromium OS Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""Run xz from PATH with a thread for each core in the system."""
7
Ben Pastenec6bf5492020-08-28 17:35:01 -07008from __future__ import division
Benjamin Gordon1f4537f2019-12-06 09:10:56 -07009from __future__ import print_function
10
Ben Pastenec6bf5492020-08-28 17:35:01 -070011import multiprocessing
Benjamin Gordon1f4537f2019-12-06 09:10:56 -070012import os
Mike Frysinger687ab9d2020-02-06 00:35:15 -050013import sys
14
Ben Pastenec6bf5492020-08-28 17:35:01 -070015from chromite.lib import commandline
16from chromite.lib import osutils
17from chromite.utils import memoize
18
Mike Frysinger687ab9d2020-02-06 00:35:15 -050019
20assert sys.version_info >= (3, 6), 'This module requires Python 3.6+'
Benjamin Gordon1f4537f2019-12-06 09:10:56 -070021
22
Ben Pastenec6bf5492020-08-28 17:35:01 -070023@memoize.Memoize
24def HasPixz():
25 """Returns path to pixz if it's on PATH or None otherwise."""
26 return osutils.Which('pixz')
27
28
29@memoize.Memoize
30def GetJobCount():
31 """Returns half of the total number of the machine's CPUs as a string.
32
33 Returns half rather than all of them to avoid starving out other parallel
34 processes on the same machine.
35 """
36 return str(int(max(1, multiprocessing.cpu_count() / 2)))
37
38
39def GetDecompressCommand():
40 """Returns decompression command."""
41 if HasPixz():
42 return ['pixz', '-d', '-p', GetJobCount()]
43 return ['xz', '-d']
44
45
46def GetParser():
47 """Return a command line parser."""
48 parser = commandline.ArgumentParser(description=__doc__)
49 parser.add_argument(
50 '-d', '--decompress', '--uncompress',
51 help='Decompress rather than compress.',
52 action='store_true')
53 return parser
54
55
Benjamin Gordon1f4537f2019-12-06 09:10:56 -070056def main(argv):
Ben Pastenec6bf5492020-08-28 17:35:01 -070057 parser = GetParser()
58 known_args, argv = parser.parse_known_args()
59 # xz doesn't support multi-threaded decompression, so try using pixz for that.
60 if known_args.decompress:
61 args = GetDecompressCommand()
62 os.execvp(args[0], args + argv)
Benjamin Gordon1f4537f2019-12-06 09:10:56 -070063 os.execvp('xz', ['xz', '-T0'] + argv)