Example #1
0
        public IExpression Parse(Parser parser, Token token)
        {
            var iterator = parser.ParseExpression(1);

            IteratorExpression iteratorExpr = null;
            string             listName     = null;

            if (iterator is IteratorExpression)
            {
                iteratorExpr = (IteratorExpression)iterator;
            }

            else if (iterator is IdentifierExpression)
            {
                listName = ((IdentifierExpression)iterator).Value;
            }

            else
            {
                ErrorManager.CreateError("You can only iterate over a list, str literal or iterator expression!", ErrorType.Error, token.Line, token.Column);
                return(null);
            }

            var block = parser.ParseExpression(1);

            if (!(block is BlockExpression))
            {
                ErrorManager.CreateError("For expression needs a block!", ErrorType.Error, token.Line, token.Column);
                return(null);
            }

            return(new ForExpression(token.Line, token.Column, iteratorExpr, listName, (BlockExpression)block));
        }
Example #2
0
        /// <summary>
        /// Build composite types from definitions
        /// </summary>
        public virtual void BuildCompositeTypes()
        {
            // Load any external references
            foreach (var reference in ServiceDefinition.ExternalReferences)
            {
                string[] splitReference = reference.Split(new[] { '#' }, StringSplitOptions.RemoveEmptyEntries);
                Debug.Assert(splitReference.Length == 2);
                string            filePath           = splitReference[0];
                string            externalDefinition = Settings.FileSystem.ReadFileAsText(filePath);
                ServiceDefinition external           = SwaggerParser.Parse(externalDefinition);
                external.Definitions.ForEach(d => ServiceDefinition.Definitions[d.Key] = d.Value);
            }

            // Build service types and validate allOf
            if (ServiceDefinition.Definitions != null)
            {
                foreach (var schemaName in ServiceDefinition.Definitions.Keys.ToArray())
                {
                    var schema = ServiceDefinition.Definitions[schemaName];
                    schema.GetBuilder(this).BuildServiceType(schemaName);

                    Resolver.ExpandAllOf(schema);
                    var parent = string.IsNullOrEmpty(schema.Extends.StripDefinitionPath())
                        ? null
                        : ServiceDefinition.Definitions[schema.Extends.StripDefinitionPath()];

                    if (parent != null &&
                        !AncestorsHaveProperties(parent.Properties, parent.Extends.StripDefinitionPath()))
                    {
                        throw ErrorManager.CreateError(Resources.InvalidAncestors, schemaName);
                    }
                }
            }
        }
        public IExpression Parse(Parser parser, Token token, IExpression left)
        {
            if (!(left is IdentifierExpression))
            {
                ErrorManager.CreateError("Explicit variable declaration syntax: name : type = value", ErrorType.Error, token.Line, token.Column);
                return(null);
            }

            var value = parser.ParseExpression(GetPrecedence() - 1);

            SailType type = SailType.UNKNOWN;

            if (value is BoolLiteralExpression || value is StringLiteralExpression || value is FloatLiteralExpression || value is IntLiteralExpression)
            {
                type = TypeResolver.ToSailType(value as ILiteralExpression);
            }

            else if (value is FunctionCallExpression)
            {
                type = SailType.UNKNOWN;
            }

            else if (value is ComparisonExpression)
            {
                type = SailType.BOOL;
            }

            else
            {
                throw new Exception("Incorrect explicit variable declaration syntax!");
            }

            return(new AssignmentExpression(token.Line, token.Column, left, value, type));
        }
        /// <summary>
        /// Gets the code generator specified in the provided Settings.
        /// </summary>
        /// <param name="settings">The code generation settings</param>
        /// <returns>Code generator specified in Settings.CodeGenerator</returns>
        public static CodeGenerator GetCodeGenerator(Settings settings)
        {
            Logger.LogInfo(Resources.InitializingCodeGenerator);
            if (settings == null || string.IsNullOrEmpty(settings.CodeGenerator))
            {
                throw new ArgumentNullException("settings");
            }

            CodeGenerator codeGenerator = null;

            string configurationFile = GetConfigurationFileContent(settings);

            if (configurationFile != null)
            {
                try
                {
                    var config = JsonConvert.DeserializeObject <AutoRestConfiguration>(configurationFile);
                    codeGenerator = LoadTypeFromAssembly <CodeGenerator>(config.CodeGenerators, settings.CodeGenerator,
                                                                         settings);
                }
                catch (Exception ex)
                {
                    throw ErrorManager.CreateError(ex, Resources.ErrorParsingConfig);
                }
            }
            else
            {
                throw ErrorManager.CreateError(Resources.ConfigurationFileNotFound);
            }
            Logger.LogInfo(Resources.GeneratorInitialized,
                           settings.CodeGenerator,
                           codeGenerator.GetType().Assembly.GetName().Version);
            return(codeGenerator);
        }
