Пример #1
0
        private static Command BuildExportCommand()
        {
            Command resolveModel = new Command("export")
            {
                CommonOptions.Dtmi,
                CommonOptions.Repo,
                CommonOptions.Output,
                CommonOptions.Silent,
                CommonOptions.ModelFile
            };

            resolveModel.Description = "Retrieve a model and its dependencies by dtmi or model file using the target repository for model resolution.";
            resolveModel.Handler     = CommandHandler.Create <string, string, IHost, string, bool, FileInfo>(async(dtmi, repository, host, output, silent, modelFile) =>
            {
                ILogger logger = GetLogger(host);
                OutputHeaders(logger);

                IDictionary <string, string> result;

                //check that we have either model file or dtmi
                if (string.IsNullOrWhiteSpace(dtmi) && modelFile == null)
                {
                    logger.LogError("Either --dtmi or --model-file must be specified!");
                    return(ReturnCodes.InvalidArguments);
                }

                Parsing parsing = new Parsing(repository, logger);
                try
                {
                    if (string.IsNullOrWhiteSpace(dtmi))
                    {
                        dtmi = parsing.GetRootDtmiFromFile(modelFile);
                    }

                    result = await parsing.GetResolver().ResolveAsync(dtmi);
                }
                catch (ResolverException resolverEx)
                {
                    logger.LogError(resolverEx.Message);
                    return(ReturnCodes.ResolutionError);
                }
                catch (KeyNotFoundException keyNotFoundEx)
                {
                    logger.LogError(keyNotFoundEx.Message);
                    return(ReturnCodes.ParserError);
                }

                List <string> resultList = result.Values.ToList();
                string normalizedList    = string.Join(',', resultList);
                string payload           = "[" + string.Join(',', normalizedList) + "]";

                using JsonDocument document = JsonDocument.Parse(payload, CommonOptions.DefaultJsonParseOptions);
                using MemoryStream stream   = new MemoryStream();
                await JsonSerializer.SerializeAsync(stream, document.RootElement, CommonOptions.DefaultJsonSerializerOptions);
                stream.Position = 0;
                using StreamReader streamReader = new StreamReader(stream);
                string jsonSerialized           = await streamReader.ReadToEndAsync();

                if (!silent)
                {
                    await Console.Out.WriteLineAsync(jsonSerialized);
                }

                if (!string.IsNullOrEmpty(output))
                {
                    logger.LogInformation($"Writing result to file '{output}'");
                    await File.WriteAllTextAsync(output, jsonSerialized, Encoding.UTF8);
                }

                return(ReturnCodes.Success);
            });

            return(resolveModel);
        }
Пример #2
0
        private static Command BuildImportModelCommand()
        {
            var modelFileOption = CommonOptions.ModelFile;

            modelFileOption.IsRequired = true; // Option is required for this command

            Command addModel = new Command("import")
            {
                modelFileOption,
                CommonOptions.LocalRepo
            };

            addModel.Description = "Adds a model to a local repository. " +
                                   "Validates Id's, dependencies and places model content in the proper location.";
            addModel.Handler = CommandHandler.Create <FileInfo, string, IHost>(async(modelFile, localRepository, host) =>
            {
                var returnCode = ReturnCodes.Success;
                ILogger logger = GetLogger(host);

                OutputHeaders(logger);

                if (localRepository == null)
                {
                    localRepository = Path.GetFullPath(".");
                }
                else if (Validations.IsRelativePath(localRepository))
                {
                    localRepository = Path.GetFullPath(localRepository);
                }

                DirectoryInfo repoDirInfo = new DirectoryInfo(localRepository);
                Parsing parsing           = new Parsing(repoDirInfo.FullName, logger);
                try
                {
                    var newModels = await ModelImporter.ImportModels(modelFile, repoDirInfo, logger);
                    foreach (var model in newModels)
                    {
                        var validationResult = await parsing.IsValidDtdlFileAsync(model, false);

                        if (!validationResult)
                        {
                            returnCode = ReturnCodes.ValidationError;
                        }
                    }
                }
                catch (ValidationException validationEx)
                {
                    logger.LogError(validationEx.Message);
                    return(ReturnCodes.ValidationError);
                }
                catch (IOException ioEx)
                {
                    logger.LogError(ioEx.Message);
                    return(ReturnCodes.ImportError);
                }

                return(returnCode);
            });

            return(addModel);
        }