Builds up the software cache directory at *sw_dir* by simply copying all required python
    modules. *sw_dir* is evaluated with :py:func:`get_sw_dir`.
14717
def build_software_cache(sw_dir=None):
    
    # ensure the cache is empty
    sw_dir = get_sw_dir(sw_dir)
    remove_software_cache(sw_dir)
    os.makedirs(sw_dir)

    # reload dependencies to find the proper module paths
    reload_dependencies(force=True)

    for mod in deps:
        path = os.path.dirname(mod.__file__)
        name, ext = os.path.splitext(os.path.basename(mod.__file__))
        # single file or module?
        if name == "__init__":
            # copy the entire module
            name = os.path.basename(path)
            shutil.copytree(path, os.path.join(sw_dir, name))
        else:
            shutil.copy2(os.path.join(path, name + ".py"), sw_dir)
1290003
def create_cache_directories(self):
        """"""
        if not os.path.isdir(self.package_cache_dir):
            if not os.path.isdir(self.stacker_cache_dir):
                os.mkdir(self.stacker_cache_dir)
            os.mkdir(self.package_cache_dir)
704042
def build_dirs(files):
    '''
    
    '''
    for i in files:
        if type(i) is list:
            build_dirs(i)
            continue
        else:
            if len(i['path']) > 1:
                addpath = os.path.join(os.getcwd(), *i['path'][:-1])
                subdirs = all_subdirs(os.getcwd())
                if addpath and addpath not in subdirs:
                    os.makedirs(addpath)
                    print 'just made path', addpath
844107
def build(self):
        
        packages = self.packages()
        if packages:
            for pkg in packages:
                if not os.path.exists(self.meta.build_path):
                    os.mkdir(self.meta.build_path)
                if not os.path.exists(self._SOURCES):
                    os.mkdir(self._SOURCES)
                sbo_url = sbo_search_pkg(pkg)
                sbo_dwn = SBoLink(sbo_url).tar_gz()
                source_dwn = SBoGrep(pkg).source().split()
                sources = []
                os.chdir(self.meta.build_path)
                script = sbo_dwn.split("/")[-1]
                Download(self.meta.build_path, sbo_dwn.split(),
                         repo="sbo").start()
                for src in source_dwn:
                    Download(self._SOURCES, src.split(), repo="sbo").start()
                    sources.append(src.split("/")[-1])
                BuildPackage(script, sources, self.meta.build_path,
                             auto=False).build()
        else:
            print("\nPackages not found in the queue for building\n")
            raise SystemExit(1)
1090107
def ensure_app_cache_dir(appname, *args):
    
    import utool as ut
    dpath = get_app_cache_dir(appname, *args)
    ut.ensuredir(dpath)
    return dpath
161483
def _populate_cache(platform, pkg_cache, mount_dir):
    '''
    
    '''
    if not pkg_cache:
        return
    if not os.path.isdir(pkg_cache):
        return

    if platform == 'pacman':
        cache_dir = '{0}/var/cache/pacman/pkg'.format(mount_dir)

    __salt__['file.mkdir'](cache_dir, 'root', 'root', '755')
    __salt__['file.copy'](pkg_cache, cache_dir, recurse=True, remove_existing=True)
71255
def build_package_data(self):
        """"""
        for package, src_dir, build_dir, filenames in self.data_files:
            for filename in filenames:
                target = os.path.join(build_dir, filename)
                self.mkpath(os.path.dirname(target))
                srcfile = os.path.join(src_dir, filename)
                outf, copied = self.copy_file(srcfile, target)
                srcfile = os.path.abspath(srcfile)
                if (copied and
                        srcfile in self.distribution.convert_2to3_doctests):
                    self.__doctests_2to3.append(outf)
1096499
def complete_from_dir(directory):
    '''
    
    '''
    global currDirModule
    if currDirModule is not None:
        if len(sys.path) > 0 and sys.path[0] == currDirModule:
            del sys.path[0]

    currDirModule = directory
    sys.path.insert(0, directory)
1106936
def install_dir(self):
        
        max_len = 500

        directory = self._get_str(self._iface.get_install_dir, [self.app_id], max_len=max_len)

        if not directory:
            # Fallback to restricted interface (can only be used by approved apps).
            directory = self._get_str(self._iface_list.get_install_dir, [self.app_id], max_len=max_len)

        return directory