Example #5
0
        public override IEnumerable <LogMessage> Compare()
        {
            var settings = Settings.Instance;

            Logger.Instance.Log(Category.Info, Resources.ParsingSwagger);
            if (string.IsNullOrWhiteSpace(Settings.Input) || string.IsNullOrWhiteSpace(Settings.Previous))
            {
                throw ErrorManager.CreateError(Resources.InputRequired);
            }

            var oldDefintion = SwaggerParser.Load(settings.Previous, settings.FileSystemInput);
            var newDefintion = SwaggerParser.Load(settings.Input, settings.FileSystemInput);

            var context = new ComparisonContext(oldDefintion, newDefintion);

            // Look for semantic errors and warnings in the new document.
            var validator   = new RecursiveObjectValidator(PropertyNameResolver.JsonName);
            var LogMessages = validator.GetValidationExceptions(newDefintion.FilePath, newDefintion, new ServiceDefinitionMetadata
            {
                ServiceDefinitionDocumentType = ServiceDefinitionDocumentType.ARM,
                MergeState = ServiceDefinitionDocumentState.Composed
            }).ToList();

            // Only compare versions if the new version is correct.
            var comparisonMessages =
                !LogMessages.Any(m => m.Severity > Category.Error) ?
                newDefintion.Compare(context, oldDefintion) :
                Enumerable.Empty <ComparisonMessage>();

            return(LogMessages
                   .Select(msg => new ComparisonMessage(new MessageTemplate {
                Id = 0, Message = msg.Message
            }, msg.Path, msg.Severity))
                   .Concat(comparisonMessages));
        }
Example #6
0
        public static ServiceDefinition Parse(string swaggerDocument)
        {
            try
            {
                swaggerDocument = swaggerDocument.EnsureYamlIsJson();
                var settings = new JsonSerializerSettings
                {
                    TypeNameHandling         = TypeNameHandling.None,
                    MetadataPropertyHandling = MetadataPropertyHandling.Ignore
                };
                settings.Converters.Add(new ResponseRefConverter(swaggerDocument));
                settings.Converters.Add(new PathItemRefConverter(swaggerDocument));
                settings.Converters.Add(new PathLevelParameterConverter(swaggerDocument));
                settings.Converters.Add(new SchemaRequiredItemConverter());
                var swaggerService = JsonConvert.DeserializeObject <ServiceDefinition>(swaggerDocument, settings);

                // Extract all external references
                JObject jObject = JObject.Parse(swaggerDocument);
                foreach (JValue value in jObject.SelectTokens("$..$ref"))
                {
                    var path = (string)value;
                    if (path != null && path.Split(new[] { '#' }, StringSplitOptions.RemoveEmptyEntries).Length == 2)
                    {
                        swaggerService.ExternalReferences.Add(path);
                    }
                }

                return(swaggerService);
            }
            catch (JsonException ex)
            {
                throw ErrorManager.CreateError(string.Format(CultureInfo.InvariantCulture, "{0}. {1}",
                                                             Resources.ErrorParsingSpec, ex.Message), ex);
            }
        }
