Esempio n. 1
0
    def Run(self, args):
        """Run 'dns resource-record-sets edit'.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      The result of the edit operation, or None if it is cancelled.
    """
        dns = self.context['dns']
        project = properties.VALUES.core.project.Get(required=True)
        soa_rr_set = self.GetSoaResourceRecordSet(dns, project, args.zone)

        next_soa_rr_set = copy.copy(soa_rr_set)
        next_soa_rr_set['rrdatas'] = [
            self._BumpVersion(soa_rr_set['rrdatas'][0])
        ]

        changes = {}
        changes['deletions'] = [soa_rr_set]
        changes['additions'] = [next_soa_rr_set]

        try:
            new_change = edit.OnlineEdit(util.PrettyPrintString(changes))
        except edit.NoSaveException:
            new_change = None
        if new_change is not None:
            change = json.loads(new_change)
            request = dns.changes().create(project=project,
                                           managedZone=args.zone,
                                           body=change)
            return request.execute()

        return None
Esempio n. 2
0
    def EditResource(self, args, backend_service_ref, file_contents, holder,
                     modifiable_record, original_object, original_record):
        while True:
            try:
                file_contents = edit.OnlineEdit(file_contents)
            except edit.NoSaveException:
                raise calliope_exceptions.ToolException(
                    'Edit aborted by user.')
            try:
                resource_list = self._ProcessEditedResource(
                    holder, backend_service_ref, file_contents,
                    original_object, original_record, modifiable_record, args)
                break
            except (ValueError, yaml.YAMLParseError, messages.ValidationError,
                    calliope_exceptions.ToolException) as e:
                message = getattr(e, 'message', str(e))

                if isinstance(e, calliope_exceptions.ToolException):
                    problem_type = 'applying'
                else:
                    problem_type = 'parsing'

                message = ('There was a problem {0} your changes: {1}'.format(
                    problem_type, message))
                if not console_io.PromptContinue(
                        message=message,
                        prompt_string=
                        'Would you like to edit the resource again?'):
                    raise calliope_exceptions.ToolException(
                        'Edit aborted by user.')
        return resource_list
Esempio n. 3
0
    def EditResource(self, args, client, holder, original_object, url_map_ref):
        original_record = encoding.MessageToDict(original_object)

        # Selects only the fields that can be modified.
        field_selector = property_selector.PropertySelector(properties=[
            'defaultService',
            'description',
            'hostRules',
            'pathMatchers',
            'tests',
        ])
        modifiable_record = field_selector.Apply(original_record)

        buf = self.BuildFileContents(args, client, modifiable_record,
                                     original_record)
        file_contents = buf.getvalue()
        while True:
            try:
                file_contents = edit.OnlineEdit(file_contents)
            except edit.NoSaveException:
                raise exceptions.ToolException('Edit aborted by user.')
            try:
                resource_list = self._ProcessEditedResource(
                    holder, url_map_ref, file_contents, original_object,
                    original_record, modifiable_record, args)
                break
            except (ValueError, yaml.error.YAMLError, messages.ValidationError,
                    exceptions.ToolException) as e:
                if isinstance(e, ValueError):
                    message = e.message
                else:
                    message = str(e)

                if isinstance(e, exceptions.ToolException):
                    problem_type = 'applying'
                else:
                    problem_type = 'parsing'

                message = ('There was a problem {0} your changes: {1}'.format(
                    problem_type, message))
                if not console_io.PromptContinue(
                        message=message,
                        prompt_string=
                        'Would you like to edit the resource again?'):
                    raise exceptions.ToolException('Edit aborted by user.')
        return resource_list
Esempio n. 4
0
  def Run(self, args):
    self.ref = self.CreateReference(args)
    get_request = self.GetGetRequest(args)

    errors = []
    objects = list(request_helper.MakeRequests(
        requests=[get_request],
        http=self.http,
        batch_url=self.batch_url,
        errors=errors,
        custom_get_requests=None))
    if errors:
      utils.RaiseToolException(
          errors,
          error_message='Could not fetch resource:')

    self.original_object = objects[0]
    self.original_record = encoding.MessageToDict(self.original_object)

    # Selects only the fields that can be modified.
    field_selector = property_selector.PropertySelector(
        properties=self._resource_spec.editables)
    self.modifiable_record = field_selector.Apply(self.original_record)

    buf = cStringIO.StringIO()
    for line in _HELP.splitlines():
      buf.write('#')
      if line:
        buf.write(' ')
      buf.write(line)
      buf.write('\n')

    buf.write('\n')
    buf.write(_SerializeDict(self.modifiable_record,
                             args.format or BaseEdit.DEFAULT_FORMAT))
    buf.write('\n')

    example = _SerializeDict(
        encoding.MessageToDict(self.example_resource),
        args.format or BaseEdit.DEFAULT_FORMAT)
    _WriteResourceInCommentBlock(example, 'Example resource:', buf)

    buf.write('#\n')

    original = _SerializeDict(self.original_record,
                              args.format or BaseEdit.DEFAULT_FORMAT)
    _WriteResourceInCommentBlock(original, 'Original resource:', buf)

    file_contents = buf.getvalue()
    while True:
      file_contents = edit.OnlineEdit(file_contents)
      try:
        resources = self.ProcessEditedResource(file_contents, args)
        break
      except (ValueError, yaml.error.YAMLError,
              protorpc.messages.ValidationError,
              calliope_exceptions.ToolException) as e:
        if isinstance(e, ValueError):
          message = e.message
        else:
          message = str(e)

        if isinstance(e, calliope_exceptions.ToolException):
          problem_type = 'applying'
        else:
          problem_type = 'parsing'

        message = ('There was a problem {0} your changes: {1}'
                   .format(problem_type, message))
        if not console_io.PromptContinue(
            message=message,
            prompt_string='Would you like to edit the resource again?'):
          raise calliope_exceptions.ToolException('Edit aborted by user.')

    resources = lister.ProcessResults(
        resources=resources,
        field_selector=property_selector.PropertySelector(
            properties=None,
            transformations=self.transformations))
    for resource in resources:
      yield resource
Esempio n. 5
0
 def testLinuxOSEdit(self):
     self.platform_os_mock.return_value = platforms.OperatingSystem.LINUX
     self.os_stat_mock.side_effect = [0, 10]
     self.assertEqual('Example text', edit.OnlineEdit('Example text'))
Esempio n. 6
0
 def testWindowsOSEdit(self):
     self.platform_os_mock.return_value = platforms.OperatingSystem.WINDOWS
     tempfile.NamedTemporaryFile = functools.partial(
         tempfile.NamedTemporaryFile, delete=False)
     self.os_stat_mock.side_effect = [0, 10]
     self.assertEqual('Example text', edit.OnlineEdit('Example text'))
Esempio n. 7
0
 def testNoSaveException(self):
     self.platform_os_mock.return_value = platforms.OperatingSystem.LINUX
     with self.assertRaises(edit.NoSaveException):
         edit.OnlineEdit('Example text')
Esempio n. 8
0
 def testLinuxEditorException(self):
     self.platform_os_mock.return_value = platforms.OperatingSystem.LINUX
     self.check_call_mock.side_effect = subprocess.CalledProcessError(
         'unused returncode', 'unused cmd')
     with self.assertRaises(edit.EditorException):
         edit.OnlineEdit('Example text')