Create the user s-tui config directory if it doesn't exist
337238
def make_user_config_dir():
    
    config_path = get_user_config_dir()

    if not user_config_dir_exists():
        try:
            os.mkdir(config_path)
            os.mkdir(os.path.join(config_path, 'hooks.d'))
        except OSError:
            return None

    return config_path
317354
def ensure_dir_does_not_exist(*args):
    """"""
    path = os.path.join(*args)
    if os.path.isdir(path):
        shutil.rmtree(path)
1085842
def try_to_create_directory(directory_path):
    
    logger = logging.getLogger("ray")
    directory_path = os.path.expanduser(directory_path)
    if not os.path.exists(directory_path):
        try:
            os.makedirs(directory_path)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise e
            logger.warning(
                "Attempted to create '{}', but the directory already "
                "exists.".format(directory_path))
        # Change the log directory permissions so others can use it. This is
        # important when multiple people are using the same machine.
    try:
        os.chmod(directory_path, 0o0777)
    except OSError as e:
        # Silently suppress the PermissionError that is thrown by the chmod.
        # This is done because the user attempting to change the permissions
        # on a directory may not own it. The chmod is attempted whether the
        # directory is new or not to avoid race conditions.
        # ray-project/ray/#3591
        if e.errno in [errno.EACCES, errno.EPERM]:
            pass
        else:
            raise
272837
def ls(system, user, local, include_missing):
    """"""

    # default action is to list *all* auto-detected files
    if not (system or user or local):
        system = user = local = True

    for path in get_configfile_paths(system=system, user=user, local=local,
                                     only_existing=not include_missing):
        click.echo(path)
671969
def get_config_file():
    
    import os
    from os.path import abspath, expanduser, join, exists

    __lib_name = get_library_name()

    assert __lib_name in ["sframe", "turicreate"]

    __default_config_path = join(expanduser("~"), ".%s" % __lib_name, "config")

    if "TURI_CONFIG_FILE" in os.environ:
        __default_config_path = abspath(expanduser(os.environ["TURI_CONFIG_FILE"]))

        if not exists(__default_config_path):
            print(("WARNING: Config file specified in environment variable "
                   "'TURI_CONFIG_FILE' as "
                   "'%s', but this path does not exist.") % __default_config_path)

    return __default_config_path
332081
private static void ensureUserRootExists() throws IOException {
        if (!m_root.exists()) {
            if (!m_root.mkdir()) {
                throw new IOException("Unable to create \"" + m_root + "\"");
            }
        }
        if (!m_root.isDirectory()) {
            throw new IOException("\"" + m_root + "\" exists but is not a directory");
        }
        if (!m_root.canRead()) {
            throw new IOException("\"" + m_root + "\" exists but is not readable");
        }
        if (!m_root.canWrite()) {
            throw new IOException("\"" + m_root + "\" exists but is not writable");
        }
        if (!m_root.canExecute()) {
            throw new IOException("\"" + m_root + "\" exists but is not executable");
        }
    }
1204543
def init(path = Dir.pwd, _options = {})
      # FIXME: for travis test: ensure the global git configurations
      # 'user.email' and 'user.name' are set
      [ 'user.name', 'user.email' ].each do |userconf|
        next unless MiniGit[userconf].nil?
        warn "The Git global configuration '#{userconf}' is not set so"
        warn "you should *seriously* consider setting them by running\n\t git config --global #{userconf} 'your_#{userconf.sub(/\./, '_')}'"
        default_val = ENV['USER']
        default_val += '@domain.org' if userconf =~ /email/
        warn "Now putting a default value '#{default_val}' you could change later on"
        run %(
                       git config --global #{userconf} "#{default_val}"
                  )
        #MiniGit[userconf] = default_val
      end
      exit_status = 1
      Dir.mkdir( path ) unless Dir.exist?( path )
      Dir.chdir( path ) do
        execute "git init" unless FalkorLib.config.debug
        exit_status = $?.to_i
      end
      # #puts "#init #{path}"
      # Dir.chdir( "#{path}" ) do
      #     %x[ pwd && git init ] unless FalkorLib.config.debug
      # end
      exit_status
    end
