Skip to content

Commit

Permalink
feat!: remove --file-name parameter for metadata and definition command
Browse files Browse the repository at this point in the history
  • Loading branch information
blackchoey committed May 17, 2024
1 parent dcd00c3 commit 5a573dc
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 132 deletions.
4 changes: 0 additions & 4 deletions src/apic-extension/azext_apic_extension/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,13 @@
from .custom import ImportSpecificationExtension
from .custom import ExportSpecificationExtension
from .custom import ExportMetadataSchemaExtension
from .custom import CreateMetadataSchemaExtension
from .custom import UpdateMetadataSchemaExtension


def load_custom_commands(self, _): # pylint: disable=unused-argument
with self.command_group('apic api definition') as g:
self.command_table['apic api definition import-specification'] = ImportSpecificationExtension(loader=self)
self.command_table['apic api definition export-specification'] = ExportSpecificationExtension(loader=self)
with self.command_group('apic metadata') as g:
self.command_table['apic metadata create'] = CreateMetadataSchemaExtension(loader=self)
self.command_table['apic metadata update'] = UpdateMetadataSchemaExtension(loader=self)
self.command_table['apic metadata export'] = ExportMetadataSchemaExtension(loader=self)
with self.command_group('apic api') as g:
g.custom_command("register", "register_apic", is_preview=True)
128 changes: 1 addition & 127 deletions src/apic-extension/azext_apic_extension/custom.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,58 +20,15 @@
from azure.cli.core.aaz._arg import AAZStrArg
from .command_patches import ImportAPIDefinitionExtension
from .command_patches import ExportAPIDefinitionExtension
from .command_patches import CreateMetadataExtension
from .command_patches import ExportMetadataExtension
from .aaz.latest.apic.metadata import Update as UpdateMetadataSchema

logger = get_logger(__name__)


class ImportSpecificationExtension(ImportAPIDefinitionExtension):
@classmethod
def _build_arguments_schema(cls, *args, **kwargs):
args_schema = super()._build_arguments_schema(*args, **kwargs)
args_schema.source_profile = AAZStrArg(
options=["--file-name"],
help='Name of the file from where to import the spec from.',
required=False,
registered=True
)
return args_schema

def pre_operations(self):
super().pre_operations()
args = self.ctx.args
data = None
value = None

# Load the JSON file
if args.source_profile:
with open(str(args.source_profile), 'rb') as f:
data = f.read()
result = chardet.detect(data)
encoding = result['encoding']

if str(args.source_profile).endswith('.yaml') or str(args.source_profile).endswith('.yml'):
with open(str(args.source_profile), 'r', encoding=encoding) as f:
content = f.read()
data = yaml.safe_load(content)
if data:
value = content

if (str(args.source_profile).endswith('.json')):
with open(str(args.source_profile), 'r', encoding=encoding) as f:
content = f.read()
data = json.loads(content)
if data:
value = content

# If any of the fields are None, get them from self.args
if value is None:
value = args.value

# Reassign the values to self.args
args.value = value

# Check the size of 'value' if format is inline and raise error if value is greater than 3 mb
if args.format == 'inline':
Expand Down Expand Up @@ -133,89 +90,6 @@ def writeResultsToFile(self, results, file_name):
else:
f.write(results)


class CreateMetadataSchemaExtension(CreateMetadataExtension):
@classmethod
def _build_arguments_schema(cls, *args, **kwargs):
args_schema = super()._build_arguments_schema(*args, **kwargs)
args_schema.source_profile = AAZStrArg(
options=["--file-name"],
help='Name of the file from that contains the metadata schema.',
required=False,
registered=True
)
return args_schema

def pre_operations(self):
args = self.ctx.args
data = None
value = args.schema

# Load the JSON file
if args.source_profile:
with open(str(args.source_profile), 'rb') as f:
data = f.read()
result = chardet.detect(data)
encoding = result['encoding']

if os.stat(str(args.source_profile)).st_size == 0:
raise ValueError('Metadtata schema file is empty. Please provide a valid metadata schema file.')

with open(str(args.source_profile), 'r', encoding=encoding) as f:
data = json.load(f)
if data:
value = json.dumps(data)

# If any of the fields are None, get them from self.args
if value is None:
logger.error('Please provide the schema to create the metadata schema'
'through --schema option or through --file-name option via a file.')

# Reassign the values to self.args
self.ctx.args.schema = value


class UpdateMetadataSchemaExtension(UpdateMetadataSchema):
@classmethod
def _build_arguments_schema(cls, *args, **kwargs):
args_schema = super()._build_arguments_schema(*args, **kwargs)
args_schema.source_profile = AAZStrArg(
options=["--file-name"],
help='Name of the file from that contains the metadata schema.',
required=False,
registered=True
)
return args_schema

def pre_operations(self):
args = self.ctx.args
data = None
value = args.schema

# Load the JSON file
if args.source_profile:
with open(str(args.source_profile), 'rb') as f:
rawdata = f.read()
result = chardet.detect(rawdata)
encoding = result['encoding']

if os.stat(str(args.source_profile)).st_size == 0:
raise ValueError('Metadtata schema file is empty. Please provide a valid metadata schema file.')

with open(str(args.source_profile), 'r', encoding=encoding) as f:
data = json.load(f)
if data:
value = json.dumps(data)

# If any of the fields are None, get them from self.args
if value is None:
logger.error('Please provide the schema to update the metadata schema '
'through --schema option or through --file-name option via a file.')

# Reassign the values to self.args
self.ctx.args.schema = value


class ExportMetadataSchemaExtension(ExportMetadataExtension):

@classmethod
Expand Down Expand Up @@ -435,7 +309,7 @@ def register_apic(cmd, api_location, resource_group, service_name, environment_n
'definition_id': extracted_definition_name,
'format': 'inline',
'specification': specification_details, # TODO write the correct spec object
'source_profile': api_location
'value': value
}

importAPISpecificationResults = ImportSpecificationExtension(cli_ctx=cmd.cli_ctx)(command_args=api_specification_args)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
from azure.cli.testsdk import ScenarioTest, ResourceGroupPreparer
from .utils import ApicServicePreparer, ApicApiPreparer, ApicVersionPreparer, ApicDefinitionPreparer

from knack.util import CLIError

class VersionCommandsTests(ScenarioTest):

@ResourceGroupPreparer(name_prefix="clirg", location='eastus', random_name_length=32)
Expand Down Expand Up @@ -123,4 +125,21 @@ def test_definition_import_inline(self):

assert exported_content == imported_content, "The exported content is not the same as the imported content."
finally:
os.remove(exported_file_path)
os.remove(exported_file_path)

@ResourceGroupPreparer(name_prefix="clirg", location='eastus', random_name_length=32)
@ApicServicePreparer()
@ApicApiPreparer()
@ApicVersionPreparer()
@ApicDefinitionPreparer()
def test_definition_import_large_value(self):
self.kwargs.update({
'specification': '{"name":"openapi","version":"3.0.0"}',
'file_name': "test_definition_import_large_value.txt"
})

with open(self.kwargs['file_name'], 'w') as file:
file.write('a' * 4 * 1024 * 1024) # generate a 4MB file

with self.assertRaisesRegexp(CLIError, 'The size of "value" is greater than 3 MB. Please use --format "link" to import the specification from a URL for size greater than 3 mb.') as cm:
self.cmd('az apic api definition import-specification -g {rg} -s {s} --api-id {api} --version-id {v} --definition-id {d} --format "inline" --specification \'{specification}\' --value "@{file_name}"')

0 comments on commit 5a573dc

Please sign in to comment.