Load config info from environment variables.

 Supported environment variables:
 - INQ_GITHUB_TOKEN: a GitHub authentication token.
 - INQ_GITHUB_USERNAME: the GitHub username corresponding to the token.

 @return [Config] The resulting configuration.
324232
def load_env
      Inq::Text.puts "Using configuration from environment variables."

      gh_token = ENV["INQ_GITHUB_TOKEN"] || ENV["HOWIS_GITHUB_TOKEN"]
      gh_username = ENV["INQ_GITHUB_USERNAME"] || ENV["HOWIS_GITHUB_USERNAME"]

      raise "INQ_GITHUB_TOKEN environment variable is not set" \
        unless gh_token
      raise "INQ_GITHUB_USERNAME environment variable is not set" \
        unless gh_username

      load({
        "sources/github" => {
          "username" => gh_username,
          "token" => gh_token,
        },
      })
    end
177995
def permit_gitrepo(config_fpath, writeback=False):
    
    # Define search replace patterns
    username_regex = utool.named_field('username', utool.REGEX_VARNAME)
    username_repl = utool.backref_field('username')
    regexpat = r'https://github.com/' + username_regex + '/'
    replpat = r'git@github.com:' + username_repl + '/'
    # Read and replace
    lines = utool.read_from(config_fpath, aslines=True)
    newlines = utool.regex_replace_lines(lines, regexpat, replpat)
    # Writeback or print
    if not WRITEBACK:
        print(''.join(newlines))
    else:
        utool.write_to(config_fpath, newlines, aslines=True)
377703
function(env) {
	ApiRequest.call(this, env, null);
	this.queueKey = env.conf.wiki.apiURI;
	this.reqType = "Config Request";

	var metas = [ 'siteinfo' ];
	var siprops = [
		'namespaces',
		'namespacealiases',
		'magicwords',
		'functionhooks',
		'extensiontags',
		'general',
		'interwikimap',
		'languages',
		'languagevariants', // T153341
		'protocols',
		'specialpagealiases',
		'defaultoptions',
		'variables',
	];
	var apiargs = {
		format: 'json',
		// XXX: should use formatversion=2
		action: 'query',
		meta: metas.join('|'),
		siprop: siprops.join('|'),
		rawcontinue: 1,
	};

	this.requestOptions = {
		method: 'GET',
		followRedirect: true,
		uri: env.conf.wiki.apiURI,
		qs: apiargs,
		timeout: env.conf.parsoid.timeouts.mwApi.configInfo,
	};

	this.request(this.requestOptions);
}
832375
def get_config_var(self, path, env=None):
        '''
        
        '''
        if env is None:
            env = {}
        result = self.conf
        for e in path.split('.'):
            if e[0] == '$':
                try:
                    result = result[env[e[1:]]]
                except KeyError as ex:
                    try:
                        result = result['.default']
                    except KeyError:
                        raise ex
            else:
                result = result[e]
        return result
699515
def load_config(path=None):
    """"""
    # NOTE: Initially I wanted to inherit Path to encapsulate Git access
    # there but there's no easy way to subclass pathlib.Path :(
    head_sha = get_sha1_from("HEAD")
    revision = head_sha
    saved_config_path = load_val_from_git_cfg("config_path")
    if not path and saved_config_path is not None:
        path = saved_config_path

    if path is None:
        path = find_config(revision=revision)
    else:
        if ":" not in path:
            path = f"{head_sha}:{path}"

            revision, _col, _path = path.partition(":")
            if not revision:
                revision = head_sha

    config = DEFAULT_CONFIG

    if path is not None:
        config_text = from_git_rev_read(path)
        d = toml.loads(config_text)
        config = config.new_child(d)

    return path, config
