tar.py 2.48 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
17 18 19 20 21 22 23 24

"""Util to invoke tarball in the system."""
# pylint: disable=invalid-name
from __future__ import absolute_import as _abs
import os
import shutil
import subprocess
from . import util
25
from .._ffi.base import py_str
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57

def tar(output, files):
    """Create tarball containing all files in root.

    Parameters
    ----------
    output : str
        The target shared library.

    files : list
        List of files to be bundled.
    """
    cmd = ["tar"]
    cmd += ["-czf"]
    temp = util.tempdir()
    fset = set()
    for fname in files:
        base = os.path.basename(fname)
        if base in fset:
            raise ValueError("duplicate file name %s" % base)
        fset.add(base)
        shutil.copy(fname, temp.relpath(base))
    cmd += [output]
    cmd += ["-C", temp.temp_dir]
    cmd += temp.listdir()
    proc = subprocess.Popen(cmd,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.STDOUT)
    (out, _) = proc.communicate()

    if proc.returncode != 0:
        msg = "Tar error:\n"
58
        msg += py_str(out)
59 60
        raise RuntimeError(msg)

61 62 63
# assign output format
tar.output_format = "tar"

64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86

def untar(tar_file, directory):
    """Unpack all tar files into the directory

    Parameters
    ----------
    tar_file : str
        The source tar file.

    directory : str
        The target directory
    """
    cmd = ["tar"]
    cmd += ["-xf"]
    cmd += [tar_file]
    cmd += ["-C", directory]
    proc = subprocess.Popen(cmd,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.STDOUT)
    (out, _) = proc.communicate()

    if proc.returncode != 0:
        msg = "Tar error:\n"
87
        msg += py_str(out)
88
        raise RuntimeError(msg)