903357
def rsync(src_dir, dst_dir, mirror, dry_run, print_func, recursed, sync_hidden):
    """"""
    # This test is a hack to avoid errors when accessing /flash. When the
    # cache synchronisation issue is solved it should be removed
    if not isinstance(src_dir, str) or not len(src_dir):
        return

    sstat = auto(get_stat, src_dir)
    smode = stat_mode(sstat)
    if mode_isfile(smode):
        print_err('Source is a file not a directory.')
        return

    d_src = {}  # Look up stat tuple from name in current directory
    src_files = auto(listdir_stat, src_dir, show_hidden=sync_hidden)
    if src_files is None:
        print_err('Source directory {} does not exist.'.format(src_dir))
        return
    for name, stat in src_files:
        d_src[name] = stat

    d_dst = {}
    dst_files = auto(listdir_stat, dst_dir, show_hidden=sync_hidden)
    if dst_files is None: # Directory does not exist
        if not make_dir(dst_dir, dry_run, print_func, recursed):
            return
    else: # dest exists
        for name, stat in dst_files:
            d_dst[name] = stat

    set_dst = set(d_dst.keys())
    set_src = set(d_src.keys())
    to_add = set_src - set_dst  # Files to copy to dest
    to_del = set_dst - set_src  # To delete from dest
    to_upd = set_dst.intersection(set_src) # In both: may need updating

    for src_basename in to_add:  # Name in source but absent from destination
        src_filename = src_dir + '/' + src_basename
        dst_filename = dst_dir + '/' + src_basename
        print_func("Adding %s" % dst_filename)
        src_stat = d_src[src_basename]
        src_mode = stat_mode(src_stat)
        if not dry_run:
            if not mode_isdir(src_mode):
                cp(src_filename, dst_filename)
        if mode_isdir(src_mode):
            rsync(src_filename, dst_filename, mirror=mirror, dry_run=dry_run,
                  print_func=print_func, recursed=True, sync_hidden=sync_hidden)

    if mirror:  # May delete
        for dst_basename in to_del:  # In dest but not in source
            dst_filename = dst_dir + '/' + dst_basename
            print_func("Removing %s" % dst_filename)
            if not dry_run:
                rm(dst_filename, recursive=True, force=True)

    for src_basename in to_upd:  # Names are identical
        src_stat = d_src[src_basename]
        dst_stat = d_dst[src_basename]
        src_filename = src_dir + '/' + src_basename
        dst_filename = dst_dir + '/' + src_basename
        src_mode = stat_mode(src_stat)
        dst_mode = stat_mode(dst_stat)
        if mode_isdir(src_mode):
            if mode_isdir(dst_mode):
                # src and dst are both directories - recurse
                rsync(src_filename, dst_filename, mirror=mirror, dry_run=dry_run,
                      print_func=print_func, recursed=True, sync_hidden=sync_hidden)
            else:
                msg = "Source '{}' is a directory and destination " \
                      "'{}' is a file. Ignoring"
                print_err(msg.format(src_filename, dst_filename))
        else:
            if mode_isdir(dst_mode):
                msg = "Source '{}' is a file and destination " \
                      "'{}' is a directory. Ignoring"
                print_err(msg.format(src_filename, dst_filename))
            else:
                if stat_mtime(src_stat) > stat_mtime(dst_stat):
                    msg = "{} is newer than {} - copying"
                    print_func(msg.format(src_filename, dst_filename))
                    if not dry_run:
                        cp(src_filename, dst_filename)
854598
def get_sw_dir(sw_dir=None):
    
    if sw_dir is None:
        sw_dir = Config.instance().get("core", "software_dir")

    sw_dir = os.path.expandvars(os.path.expanduser(sw_dir))

    return sw_dir
1141537
def _get_cache_dir(candidate):
    """"""
    if candidate:
        return candidate

    import distutils.dist  # suppress(import-error)
    import distutils.command.build  # suppress(import-error)
    build_cmd = distutils.command.build.build(distutils.dist.Distribution())
    build_cmd.finalize_options()
    cache_dir = os.path.abspath(build_cmd.build_temp)

    # Make sure that it is created before anyone tries to use it
    try:
        os.makedirs(cache_dir)
    except OSError as error:
        if error.errno != errno.EEXIST:
            raise error

    return cache_dir