Example #7
0
        // identifier : type = value [as type];
        public IExpression Parse(Parser parser, Token token, IExpression left)
        {
            var type = parser.ParseExpression(GetPrecedence() - 1);

            if (!(type is TypeNameExpression))
            {
                ErrorManager.CreateError("Variable name must be a valid identifier!", ErrorType.Error, token.Line, token.Column);
                return(null);
            }

            var resolved = TypeResolver.ToSailType(type as TypeNameExpression);

            var equals = parser.TokenStream.PeekAny(TokenType.ASSIGNMENT);

            if (!equals)
            {
                return(new VarDeclarationNoAssignExpression(token.Line, token.Column, (left as IdentifierExpression).Value, resolved));
            }

            // Skip equals
            parser.TokenStream.Read();

            var value = parser.TokenStream.Peek();

            if (value == null)
            {
                ErrorManager.CreateError("Expected value on variable declaration!", ErrorType.Error, token.Line, token.Column);
                return(null);
            }

            var valueExpr   = parser.ParseExpression(GetPrecedence());
            var typeOfValue = TypeResolver.ToSailType(valueExpr as ILiteralExpression);

            // DIRTY HACK
            if (!(valueExpr is FunctionCallExpression || valueExpr is ComparisonExpression))
            {
                if (typeOfValue != resolved)
                {
                    ErrorManager.CreateError("Type mismatch! Expecting " + resolved + " but got " + typeOfValue, ErrorType.Error, token.Line, token.Column);
                    return(null);
                }
            }

            // Unfinished casting support :3
            bool cast = parser.TokenStream.PeekAll(TokenType.AS);

            if (cast)
            {
                parser.TokenStream.Read();

                var castType = parser.ParseExpression(1);
                if (castType != null)
                {
                    var castTypeExpr = TypeResolver.ToSailType(castType as TypeNameExpression);
                    resolved = castTypeExpr;
                }
            }

            return(new AssignmentExpression(token.Line, token.Column, left, valueExpr, resolved, resolved));
        }
        public static ServiceDefinition Parse(string swaggerDocument)
        {
            try
            {
                swaggerDocument = swaggerDocument.EnsureYamlIsJson();
                var settings = new JsonSerializerSettings
                {
                    TypeNameHandling         = TypeNameHandling.None,
                    MetadataPropertyHandling = MetadataPropertyHandling.Ignore
                };
                settings.Converters.Add(new ResponseRefConverter(swaggerDocument));
                settings.Converters.Add(new PathItemRefConverter(swaggerDocument));
                settings.Converters.Add(new PathLevelParameterConverter(swaggerDocument));
                var swaggerService = JsonConvert.DeserializeObject <ServiceDefinition>(swaggerDocument, settings);

                // for parameterized host, will be made available via JsonRpc accessible state in the future
                if (swaggerService.Servers == null || swaggerService.Servers.Count == 0)
                {
                    swaggerService.Servers = new List <Server>
                    {
                        new Server
                        {
                            Url = "/"
                        }
                    };
                }
                return(swaggerService);
            }
            catch (JsonException ex)
            {
                throw ErrorManager.CreateError("{0}. {1}\n{2}", Resources.ErrorParsingSpec, ex.Message, swaggerDocument);
            }
        }
Example #9
0
        public override IEnumerable <ComparisonMessage> Compare()
        {
            Logger.LogInfo(Resources.ParsingSwagger);
            if (string.IsNullOrWhiteSpace(Settings.Input) || string.IsNullOrWhiteSpace(Settings.Previous))
            {
                throw ErrorManager.CreateError(Resources.InputRequired);
            }

            var oldDefintion = SwaggerParser.Load(Settings.Previous, Settings.FileSystem);
            var newDefintion = SwaggerParser.Load(Settings.Input, Settings.FileSystem);

            var context = new ComparisonContext(oldDefintion, newDefintion);

            // Look for semantic errors and warnings in the new document.
            var validator          = new RecursiveObjectValidator(PropertyNameResolver.JsonName);
            var validationMessages = validator.GetValidationExceptions(newDefintion).ToList();

            // Only compare versions if the new version is correct.
            var comparisonMessages =
                !validationMessages.Any(m => m.Severity > LogEntrySeverity.Error) ?
                newDefintion.Compare(context, oldDefintion) :
                Enumerable.Empty <ComparisonMessage>();

            return(validationMessages
                   .Select(msg =>
                           new ComparisonMessage(new MessageTemplate {
                Id = 0, Message = msg.Message
            }, string.Join("/", msg.Path), msg.Severity))
                   .Concat(comparisonMessages));
        }
Example #10
0
        public IExpression Parse(Parser parser, Token token)
        {
            var obj = parser.ParseExpression(1);

            string variableName = null;
            object value        = null;

            if (obj is IdentifierExpression)
            {
                variableName = ((IdentifierExpression)obj).Value;
            }

            else if (obj is ILiteralExpression)
            {
                value = ((ILiteralExpression)obj).GetValue();
            }

            else
            {
                ErrorManager.CreateError("Can only find types of variables and literals!", ErrorType.Error, token.Line, token.Column);
                return(null);
            }

            return(new TypeOfExpression(token.Line, token.Column, variableName, value));
        }