986067
async function initRepo({
  repository,
  token,
  endpoint,
  forkMode,
  forkToken,
  gitPrivateKey,
  gitFs,
  localDir,
  includeForks,
}) {
  logger.debug(`initRepo("${repository}")`);
  const opts = hostRules.find({ platform: 'github' }, { token, endpoint });
  if (!opts.token) {
    throw new Error(`No token found for GitHub repository ${repository}`);
  }
  hostRules.update({ ...opts, platform: 'github', default: true });
  logger.info('Authenticated as user: ' + (await getRenovateUsername()));
  logger.info('Using renovate version: ' + global.renovateVersion);
  // config is used by the platform api itself, not necessary for the app layer to know
  cleanRepo();
  config.isGhe = endpoint && !endpoint.startsWith('https://api.github.com');
  config.localDir = localDir;
  config.platform = 'github';
  config.repository = repository;
  [config.repositoryOwner, config.repositoryName] = repository.split('/');
  config.gitPrivateKey = gitPrivateKey;
  // platformConfig is passed back to the app layer and contains info about the platform they require
  const platformConfig = {};
  let res;
  try {
    res = await get(`repos/${repository}`);
    logger.trace({ repositoryDetails: res.body }, 'Repository details');
    // istanbul ignore if
    if (res.body.fork && gitFs && !includeForks) {
      try {
        const renovateConfig = JSON.parse(
          Buffer.from(
            (await get(
              `repos/${config.repository}/contents/${defaultConfigFile}`
            )).body.content,
            'base64'
          ).toString()
        );
        if (!renovateConfig.includeForks) {
          throw new Error();
        }
      } catch (err) {
        throw new Error('fork');
      }
    }
    // istanbul ignore if
    if (res.body.full_name && res.body.full_name !== repository) {
      logger.info(
        { repository, this_repository: res.body.full_name },
        'Repository has been renamed'
      );
      throw new Error('renamed');
    }
    if (res.body.archived) {
      logger.info(
        'Repository is archived - throwing error to abort renovation'
      );
      throw new Error('archived');
    }
    platformConfig.privateRepo = res.body.private === true;
    platformConfig.isFork = res.body.fork === true;
    const owner = res.body.owner.login;
    logger.debug(`${repository} owner = ${owner}`);
    // Use default branch as PR target unless later overridden.
    config.defaultBranch = res.body.default_branch;
    // Base branch may be configured but defaultBranch is always fixed
    config.baseBranch = config.defaultBranch;
    logger.debug(`${repository} default branch = ${config.baseBranch}`);
    // GitHub allows administrators to block certain types of merge, so we need to check it
    if (res.body.allow_rebase_merge) {
      config.mergeMethod = 'rebase';
    } else if (res.body.allow_squash_merge) {
      config.mergeMethod = 'squash';
    } else if (res.body.allow_merge_commit) {
      config.mergeMethod = 'merge';
    } else {
      // This happens if we don't have Administrator read access, it is not a critical error
      logger.info('Could not find allowed merge methods for repo');
    }
  } catch (err) /* istanbul ignore next */ {
    logger.debug('Caught initRepo error');
    if (err.message === 'archived' || err.message === 'renamed') {
      throw err;
    }
    if (err.statusCode === 403) {
      throw new Error('forbidden');
    }
    if (err.statusCode === 404) {
      throw new Error('not-found');
    }
    if (err.message.startsWith('Repository access blocked')) {
      throw new Error('blocked');
    }
    if (err.message === 'fork') {
      throw err;
    }
    logger.info({ err }, 'Unknown GitHub initRepo error');
    throw err;
  }
  // This shouldn't be necessary, but occasional strange errors happened until it was added
  config.issueList = null;
  config.prList = null;
  config.openPrList = null;
  config.closedPrList = null;
  config.storage = new Storage();
  await config.storage.initRepo(config);
  if (forkMode) {
    logger.info('Bot is in forkMode');
    config.forkToken = forkToken;
    // Save parent SHA then delete
    const parentSha = await getBaseCommitSHA();
    config.baseCommitSHA = null;
    // save parent name then delete
    config.parentRepo = config.repository;
    config.repository = null;
    // Get list of existing repos
    const existingRepos = (await get('user/repos?per_page=100', {
      token: forkToken || opts.token,
      paginate: true,
    })).body.map(r => r.full_name);
    try {
      config.repository = (await get.post(`repos/${repository}/forks`, {
        token: forkToken || opts.token,
      })).body.full_name;
    } catch (err) /* istanbul ignore next */ {
      logger.info({ err }, 'Error forking repository');
      throw new Error('cannot-fork');
    }
    if (existingRepos.includes(config.repository)) {
      logger.info(
        { repository_fork: config.repository },
        'Found existing fork'
      );
      // Need to update base branch
      logger.debug(
        { baseBranch: config.baseBranch, parentSha },
        'Setting baseBranch ref in fork'
      );
      // This is a lovely "hack" by GitHub that lets us force update our fork's master
      // with the base commit from the parent repository
      try {
        await get.patch(
          `repos/${config.repository}/git/refs/heads/${config.baseBranch}`,
          {
            body: {
              sha: parentSha,
              force: true,
            },
            token: forkToken || opts.token,
          }
        );
      } catch (err) /* istanbul ignore next */ {
        if (
          err.statusCode === 422 &&
          err.message.startsWith('Object does not exist')
        ) {
          throw new Error('repository-changed');
        }
      }
    } else {
      logger.info({ repository_fork: config.repository }, 'Created fork');
      // Wait an arbitrary 30s to hopefully give GitHub enough time for forking to complete
      await delay(30000);
    }
    await config.storage.initRepo(config);
  }

  // istanbul ignore if
  if (gitFs) {
    logger.debug('Enabling Git FS');
    let { host } = URL.parse(opts.endpoint);
    if (host === 'api.github.com') {
      host = null;
    }
    host = host || 'github.com';
    const url = GitStorage.getUrl({
      gitFs,
      auth:
        config.forkToken ||
        (global.appMode ? `x-access-token:${opts.token}` : opts.token),
      hostname: host,
      repository: config.repository,
    });
    config.storage = new GitStorage();
    await config.storage.initRepo({
      ...config,
      url,
    });
  }

  return platformConfig;
}
493325
def config():
    
    cfg = ConfigParser()
    cfg.read(os.path.join(os.path.dirname(os.path.realpath(ips_vagrant.__file__)), 'config/ipsv.conf'))
    return cfg