1200467
def change_dir(directory):
  
  def cd_decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
      org_path = os.getcwd()
      os.chdir(directory)
      func(*args, **kwargs)
      os.chdir(org_path)
    return wrapper
  return cd_decorator
139990
def _setup_dir(self, base_dir):
        
        stats_dir = self._sdir(base_dir)

        if not os.path.isdir(stats_dir):
            try:
                os.mkdir(stats_dir)
            except OSError:
                raise errors.DirectorySetupFail()
1282864
def build_install(self):
        
        slackbuilds = self.dependencies + self.master_packages
        installs, upgraded, = [], []
        if not os.path.exists(self.build_folder):
            os.makedirs(self.build_folder)
        if not os.path.exists(self._SOURCES):
            os.makedirs(self._SOURCES)
        os.chdir(self.build_folder)
        for prgnam in slackbuilds:
            if (self.meta.not_downgrade == "on" and
                    self.not_downgrade(prgnam) is True):
                continue
            pkg = "-".join(prgnam.split("-")[:-1])
            installed = "".join(find_package(prgnam, self.meta.pkg_path))
            src_link = SBoGrep(pkg).source().split()
            if (installed and "--download-only" not in self.flag and
                    "--rebuild" not in self.flag):
                self.msg.template(78)
                self.msg.pkg_found(prgnam)
                self.msg.template(78)
            elif self.unst[0] in src_link or self.unst[1] in src_link:
                self.msg.template(78)
                print("| Package {0} {1}{2}{3}".format(
                    prgnam, self.meta.color["RED"], "".join(src_link),
                    self.meta.color["ENDC"]))
                self.msg.template(78)
            else:
                sbo_url = sbo_search_pkg(pkg)
                sbo_link = SBoLink(sbo_url).tar_gz()
                script = sbo_link.split("/")[-1]
                if self.meta.sbosrcarch in ["on", "ON"]:
                    src_link = self.sbosrcarsh(prgnam, sbo_link, src_link)
                Download(self.build_folder, sbo_link.split(),
                         repo="sbo").start()
                Download(self._SOURCES, src_link, repo="sbo").start()
                if "--download-only" in self.flag:
                    continue
                sources = self.filenames(src_link)
                BuildPackage(script, sources, self.build_folder,
                             auto=False).build()
                binary = slack_package(prgnam)
                if os.path.isfile("".join(binary)):
                    if GetFromInstalled(pkg).name() == pkg:
                        print("[ {0}Upgrading{1} ] --> {2}".format(
                            self.meta.color["YELLOW"],
                            self.meta.color["ENDC"], prgnam))
                        upgraded.append(prgnam)
                    else:
                        print("[ {0}Installing{1} ] --> {2}".format(
                            self.meta.color["GREEN"],
                            self.meta.color["ENDC"], prgnam))
                        installs.append(prgnam)
                    if ("--rebuild" in self.flag and
                            GetFromInstalled(pkg).name() == pkg):
                        PackageManager(binary).upgrade(flag="--reinstall")
                    else:
                        PackageManager(binary).upgrade(flag="--install-new")
        return installs, upgraded
1298548
def remove_software_cache(sw_dir=None):
    
    sw_dir = get_sw_dir(sw_dir)
    if os.path.exists(sw_dir):
        shutil.rmtree(sw_dir)
209025
def init():
    '''
    
    '''
    if not os.path.exists(__opts__['spm_cache_dir']):
        log.debug('Creating SPM cache directory at %s', __opts__['spm_db'])
        os.makedirs(__opts__['spm_cache_dir'])

    if not os.path.exists(__opts__['spm_db']):
        log.debug('Creating new package database at %s', __opts__['spm_db'])

    sqlite3.enable_callback_tracebacks(True)
    conn = sqlite3.connect(__opts__['spm_db'], isolation_level=None)

    try:
        conn.execute('SELECT count(*) FROM packages')
    except OperationalError:
        conn.execute('''CREATE TABLE packages (
            package text,
            version text,
            release text,
            installed text,
            os text,
            os_family text,
            dependencies text,
            os_dependencies text,
            os_family_dependencies text,
            summary text,
            description text
        )''')

    try:
        conn.execute('SELECT count(*) FROM files')
    except OperationalError:
        conn.execute('''CREATE TABLE files (
            package text,
            path text,
            size real,
            mode text,
            sum text,
            major text,
            minor text,
            linkname text,
            linkpath text,
            uname text,
            gname text,
            mtime text
        )''')

    return conn