Example #11
0
        /// <summary>
        /// Generates client using provided settings.
        /// </summary>
        /// <param name="settings">Code generator settings.</param>
        public static void Generate(Settings settings)
        {
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }
            Logger.Entries.Clear();
            Logger.LogInfo(Resources.AutoRestCore, Version);
            CodeGenerator codeGenerator = ExtensionsLoader.GetCodeGenerator(settings);
            Modeler       modeler       = ExtensionsLoader.GetModeler(settings);

            settings.Validate();
            ServiceClient serviceClient;

            try
            {
                serviceClient = modeler.Build();
            }
            catch (Exception exception)
            {
                throw ErrorManager.CreateError(exception, Resources.ErrorGeneratingClientModel, exception.Message);
            }
            try
            {
                codeGenerator.NormalizeClientModel(serviceClient);
                codeGenerator.Generate(serviceClient).GetAwaiter().GetResult();
            }
            catch (Exception exception)
            {
                throw ErrorManager.CreateError(exception, Resources.ErrorSavingGeneratedCode, exception.Message);
            }
        }
Example #12
0
        /// <summary>
        /// Initialize the base service and populate global service properties
        /// </summary>
        /// <returns>The base ServiceModel Service</returns>
        public virtual void InitializeClientModel()
        {
            if (string.IsNullOrEmpty(ServiceDefinition.Swagger))
            {
                throw ErrorManager.CreateError(Resources.UnknownSwaggerVersion);
            }

            if (ServiceDefinition.Info == null)
            {
                throw ErrorManager.CreateError(Resources.InfoSectionMissing);
            }

            CodeModel = New <CodeModel>();

            if (string.IsNullOrWhiteSpace(Settings.ClientName) && ServiceDefinition.Info.Title == null)
            {
                throw ErrorManager.CreateError(Resources.TitleMissing);
            }

            CodeModel.Name = ServiceDefinition.Info.Title?.Replace(" ", "");

            CodeModel.Namespace     = Settings.Namespace;
            CodeModel.ModelsName    = Settings.ModelsName;
            CodeModel.ApiVersion    = ServiceDefinition.Info.Version;
            CodeModel.Documentation = ServiceDefinition.Info.Description;
            CodeModel.BaseUrl       = string.Format(CultureInfo.InvariantCulture, "{0}://{1}{2}",
                                                    ServiceDefinition.Schemes[0].ToString().ToLower(),
                                                    ServiceDefinition.Host, ServiceDefinition.BasePath);

            // Copy extensions
            ServiceDefinition.Extensions.ForEach(extention => CodeModel.Extensions.AddOrSet(extention.Key, extention.Value));
        }
Example #13
0
        public IExpression Parse(Parser parser, Token token)
        {
            var condition = parser.ParseExpression(1);

            var ifBlock = parser.ParseExpression(1);

            if (ifBlock == null)
            {
                ErrorManager.CreateError("If statement is missing a body! ({ ... })", ErrorType.Error, token.Line, token.Column);
                return(null);
            }

            var elseIfBlocks = new List <ElseIfExpression>();

            if (parser.TokenStream.Peek().Type == TokenType.ELSEIF)
            {
                while (parser.TokenStream.Peek().Type == TokenType.ELSEIF)
                {
                    var elseIfExpr = parser.ParseExpression(1);

                    elseIfBlocks.Add((ElseIfExpression)elseIfExpr);
                }
            }

            ElseExpression elseExpr = null;

            if (parser.TokenStream.Peek().Type == TokenType.ELSE)
            {
                elseExpr = parser.ParseExpression(1) as ElseExpression;
            }

            return(new IfExpression(token.Line, token.Column, (BlockExpression)ifBlock, condition, elseIfBlocks, elseExpr));
        }
Example #14
0
        public void Visit(BlockExpression block)
        {
            if (block.Owner != null)
            {
                if (_functionVariables.Count != block.Owner.Params.Count)
                {
                    ErrorManager.CreateError("Wrong amount of arguments passed to function!", ErrorType.Error, block.Line, block.Column);
                    return;
                }

                for (int i = block.Owner.Params.Count - 1; i >= 0; i--)
                {
                    var param   = _functionVariables.Pop();
                    var current = block.Owner.Params[i];

                    if (current.Type != param.Type)
                    {
                        ErrorManager.CreateError("Type mismatch in function! Expected " + block.Owner.Params[i].Type + " but got " + param.Type, ErrorType.Error, block.Line, block.Column);
                        return;
                    }

                    _variables.Add(new SailObject(current.Name, param.Value, param.Type));
                }
            }

            foreach (var ex in block.Expressions)
            {
                Visit(ex);
            }
        }