1682
def main(overwrite):
    
    logger.debug("Checking existence of '%s'.", CONF_PATH)
    if not os.path.exists(CONF_PATH):
        logger.debug("Directory %s not found! Panicking..", CONF_PATH)
        raise UserWarning(
            "Can't find '%s' - it looks like ProFTPD is not installed!" % (
                CONF_PATH,
            )
        )

    # check existence of proftpd.conf
    logger.debug("Checking existence of configuration file '%s'.", CONF_FILE)
    if not os.path.exists(CONF_FILE):
        logger.debug("Configuration file not found, creating..")
        _write_conf_file()
    else:
        logger.debug("Found.")

        if not os.path.exists(CONF_FILE + "_"):
            logger.debug(
                "Backing up the configuration file '%s' -> '%s'.",
                CONF_FILE,
                CONF_FILE + "_"
            )
            shutil.copyfile(CONF_FILE, CONF_FILE + "_")
        else:
            logger.debug(
                "Backup already exists. '%s' will be overwritten.",
                CONF_FILE
            )
    if overwrite:
        logger.debug("--update switch not found, overwriting conf file")
        _write_conf_file()

    logger.debug("Checking existence of the '%s' file.", MODULES_FILE)
    if not os.path.exists(MODULES_FILE) and _is_deb_system():
        with open(MODULES_FILE, "w") as f:
            f.write(DEFAULT_MODULES_CONF)
            logger.debug("Modules file not found. Created '%s'.", MODULES_FILE)

    # create data directory, where the user informations will be stored
    logger.debug("Checking existence of user's directory '%s'.", DATA_PATH)
    if not os.path.exists(DATA_PATH):
        logger.debug("Directory '%s' not found, creating..", DATA_PATH)

        os.makedirs(DATA_PATH, 0777)

        logger.debug("Done. '%s' created.", DATA_PATH)

    # create user files if they doesn't exists
    logger.debug("Checking existence of passwd file '%s'.", LOGIN_FILE)
    if not os.path.exists(LOGIN_FILE):
        logger.debug("passwd file not found, creating..")

        open(LOGIN_FILE, "a").close()

        logger.debug("Done. '%s' created.")

    logger.debug("Setting permissions..")
    os.chown(LOGIN_FILE, get_ftp_uid(), -1)
    os.chmod(LOGIN_FILE, 0400)

    # load values from protpd conf file
    logger.debug("Switching and adding options..")
    data = ""
    with open(CONF_FILE) as f:
        data = f.read()

    # set path to passwd file
    logger.debug("\tAuthUserFile")
    data = add_or_update(
        data,
        "AuthUserFile",
        LOGIN_FILE
    )
    logger.debug("\tRequireValidShell")
    data = add_or_update(data, "RequireValidShell", "off")
    logger.debug("\tDefaultRoot")
    data = add_or_update(data, "DefaultRoot", "~")

    # http://www.proftpd.org/docs/modules/mod_log.html
    logger.debug("\tLogFormat")
    data = add_or_update(data, "LogFormat", 'paths "%f, %u, %m, %{%s}t"')
    logger.debug("\tExtendedLog")
    data = add_or_update(
        data,
        "ExtendedLog",
        LOG_FILE + " WRITE paths"
    )

    if not _is_deb_system():
        logger.debug("Detected non debian based linux. Aplying SUSE changes.")
        data = comment(data, "IdentLookups off")
        data = comment(data, "Include /etc/proftpd/modules.conf")
        data = add_or_update(data, "User", "ftp")

    # save changed file
    logger.debug("Saving into config file..")
    with open(CONF_FILE, "w") as f:
        f.write(data)
        logger.debug("Done.")

    logger.debug("Sending proftpd signal to reload configuration..")
    reload_configuration()
    logger.debug("Done.")
    logger.info("All set.")
748686
def init():
    """"""
    default_config_path = path.join(
        (os.environ.get('TLDR_CONFIG_DIR') or path.expanduser('~')),
        '.tldrrc')
    if path.exists(default_config_path):
        click.echo("There is already a config file exists, "
                   "skip initializing it.")
    else:
        repo_path = click.prompt("Input the tldr repo path(absolute path)")
        if not path.exists(repo_path):
            sys.exit("Repo path not exist, clone it first.")

        platform = click.prompt("Input your platform(linux, osx or sunos)")
        if platform not in ['linux', 'osx', 'sunos']:
            sys.exit("Platform should be in linux, osx or sunos.")

        colors = {
            "description": "blue",
            "usage": "green",
            "command": "cyan"
        }

        config = {
            "repo_directory": repo_path,
            "colors": colors,
            "platform": platform
        }
        with open(default_config_path, 'w') as f:
            f.write(yaml.safe_dump(config, default_flow_style=False))

        click.echo("Initializing the config file at {0}".format(
            default_config_path))
