Esempio n. 1
0
        public string GetOutputFilePath(TargetLanguage targetLanguage)
        {
            if (!MetadataMap.TryGetValue(targetLanguage, out var metadata))
            {
                Logger.LogError($"Failed to get metadata for target language {targetLanguage}.");
                return(null);
            }

            var currentFolder = Directory.GetCurrentDirectory();

            var schemaFileDirectoryName = Path.GetDirectoryName(SchemaFile);

            var outputPath     = Path.GetFullPath(metadata.FileOutputPath);
            var outputFileName = $"{Path.GetFileNameWithoutExtension(SchemaFile)}.{targetLanguage.ToString().ToLower()}";

            if (File.Exists(outputPath))
            {
                Logger.LogError($"{nameof(JsonSchemaItemMetadata.FileOutputPath)} must be a folder.");
                return(null);
            }

            var isUnderProjectFolder = schemaFileDirectoryName.IndexOf(currentFolder) == 0;

            if (!isUnderProjectFolder && metadata.Flatten)
            {
                Logger.LogWarning("Schema file is not under project path, flatten will be skipped.");
            }

            var shouldAppendRelativePath = isUnderProjectFolder && !metadata.Flatten;

            return(shouldAppendRelativePath
                ? Path.Combine(outputPath, schemaFileDirectoryName.Remove(0, currentFolder.Length + 1), outputFileName)
                : Path.Combine(outputPath, outputFileName));
        }
Esempio n. 2
0
        public void Start()
        {
            ConsoleWriteLine("Checking \'" + SourceFile + "\'...");
            int line = 0;

            using (StreamReader streamReader = new StreamReader(SourceFile))
            {
                while (!streamReader.EndOfStream)
                {
                    line++;
                    string lineText = streamReader.ReadLine();
                    if (lineText == null)
                    {
                        continue;
                    }
                    lineText = lineText.Replace(SourceLanguage.ToString(), TargetLanguage.ToString());
                    _lines.Add(lineText);
                    //if (lineText.Contains("\"") && lineText.Contains(".Add"))
                    //    ConsoleWriteLine(line + ": " + GetSourceText(lineText));
                    //else
                    //    ConsoleWriteLine(line + ": " + lineText);
                }
            }
            ProcessLines();
        }
Esempio n. 3
0
        public static CompileResult Compile(string typeSql, string typeSqlFileName, TargetLanguage targetLanguage = TargetLanguage.CSharp)
        {
            //create the antlr-based lexer and parser
            var lexer = new TypeSqlLexer(new ANTLRStringStream(typeSql));
             var rewriteTokenStream = new TokenRewriteStream(lexer);
            var parser = new TypeSqlParser(rewriteTokenStream);

            //parse the typeSql, producing the AST
            var ast = (CommonTree) parser.typesql().Tree;
             var nodeStream = new CommonTreeNodeStream(ast);

            //transform the AST into raw-sql
             var rawSqlOutput = new RawSqlTransform(nodeStream);
             nodeStream.TokenStream = rewriteTokenStream;
             rawSqlOutput.typeSql();
             string rawSql = rewriteTokenStream.ToString();

            //reset
             lexer.Reset();
             rewriteTokenStream.Reset();
             nodeStream.Reset();
            //and transform the AST into DAO source code
             var daoTransform = new DaoTransform(nodeStream){TemplateGroup = new StringTemplateGroup(
                new StreamReader(typeof(TypeSqlCompiler).Assembly.GetManifestResourceStream(string.Format("TypeSql.Parsing.DapperDao.{0}.stg", targetLanguage.ToString() ))),
                typeof (TemplateLexer))};
             var template = daoTransform.typeSql(typeSqlFileName, rawSql).Template;
             string daoSourceCode = template.ToString();

            return new CompileResult(daoSourceCode, rawSql);
        }