859874
def load_config(filepath)
      return {} if filepath.nil? || !File.exist?(filepath)

      config_file = File.open(filepath).read

      # Replace environment variables
      config_file = parse_environment_variables(config_file)

      YAML.safe_load(config_file)
    end
847342
def collect_github_config():
	
	github_config = {}
	for field in ["user", "token"]:
		try:
			github_config[field] = subprocess.check_output(["git", "config", "github.{}".format(field)]).decode('utf-8').strip()
		except (OSError, subprocess.CalledProcessError):
			pass
	return github_config
1179911
def load_variables():
    """"""
    if (not os.environ.get("PYCONFLUENCE_TOKEN") or
            not os.environ.get("PYCONFLUENCE_USER") or
            not os.environ.get("PYCONFLUENCE_ORG")):
        print ("One or more pyconfluence environment variables are not set. "
               "See README for directions on how to resolve this.")
        sys.exit("Error")

    global token
    global user
    global base_url
    token = os.environ["PYCONFLUENCE_TOKEN"]
    user = os.environ["PYCONFLUENCE_USER"]
    base_url = ("https://" + os.environ["PYCONFLUENCE_ORG"] + ".atlassian"
                ".net/wiki/rest/api/content")
979178
def get_config(repo_root):
    """"""
    config = os.path.join(os.path.dirname(__file__), 'configs', 'config.yaml')

    if repo_root:
        repo_config = os.path.join(repo_root, '.gitlint.yaml')
        if os.path.exists(repo_config):
            config = repo_config

    with open(config) as f:
        # We have to read the content first as yaml hangs up when reading from
        # MockOpen
        content = f.read()
        # Yaml.load will return None when the input is empty.
        if not content:
            yaml_config = {}
        else:
            yaml_config = yaml.load(content)

    return linters.parse_yaml_config(yaml_config, repo_root)