Example #15
0
        public static ServiceDefinition Parse(string swaggerDocument)
        {
            try
            {
                swaggerDocument = Normalize(swaggerDocument);
                var settings = new JsonSerializerSettings
                {
                    TypeNameHandling         = TypeNameHandling.None,
                    MetadataPropertyHandling = MetadataPropertyHandling.Ignore
                };
                settings.Converters.Add(new ResponseRefConverter(swaggerDocument));
                settings.Converters.Add(new PathItemRefConverter(swaggerDocument));
                settings.Converters.Add(new PathLevelParameterConverter(swaggerDocument));
                settings.Converters.Add(new SchemaRequiredItemConverter());
                settings.Converters.Add(new SecurityDefinitionConverter());
                var swaggerService = JsonConvert.DeserializeObject <ServiceDefinition>(swaggerDocument, settings);

                // for parameterized host, will be made available via JsonRpc accessible state in the future
                if (swaggerService.Schemes == null || swaggerService.Schemes.Count != 1)
                {
                    swaggerService.Schemes = new List <TransferProtocolScheme> {
                        TransferProtocolScheme.Http
                    };
                }
                if (string.IsNullOrEmpty(swaggerService.Host))
                {
                    swaggerService.Host = "localhost";
                }
                return(swaggerService);
            }
            catch (JsonException ex)
            {
                throw ErrorManager.CreateError("{0}. {1}\n{2}", Resources.ErrorParsingSpec, ex.Message, swaggerDocument);
            }
        }
        /// <summary>
        /// Initialize the base service and populate global service properties
        /// </summary>
        /// <returns>The base ServiceModel Service</returns>
        private void InitializeClientModel()
        {
            if (ServiceDefinition.Info == null)
            {
                throw ErrorManager.CreateError(Resources.InfoSectionMissing);
            }

            CodeModel = New <CodeModel>();

            if (string.IsNullOrWhiteSpace(settings.ClientName) && ServiceDefinition.Info.Title == null)
            {
                throw ErrorManager.CreateError(Resources.TitleMissing);
            }

            CodeModel.Name = ServiceDefinition.Info.Title?.Replace(" ", "");

            CodeModel.Namespace  = settings.Namespace;
            CodeModel.ModelsName = settings.ModelsName;
            CodeModel.ApiVersion = ServiceDefinition.Info.Version == "" // since info.version is required according to spec, swagger2openapi sets it to "" if missing
                ? null                                                  // ...but that mocks with our multi-api-version treatment of inlining the api-version
                : ServiceDefinition.Info.Version;
            CodeModel.Documentation = ServiceDefinition.Info.Description;
            CodeModel.BaseUrl       = ServiceDefinition.Servers.FirstOrDefault()?.Url?.TrimEnd('/');
            if (string.IsNullOrEmpty(CodeModel.BaseUrl))
            {
                CodeModel.BaseUrl = "http://localhost";
            }

            // Copy extensions
            ServiceDefinition.Info?.CodeGenerationSettings?.Extensions.ForEach(extention => CodeModel.CodeGenExtensions.AddOrSet(extention.Key, extention.Value));
            ServiceDefinition.Extensions.ForEach(extention => CodeModel.Extensions.AddOrSet(extention.Key, extention.Value));
        }
        /// <summary>
        /// Build composite types from definitions
        /// </summary>
        public virtual void BuildCompositeTypes()
        {
            var schemas = ServiceDefinition.Components.Schemas;

            // Build service types and validate allOf
            if (schemas != null)
            {
                foreach (var schemaName in schemas.Keys.ToArray())
                {
                    var schema = schemas[schemaName];
                    schema.GetBuilder(this).BuildServiceType(schemaName, false);

                    Resolver.ExpandAllOf(schema);
                    var parent = string.IsNullOrEmpty(schema.Extends.StripComponentsSchemaPath())
                        ? null
                        : schemas[schema.Extends.StripComponentsSchemaPath()];

                    if (parent != null &&
                        !AncestorsHaveProperties(parent.Properties, parent.Extends) &&
                        !GenerateEmptyClasses)
                    {
                        throw ErrorManager.CreateError(Resources.InvalidAncestors, schemaName);
                    }
                }
            }
        }