Esempio n. 4
0
        public ISourceFileGenerator CreateSourceFileGenerator(TargetLanguage targetLanguage)
        {
            ISourceFileGenerator generator = null;

            switch (targetLanguage)
            {
            case TargetLanguage.VisualBasic:
                generator = _serviceProvider.GetService <VisualBasicSourceFileGenerator>();
                break;
            }

            //Shouldnt ever happen but if a new language is added but no generator
            if (generator == null)
            {
                _logger.Error("An invalid language type was provided");

                throw new NotSupportedException("Target language not supported");
            }

            _logger.Verbose($"Generating {targetLanguage.ToString()} source file generator");

            return(generator);
        }
 /// <summary>
 ///     Set a property as a target language.
 /// </summary>
 /// <param name="name">The name of the property.</param>
 /// <param name="targetLanguage">The target language.</param>
 public void SetProperty(String name, TargetLanguage targetLanguage)
 {
     _data[name] = targetLanguage.ToString().ToUpper();
 }
 /// <summary>
 ///     Set a property as a target language.
 /// </summary>
 /// <param name="name">The name of the property.</param>
 /// <param name="targetLanguage">The target language.</param>
 public void SetProperty(String name, TargetLanguage targetLanguage)
 {
     _data[name] = targetLanguage.ToString().ToUpper();
 }
