Create a TAR archive.
179235
def create_tar (archive, compression, cmd, verbosity, interactive, filenames):
    """"""
    cmdlist = [cmd, '-c']
    add_star_opts(cmdlist, compression, verbosity)
    cmdlist.append("file=%s" % archive)
    cmdlist.extend(filenames)
    return cmdlist
346121
def create_archive(archive, filenames, verbosity=0, program=None, interactive=True):
    """"""
    util.check_new_filename(archive)
    util.check_archive_filelist(filenames)
    if verbosity >= 0:
        util.log_info("Creating %s ..." % archive)
    res = _create_archive(archive, filenames, verbosity=verbosity,
                          interactive=interactive, program=program)
    if verbosity >= 0:
        util.log_info("... %s created." % archive)
    return res
506652
def archive(self):
        """"""

        # Traverse the model directory deleting symlinks, zero length files
        # and empty directories
        for path, dirs, files in os.walk(self.work_path, topdown=False):
            for f_name in files:
                f_path = os.path.join(path, f_name)
                if os.path.islink(f_path) or os.path.getsize(f_path) == 0:
                    os.remove(f_path)
            if len(os.listdir(path)) == 0:
                os.rmdir(path)
842115
def _tar(name, root, path=None, compress='bzip2'):
    '''
    
    '''
    if path is None:
        path = os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'img')
    if not __salt__['file.directory_exists'](path):
        try:
            __salt__['file.mkdir'](path)
        except Exception as exc:
            return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))}

    compression, ext = _compress(compress)

    tarfile = '{0}/{1}.tar.{2}'.format(path, name, ext)
    out = __salt__['archive.tar'](
        options='{0}pcf'.format(compression),
        tarfile=tarfile,
        sources='.',
        dest=root,
    )
583701
def create_packages_archive(packages, filename):
    
    import tarfile
    tar = tarfile.open(filename, "w")

    def add(src, dst):
        logger.debug('adding to tar: %s -> %s', src, dst)
        tar.add(src, dst)

    def add_files_for_package(sub_package_path, root_package_path, root_package_name):
        for root, dirs, files in os.walk(sub_package_path):
            if '.svn' in dirs:
                dirs.remove('.svn')
            for f in files:
                if not f.endswith(".pyc") and not f.startswith("."):
                    add(dereference(root + "/" + f), root.replace(root_package_path, root_package_name) + "/" + f)

    for package in packages:
        # Put a submodule's entire package in the archive. This is the
        # magic that usually packages everything you need without
        # having to attach packages/modules explicitly
        if not getattr(package, "__path__", None) and '.' in package.__name__:
            package = __import__(package.__name__.rpartition('.')[0], None, None, 'non_empty')

        n = package.__name__.replace(".", "/")

        if getattr(package, "__path__", None):
            # TODO: (BUG) picking only the first path does not
            # properly deal with namespaced packages in different
            # directories
            p = package.__path__[0]

            if p.endswith('.egg') and os.path.isfile(p):
                raise 'egg files not supported!!!'
                # Add the entire egg file
                # p = p[:p.find('.egg') + 4]
                # add(dereference(p), os.path.basename(p))

            else:
                # include __init__ files from parent projects
                root = []
                for parent in package.__name__.split('.')[0:-1]:
                    root.append(parent)
                    module_name = '.'.join(root)
                    directory = '/'.join(root)

                    add(dereference(__import__(module_name, None, None, 'non_empty').__path__[0] + "/__init__.py"),
                        directory + "/__init__.py")

                add_files_for_package(p, p, n)

                # include egg-info directories that are parallel:
                for egg_info_path in glob.glob(p + '*.egg-info'):
                    logger.debug(
                        'Adding package metadata to archive for "%s" found at "%s"',
                        package.__name__,
                        egg_info_path
                    )
                    add_files_for_package(egg_info_path, p, n)

        else:
            f = package.__file__
            if f.endswith("pyc"):
                f = f[:-3] + "py"
            if n.find(".") == -1:
                add(dereference(f), os.path.basename(f))
            else:
                add(dereference(f), n + ".py")
    tar.close()
550532
def extract(self, destination):
        """"""
        with tarfile.open(self.archive, 'r:') as tar:
            tar.extractall(path=destination)