186439
def add(name,
        uid=None,
        gid=None,
        groups=None,
        home=None,
        shell=None,
        fullname=None,
        createhome=True,
        **kwargs):
    '''
    
    '''
    if info(name):
        raise CommandExecutionError('User \'{0}\' already exists'.format(name))

    if salt.utils.stringutils.contains_whitespace(name):
        raise SaltInvocationError('Username cannot contain whitespace')

    if uid is None:
        uid = _first_avail_uid()
    if gid is None:
        gid = 20  # gid 20 == 'staff', the default group
    if home is None:
        home = '/Users/{0}'.format(name)
    if shell is None:
        shell = '/bin/bash'
    if fullname is None:
        fullname = ''

    if not isinstance(uid, int):
        raise SaltInvocationError('uid must be an integer')
    if not isinstance(gid, int):
        raise SaltInvocationError('gid must be an integer')

    name_path = '/Users/{0}'.format(name)
    _dscl([name_path, 'UniqueID', uid])
    _dscl([name_path, 'PrimaryGroupID', gid])
    _dscl([name_path, 'UserShell', shell])
    _dscl([name_path, 'NFSHomeDirectory', home])
    _dscl([name_path, 'RealName', fullname])

    # Make sure home directory exists
    if createhome:
        __salt__['file.mkdir'](home, user=uid, group=gid)

    # dscl buffers changes, sleep before setting group membership
    time.sleep(1)
    if groups:
        chgroups(name, groups)
    return True
983715
def Initialize(config=None,
               external_hostname = None,
               admin_password = None,
               redownload_templates = False,
               repack_templates = True,
               token = None):
  """"""

  print("Checking write access on config %s" % config["Config.writeback"])
  if not os.access(config.parser.filename, os.W_OK):
    raise IOError("Config not writeable (need sudo?)")

  print("\nStep 0: Importing Configuration from previous installation.")
  options_imported = 0
  prev_config_file = config.Get("ConfigUpdater.old_config", default=None)
  if prev_config_file and os.access(prev_config_file, os.R_OK):
    print("Found config file %s." % prev_config_file)
    # pytype: disable=wrong-arg-count
    if builtins.input("Do you want to import this configuration? "
                      "[yN]: ").upper() == "Y":
      options_imported = ImportConfig(prev_config_file, config)
    # pytype: enable=wrong-arg-count
  else:
    print("No old config file found.")

  print("\nStep 1: Setting Basic Configuration Parameters")
  print("We are now going to configure the server using a bunch of questions.")
  ConfigureDatastore(config)
  ConfigureUrls(config, external_hostname=external_hostname)
  ConfigureEmails(config)

  print("\nStep 2: Key Generation")
  if config.Get("PrivateKeys.server_key", default=None):
    if options_imported > 0:
      print("Since you have imported keys from another installation in the "
            "last step,\nyou probably do not want to generate new keys now.")
    # pytype: disable=wrong-arg-count
    if (builtins.input("You already have keys in your config, do you want to"
                       " overwrite them? [yN]: ").upper() or "N") == "Y":
      config_updater_keys_util.GenerateKeys(config, overwrite_keys=True)
    # pytype: enable=wrong-arg-count
  else:
    config_updater_keys_util.GenerateKeys(config)

  FinalizeConfigInit(
      config,
      token,
      admin_password=admin_password,
      redownload_templates=redownload_templates,
      repack_templates=repack_templates,
      prompt=True)