Esempio n. 7
0
        private void ParseArgs(string[] args)
        {
            var resolvedArgs = args
                               .SelectMany(ResolveOptionsFromFile)
                               .ToArray();

            var options = new[]
            {
                new Option {
                    Key = "Language", Setter = value => _targetLanguage = (TargetLanguage)System.Enum.Parse(typeof(TargetLanguage), value, true), Getter = () => _targetLanguage.ToString(), Description = $"Language for the generated service model code. One of: {string.Join(", ", System.Enum.GetNames(typeof(TargetLanguage)))}. This option should be set before setting any -Namespace, -UsingDirectives, or -Aliases options."
                },
                new Option {
                    Key = "URL", Setter = value => _url = value, Getter = () => _url, Description = "URL for Swagger 2.0 JSON"
                },
                new Option {
                    Key = "Filename", Setter = value => _filename[_targetLanguage] = value, Getter = () => _filename[_targetLanguage], Description = "Filename for the generated service model code"
                },
                new Option {
                    Key = "Namespace", Setter = value => _namespace[_targetLanguage] = value, Getter = () => _namespace[_targetLanguage], Description = "Namespace for the generated service model"
                },
                new Option {
                    Key = "UsingDirectives", Setter = value => _usingDirectives[_targetLanguage] = value, Getter = () => _usingDirectives[_targetLanguage], Description = "using directives (semicolon-separated) for the generated service model"
                },
                new Option {
                    Key = "Aliases", Setter = value => _aliases[_targetLanguage] = value, Getter = () => _aliases[_targetLanguage], Description = "Type aliases (semicolon-separated) in SwaggerType=AliasType format"
                },
                new Option {
                    Key = "Obsolete", Setter = value => _obsoleteDtos[_targetLanguage] = value, Getter = () => _obsoleteDtos[_targetLanguage], Description = "Obsolete DTOs (semicolon-separated) in ObsoleteDtoName=PreferredDtoName format"
                },
                new Option {
                    Key = "Fixups", Setter = value => _fixups = value, Getter = () => _fixups, Description = "Fixups (semicolon-separated) in Verb:Route=RequestDtoName format"
                },
                new Option {
                    Key = "Enums", Setter = value => _enums = value, Getter = () => _enums, Description = "Enum overrides (semicolon-separated) in EnumTypeName=fieldName.Value1,...,ValueN format"
                },
            };

            _usageMessage =
                $"Generates the Samples SDK service model DTOs from a Swagger 2.0 JSON spec."
                + $"\n"
                + $"\nusage: {Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location)} [-option=value] [@optionsFile] ... [commands ...]"
                + $"\n"
                + $"\nSupported -option=value settings (/option=value works too):\n\n  -{string.Join("\n  -", options.Select(o => o.UsageText()))}"
                + $"\n"
                + $"\nUse the @optionsFile syntax to read more options from a file."
                + $"\n"
                + $"\n  Each line in the file is treated as a command line option."
                + $"\n  Blank lines and leading/trailing whitespace is ignored."
                + $"\n  Comment lines begin with a # or // marker."
            ;

            foreach (var arg in resolvedArgs)
            {
                var match = ArgRegex.Match(arg);

                if (!match.Success)
                {
                    throw new ExpectedException($"Unknown argument: {arg}\n\n{_usageMessage}");
                }

                var key   = match.Groups["key"].Value.ToLower();
                var value = match.Groups["value"].Value;

                var option =
                    options.FirstOrDefault(o => o.Key.Equals(key, StringComparison.InvariantCultureIgnoreCase));

                if (option == null)
                {
                    throw new ExpectedException($"Unknown -option=value: {arg}\n\n{_usageMessage}");
                }

                option.Setter(value);
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Performs the actual search by looping through the
        /// delimited segment pairs contained in the text file.
        /// Depening on the search mode, a segment lookup (with exact machting) or a source / target
        /// concordance search is done.
        /// </summary>
        /// <param name="settings"></param>
        /// <param name="segment"></param>
        /// <returns></returns>
        #region "SearchSegment"
        public SearchResults SearchSegment(SearchSettings settings, Segment segment)
        {
            //FUTURE: consider making GT and MT lookup classes static utility classes

            Segment translation = new Segment(_languageDirection.TargetCulture);//this will be the target segment

            #region "SearchResultsObject"
            SearchResults results = new SearchResults();
            results.SourceSegment = segment.Duplicate();

            #endregion

            #region "Confirmation Level"
            if (!_options.ResendDrafts && inputTu.ConfirmationLevel != ConfirmationLevel.Unspecified) //i.e. if it's status is other than untranslated
            {                                                                                         //don't do the lookup, b/c we don't need to pay google to translate text already translated if we edit a segment
                translation.Add(PluginResources.TranslationLookupDraftNotResentMessage);
                //later get these strings from resource file
                results.Add(CreateSearchResult(segment, translation, segment.ToString()));
                return(results);
            }
            #endregion


            // Look up the currently selected segment in the collection (normal segment lookup).
            #region "SegmentLookup"
            string sourceLang     = SourceLanguage.ToString();
            string targetLang     = TargetLanguage.ToString();
            string translatedText = "";
            //a new seg avoids modifying the current segment object
            Segment newseg = segment.Duplicate();

            //do preedit if checked
            bool sendTextOnly = _options.SendPlainTextOnly || !newseg.HasTags;
            if (!sendTextOnly)
            {
                //do preedit with tagged segment
                if (_options.UsePreEdit)
                {
                    if (preLookupSegmentEditor == null)
                    {
                        preLookupSegmentEditor = new SegmentEditor(_options.PreLookupFilename);
                    }
                    newseg = getEditedSegment(preLookupSegmentEditor, newseg);
                }
                //return our tagged target segment
                MtTranslationProviderTagPlacer tagplacer = new MtTranslationProviderTagPlacer(newseg);
                ////tagplacer is constructed and gives us back a properly marked up source string for google
                if (_options.SelectedProvider == MtTranslationOptions.ProviderType.GoogleTranslate)
                {
                    translatedText = LookupGT(tagplacer.PreparedSourceText, _options, "html");
                }
                else if (_options.SelectedProvider == MtTranslationOptions.ProviderType.MicrosoftTranslator)
                {
                    translatedText = LookupMST(tagplacer.PreparedSourceText, _options, "text/html");
                }
                //now we send the output back to tagplacer for our properly tagged segment
                translation = tagplacer.GetTaggedSegment(translatedText).Duplicate();

                //now do post-edit if that option is checked
                if (_options.UsePostEdit)
                {
                    if (postLookupSegmentEditor == null)
                    {
                        postLookupSegmentEditor = new SegmentEditor(_options.PostLookupFilename);
                    }
                    translation = getEditedSegment(postLookupSegmentEditor, translation);
                }
            }
            else //only send plain text
            {
                string sourcetext = newseg.ToPlain();
                //do preedit with string
                if (_options.UsePreEdit)
                {
                    if (preLookupSegmentEditor == null)
                    {
                        preLookupSegmentEditor = new SegmentEditor(_options.PreLookupFilename);
                    }
                    sourcetext = getEditedString(preLookupSegmentEditor, sourcetext);
                    //change our source segment so it gets sent back with modified text to show in translation results window that it was changed before sending
                    newseg.Clear();
                    newseg.Add(sourcetext);
                }

                //now do lookup
                if (_options.SelectedProvider == MtTranslationOptions.ProviderType.GoogleTranslate)
                {
                    translatedText = LookupGT(sourcetext, _options, "html"); //plain??
                }
                else if (_options.SelectedProvider == MtTranslationOptions.ProviderType.MicrosoftTranslator)
                {
                    translatedText = LookupMST(sourcetext, _options, "text/plain");
                }

                //now do post-edit if that option is checked
                if (_options.UsePostEdit)
                {
                    if (postLookupSegmentEditor == null)
                    {
                        postLookupSegmentEditor = new SegmentEditor(_options.PostLookupFilename);
                    }
                    translatedText = getEditedString(postLookupSegmentEditor, translatedText);
                }
                translation.Add(translatedText);
            }

            results.Add(CreateSearchResult(newseg, translation, newseg.ToPlain()));

            #endregion

            #region "Close"
            return(results);

            #endregion
        }
Esempio n. 9
0
        private void ParseArgs(string[] args)
        {
            var options = new[]
            {
                new Option {
                    Key = "Language", Setter = value => _targetLanguage = (TargetLanguage)System.Enum.Parse(typeof(TargetLanguage), value, true), Getter = () => _targetLanguage.ToString(), Description = $"Language for the generated service model code. One of: {string.Join(", ", System.Enum.GetNames(typeof(TargetLanguage)))}. This option should be set before setting any -Namespace, -UsingDirectives, or -Aliases options."
                },
                new Option {
                    Key = "URL", Setter = value => _url = value, Getter = () => _url, Description = "URL for Swagger 2.0 JSON"
                },
                new Option {
                    Key = "Filename", Setter = value => _filename[_targetLanguage] = value, Getter = () => _filename[_targetLanguage], Description = "Filename for the generated service model code"
                },
                new Option {
                    Key = "Namespace", Setter = value => _namespace[_targetLanguage] = value, Getter = () => _namespace[_targetLanguage], Description = "Namespace for the generated service model"
                },
                new Option {
                    Key = "UsingDirectives", Setter = value => _usingDirectives[_targetLanguage] = value, Getter = () => _usingDirectives[_targetLanguage], Description = "using directives (semicolon-separated) for the generated sevice model"
                },
                new Option {
                    Key = "Aliases", Setter = value => _aliases[_targetLanguage] = value, Getter = () => _aliases[_targetLanguage], Description = "Type aliases (semicolon-separated) in SwaggerType=AliasType format"
                },
                new Option {
                    Key = "Fixups", Setter = value => _fixups = value, Getter = () => _fixups, Description = "Fixups (semicolon-separated) in Verb:Route=RequestDtoName format"
                },
                new Option {
                    Key = "Enums", Setter = value => _enums = value, Getter = () => _enums, Description = "Enum overrides (semicolon-separated) in EnumTypeName=fieldName.Value1,...,ValueN format"
                },
            };

            _usageMessage =
                $"Clones an AQTS configuration (using TimeSeriesSupport) to an NG system (using public APIs)"
                + $"\n\nusage: {Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location)} [-option=value] ... [commands ...]"
                + $"\n\nSupported -option=value settings (/option=value works too):\n\n  -{string.Join("\n  -", options.Select(o => o.UsageText()))}"
            ;

            foreach (var arg in args)
            {
                var match = ArgRegex.Match(arg);

                if (!match.Success)
                {
                    throw new ExpectedException($"Unknown argument: {arg}\n\n{_usageMessage}");
                }

                var key   = match.Groups["key"].Value.ToLower();
                var value = match.Groups["value"].Value;

                var option =
                    options.FirstOrDefault(o => o.Key.Equals(key, StringComparison.InvariantCultureIgnoreCase));

                if (option == null)
                {
                    throw new ExpectedException($"Unknown -option=value: {arg}\n\n{_usageMessage}");
                }

                option.Setter(value);
            }
        }
Esempio n. 10
0
        private static Dictionary<string, string> GetTranslateRessources(string[] splitArray, TargetLanguage language)
        {
            Dictionary<string, string> resultDictionary = new Dictionary<string, string>();

            foreach (string item in splitArray)
            {
                string[] lines = item.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string line in lines)
                {
                    if ("[" + language.ToString() + "]" == line.Trim())
                    {
                        AddToDictionary(resultDictionary, lines);
                        return resultDictionary;
                    }
                }
            }

            throw new IndexOutOfRangeException(language.ToString() + " not found.");
        }