1345753
def generate(self):
        
        if self._tar_buffer.tell():
            self._tar_buffer.seek(0, 0)
            yield self._tar_buffer.read()

        for fname in self._files_to_add:
            last = self._tar_buffer.tell()
            self._tar_obj.add(fname)
            self._tar_buffer.seek(last, os.SEEK_SET)
            data = self._tar_buffer.read()
            yield data

        for info, content in self._ios_to_add.items():
            last = self._tar_buffer.tell()
            self._tar_obj.addfile(info, content)
            self._tar_buffer.seek(last, os.SEEK_SET)
            data = self._tar_buffer.read()
            yield data

        self._tar_obj.close()
        yield self._tar_buffer.read()
        self._generated = True
1354811
public function create()
    {
        $folder = $this->getBackupFolder();

        $files = $this->backupFiles($folder);
        $db = $this->backupDatabase($folder);

        $resultFilename = $this->getBackupFilename();
        $archiveFile = dirname($folder) . DIRECTORY_SEPARATOR . $resultFilename . '.tar';

        // Create new archive
        $archive = new \PharData($archiveFile);

        // add folder
        $archive->buildFromDirectory($folder);

        // Remove temp directory
        FileHelper::removeDirectory($folder);

        return $archiveFile;
    }
872033
def create_tar(self):
        """"""

        def add_file_to_tar(tar, orig_fn, new_fn, func=None):
            tf = tarfile.TarInfo(name=new_fn)
            with open(orig_fn) as f:
                tfs = f.read()

            if func is not None:
                tfs = func(tfs)
            tf.size = len(tfs)
            tfs = io.BytesIO(tfs.encode('utf8'))
            tar.addfile(tarinfo=tf, fileobj=tfs)

        def add_text_to_tar(tar, new_fn, text, func=None):
            tf = tarfile.TarInfo(name=new_fn)
            if func is not None:
                text = func(text)
            tf.size = len(text)
            tfs = io.BytesIO(text.encode('utf8'))
            tar.addfile(tarinfo=tf, fileobj=tfs)

        def strip_lines(text):
            text = text.replace("\t", " ")
            while text.find("  ") != -1:
                text = text.replace("  ", " ")
            lines = [x.strip() for x in text.strip().split("\n")]
            return "\n".join(lines) + "\n"

        tar = tarfile.TarFile(self._tar_fn, "w")
        for i in range(len(self.bams)):
            roc_fn = self.bams[i].roc_fn()
            t_roc_fn = os.path.basename(roc_fn)

            gp_fn = self.bams[i].gp_fn()
            t_gp_fn = os.path.basename(gp_fn)

            svg_fn = self.bams[i].svg_fn()
            t_svg_fn = os.path.basename(svg_fn)

            add_file_to_tar(tar, roc_fn, t_roc_fn)
            add_file_to_tar(
                tar, gp_fn, t_gp_fn, lambda x: strip_lines(x.replace(roc_fn, t_roc_fn).replace(svg_fn, t_svg_fn))
            )

        gp_fn = self._gp_fn
        t_gp_fn = os.path.basename(gp_fn)
        svg_dir = os.path.join(self.panel_dir, "graphics") + "/"
        roc_dir = os.path.join(self.panel_dir, "roc") + "/"
        add_file_to_tar(tar, gp_fn, t_gp_fn, lambda x: strip_lines(x.replace(svg_dir, "").replace(roc_dir, "")))

        makefile = [
            ".PHONY: all",
            "all:",
            "\tgnuplot *.gp",
            "clean:",
            "\trm -f *.svg",
            "",
        ]
        add_text_to_tar(tar, "Makefile", "\n".join(makefile))
197274
def create_arj (archive, compression, cmd, verbosity, interactive, filenames):
    """"""
    cmdlist = [cmd, 'a', '-r']
    if not interactive:
        cmdlist.append('-y')
    cmdlist.append(archive)
    cmdlist.extend(filenames)
    return cmdlist
794995
def _create(archive, compression, cmd, format, verbosity, filenames):
    """"""
    if len(filenames) > 1:
        raise util.PatoolError('multi-file compression not supported in Python lzma')
    try:
        with lzma.LZMAFile(archive, mode='wb', **_get_lzma_options(format, preset=9)) as lzmafile:
            filename = filenames[0]
            with open(filename, 'rb') as srcfile:
                data = srcfile.read(READ_SIZE_BYTES)
                while data:
                    lzmafile.write(data)
                    data = srcfile.read(READ_SIZE_BYTES)
    except Exception as err:
        msg = "error creating %s: %s" % (archive, err)
        raise util.PatoolError(msg)
    return None