458767
def create(self):
        """"""

        self.before_create()

        puts(green('Creating app context'))
        tdir = os.path.dirname(__file__)

        # Ensure the app context user exists
        user_ensure(self.user, home='/home/' + self.user)
        dir_ensure('/home/%s/.ssh' % self.user)

        t = '/home/%s/.ssh/authorized_keys'
        app_authorized_keys = t % env.user
        ctx_authorized_keys = t % self.user

        # Ensure the app user has the same authorized_keys as the admin user
        if file_exists(app_authorized_keys) and \
           not file_exists(ctx_authorized_keys):
            sudo('cp %s %s' % (app_authorized_keys, ctx_authorized_keys))
            file_attribs(ctx_authorized_keys, mode=755,
                         owner=self.user, group=self.user)

        # Actions to be performed with the app context user
        with settings(user=self.user):
            # Make sure the dot files exist
            # This is mostly necessary for virtualenvwrapper to work properly
            for f in ['bashrc', 'bash_profile', 'profile']:
                lfn = os.path.join(tdir, 'templates', '%s.tmpl' % f)
                contents = file_local_read(lfn) % self.__dict__
                rfn = '/home/%s/.%s' % (self.user, f)
                file_ensure(rfn, owner=self.user, group=self.user)
                file_update(rfn, lambda _: contents)

            # Make sure the sites folder exists
            dir_ensure('/home/%s/sites' % self.user)

            # Make sure the app's required folders exist
            for d in [self.root_dir, self.releases_dir, self.etc_dir,
                      self.log_dir, self.run_dir, self.shared_dir]:
                dir_ensure(d)

            # Create the virtualenv
            run('mkvirtualenv ' + self.name)

        self.after_create()
932825
def setup():
    """"""
    # Create the Wallace config file if it does not already exist.
    config_name = ".wallaceconfig"
    config_path = os.path.join(os.path.expanduser("~"), config_name)

    if os.path.isfile(config_path):
        log("Wallace config file already exists.", chevrons=False)

    else:
        log("Creating Wallace config file at ~/.wallaceconfig...",
            chevrons=False)
        wallace_module_path = os.path.dirname(os.path.realpath(__file__))
        src = os.path.join(wallace_module_path, "config", config_name)
        shutil.copyfile(src, config_path)
483157
def ensure_dir_exists(directory):
    ""
    if directory.startswith('gs://'):
        return
    if not os.path.exists(directory):
        dbg("Making dir {}".format(directory))
    os.makedirs(directory, exist_ok=True)
994807
def cli(ctx, hostname, username, password, config_dir, https):
    """"""
    ctx.is_root = True
    ctx.user_values_entered = False
    ctx.config_dir = os.path.abspath(os.path.expanduser(config_dir))
    ctx.config = load_config(ctx)
    ctx.hostname = hostname
    ctx.username = username
    ctx.password = password
    ctx.https = https

    # Creating the WVA object is deferred as some commands like clearconfig
    # should not require a username/password to perform them
    ctx.wva = None
763698
def _get_or_create_config(path, prompt=True):
    
    dirname = os.path.dirname(path)
    filename = os.path.basename(path)

    try:
        os.makedirs(dirname)
    except OSError:
        pass

    try:
        with open(path, 'r+') as f:
            if os.path.isfile(path):
                puts("{0} already exists, backing up".format(colored.green(path)))
                _backup(dirname, filename)
            return yaml.load(f)
    except IOError:
        return {}
570360
function create(options, cb) {

	options.force = (options.force) ? options.force : false;
	options.preserve = (options.preserve) ? options.preserve : true;
	options.password = getPwHash(options.password);  
	console.log('Gernerating directories with folling options:\n', options, '\n');
	if(options.test) {return;}
	//create directory
	if(options.force || !fs.existsSync(options.dest)) {
		wrench.mkdirSyncRecursive(options.dest);
		wrench.copyDirSyncRecursive(options.src, options.dest, { preserve: options.preserve }); 
	}
	if(options.files.length) {
		_.each(options.files, function(file) {
			fs.exists(path.join(options.dest,options.pwfile), function(exists) {
				if(!exists || options.force || file.force) {
					fs.writeFile(path.join(options.dest,strReplace(file.name, options)),  strReplace(file.data, options), function(err){
						if(err) {throw err;}
					});
				}
			});
		});
	}
	//Search and replace 
	replace(options.dest, {
		filters: ['index\.php$', '\.htaccess']
		, type: 'replace' 
		, values: [{
			user: options.user
			, root: options.root
			, project: options.project
			, title: options.title
			, userDir: options.userDir
			, pwfile: options.pwfile
		}]
	}, function(err, data) {
		if(cb) {
			cb(err, data);
			}
	});
}