Example #18
0
        /// <summary>
        /// Gets the modeler specified in the provided Settings.
        /// </summary>
        /// <param name="settings">The code generation settings</param>
        /// <returns>Modeler specified in Settings.Modeler</returns>
        public static Modeler GetModeler(Settings settings)
        {
            Logger.LogInfo(Resources.ModelerInitialized);
            if (settings == null || string.IsNullOrEmpty(settings.Modeler))
            {
                throw new ArgumentNullException("settings", "settings or settings.Modeler cannot be null.");
            }

            Modeler modeler = null;

            string configurationFile = GetConfigurationFileContent(settings);

            if (configurationFile != null)
            {
                try
                {
                    var config = JsonConvert.DeserializeObject <AutoRestConfiguration>(configurationFile);
                    modeler = LoadTypeFromAssembly <Modeler>(config.Modelers, settings.Modeler, settings);
                }
                catch (Exception ex)
                {
                    throw ErrorManager.CreateError(ex, Resources.ErrorParsingConfig);
                }
            }
            else
            {
                throw ErrorManager.CreateError(Resources.ConfigurationFileNotFound);
            }

            Logger.LogInfo(Resources.ModelerInitialized,
                           settings.Modeler,
                           modeler.GetType().Assembly.GetName().Version);
            return(modeler);
        }
Example #19
0
        private static void AssertJsonEquals <T>(T compositeParam, T subParam)
        {
            if (compositeParam != null)
            {
                var jsonSettings = new JsonSerializerSettings
                {
                    Formatting            = Formatting.Indented,
                    NullValueHandling     = NullValueHandling.Ignore,
                    ContractResolver      = new CamelCaseContractResolver(),
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                };
                jsonSettings.Converters.Add(new StringEnumConverter {
                    CamelCaseText = true
                });

                var compositeParamJson = JsonConvert.SerializeObject(compositeParam, jsonSettings);
                var subParamJson       = JsonConvert.SerializeObject(subParam, jsonSettings);

                if (!compositeParamJson.Equals(subParamJson))
                {
                    throw ErrorManager.CreateError(string.Format(CultureInfo.InvariantCulture,
                                                                 "{0}s are not the same.\nObject 1: {1}\nObject 2:{2}",
                                                                 typeof(T).Name, compositeParamJson, subParamJson));
                }
            }
        }
Example #20
0
        public static ServiceDefinition Parse(string path, string swaggerDocument)
        {
            try
            {
                swaggerDocument = Normalize(path, swaggerDocument);
                var settings = new JsonSerializerSettings
                {
                    TypeNameHandling         = TypeNameHandling.None,
                    MetadataPropertyHandling = MetadataPropertyHandling.Ignore
                };
                settings.Converters.Add(new ResponseRefConverter(swaggerDocument));
                settings.Converters.Add(new PathItemRefConverter(swaggerDocument));
                settings.Converters.Add(new PathLevelParameterConverter(swaggerDocument));
                settings.Converters.Add(new SchemaRequiredItemConverter());
                settings.Converters.Add(new SecurityDefinitionConverter());
                var swaggerService = JsonConvert.DeserializeObject <ServiceDefinition>(swaggerDocument, settings);

                // for parameterized host, will be made available via JsonRpc accessible state in the future
                ServiceDefinition.Instance = swaggerService;
                Uri filePath = null;
                Uri.TryCreate(path, UriKind.RelativeOrAbsolute, out filePath);
                swaggerService.FilePath = filePath;
                return(swaggerService);
            }
            catch (JsonException ex)
            {
                throw ErrorManager.CreateError("{0}. {1}\n{2}", Resources.ErrorParsingSpec, ex.Message, swaggerDocument);
            }
        }
Example #21
0
        public override ServiceClient Build()
        {
            var compositeSwaggerModel = Parse(Settings.Input);

            if (compositeSwaggerModel == null)
            {
                throw ErrorManager.CreateError(Resources.ErrorParsingSpec);
            }

            if (!compositeSwaggerModel.Documents.Any())
            {
                throw ErrorManager.CreateError(string.Format(CultureInfo.InvariantCulture, "{0}. {1}",
                                                             Resources.ErrorParsingSpec, "Documents collection can not be empty."));
            }

            if (compositeSwaggerModel.Info == null)
            {
                throw ErrorManager.CreateError(Resources.InfoSectionMissing);
            }

            ServiceClient compositeClient = InitializeServiceClient(compositeSwaggerModel);

            foreach (var childSwaggerPath in compositeSwaggerModel.Documents)
            {
                Settings.Input = childSwaggerPath;
                var swaggerModeler = new SwaggerModeler(Settings);
                var serviceClient  = swaggerModeler.Build();
                compositeClient = Merge(compositeClient, serviceClient);
            }
            return(compositeClient);
        }