1329558
def build_archive_file(archive_contents, zip_file):
    """"""

    # This is tested against Desktop and Server, and reverse engineered by lots
    # of trial and error. Do not change this logic.
    for root_dir, _, files in os.walk(archive_contents):
        relative_dir = os.path.relpath(root_dir, archive_contents)
        for f in files:
            temp_file_full_path = os.path.join(
                archive_contents, relative_dir, f)
            zipname = os.path.join(relative_dir, f)
            zip_file.write(temp_file_full_path, arcname=zipname)
975352
private String[] createArchivesArray() {
        Collection<String> archiveExtensions = new ArrayList<>();
        archiveExtensions.addAll(ZIP_EXTENSIONS);
        archiveExtensions.addAll(GEM_EXTENSIONS);
        archiveExtensions.addAll(TAR_EXTENSIONS);

        String[] archiveIncludesPattern = new String[archiveExtensions.size()];
        int i = 0;
        for (String extension : archiveExtensions) {
            archiveIncludesPattern[i++] = GLOB_PATTERN_PREFIX + extension;
        }
        return archiveIncludesPattern;
    }
279794
def extract_archive(client, archive_path, extract_path=None):
    
    command = 'tar -xf {path}'.format(path=archive_path)

    if extract_path:
        command += ' -C {extract_path}'.format(extract_path=extract_path)

    out = execute_ssh_command(client, command)
    return out
97357
def extract_tar(tar_path, target_folder):
    
    with tarfile.open(tar_path, 'r') as archive:
        archive.extractall(target_folder)
511398
def archive(context, clear_log, items, path, name):
    
    history_log = context.obj['history_log']
    no_color = context.obj['no_color']

    with open(history_log, 'r') as f:
        # Get history items
        history_items = f.readlines()

    if items:
        # Split comma separated list and cast indices to integer.
        items = [int(item) for item in items.split(',')]

        lines = []
        for index in items:
            lines.append(history_items[len(history_items) - index])
        history_items = lines

    with tempfile.TemporaryDirectory() as temp_dir:
        for item in history_items:
            # Copy log and results file,
            # update results file with relative path.
            archive_history_item(item, temp_dir, no_color)

        file_name = ''.join([name, '.tar.gz'])
        archive_path = os.path.join(path, file_name)

        with tarfile.open(archive_path, "w:gz") as tar:
            # Create tar archive
            tar.add(temp_dir, arcname='results')

    if clear_log:
        if items:
            # Remove duplicates to prevent unwanted deletion.
            items = list(set(items))

            # Must delete items from bottom to top of history file
            # to preserve indices. (Index 0 is last item in file)
            items.sort()
            for index in items:
                context.invoke(delete, item=index)
        else:
            context.invoke(clear)

    click.echo(
        'Exported results history to archive: {0}'.format(archive_path)
    )
802950
def _write_to_tar(self, dtype_out_time):
        """"""
        # When submitted in parallel and the directory does not exist yet
        # multiple processes may try to create a new directory; this leads
        # to an OSError for all processes that tried to make the
        # directory, but were later than the first.
        try:
            os.makedirs(self.dir_tar_out)
        except OSError:
            pass
        # tarfile 'append' mode won't overwrite the old file, which we want.
        # So open in 'read' mode, extract the file, and then delete it.
        # But 'read' mode throws OSError if file doesn't exist: make it first.
        utils.io.dmget([self.path_tar_out])
        with tarfile.open(self.path_tar_out, 'a') as tar:
            pass
        with tarfile.open(self.path_tar_out, 'r') as tar:
            old_data_path = os.path.join(self.dir_tar_out,
                                         self.file_name[dtype_out_time])
            try:
                tar.extract(self.file_name[dtype_out_time],
                            path=old_data_path)
            except KeyError:
                pass
            else:
                # The os module treats files on archive as non-empty
                # directories, so can't use os.remove or os.rmdir.
                shutil.rmtree(old_data_path)
                retcode = subprocess.call([
                    "tar", "--delete", "--file={}".format(self.path_tar_out),
                    self.file_name[dtype_out_time]
                ])
                if retcode:
                    msg = ("The 'tar' command to save your aospy output "
                           "exited with an error.  Most likely, this is due "
                           "to using an old version of 'tar' (especially if "
                           "you are on a Mac).  Consider installing a newer "
                           "version of 'tar' or disabling tar output by "
                           "setting `write_to_tar=False` in the "
                           "`calc_exec_options` argument of "
                           "`submit_mult_calcs`.")
                    logging.warn(msg)
        with tarfile.open(self.path_tar_out, 'a') as tar:
            tar.add(self.path_out[dtype_out_time],
                    arcname=self.file_name[dtype_out_time])