Ejemplo n.º 1
0
    def _GetMetaPropertiesToDisplay(args):
        """List available regular property-like settings."""

        # Simplifed control flow because there's only one meta property.
        # It's not a good idea to generalize because we can't really
        # test with just a single metaproperty choice.

        meta_property_requested = List._PositionalRequestsMetaProperties(args)

        # User explicitly requested a regular property
        if args.property and not meta_property_requested:
            return {}

        active_config = named_configs.GetNameOfActiveNamedConfig()
        active_config_as_property = {'meta': {'active_config': active_config}}

        # User wants to see meta/active_config
        if List._PositionalRequestsMetaProperties(args) or args.all:
            return active_config_as_property

        # Show meta/active config iff set (i.e. non-None)
        if active_config:
            return active_config_as_property

        return {}
Ejemplo n.º 2
0
def _GetToolEnv(env=None):
    """Generate the environment that should be used for the subprocess.

  Args:
    env: {str, str}, An existing environment to augment.  If None, the current
      environment will be cloned and used as the base for the subprocess.

  Returns:
    The modified env.
  """
    if env is None:
        env = dict(os.environ)
    env['CLOUDSDK_WRAPPER'] = '1'

    # Flags can set properties which override the properties file and the existing
    # env vars.  We need to propagate them to children processes through the
    # environment so that those commands will use the same settings.
    for s in properties.VALUES:
        for p in s:
            _AddOrRemoveVar(env, p.EnvironmentName(),
                            p.Get(required=False, validate=False))

    # Configuration needs to be handled separately because it's not a real
    # property (although it behaves like one).
    _AddOrRemoveVar(env, config.CLOUDSDK_ACTIVE_CONFIG_NAME,
                    named_configs.GetNameOfActiveNamedConfig())

    return env
 def __init__(self):
   self.paths = config.Paths()
   self.active_config_name = named_configs.GetNameOfActiveNamedConfig()
   if self.active_config_name is not None:
     self.active_config_path = named_configs.GetFileForActiveNamedConfig()
   self.account = properties.VALUES.core.account.Get(validate=False)
   self.project = properties.VALUES.core.project.Get(validate=False)
   self.properties = properties.VALUES.AllValues()
  def Run(self, args):
    if args.all and args.property:
      raise BadConfigListInvocation('`gcloud config list` cannot take both '
                                    'a property name and the `--all` flag.')

    config_name = named_configs.GetNameOfActiveNamedConfig()
    if config_name is None:
      config_name = named_configs.RESERVED_NAMED_CONFIG_NAME_NONE
    log.status.write('Your active configuration is: [{0}]\n\n'.format(
        config_name))
    return self._GetPropertiesToDisplay(args)
Ejemplo n.º 5
0
 def __init__(self):
     cfg_paths = config.Paths()
     self.paths = {
         'installation_properties_path':
         cfg_paths.installation_properties_path,
         'global_config_dir': cfg_paths.global_config_dir,
     }
     self.active_config_name = named_configs.GetNameOfActiveNamedConfig()
     if self.active_config_name is not None:
         self.paths['active_config_path'] = (
             named_configs.GetFileForActiveNamedConfig())
     else:
         self.paths['user_properties_path'] = cfg_paths.user_properties_path
     self.account = properties.VALUES.core.account.Get(validate=False)
     self.project = properties.VALUES.core.project.Get(validate=False)
     self.properties = properties.VALUES.AllValues()