Example #22
0
        public Token Expect(TokenType type)
        {
            if (TokenStream.Peek().Type != type)
            {
                ErrorManager.CreateError($"Expected {type.ToString().ToLower()}!", ErrorType.Error, TokenStream.Current.Line, TokenStream.Current.Column);
            }

            return(TokenStream.Read());
        }
Example #23
0
        public void Visit(FunctionCallExpression funcCall)
        {
            _functionVariables.Clear();

            var funcToCall = _functions.FirstOrDefault(f => f.Name == funcCall.FunctionName);

            foreach (var v in funcCall.Parameters)
            {
                object   value = null;
                SailType type  = SailType.UNKNOWN;

                if (v is IdentifierExpression)
                {
                    var variable = _variables.FirstOrDefault(va => va.Name == (v as IdentifierExpression).Value);

                    if (variable == null)
                    {
                        ErrorManager.CreateError("Argument passed to function doesn't exist!", ErrorType.Error, funcCall.Line, funcCall.Column);
                        return;
                    }

                    value = variable.Value;
                    type  = variable.Type;
                }

                else if (v is ILiteralExpression)
                {
                    var literal = v as ILiteralExpression;

                    type  = TypeResolver.ToSailType(literal);
                    value = literal.GetValue();
                }

                else if (v is ComparisonExpression)
                {
                    Visit(v);

                    type  = SailType.BOOL;
                    value = (bool)_comparisonResults.Pop().Value;
                }

                else
                {
                    ErrorManager.CreateError("Argument passed to function must be a variable name or value!", ErrorType.Error, funcCall.Line, funcCall.Column);
                    return;
                }

                _functionVariables.Push(new SailObject(null, value, type));
            }

            if (funcCall != null)
            {
                funcToCall.Invoke(this);
            }
        }
Example #24
0
        /// <summary>
        /// Builds service model from swagger file.
        /// </summary>
        /// <returns></returns>
        public override CodeModel Build()
        {
            Logger.Instance.Log(Category.Info, Resources.ParsingSwagger);
            if (string.IsNullOrWhiteSpace(Settings.Input))
            {
                throw ErrorManager.CreateError(Resources.InputRequired);
            }
            var serviceDefinition = SwaggerParser.Load(Settings.Input, Settings.FileSystemInput);

            return(Build(serviceDefinition));
        }
Example #25
0
        public IExpression Parse(Parser parser, Token token)
        {
            var block = parser.ParseExpression(1);

            if (!(block is BlockExpression))
            {
                ErrorManager.CreateError("Else expression is missing a block!", ErrorType.Error, token.Line, token.Column);
                return(null);
            }

            return(new ElseExpression(token.Line, token.Column, (BlockExpression)block));
        }
Example #26
0
 private static void AssertEquals <T>(T compositeProperty, T subProperty, string propertyName)
 {
     if (compositeProperty != null)
     {
         if (!compositeProperty.Equals(subProperty))
         {
             throw ErrorManager.CreateError(string.Format(CultureInfo.InvariantCulture,
                                                          "{0} has different values in sub swagger documents.",
                                                          propertyName));
         }
     }
 }
Example #27
0
        public override ServiceClient Build()
        {
            var compositeSwaggerModel = Parse(Settings.Input);

            if (compositeSwaggerModel == null)
            {
                throw ErrorManager.CreateError(Resources.ErrorParsingSpec);
            }

            if (!compositeSwaggerModel.Documents.Any())
            {
                throw ErrorManager.CreateError(string.Format(CultureInfo.InvariantCulture, "{0}. {1}",
                                                             Resources.ErrorParsingSpec, "Documents collection can not be empty."));
            }

            if (compositeSwaggerModel.Info == null)
            {
                throw ErrorManager.CreateError(Resources.InfoSectionMissing);
            }

            //Ensure all the docs are absolute paths
            var basePath      = Directory.GetParent(Settings.Input).FullName;
            var isBasePathUri = Uri.IsWellFormedUriString(basePath, UriKind.Absolute);

            for (var i = 0; i < compositeSwaggerModel.Documents.Count; i++)
            {
                if (!(Path.IsPathRooted(compositeSwaggerModel.Documents[i]) ||
                      Uri.IsWellFormedUriString(compositeSwaggerModel.Documents[i], UriKind.Absolute)))
                {
                    var tempPath = Path.Combine(basePath, compositeSwaggerModel.Documents[i]);
                    if (isBasePathUri)
                    {
                        compositeSwaggerModel.Documents[i] = new Uri(tempPath).AbsoluteUri;
                    }
                    else
                    {
                        compositeSwaggerModel.Documents[i] = Path.GetFullPath(tempPath);
                    }
                }
            }

            ServiceClient compositeClient = InitializeServiceClient(compositeSwaggerModel);

            foreach (var childSwaggerPath in compositeSwaggerModel.Documents)
            {
                Settings.Input = childSwaggerPath;
                var swaggerModeler = new SwaggerModeler(Settings);
                var serviceClient  = swaggerModeler.Build();
                compositeClient = Merge(compositeClient, serviceClient);
            }
            return(compositeClient);
        }