340150
@Override
    public IssueServiceConfiguration getConfigurationByName(String name) {
        // Parsing of the name
        String[] tokens = StringUtils.split(name, GitHubGitConfiguration.CONFIGURATION_REPOSITORY_SEPARATOR);
        if (tokens == null || tokens.length != 2) {
            throw new IllegalStateException("The GitHub issue configuration identifier name is expected using configuration:repository as a format");
        }
        String configuration = tokens[0];
        String repository = tokens[1];
        return new GitHubIssueServiceConfiguration(
                configurationService.getConfiguration(configuration),
                repository
        );
    }
232686
def load_conf(configfile, config=None):
    """"""
    default_login = 'your-login-for-api-here'
    default_password = 'your-password-for-api-here'
    config = config or {}
    configfile = local.path(configfile)
    if not configfile.exists():
        configfile.dirname.mkdir()
    else:
        assert_secure_file(configfile)
    with secure_filestore(), cli.Config(configfile) as conf:
        config['url'] = conf.get('habitipy.url', 'https://habitica.com')
        config['login'] = conf.get('habitipy.login', default_login)
        config['password'] = conf.get('habitipy.password', default_password)
        if config['login'] == default_login or config['password'] == default_password:
            if cli.terminal.ask(
                    _("""Your creditentials are invalid. Do you want to enter them now?"""),
                    default=True):
                msg = _("""
                You can get your login information at
                https://habitica.com/#/options/settings/api
                Both your user id and API token should look like this:
                xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
                where 'x' is a number between 0-9 or a character a-f.
                """)
                print(dedent(msg))
                msg = _("""Please enter your login (user ID)""")
                config['login'] = cli.terminal.prompt(msg, validator=is_uuid)
                msg = _("""Please enter your password (API token)""")
                config['password'] = cli.terminal.prompt(msg, validator=is_uuid)
                conf.set('habitipy.login', config['login'])
                conf.set('habitipy.password', config['password'])
                print(dedent(_("""
                Your creditentials are securely stored in
                {configfile}
                You can edit that file later if you need.
                """)).format(configfile=configfile))
        config['show_numbers'] = conf.get('habitipy.show_numbers', 'y')
        config['show_numbers'] = config['show_numbers'] in YES_ANSWERS
        config['show_style'] = conf.get('habitipy.show_style', 'wide')
        if config['show_style'] not in CHECK_MARK_STYLES:
            config['show_style'] = 'wide'
    return config
618689
def fetch_github_token
      env_var = @options[:token].presence || ENV["CHANGELOG_GITHUB_TOKEN"]

      Helper.log.warn NO_TOKEN_PROVIDED unless env_var

      env_var
    end
504772
def get_aliyun_config(name, default=None):
    '''
    
    '''
    config = os.environ.get(name, getattr(settings, name, default))
    if config is not None:
        if isinstance(config, str):
            return config.strip()
        else:
            return config
    else:
        raise ImproperlyConfigured(
            'Can not get config for {} either in environment'
            'variable or in settings.py'.format(name))
398172
@Nonnull
    public static GitHubPluginConfig configuration() {
        return defaultIfNull(
                GitHubPluginConfig.all().get(GitHubPluginConfig.class),
                GitHubPluginConfig.EMPTY_CONFIG
        );
    }
1363213
def _github_store_authorization(cls, user, auth):
        
        ClHelper.run_command("git config --global github.token.{login} {token}".format(
            login=user.login, token=auth.token), log_secret=True)
        ClHelper.run_command("git config --global github.user.{login} {login}".format(
            login=user.login))