Ejemplo n.º 6
0
  def Run(self, args):
    fname = named_configs.GetPathForConfigName(args.configuration_name)

    if not named_configs.IsPathReadable(fname):
      raise named_configs.NamedConfigLoadError(
          'Reading named configuration [{0}] failed because [{1}] cannot '
          'be read.'.format(args.configuration_name, fname))

    return {
        'name': args.configuration_name,
        'is_active': (args.configuration_name ==
                      named_configs.GetNameOfActiveNamedConfig()),
        'properties': properties.VALUES.AllValues(
            list_unset=args.all,
            properties_file=properties.PropertiesFile([fname]),
            only_file_contents=True),
    }
  def Run(self, args):
    # Fail the delete operation when we're attempting to delete the
    # active config.
    current_config = named_configs.GetNameOfActiveNamedConfig()
    if current_config in args.configuration_names:
      raise named_configs.NamedConfigWriteError(
          'Deleting named configuration failed because configuration '
          '[{0}] is set as active.  Use `gcloud config configurations '
          'activate` to change the active configuration.'.format(
              current_config))

    printer = console_io.ListPrinter(
        'The following configurations will be deleted:')
    printer.Print(args.configuration_names, output_stream=log.status)
    console_io.PromptContinue(default=True, cancel_on_no=True)

    for configuration_name in args.configuration_names:
      named_configs.DeleteNamedConfig(configuration_name)
      log.DeletedResource(configuration_name)
Ejemplo n.º 8
0
def PersistProperty(prop, value, scope=None, properties_file=None):
    """Sets the given property in the properties file.

  This function should not generally be used as part of normal program
  execution.  The property files are user editable config files that they should
  control.  This is mostly for initial setup of properties that get set during
  SDK installation.

  Args:
    prop: properties.Property, The property to set.
    value: str, The value to set for the property. If None, the property is
      removed.
    scope: Scope, The config location to set the property in.  If given, only
      this location will be udpated and it is an error if that location does
      not exist.  If not given, it will attempt to update the property in the
      first of the following places that exists:
        - the workspace config
        - the active named config
        - user level config
      It will never fall back to installation properties; you must
      use that scope explicitly to set that value.
    properties_file: str, Path to an explicit properties file to use (instead of
      one of the known locations).  It is an error to specify a scope and an
      explicit file.

  Raises:
    ValueError: If you give both a scope and a properties file.
    MissingConfigLocationError: If there is not file for the given scope.
    ReadOnlyNamedConfigNotSettableError: If the user is attempting to set
      a property in a read-only configuration.
    InternalError: If there's a programming error.
  """
    prop.Validate(value)
    if scope and properties_file:
        raise ValueError(
            'You cannot provide both a scope and a specific properties'
            ' file.')
    if not properties_file:
        if scope:
            if scope == Scope.INSTALLATION:
                config.EnsureSDKWriteAccess()
            properties_file = scope.get_file()
            if not properties_file:
                raise MissingConfigLocationError(scope)
        else:
            properties_file = Scope.WORKSPACE.get_file()
            if not properties_file:
                properties_file = named_configs.GetEffectiveNamedConfigFile()
                if properties_file is None:
                    # Should be dead code.
                    raise exceptions.InternalError(
                        'Unexpected None properties file.')
                if properties_file == os.path.devnull:
                    # Refuse to write and fail with an informative error
                    # TODO(b/22817095) Simplify control flow and update
                    # messaging when moving to automatic upgrade scenario
                    # on all release tracks.
                    if (named_configs.GetNameOfActiveNamedConfig() ==
                            named_configs.RESERVED_NAMED_CONFIG_NAME_NONE):
                        raise ReadOnlyNamedConfigNotSettableError(
                            named_configs.RESERVED_NAMED_CONFIG_NAME_NONE)
                    if not Scope.USER.get_file():
                        raise MissingConfigLocationError(Scope.USER)

    parsed_config = ConfigParser.ConfigParser()
    parsed_config.read(properties_file)

    if not parsed_config.has_section(prop.section):
        if value is None:
            return
        parsed_config.add_section(prop.section)

    if value is None:
        parsed_config.remove_option(prop.section, prop.name)
    else:
        parsed_config.set(prop.section, prop.name, str(value))

    properties_dir, unused_name = os.path.split(properties_file)
    files.MakeDir(properties_dir)
    with open(properties_file, 'w') as fp:
        parsed_config.write(fp)

    PropertiesFile.Invalidate()