Example #28
0
        public IExpression Parse(Parser parser, Token token)
        {
            var elseIfCondition = parser.ParseExpression(1);
            var block           = parser.ParseExpression(1) as BlockExpression;

            if (block == null)
            {
                ErrorManager.CreateError("Else if expression is missing a block!", ErrorType.Error, token.Line, token.Column);
                return(null);
            }

            return(new ElseIfExpression(token.Line, token.Column, block, elseIfCondition));
        }
Example #29
0
        /// <summary>
        /// Generates client using provided settings.
        /// </summary>
        /// <param name="settings">Code generator settings.</param>
        public static void Generate(Settings settings)
        {
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }
            Logger.Entries.Clear();
            Logger.LogInfo(Resources.AutoRestCore, Version);
            Modeler       modeler       = ExtensionsLoader.GetModeler(settings);
            ServiceClient serviceClient = null;

            IEnumerable <ValidationMessage> messages = new List <ValidationMessage>();

            try
            {
                serviceClient = modeler.Build(out messages);
            }
            catch (Exception exception)
            {
                throw ErrorManager.CreateError(exception, Resources.ErrorGeneratingClientModel, exception.Message);
            }
            finally
            {
                // Make sure to log any validation messages
                foreach (var message in messages)
                {
                    Logger.Entries.Add(new LogEntry(message.Severity, message.ToString()));
                }
                if (messages.Any(entry => entry.Severity >= settings.ValidationLevel))
                {
                    throw ErrorManager.CreateError(null, Resources.ErrorGeneratingClientModel, Resources.CodeGenerationError);
                }
            }

            CodeGenerator codeGenerator = ExtensionsLoader.GetCodeGenerator(settings);

            Logger.WriteOutput(codeGenerator.UsageInstructions);

            settings.Validate();
            try
            {
                codeGenerator.NormalizeClientModel(serviceClient);
                codeGenerator.Generate(serviceClient).GetAwaiter().GetResult();
            }
            catch (Exception exception)
            {
                throw ErrorManager.CreateError(exception, Resources.ErrorSavingGeneratedCode, exception.Message);
            }
        }
Example #30
0
        /// <summary>
        /// Gets the code generator specified in the provided Settings.
        /// </summary>
        /// <param name="settings">The code generation settings</param>
        /// <returns>Code generator specified in Settings.CodeGenerator</returns>
        public static CodeGenerator GetCodeGenerator(Settings settings)
        {
            Logger.LogInfo(Resources.InitializingCodeGenerator);
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }

            if (string.IsNullOrEmpty(settings.CodeGenerator))
            {
                throw new ArgumentException(
                          string.Format(CultureInfo.InvariantCulture,
                                        Resources.ParameterValueIsMissing, "CodeGenerator"));
            }

            CodeGenerator codeGenerator = null;

            if (string.Equals("None", settings.CodeGenerator, StringComparison.OrdinalIgnoreCase))
            {
                codeGenerator = new NoOpCodeGenerator(settings);
            }
            else
            {
                string configurationFile = GetConfigurationFileContent(settings);

                if (configurationFile != null)
                {
                    try
                    {
                        var config = JsonConvert.DeserializeObject <AutoRestConfiguration>(configurationFile);
                        codeGenerator = LoadTypeFromAssembly <CodeGenerator>(config.CodeGenerators, settings.CodeGenerator,
                                                                             settings);
                        codeGenerator.PopulateSettings(settings.CustomSettings);
                    }
                    catch (Exception ex)
                    {
                        throw ErrorManager.CreateError(ex, Resources.ErrorParsingConfig);
                    }
                }
                else
                {
                    throw ErrorManager.CreateError(Resources.ConfigurationFileNotFound);
                }
            }
            Logger.LogInfo(Resources.GeneratorInitialized,
                           settings.CodeGenerator,
                           codeGenerator.GetType().Assembly.GetName().Version);
            return(codeGenerator);
        }