Example #1
0
 public bool SignalExternalCommandLineArgs(IList<string> args)
 {
     args.RemoveAt(0); //Removes the executable file name
     cmdLineResult = Parser.Default.ParseArguments<Options>(args.ToArray());
     ParseArguments();
     return true;
 }
Example #2
0
        public static XDoc RetrievePageXDoc(PageBE page, uint pageId, ParserMode mode, string language, bool isInclude, int section, Title relToTitle, bool xhtml, out ParserResult parserResult) {
            uint contextPageId = pageId;
            if((mode == ParserMode.VIEW) && (contextPageId != uint.MaxValue) && page.Title.IsTemplate) {

                // NOTE (steveb): page being rendered is a template and a contextual page was specified; this means we're rendering a global template page
                PageBE contextPage = GetPageById(contextPageId);
                if(contextPage == null) {
                    parserResult = new ParserResult();
                    return null;
                }
                parserResult = DekiXmlParser.ParseGlobalTemplate(contextPage, page);
            } else {
                parserResult = DekiXmlParser.Parse(page, page.ContentType, language ?? page.Language, page.GetText(DbUtils.CurrentSession), mode, isInclude, section, null, relToTitle);
            }
            if(page.Title.IsTemplate && isInclude) {
                DekiXmlParser.PostProcessTemplateInsertBody(parserResult, page);
            }

            // post process tail element
            DekiXmlParser.PostProcessParserResults(parserResult);

            // BUGBUGBUG (steveb): we cannot properly restore an old title unless it had a display title set

            // wrap the result in a content tag and return it to the user
            XDoc result = new XDoc("content")
                    .Attr("type", parserResult.ContentType)
                    .Attr("etag", page.Etag)
                    .Attr("title", page.CustomTitle ?? page.Title.AsUserFriendlyName());

            // check if page contains unsafe content
            if(mode == ParserMode.EDIT) {
                result.Attr("unsafe", !DekiScriptLibrary.VerifyXHtml(parserResult.MainBody, true));
            }

            if(xhtml) {
                result.AddNodes(parserResult.Content);
            } else {

                // encode the result as nodes of text
                foreach(XDoc entry in parserResult.Content.Elements) {
                    if(entry.HasName("body")) {
                        result.Start("body").Attr("target", entry["@target"].AsText).Value(entry.ToInnerXHtml()).End();
                    } else {
                        result.Elem(entry.Name, entry.ToInnerXHtml());
                    }
                }
            }
            return result;
        }
Example #3
0
 private static void* __CopyValue(ParserResult.__Internal native)
 {
     var ret = Marshal.AllocHGlobal(28);
     global::CppSharp.Parser.ParserResult.__Internal.cctor_1(ret, new global::System.IntPtr(&native));
     return ret.ToPointer();
 }
Example #4
0
 private static ParserResult.Internal* __CopyValue(ParserResult.Internal native)
 {
     var ret = Marshal.AllocHGlobal(56);
     CppSharp.Parser.ParserResult.Internal.cctor_1(ret, new global::System.IntPtr(&native));
     return (ParserResult.Internal*) ret;
 }
            public void when_called()
            {
                before = () => { _parser = Parser.DefaultParser; };

                act = () => { _result = _parser.Parse <BasicOptions>(_args); };

                context["Given a valid command line for Basic Options"] = () =>
                {
                    const string    fileName  = @"C:\Temp\MyFileName.txt";
                    const int       lineCount = 25;
                    var             dateTime  = new DateTime(2018, 08, 11);
                    const OneToFive oneToFive = OneToFive.Four;

                    before = () =>
                    {
                        _args = new[]
                        {
                            fileName,
                            "-lc", lineCount.ToString(),
                            "-dt", dateTime.ToString("yyyy-MM-dd"),
                            "-otf", oneToFive.ToString()
                        };
                    };

                    it["should return a valid result"] = () => _result.ShouldNotBeNull();

                    it["should return an Options instance"] = () => _result.Options.ShouldNotBeNull();

                    it["should map FileName correctly"]     = () => _result.Options.FileName.ShouldBe(fileName);
                    it["should map LineCount correctly"]    = () => _result.Options.LineCount.ShouldBe(lineCount);
                    it["should return Timestamp correctly"] = () => _result.Options.Timestamp.ShouldBe(dateTime);
                    it["should return OneToFive correctly"] = () => _result.Options.OneToFive.ShouldBe(OneToFive.Four);
                };

                context["Given a valid command line for Basic Options with positional Parameter at the end"] = () =>
                {
                    const string    fileName  = @"C:\Temp\MyFileName.txt";
                    const int       lineCount = 25;
                    var             dateTime  = new DateTime(2018, 08, 11);
                    const OneToFive oneToFive = OneToFive.Four;

                    before = () =>
                    {
                        _args = new[]
                        {
                            "-lc", lineCount.ToString(),
                            "-dt", dateTime.ToString("yyyy-MM-dd"),
                            "-otf", oneToFive.ToString(),
                            fileName
                        };
                    };

                    it["should return a valid result"] = () => _result.ShouldNotBeNull();

                    it["should return an Options instance"] = () => _result.Options.ShouldNotBeNull();

                    it["should map FileName correctly"]     = () => _result.Options.FileName.ShouldBe(fileName);
                    it["should map LineCount correctly"]    = () => _result.Options.LineCount.ShouldBe(lineCount);
                    it["should return Timestamp correctly"] = () => _result.Options.Timestamp.ShouldBe(dateTime);
                    it["should return OneToFive correctly"] = () => _result.Options.OneToFive.ShouldBe(OneToFive.Four);
                };

                context["Given a valid command line for Basic Options with positional Parameter in the middle"] = () =>
                {
                    const string    fileName  = @"C:\Temp\MyFileName.txt";
                    const int       lineCount = 25;
                    var             dateTime  = new DateTime(2018, 08, 11);
                    const OneToFive oneToFive = OneToFive.Four;

                    before = () =>
                    {
                        _args = new[]
                        {
                            "-lc", lineCount.ToString(),
                            "-dt", dateTime.ToString("yyyy-MM-dd"),
                            "-otf", oneToFive.ToString(),
                            fileName
                        };
                    };

                    it["should return a valid result"] = () => _result.ShouldNotBeNull();

                    it["should return an Options instance"] = () => _result.Options.ShouldNotBeNull();

                    it["should map FileName correctly"]     = () => _result.Options.FileName.ShouldBe(fileName);
                    it["should map LineCount correctly"]    = () => _result.Options.LineCount.ShouldBe(lineCount);
                    it["should return Timestamp correctly"] = () => _result.Options.Timestamp.ShouldBe(dateTime);
                    it["should return OneToFive correctly"] = () => _result.Options.OneToFive.ShouldBe(OneToFive.Four);
                };
            }
Example #6
0
        static int Main(string[] args)
        {
            ParserResult <CommandLineArguments> options = null;

            try
            {
                options = Parser.Default.ParseArguments <CommandLineArguments>(args);
                if (!IsValid(options))
                {
                    return(-2);
                }
            }
            catch
            {
                Console.WriteLine();
                Console.WriteLine("Failed to parse command line arguments. See valid command line arguments below:");

                var h = new HelpText {
                    AddDashesToOption = true, AdditionalNewLineAfterOption = true
                };

                h.AddOptions(new CommandLineArguments());
                Console.WriteLine(h.ToString());

                return(-3);
            }

            RedirectConsoleOutput(options.Value.OutputFile);

            if (!ReadResponseFile(options.Value))
            {
                return(-4);
            }

            try
            {
                options.Value.ProjectPath = Path.GetFullPath(options.Value.ProjectPath);

                // We should ignore scripts in assets/WebGLTemplates
                var ignoredPathsRegex = new Regex(string.Format("assets{0}{0}webgltemplates{0}{0}", Path.DirectorySeparatorChar), RegexOptions.Compiled | RegexOptions.IgnoreCase);

                var editorSubFolder        = String.Format("{0}Editor{0}", Path.DirectorySeparatorChar);
                var pluginsEditorSubFolder = String.Format("{0}Plugins{0}Editor{0}", Path.DirectorySeparatorChar);
                var pluginSubFolder        = String.Format("{0}Plugins{0}", Path.DirectorySeparatorChar);

                var allFiles = Directory.GetFiles(Path.Combine(options.Value.ProjectPath, "Assets"), "*.js", SearchOption.AllDirectories).Where(path => !ignoredPathsRegex.IsMatch(path));
                var filter   = new Regex(string.Format(@"{0}|{1}|{2}", editorSubFolder, pluginSubFolder, pluginsEditorSubFolder).Replace("\\", "\\\\"), RegexOptions.Compiled);

                var runtimeScripts = allFiles.Where(scriptPath => !filter.IsMatch(scriptPath)).Select(scriptPath => new SourceFile {
                    FileName = scriptPath, Contents = File.ReadAllText(scriptPath)
                }).ToArray();
                var editorScripts = allFiles.Where(scriptPath => scriptPath.Contains(editorSubFolder) && !scriptPath.Contains(pluginsEditorSubFolder)).Select(scriptPath => new SourceFile {
                    FileName = scriptPath, Contents = File.ReadAllText(scriptPath)
                }).ToArray();
                var pluginScripts = allFiles.Where(scriptPath => scriptPath.Contains(pluginSubFolder) && !scriptPath.Contains(pluginsEditorSubFolder)).Select(scriptPath => new SourceFile {
                    FileName = scriptPath, Contents = File.ReadAllText(scriptPath)
                }).ToArray();
                var pluginEditorScritps = allFiles.Where(scriptPath => scriptPath.Contains(pluginsEditorSubFolder)).Select(scriptPath => new SourceFile {
                    FileName = scriptPath, Contents = File.ReadAllText(scriptPath)
                }).ToArray();

                if (!ValidateAssemblyReferences(options))
                {
                    return(-1);
                }

                if (options.Value.DumpScripts)
                {
                    DumpScripts("Runtime", runtimeScripts);
                    DumpScripts("Editor", editorScripts);
                    DumpScripts("Plugin", pluginScripts);
                    DumpScripts("Plugin/Editor", pluginEditorScritps);
                }

                var converter = new UnityScript2CSharpConverter(options.Value.IgnoreErrors, options.Value.SkipComments, options.Value.ShowOrphanComments);

                var referencedSymbols = new List <SymbolInfo>();
                var errors            = new HashSet <CompilerError>(new CompilerErrorComparer());

                ConvertScripts(AssemblyType.Runtime, runtimeScripts, converter, options.Value, referencedSymbols, errors);
                ConvertScripts(AssemblyType.Editor, editorScripts, converter, options.Value, referencedSymbols, errors);
                ConvertScripts(AssemblyType.RuntimePlugins, pluginScripts, converter, options.Value, referencedSymbols, errors);
                ConvertScripts(AssemblyType.EditorPlugins, pluginEditorScritps, converter, options.Value, referencedSymbols, errors);

                ReportConversionFinished(runtimeScripts.Length + editorScripts.Length + pluginScripts.Length, options.Value, referencedSymbols, errors);
            }
            catch (Exception ex)
            {
                using (WithConsoleColors.SetTo(ConsoleColor.DarkRed, ConsoleColor.Black))
                {
                    Console.WriteLine(ex.Message);
                    if (options.Value.Verbose)
                    {
                        Console.WriteLine();
                        Console.WriteLine(ex.StackTrace);
                    }

                    if (!options.Value.IgnoreErrors)
                    {
                        Console.WriteLine("Consider running converter with '-i' option.");
                    }
                }

                return(-5);
            }

            return(0);
        }
Example #7
0
 private ParserResult(ParserResult.Internal native)
     : this(__CopyValue(native))
 {
     __ownsNativeInstance = true;
 }
Example #8
0
 void OnSourceFileParsed(IList<SourceFile> files, ParserResult result)
 {
     OnFileParsed(files.Select(f => f.Path), result);
 }
Example #9
0
        public virtual void Calculate(DateTime t1, DateTime t2)
        {
            var t1a = t1;
            var t2a = t2;

            Logger.OnLogEvent += Logger_OnLogEvent;

            var seriesBeforeCalc = this.Clone();
            //if( this.TimeInterval == TimeSeries.TimeInterval.Irregular)
               t2a = t2.AddDays(1); // we may need midnight value in the next day.

               if (this.TimeInterval == TimeSeries.TimeInterval.Daily)
               {
                   // daily_wrdo_pu needs AdjustStartingDate
                   t1a = this.AdjustStartingDateFromProperties(t1, t2a);// DO DO??? needed??
               }

            Exception error = new Exception();

            if (Expression != null && Expression.Trim() != "")
            {
                string tmpExpression = Expression;

                Logger.WriteLine("begin Calculate()");

                Expression = ExpressionPreProcessor();

                ParserResult result = null;
                try
                {
                    result = Parser.Evaluate(this.Expression, t1a, t2a, this.TimeInterval);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    Logger.WriteLine(e.Message, "ui");
                    Messages.Add(e.Message);
                    error = e;
                    result = null;
                }

                if (result != null && ( result.IsDouble || result.IsInteger ))
                { // constant expression, need to convert to a Series.
                    Series constant = new Series();
                    constant.TimeInterval = this.TimeInterval;
                    constant = Math.FillMissingWithZero(constant, t1, t2);
                    if( result.IsDouble)
                      constant = Math.Add(constant, result.Double);
                    else
                      constant = Math.Add(constant, result.Integer);
                    result = new ParserResult(constant);
                }

                if (result != null &&  result.IsSeries)
                {
                    result.Series.Trim(t1, t2);
                    //var s = result.Series;
                    //result.Series = Math.Subset(s, t1, t2); // trim extra data used for calculations

                    Logger.WriteLine("Calculation result has " + result.Series.Count + " rows");
                    this.TimeInterval = result.Series.TimeInterval;
                    string tableName = this.Table.TableName;

                    this.Table = result.Series.Table;
                    this.Table.TableName = tableName;
                    if (m_db != null)
                    {
                       // Logger.WriteLine("Setting Flags");
                        m_db.Quality.SetFlags(this);
                    }

                    this.Table.AcceptChanges();// prevents error releated to Deleted rows from Trim() above.
                    foreach (DataRow row in this.Table.Rows)
                    {
                        row.SetAdded(); // so database will insert these rows.
                    }
                    if (m_db != null) // database is not required for calculations.
                    {

                        //bool canSave = m_db.Server.HasSavePrivilge(this.Table.TableName);
                      //  if(canSave)
                        m_db.SaveTimeSeriesTable(this.ID, this, DatabaseSaveOptions.UpdateExisting);
                        Expression = tmpExpression;

                        if (seriesBeforeCalc.TimeInterval != this.TimeInterval
                            || seriesBeforeCalc.Units != this.Units)
                        {
                            Logger.WriteLine("Warning Units or interval has changed.");
                            //if(canSave)
                            m_db.SaveProperties(this); // time interval, units, are dependent on calculation.
                        }
                    }

                }
                else
                {
                    Clear();
                    Console.WriteLine(error.Message);
                    Logger.WriteLine(error.Message);
                }

                Logger.WriteLine("Calculate() completed");
                Logger.OnLogEvent -= Logger_OnLogEvent;
            }
        }
Example #10
0
        /**
         * Parses a piece of Java code that matches a certain grammar rule.
         *
         * @param pSource  The Java source that should get parsed.
         * @param pCodeFragmentType  The code fragment type defining the grammar
         *                           rule that should be used to parse the code
         *                           fragment.
         * @param pErrorMessages  If this argument is not <code>null</code> error
         *                        messages emited by the parser will be added to
         *                        this list. Otherwise these error messages will be
         *                        written to <code>System.err</code>.
         *
         * @return  An object of type <code>JSOParser.ParserResult</code>
         *          containing the root node representing a Java code fragment and
         *          the token stream containing the tokens of the parsed source.
         *
         * @
         *         if parsing the code fragment or creating the AST failes.
         * @throws RecognitionException
         *
         * __TEST__  All parsable code fragments still untested for parser failure.
         */
        private ParserResult parse(
            ANTLRStringStream pSource, CodeFragmentType pCodeFragmentType,
            List<String> pErrorMessages)
        {
            ParserResult result = new ParserResult();
            bool isMessageCollectingEnabled = pErrorMessages != null;
            mLexer.CharStream = pSource;
            mLexer.EnableErrorMessageCollection(isMessageCollectingEnabled);
            TokenRewriteStream tokenRewriteStream =
            new TokenRewriteStream(mLexer);
            if (mParser != null) {
            mParser.TokenStream = tokenRewriteStream;
            } else {
            mParser = new JavaParser(tokenRewriteStream);
            mParser.TreeAdaptor = mAST2JSOMTreeAdaptor;
            }
            mParser.EnableErrorMessageCollection(isMessageCollectingEnabled);
            AST2JSOMTree tree = null;
            if (pCodeFragmentType == CodeFragmentType.ANNOTATION) {
            tree = (AST2JSOMTree) mParser.annotation().Tree;
            } else if (pCodeFragmentType == CodeFragmentType.ASSERT_STATEMENT) {
            tree = (AST2JSOMTree) mParser.assertStatement().Tree;
            } else if (pCodeFragmentType == CodeFragmentType.BREAK_STATEMENT) {
            tree = (AST2JSOMTree) mParser.breakStatement().Tree;
            } else if (pCodeFragmentType == CodeFragmentType.CLASS_EXTENDS_CLAUSE) {
            tree = (AST2JSOMTree) mParser.classExtendsClause().Tree;
            } else if (   pCodeFragmentType
                   == CodeFragmentType.COMPLEX_TYPE_IDENTIFIER) {
            tree = (AST2JSOMTree) mParser.typeIdent().Tree;
            } else if (pCodeFragmentType == CodeFragmentType.CONTINUE_STATEMENT) {
            tree = (AST2JSOMTree) mParser.continueStatement().Tree;
            } else if (pCodeFragmentType == CodeFragmentType.DO_WHILE_STATEMENT) {
            tree = (AST2JSOMTree) mParser.doWhileStatement().Tree;
            } else if (pCodeFragmentType == CodeFragmentType.ENUM_CONSTANT) {
            tree = (AST2JSOMTree) mParser.enumConstant().Tree;
            } else if (pCodeFragmentType == CodeFragmentType.EXPRESSION) {
            tree = (AST2JSOMTree) mParser.expression().Tree;
            } else if (pCodeFragmentType == CodeFragmentType.EXPRESSION_STATEMENT) {
            tree = (AST2JSOMTree) mParser.expressionStatement().Tree;
            } else if (pCodeFragmentType == CodeFragmentType.FOR_STATEMENT) {
            tree = (AST2JSOMTree) mParser.forStatement().Tree;
            } else if (pCodeFragmentType == CodeFragmentType.FOREACH_STATEMENT) {
            tree = (AST2JSOMTree) mParser.forEachStatement().Tree;
            } else if (   pCodeFragmentType
                   == CodeFragmentType.FORMAL_PARAMETER_LIST) {
            tree = (AST2JSOMTree) mParser.formalParameterList().Tree;
            } else if (   pCodeFragmentType
                   == CodeFragmentType.GENERIC_TYPE_ARGUMENT_LIST) {
            tree = (AST2JSOMTree) mParser.genericTypeArgumentList().Tree;
            } else if (   pCodeFragmentType
                == CodeFragmentType.GENERIC_TYPE_PARAMETER_LIST) {
             tree = (AST2JSOMTree) mParser.genericTypeParameterList().Tree;
            } else if (pCodeFragmentType == CodeFragmentType.IF_STATEMENT) {
            tree = (AST2JSOMTree) mParser.ifStatement().Tree;
            } else if (pCodeFragmentType == CodeFragmentType.IMPLEMENTS_CLAUSE) {
            tree = (AST2JSOMTree) mParser.implementsClause().Tree;
            } else if (pCodeFragmentType == CodeFragmentType.IMPORT_DECLARATION) {
            tree = (AST2JSOMTree) mParser.importDeclaration().Tree;
            } else if (   pCodeFragmentType
                   == CodeFragmentType.INTERFACE_EXTENDS_CLAUSE) {
            tree = (AST2JSOMTree) mParser.interfaceExtendsClause().Tree;
            } else if (pCodeFragmentType == CodeFragmentType.JAVA_SOURCE) {
            tree = (AST2JSOMTree) mParser.javaSource().Tree;
            } else if (pCodeFragmentType == CodeFragmentType.LABELED_STATEMENT) {
            tree = (AST2JSOMTree) mParser.labeledStatement().Tree;
            } else if (pCodeFragmentType == CodeFragmentType.LOCAL_VARIABLE_DECLARATION) {
            tree = (AST2JSOMTree) mParser.localVariableDeclaration().Tree;
            } else if (pCodeFragmentType == CodeFragmentType.MODIFIER_LIST) {
            tree = (AST2JSOMTree) mParser.modifierList().Tree;
            } else if (pCodeFragmentType == CodeFragmentType.PRIMITIVE_TYPE) {
            tree = (AST2JSOMTree) mParser.primitiveType().Tree;
            } else if (pCodeFragmentType == CodeFragmentType.QUALIFIED_IDENTIFIER) {
            tree = (AST2JSOMTree) mParser.qualifiedIdentifier().Tree;
            } else if (pCodeFragmentType == CodeFragmentType.RETURN_STATEMENT) {
            tree = (AST2JSOMTree) mParser.returnStatement().Tree;
            } else if (pCodeFragmentType == CodeFragmentType.STATEMENT) {
            tree = (AST2JSOMTree) mParser.statement().Tree;
            } else if (pCodeFragmentType == CodeFragmentType.STATEMENT_BLOCK) {
            tree = (AST2JSOMTree) mParser.block().Tree;
            } else if (pCodeFragmentType == CodeFragmentType.STATEMENT_BLOCK_ELEMENT) {
            tree = (AST2JSOMTree) mParser.blockStatement().Tree;
            } else if (pCodeFragmentType == CodeFragmentType.SWITCH_CASE_LABEL) {
            tree = (AST2JSOMTree) mParser.switchCaseLabel().Tree;
            } else if (pCodeFragmentType == CodeFragmentType.SWITCH_DEFAULT_LABEL) {
            tree = (AST2JSOMTree) mParser.switchDefaultLabel().Tree;
            } else if (pCodeFragmentType == CodeFragmentType.SWITCH_STATEMENT) {
            tree = (AST2JSOMTree) mParser.switchStatement().Tree;
            } else if (pCodeFragmentType == CodeFragmentType.SYNCHRONIZED_STATEMENT) {
            tree = (AST2JSOMTree) mParser.synchronizedStatement().Tree;
            } else if (pCodeFragmentType == CodeFragmentType.THROW_STATEMENT) {
            tree = (AST2JSOMTree) mParser.throwStatement().Tree;
            } else if (pCodeFragmentType == CodeFragmentType.THROWS_CLAUSE) {
            tree = (AST2JSOMTree) mParser.throwsClause().Tree;
            } else if (pCodeFragmentType == CodeFragmentType.TRY_STATEMENT) {
            tree = (AST2JSOMTree) mParser.tryStatement().Tree;
            } else if (pCodeFragmentType == CodeFragmentType.TRY_STATEMENT_CATCH_CLAUSE) {
            tree = (AST2JSOMTree) mParser.catchClause().Tree;
            } else if (pCodeFragmentType == CodeFragmentType.TYPE) {
            tree = (AST2JSOMTree) mParser.type().Tree;
            } else if (pCodeFragmentType == CodeFragmentType.TYPE_DECLARATION) {
            tree = (AST2JSOMTree) mParser.typeDeclaration().Tree;
            } else if (pCodeFragmentType == CodeFragmentType.VARIABLE_DECLARATOR_IDENTIFIER) {
            // Simply use the grammar rule for local variables.
            tree = (AST2JSOMTree) mParser.variableDeclaratorId().Tree;
            } else if (pCodeFragmentType == CodeFragmentType.VARIABLE_INITIALIZER) {
            tree = (AST2JSOMTree) mParser.variableInitializer().Tree;
            } else if (pCodeFragmentType == CodeFragmentType.WHILE_STATEMENT) {
            tree = (AST2JSOMTree) mParser.whileStatement().Tree;
            } else if (pCodeFragmentType != null) {
            throw new JSourceUnmarshallerException(
                    UnmarshallerMessages
                        .getUnsupportedCodeFragmentTypeMessage(
                                                    pCodeFragmentType));
            } else {
            // TODO  Internationalize the message.
            throw new JSourceUnmarshallerException(
                    "The argument stating the code fragment type mustn't be " +
                    "'null'");
            }
            // On parser errors the generated parser may return something
            // undefined rather than 'null'.
            if (!mParser.HasErrors()) {
            // TODO  It seems that the JSourceObjectizer uses the parser result
            //       instead of the tree parser result. CHECK THIS!
            CommonTreeNodeStream treeNodes =
                new CommonTreeNodeStream(mAST2JSOMTreeAdaptor, tree);
            treeNodes.TokenStream = tokenRewriteStream;
            if (mTreeParser != null) {
                mTreeParser.Reset();
                mTreeParser.SetTreeNodeStream(treeNodes);
            } else {
                mTreeParser = new JavaTreeParser(treeNodes);
            }
            mTreeParser.EnableErrorMessageCollection(
                    isMessageCollectingEnabled);
            if (pCodeFragmentType == CodeFragmentType.ANNOTATION) {
                mTreeParser.annotation();
            } else if (   pCodeFragmentType
                       == CodeFragmentType.COMPLEX_TYPE_IDENTIFIER) {
                mTreeParser.typeIdent();
            } else if (pCodeFragmentType == CodeFragmentType.ENUM_CONSTANT) {
                mTreeParser.enumConstant();
            } else if (pCodeFragmentType == CodeFragmentType.EXPRESSION) {
                mTreeParser.expression();
            } else if (      pCodeFragmentType
                          == CodeFragmentType.CLASS_EXTENDS_CLAUSE
                       ||    pCodeFragmentType
                          == CodeFragmentType.INTERFACE_EXTENDS_CLAUSE) {
                mTreeParser.extendsClause();
            } else if (   pCodeFragmentType
                       == CodeFragmentType.FORMAL_PARAMETER_LIST) {
                mTreeParser.formalParameterList();
            } else if (   pCodeFragmentType
                       == CodeFragmentType.GENERIC_TYPE_ARGUMENT_LIST) {
                mTreeParser.genericTypeArgumentList();
            } else if (   pCodeFragmentType
                    == CodeFragmentType.GENERIC_TYPE_PARAMETER_LIST) {
                mTreeParser.genericTypeParameterList();
            } else if (   pCodeFragmentType
                    == CodeFragmentType.IMPLEMENTS_CLAUSE) {
                mTreeParser.implementsClause();
            } else if (   pCodeFragmentType
                       == CodeFragmentType.IMPORT_DECLARATION) {
                mTreeParser.importDeclaration();
            } else if (pCodeFragmentType == CodeFragmentType.JAVA_SOURCE) {
                mTreeParser.javaSource();
            } else if (pCodeFragmentType == CodeFragmentType.LOCAL_VARIABLE_DECLARATION) {
                mTreeParser.localVariableDeclaration();
            } else if (pCodeFragmentType == CodeFragmentType.MODIFIER_LIST) {
                mTreeParser.modifierList();
            } else if (pCodeFragmentType == CodeFragmentType.PRIMITIVE_TYPE) {
                mTreeParser.primitiveType();
            } else if (   pCodeFragmentType
                       == CodeFragmentType.QUALIFIED_IDENTIFIER) {
                mTreeParser.qualifiedIdentifier();
            } else if (   pCodeFragmentType == CodeFragmentType.STATEMENT
                       || pCodeFragmentType == CodeFragmentType.ASSERT_STATEMENT
                       || pCodeFragmentType == CodeFragmentType.BREAK_STATEMENT
                       || pCodeFragmentType == CodeFragmentType.CONTINUE_STATEMENT
                       || pCodeFragmentType == CodeFragmentType.DO_WHILE_STATEMENT
                       || pCodeFragmentType == CodeFragmentType.EXPRESSION_STATEMENT
                       || pCodeFragmentType == CodeFragmentType.FOR_STATEMENT
                       || pCodeFragmentType == CodeFragmentType.FOREACH_STATEMENT
                       || pCodeFragmentType == CodeFragmentType.IF_STATEMENT
                       || pCodeFragmentType == CodeFragmentType.LABELED_STATEMENT
                       || pCodeFragmentType == CodeFragmentType.RETURN_STATEMENT
                       || pCodeFragmentType == CodeFragmentType.SWITCH_STATEMENT
                       || pCodeFragmentType == CodeFragmentType.SYNCHRONIZED_STATEMENT
                       || pCodeFragmentType == CodeFragmentType.THROW_STATEMENT
                       || pCodeFragmentType == CodeFragmentType.TRY_STATEMENT
                       || pCodeFragmentType == CodeFragmentType.WHILE_STATEMENT) {
                mTreeParser.statement();
            } else if (pCodeFragmentType == CodeFragmentType.SWITCH_CASE_LABEL) {
                mTreeParser.switchCaseLabel();
            } else if (pCodeFragmentType == CodeFragmentType.SWITCH_DEFAULT_LABEL) {
                mTreeParser.switchDefaultLabel();
            } else if (pCodeFragmentType == CodeFragmentType.STATEMENT_BLOCK) {
                mTreeParser.block();
            } else if (pCodeFragmentType == CodeFragmentType.STATEMENT_BLOCK_ELEMENT) {
                mTreeParser.blockStatement();
            } else if (pCodeFragmentType == CodeFragmentType.THROWS_CLAUSE) {
                mTreeParser.throwsClause();
            } else if (pCodeFragmentType == CodeFragmentType.TRY_STATEMENT_CATCH_CLAUSE) {
                mTreeParser.catchClause();
            } else if (pCodeFragmentType == CodeFragmentType.TYPE) {
                mTreeParser.type();
            } else if (pCodeFragmentType == CodeFragmentType.TYPE_DECLARATION) {
                mTreeParser.typeDeclaration();
            } else if (pCodeFragmentType == CodeFragmentType.VARIABLE_DECLARATOR_IDENTIFIER) {
                mTreeParser.variableDeclaratorId();
            } else if (pCodeFragmentType == CodeFragmentType.VARIABLE_INITIALIZER) {
                mTreeParser.variableInitializer();
            } else if (pCodeFragmentType != null) {
                throw new JSourceUnmarshallerException(
                        UnmarshallerMessages
                            .getUnsupportedCodeFragmentTypeMessage(
                                                        pCodeFragmentType));
            } else {
                // TODO  Internationalize the message.
                throw new JSourceUnmarshallerException(
                        "The argument stating the code fragment type mustn't be " +
                        "'null'");
            }

            result.mLineCount = mLexer.Line;
            result.mTokenRewriteStream = tokenRewriteStream;
            result.mTree = tree;
            }

            return result;
        }
Example #11
0
        /**
         * Parses a piece of Java code that matches a certain grammar rule.
         *
         * @param pCodeFragment  The Java code fragment that should get parsed.
         * @param pCodeFragmentType  The code fragment type defining the grammar
         *                           rule that should be used to parse the code
         *                           fragment.
         * @param pErrorMessages  If this argument is not <code>null</code> error
         *                        messages emited by the parser will be added to
         *                        this list. Otherwise these error messages will be
         *                        written to <code>System.err</code>.
         *
         * @return  An object of type <code>JSOParser.ParserResult</code>
         *          containing the root node representing a Java code fragment and
         *          the token stream containing the tokens of the parsed source. If
         *          parsing the code fragment has been failed but no exception
         *          has been thrown <code>null</code> will be returned and it's
         *          very likely that there's at least one message within the message
         *          list passed to this method (if a list has been passed at all, of
         *          course).
         *
         * @  if parsing the code fragment
         *                                       failed.
         */
        protected ParserResult parse(
            String pCodeFragment, CodeFragmentType pCodeFragmentType,
            List<String> pErrorMessages)
        {
            ParserResult result = new ParserResult();
            try {
            result = parse(
                    new ANTLRStringStream(pCodeFragment), pCodeFragmentType,
                    pErrorMessages);
            } catch (RecognitionException re) {
            throw new JSourceUnmarshallerException(
                    UnmarshallerMessages
                    .getJavaCodeFragmentParsingFailedMessage(
                            pCodeFragment, pCodeFragmentType), re);
            } catch (JSourceUnmarshallerException jsue) {
            // Just catch 'JSourceUnmarshallerException' exceptions in order to
            // avoid jumping into the following 'catch' block.
            throw jsue;
            } catch (Exception e) {
            throw new JSourceUnmarshallerException(
                    UnmarshallerMessages
                    .getJavaCodeFragmentParsingFailedMessage(
                            pCodeFragment, pCodeFragmentType), e);
            } finally {
            if (pErrorMessages != null) {
                List<String> parserMessages;
                bool isMessageHeaderEnabled = true;
                parserMessages = mLexer.GetMessages();
                if (parserMessages.Count > 0) {
                    pErrorMessages.Add(
                            UnmarshallerMessages
                                .getParserMessagesEmitedForCodeFragmentMessage(
                                        pCodeFragment, pCodeFragmentType));
                    isMessageHeaderEnabled = false;
                    foreach (String message in parserMessages) {
                        pErrorMessages.Add(
                                UnmarshallerMessages
                                    .getLexerMessageMessage() + message);
                    }
                }
                if (mParser != null) {
                    parserMessages = mParser.GetMessages();
                    if (parserMessages.Count > 0) {
                        if (isMessageHeaderEnabled) {
                            pErrorMessages.Add(
                                    UnmarshallerMessages
                                        .getParserMessagesEmitedForCodeFragmentMessage(
                                                pCodeFragment,
                                                pCodeFragmentType));
                        }
                        isMessageHeaderEnabled = false;
                        foreach (String message in parserMessages) {
                            pErrorMessages.Add(
                                    UnmarshallerMessages
                                        .getParserMessageMessage() + message);
                        }
                    }
                }
                if (mTreeParser != null) {
                    parserMessages = mTreeParser.GetMessages();
                    if (parserMessages.Count > 0) {
                        if (isMessageHeaderEnabled) {
                            pErrorMessages.Add(
                                    UnmarshallerMessages
                                    .getParserMessagesEmitedForCodeFragmentMessage(
                                            pCodeFragment, pCodeFragmentType));
                        }
                        foreach (String message in parserMessages) {
                            String TEST_STR = "JavaTreeParser.g: ";
                            int offset = message.IndexOf(TEST_STR);
                            if (offset != -1) {
                                pErrorMessages.Add(
                                        UnmarshallerMessages
                                            .getTreeParserMessageMessage() +
                                        message.Substring(
                                                offset + TEST_STR.Length));
                            } else {
                                pErrorMessages.Add(
                                        UnmarshallerMessages
                                            .getTreeParserMessageMessage() +
                                        message);
                            }
                        }
                    }
                }
            }
            }
            if (result.mTree != null) {
            return result;
            }

            return null;
        }
Example #12
0
        // Process comparison operators
        void EvalExp1Comparison(out ParserResult result)
        {
            string comp;
            ParserResult partialResult;

            Eval2Add(out result);
            while ((comp = token) == ">" || comp == "<")
            {
                stack.Add(" comparison : " + comp);
                GetToken();
                Eval2Add(out partialResult);

                if (Debug && result.IsSeries && partialResult.IsSeries)
                {
                    Console.WriteLine("Part A ");
                    partialResult.Series.WriteToConsole();
                    Console.WriteLine("Part B");
                    result.Series.WriteToConsole();
                }
                switch (comp)
                {
                    case ">":
                        result = result.GreaterThan(partialResult);
                        break;
                    case "<":
                        result = result.LessThan(partialResult);
                        break;
                }
                if ((Debug && result.IsSeries && partialResult.IsSeries))
                {
                    Console.WriteLine("Part A " + comp + " Part B ");
                    result.Series.WriteToConsole();
                }
            }

            //Eval2Add(out result);
        }
Example #13
0
 // Process a parenthesized expression.
 void Eval6Parenthesis(out ParserResult result)
 {
     if ((token == "("))
     {
         stack.Add("opening parenthesis ( ");
         GetToken();
         Eval2Add(out result);
         if (token != ")")
             SyntaxErr(Errors.UNBALPARENS);
         GetToken();
     }
     else Atom(out result);
 }
Example #14
0
        // Evaluate a unary + or -.
        void Eval5Sign(out ParserResult result)
        {
            string op;

            op = "";
            if ((tokType == Types.DELIMITER) &&
                token == "+" || token == "-")
            {
                stack.Add(" operator : "+token);
                op = token;
                GetToken();
            }
            Eval6Parenthesis(out result);
            if (op == "-") result = new ParserResult(-1) * result;
        }
Example #15
0
        // Process an exponent.
        void Eval4Exponent(out ParserResult result)
        {
            ParserResult partialResult;

            Eval5Sign(out result);
            if (token == "^")
            {
                stack.Add(" exponent: ^");
                GetToken();
                Eval4Exponent(out partialResult);
                result = ParserResult.Pow(result, partialResult);
            }
        }
Example #16
0
 public void ParseTest(ParserResult expect, List <string> parameters, bool upperCaseKeys, bool trimQuotes)
 {
     this.AssertParseTestEqual(expect, parameters, upperCaseKeys, trimQuotes);
 }
Example #17
0
        private static int Main(string[] args)
        {
            WriteLine($"Roslynator Command Line Tool version {typeof(Program).GetTypeInfo().Assembly.GetName().Version}", Verbosity.Quiet);
            WriteLine("Copyright (c) Josef Pihrt. All rights reserved.", Verbosity.Quiet);
            WriteLine(Verbosity.Quiet);

            try
            {
                ParserResult <object> parserResult = Parser.Default.ParseArguments <
#if DEBUG
                    AnalyzeAssemblyCommandLineOptions,
                    FindSymbolsCommandLineOptions,
                    SlnListCommandLineOptions,
                    ListVisualStudioCommandLineOptions,
                    GenerateSourceReferencesCommandLineOptions,
#endif
                    FixCommandLineOptions,
                    AnalyzeCommandLineOptions,
                    ListSymbolsCommandLineOptions,
                    FormatCommandLineOptions,
                    PhysicalLinesOfCodeCommandLineOptions,
                    LogicalLinesOfCodeCommandLineOptions,
                    GenerateDocCommandLineOptions,
                    GenerateDocRootCommandLineOptions>(args);

                bool verbosityParsed = false;

                parserResult.WithParsed <AbstractCommandLineOptions>(options =>
                {
                    var defaultVerbosity = Verbosity.Normal;

                    if (options.Verbosity == null ||
                        TryParseVerbosity(options.Verbosity, out defaultVerbosity))
                    {
                        ConsoleOut.Verbosity = defaultVerbosity;

                        Verbosity fileLogVerbosity = defaultVerbosity;

                        if (options.FileLogVerbosity == null ||
                            TryParseVerbosity(options.FileLogVerbosity, out fileLogVerbosity))
                        {
                            if (options.FileLog != null)
                            {
                                var fs = new FileStream(options.FileLog, FileMode.Create, FileAccess.Write, FileShare.Read);
                                var sw = new StreamWriter(fs, Encoding.UTF8, bufferSize: 4096, leaveOpen: false);
                                Out    = new TextWriterWithVerbosity(sw)
                                {
                                    Verbosity = fileLogVerbosity
                                };
                            }

                            verbosityParsed = true;
                        }
                    }
                });

                if (!verbosityParsed)
                {
                    return(1);
                }

                return(parserResult.MapResult(
#if DEBUG
                           (AnalyzeAssemblyCommandLineOptions options) => AnalyzeAssembly(options),
                           (FindSymbolsCommandLineOptions options) => FindSymbolsAsync(options).Result,
                           (SlnListCommandLineOptions options) => SlnListAsync(options).Result,
                           (ListVisualStudioCommandLineOptions options) => ListVisualStudio(options),
                           (GenerateSourceReferencesCommandLineOptions options) => GenerateSourceReferencesAsync(options).Result,
#endif
                           (FixCommandLineOptions options) => FixAsync(options).Result,
                           (AnalyzeCommandLineOptions options) => AnalyzeAsync(options).Result,
                           (ListSymbolsCommandLineOptions options) => ListSymbolsAsync(options).Result,
                           (FormatCommandLineOptions options) => FormatAsync(options).Result,
                           (PhysicalLinesOfCodeCommandLineOptions options) => PhysicalLinesOfCodeAsync(options).Result,
                           (LogicalLinesOfCodeCommandLineOptions options) => LogicalLinesOrCodeAsync(options).Result,
                           (GenerateDocCommandLineOptions options) => GenerateDocAsync(options).Result,
                           (GenerateDocRootCommandLineOptions options) => GenerateDocRootAsync(options).Result,
                           _ => 1));
            }
            catch (Exception ex)
            {
                if (ex is AggregateException aggregateException)
                {
                    foreach (Exception innerException in aggregateException.InnerExceptions)
                    {
                        WriteError(innerException);
                    }
                }
                else if (ex is FileNotFoundException ||
                         ex is InvalidOperationException)
                {
                    WriteError(ex);
                }
                else
                {
                    throw;
                }
            }
            finally
            {
                Out?.Dispose();
                Out = null;
#if DEBUG
                if (Debugger.IsAttached)
                {
                    Console.ReadKey();
                }
#endif
            }

            return(1);
        }
Example #18
0
 internal ParserResult(ParserResult.Internal native)
     : this(&native)
 {
 }
Example #19
0
        protected bool ParsedTest()
        {
            ParserResult root = ISequencer <T> .Parse(
                "[version: ][i/code: ][message:\r\n][<headers:\r\n\r\n>][name::][|value|:\r\n|$][</>][$|body|$]",
                "HTTP/1.1 404 Not found\r\nHeader1: data1\r\nCookie: theme=light; sessionToken=abc123\r\nHeaderMultiple: x 1\r\nHeaderMultiple: x 2\r\nHeaderMultiple: x 3\r\nHeader2: data2\r\nHeader3: data3\r\nHeader4: data4\r\n\r\n      Hello! This is the body!".GetBytes()
                ).Close();

            if (IsVerbose)
            {
                Console.WriteLine(":: ParsedTest");

                Console.WriteLine(" :!*********************: headers.<$name=HeaderMultiple$>.value");
                foreach (var e in root.GetAll <string>("headers.<$name=HeaderMultiple$>.value"))
                {
                    Console.WriteLine(" :!: " + e);
                }
                Console.WriteLine(" :!*********************: ");

                Console.WriteLine("Version :");
                Console.WriteLine(root["version"]);
                Console.WriteLine("Code :");
                Console.WriteLine(root["code"]);
                Console.WriteLine("Message :");
                Console.WriteLine(root["message"]);

                Console.WriteLine("Headers :");
                foreach (var e in root.GetList("headers"))
                {
                    Console.WriteLine(e["name"] + " = " + e["value"] + "|");
                }

                Console.WriteLine("Cookies :");

                var cookies = ByteSequencer.Parse(
                    "[<cookies:$>][|name|:=][value:;|$][</>]",
                    root.GetString("headers.<|name=cookie|>.value")
                    ).Close();

                foreach (var e in cookies.GetList("cookies"))
                {
                    Console.WriteLine(e["name"] + " //=// " + e["value"]);
                }

                Console.WriteLine("Body :");
                Console.WriteLine(root["body"]);
            }

            if (!root["version"].Equals("HTTP/1.1"))
            {
                return(false);
            }

            if (!root["code"].Equals(404))
            {
                return(false);
            }

            if (!root["message"].Equals("Not found"))
            {
                return(false);
            }

            if (!root["headers.<0>.name"].Equals("Header1"))
            {
                return(false);
            }
            if (!root["headers.<0>.value"].Equals("data1"))
            {
                return(false);
            }

            if (!root["headers.<5>.name"].Equals("Header2"))
            {
                return(false);
            }
            if (!root["headers.<5>.value"].Equals("data2"))
            {
                return(false);
            }

            if (!root["headers.<6>.name"].Equals("Header3"))
            {
                return(false);
            }
            if (!root["headers.<6>.value"].Equals("data3"))
            {
                return(false);
            }

            if (!root["headers.<7>.name"].Equals("Header4"))
            {
                return(false);
            }
            if (!root["headers.<7>.value"].Equals("data4"))
            {
                return(false);
            }

            if (!root["body"].Equals("Hello! This is the body!"))
            {
                return(false);
            }

            return(true);
        }
Example #20
0
        protected override void HandleValue(ServerContext context, ParserResult result)
        {
            var input     = "";
            var selection = ' ';

            Console.WriteLine();
            Console.WriteLine(Strings.Migration.selectdb);
            Console.WriteLine();
            Console.WriteLine(
                Strings.Migration.selectgamedb.ToString(
                    Options.GameDb.Type == DatabaseOptions.DatabaseType.sqlite
                        ? Strings.Migration.currentlysqlite
                        : Strings.Migration.currentlymysql
                    )
                );

            Console.WriteLine(
                Strings.Migration.selectplayerdb.ToString(
                    Options.PlayerDb.Type == DatabaseOptions.DatabaseType.sqlite
                        ? Strings.Migration.currentlysqlite
                        : Strings.Migration.currentlymysql
                    )
                );

            Console.WriteLine();
            Console.WriteLine(Strings.Migration.cancel);

            // TODO: Remove > when moving to ReadKeyWait when console magic is ready
            Console.Write("> ");
            input     = Console.ReadLine();
            selection = input.Length > 0 ? input[0] : ' ';
            Console.WriteLine();
            DatabaseOptions db;

            if (selection.ToString() == Strings.Migration.selectgamedbkey.ToString())
            {
                db = Options.GameDb;
            }
            else if (selection.ToString() == Strings.Migration.selectplayerdbkey.ToString())
            {
                db = Options.PlayerDb;
            }
            else
            {
                Console.WriteLine(Strings.Migration.migrationcancelled);

                return;
            }

            var dbString = db == Options.GameDb ? Strings.Migration.gamedb : Strings.Migration.playerdb;

            Console.WriteLine();
            Console.WriteLine(Strings.Migration.selectdbengine.ToString(dbString));
            Console.WriteLine(Strings.Migration.migratetosqlite);
            Console.WriteLine(Strings.Migration.migratetomysql);
            Console.WriteLine();
            Console.WriteLine(Strings.Migration.cancel);

            // TODO: Remove > when moving to ReadKeyWait when console magic is ready
            Console.Write("> ");
            input     = Console.ReadLine();
            selection = input.Length > 0 ? input[0] : ' ';
            Console.WriteLine();
            var dbengine = DatabaseOptions.DatabaseType.sqlite;

            if (selection.ToString() != Strings.Migration.selectsqlitekey.ToString() &&
                selection.ToString() != Strings.Migration.selectmysqlkey.ToString())
            {
                Console.WriteLine(Strings.Migration.migrationcancelled);

                return;
            }

            if (selection.ToString() == Strings.Migration.selectmysqlkey.ToString())
            {
                dbengine = DatabaseOptions.DatabaseType.mysql;
            }

            if (db.Type == dbengine)
            {
                var engineString = dbengine == DatabaseOptions.DatabaseType.sqlite
                    ? Strings.Migration.sqlite
                    : Strings.Migration.mysql;

                Console.WriteLine();
                Console.WriteLine(Strings.Migration.alreadyusingengine.ToString(dbString, engineString));
                Console.WriteLine();
            }
            else
            {
                try
                {
                    DbInterface.Migrate(db, dbengine);
                }
                catch (Exception exception)
                {
                    Log.Error(exception);
                }
            }
        }
Example #21
0
 protected override void HandleValue(ServerContext context, ParserResult result)
 {
     NetDebug.GenerateDebugFile();
 }
Example #22
0
        public static void Main(string[] args)
        {
            CommandLineOptions clOptions = null;

            if (args.Length > 0)
            {
                ParserResult <CommandLineOptions> result = Parser.Default.ParseArguments <CommandLineOptions>(args).WithParsed(options => {
                    clOptions = options;
                });

                if (result.Tag == ParserResultType.NotParsed)
                {
                    HelpText.AutoBuild(result);
                    return;
                }
            }
            else
            {
                FreeConsole();
                bytePatchManager     = new BytePatchManager(MessageBox.Show);
                guiApp               = new Application();
                guiApp.Run(guiWindow = new PatcherGui());
                return;
            }

            if (clOptions == null)
            {
                return;
            }
            bytePatchManager = new BytePatchManager(CustomConsoleWrite);

            List <string> applicationPaths = new List <string>();
            List <int>    groups           = new List <int>(clOptions.Groups);

            if (groups.Count == 0)
            {
                Console.WriteLine("Groups need to be defined. Use --help for help.");
                return;
            }

            if (clOptions.CustomPath != null && clOptions.CustomPath.Length > 0)
            {
                if (!Directory.Exists(clOptions.CustomPath))
                {
                    Console.WriteLine("CustomPath not found");
                    return;
                }

                applicationPaths.AddRange(new CustomPath(clOptions.CustomPath).FindDllFiles());
            }
            else
            {
                applicationPaths.AddRange(new InstallationFinder.InstallationManager().FindAllChromiumInstallations());
            }

            foreach (GuiPatchGroupData patchData in bytePatchManager.PatchGroups)
            {
                if (!groups.Contains(patchData.Group))
                {
                    bytePatchManager.DisabledGroups.Add(patchData.Group);
                }
            }

            if (applicationPaths.Count == 0)
            {
                Console.WriteLine("Error: No patchable dll file found!");
            }

            foreach (string path in applicationPaths)
            {
                try {
                    DllPatcher patcher = new DllPatcher(path);
                    patcher.Patch(Console.WriteLine);
                } catch (Exception ex) {
                    Console.WriteLine("Error while patching " + path + ":" + ex.Message);
                }
            }

            if (!clOptions.NoWait)
            {
                Thread.Sleep(5000); // Wait a bit to let the user see the result
            }
        }
Example #23
0
 public static TResult MapResult <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18,
                                  T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, TResult>(
     this ParserResult <object> result,
     Func <T1, TResult> parsedFunc1,
     Func <T2, TResult> parsedFunc2,
     Func <T3, TResult> parsedFunc3,
     Func <T4, TResult> parsedFunc4,
     Func <T5, TResult> parsedFunc5,
     Func <T6, TResult> parsedFunc6,
     Func <T7, TResult> parsedFunc7,
     Func <T8, TResult> parsedFunc8,
     Func <T9, TResult> parsedFunc9,
     Func <T10, TResult> parsedFunc10,
     Func <T11, TResult> parsedFunc11,
     Func <T12, TResult> parsedFunc12,
     Func <T13, TResult> parsedFunc13,
     Func <T14, TResult> parsedFunc14,
     Func <T15, TResult> parsedFunc15,
     Func <T16, TResult> parsedFunc16,
     Func <T17, TResult> parsedFunc17,
     Func <T18, TResult> parsedFunc18,
     Func <T19, TResult> parsedFunc19,
     Func <T20, TResult> parsedFunc20,
     Func <T21, TResult> parsedFunc21,
     Func <T22, TResult> parsedFunc22,
     Func <T23, TResult> parsedFunc23,
     Func <T24, TResult> parsedFunc24,
     Func <T25, TResult> parsedFunc25,
     Func <T26, TResult> parsedFunc26,
     Func <T27, TResult> parsedFunc27,
     Func <T28, TResult> parsedFunc28,
     Func <T29, TResult> parsedFunc29,
     Func <T30, TResult> parsedFunc30,
     Func <T31, TResult> parsedFunc31,
     Func <T32, TResult> parsedFunc32,
     Func <T33, TResult> parsedFunc33,
     Func <IEnumerable <Error>, TResult> notParsedFunc)
 {
     if (!(result is Parsed <object> parsed))
     {
         return(notParsedFunc(((NotParsed <object>)result).Errors));
     }
     if (parsed.Value is T1)
     {
         return(parsedFunc1((T1)parsed.Value));
     }
     if (parsed.Value is T2)
     {
         return(parsedFunc2((T2)parsed.Value));
     }
     if (parsed.Value is T3)
     {
         return(parsedFunc3((T3)parsed.Value));
     }
     if (parsed.Value is T4)
     {
         return(parsedFunc4((T4)parsed.Value));
     }
     if (parsed.Value is T5)
     {
         return(parsedFunc5((T5)parsed.Value));
     }
     if (parsed.Value is T6)
     {
         return(parsedFunc6((T6)parsed.Value));
     }
     if (parsed.Value is T7)
     {
         return(parsedFunc7((T7)parsed.Value));
     }
     if (parsed.Value is T8)
     {
         return(parsedFunc8((T8)parsed.Value));
     }
     if (parsed.Value is T9)
     {
         return(parsedFunc9((T9)parsed.Value));
     }
     if (parsed.Value is T10)
     {
         return(parsedFunc10((T10)parsed.Value));
     }
     if (parsed.Value is T11)
     {
         return(parsedFunc11((T11)parsed.Value));
     }
     if (parsed.Value is T12)
     {
         return(parsedFunc12((T12)parsed.Value));
     }
     if (parsed.Value is T13)
     {
         return(parsedFunc13((T13)parsed.Value));
     }
     if (parsed.Value is T14)
     {
         return(parsedFunc14((T14)parsed.Value));
     }
     if (parsed.Value is T15)
     {
         return(parsedFunc15((T15)parsed.Value));
     }
     if (parsed.Value is T16)
     {
         return(parsedFunc16((T16)parsed.Value));
     }
     if (parsed.Value is T17)
     {
         return(parsedFunc17((T17)parsed.Value));
     }
     if (parsed.Value is T18)
     {
         return(parsedFunc18((T18)parsed.Value));
     }
     if (parsed.Value is T19)
     {
         return(parsedFunc19((T19)parsed.Value));
     }
     if (parsed.Value is T20)
     {
         return(parsedFunc20((T20)parsed.Value));
     }
     if (parsed.Value is T21)
     {
         return(parsedFunc21((T21)parsed.Value));
     }
     if (parsed.Value is T22)
     {
         return(parsedFunc22((T22)parsed.Value));
     }
     if (parsed.Value is T23)
     {
         return(parsedFunc23((T23)parsed.Value));
     }
     if (parsed.Value is T24)
     {
         return(parsedFunc24((T24)parsed.Value));
     }
     if (parsed.Value is T25)
     {
         return(parsedFunc25((T25)parsed.Value));
     }
     if (parsed.Value is T26)
     {
         return(parsedFunc26((T26)parsed.Value));
     }
     if (parsed.Value is T27)
     {
         return(parsedFunc27((T27)parsed.Value));
     }
     if (parsed.Value is T28)
     {
         return(parsedFunc28((T28)parsed.Value));
     }
     if (parsed.Value is T29)
     {
         return(parsedFunc29((T29)parsed.Value));
     }
     if (parsed.Value is T30)
     {
         return(parsedFunc30((T30)parsed.Value));
     }
     if (parsed.Value is T31)
     {
         return(parsedFunc31((T31)parsed.Value));
     }
     if (parsed.Value is T32)
     {
         return(parsedFunc32((T32)parsed.Value));
     }
     if (parsed.Value is T33)
     {
         return(parsedFunc33((T33)parsed.Value));
     }
     throw new InvalidOperationException();
 }
 static void Main(string[] args)
 {
     CommandLineOpts opts = new CommandLineOpts();
     ParserResult <CommandLineOpts> result = CommandLine.Parser.Default.ParseArguments <CommandLineOpts>(args)
                                             .WithParsed <CommandLineOpts>(options => RunWithOptions(options));
 }
Example #25
0
 protected ParserResult(ParserResult.Internal* native, bool skipVTables = false)
 {
     if (native == null)
         return;
     __Instance = new global::System.IntPtr(native);
 }
Example #26
0
        public Test()
        {
            string data = $"Ok, there are some important dates for us.\n " +
                          $"First is 23-10-2002. The second two are: 23/11/2002 and 24/10/02. " +
                          $"Do we have to watch crefully also these three: 10/23/2002, 23/11/2002 and 24/10/02? " +
                          $"I believe some dates may mean nothing, for example: Oct 23,20002 and October 23, 2002. " +
                          $"i think we all rule for participating. Was my brother born at 23 Oct 2002? Yes, mother at 23 October 2002. " +
                          $"I think i have been ?outed. Isn't? it?";

            try
            {
                var splitSentences = new SingleRegExpRule(@"(?<=[.!?])\s+(?=[A-Z])", RuleType.RegExpSplit, "Split sentences");

                var filterQuestions = new SingleRegExpRule(@"[?]$", RuleType.RegExpMatches, "Filter quesions");

                var filterSentencesWithDate = new MultipleRegExpRules(new List <string>
                {
                    @"\d{1,2}[/-]\d{1,2}[/-]\d{2,4}",
                    @"(?:\d{1,2} )?(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]* (?:\d{1,2}, )?\d{4}"
                }, RuleType.RegExpMatches, RulesConnectionType.Union, "Filter dates");

                var initData = new ParserResult(data, null);
                var result   = initData.SplitByRegExp(splitSentences).FilterByRegExp(filterQuestions).FilterByRegExp(filterSentencesWithDate);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            //var filterSentencesWithDate1 = new Rule(@"\d{1,2}[/-]\d{1,2}[/-]\d{2,4}",
            //    RuleType.RegExpMatches, 2, null, "Filter date (format 1)");
            //var filterSentencesWithDate2 = new Rule(@"(?:\d{1,2} )?(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]* (?:\d{1,2}, )?\d{4}",
            //    RuleType.RegExpMatches, 2, null, "Filter date (format 2)");


            //split
            Console.WriteLine("SPLITTED INTO SENTENCES");
            var split_senteces = Regex.Split(data, @"(?<=[.!?])\s+(?=[A-Z])");

            //var split_senteces = Regex.Matches(data, @"(?<=[.!?])\s+(?=[A-Z])");
            Console.WriteLine("Count: {0}", split_senteces.Length);
            for (int i = 0; i < split_senteces.Length; i++)
            {
                Console.WriteLine("#{0}: {1}", i + 1, split_senteces[i]);
            }

            //filter by condition
            Console.WriteLine("QUESTIONS");
            var questions = split_senteces.Where(sentence => Regex.Match(sentence, @"[?]$").Success);

            foreach (var sentence in questions)
            {
                Console.WriteLine(sentence);
            }

            //filter by condition
            Console.WriteLine("QUESTIONS WITH DATES");
            //var datesReg1 = @"\d{1,2}[/-]\d{1,2}[/-]\d{2,4}";
            //var datesReg2 = @"(?:\d{1,2} )?(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]* (?:\d{1,2}, )?\d{4}";
            var dateRegs = new List <string>();

            dateRegs.Add(@"\d{1,2}[/-]\d{1,2}[/-]\d{2,4}");
            dateRegs.Add(@"(?:\d{1,2} )?(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]* (?:\d{1,2}, )?\d{4}");

            foreach (var sentence in questions)
            {
                foreach (var datesReg in dateRegs)
                {
                    var matches = Regex.Matches(sentence, datesReg);
                    if (matches.Count > 0)
                    {
                        Console.WriteLine("({0}) {1}", matches.Count, sentence);
                        foreach (Match match in matches)
                        {
                            Console.Write("value: {0}, index: {1} \n", match.Value, match.Index);
                        }
                    }
                }
            }

            //var questionsWithDates = questions.Where(sentence => Regex.Match(sentence, datesReg1).Success || Regex.Match(sentence, datesReg2).Success);
            //foreach (var sentence in questionsWithDates)
            //    Console.WriteLine(sentence);

/*
 *          //count
 *          Console.WriteLine("FIND WORD 'I'");
 *          var foundWords = Regex.Matches(data, @"[.,?!]?\s+I\s+");
 *          foreach (Match res in foundWords)
 *          {
 *              Console.WriteLine("value: {0}, index: {1}", res.Value, res.Index);
 *          }
 *
 *          //calculate frequency of the word in text
 *          var words = data.Split(' ');
 *          float f = (float)foundWords.Count / words.Length * 100;
 *          Console.WriteLine("FREQUENCY: {0:0.00}%", f);
 */

            //take list of strings winth length>=1
            //iterate over list and look for matches => list of matches with index, match itselt, its lenths
            //1. total dates, total sentences with dates, print these sentences ordered by frequency.

/*
 *          //list entries
 *          Console.WriteLine("LIST ALL DATES");
 *          var datesReg1 = @"\d{1,2}[/-]\d{1,2}[/-]\d{2,4}";
 *          var datesReg2 = @"(?:\d{1,2} )?(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]* (?:\d{1,2}, )?\d{4}";
 *          var datesRes1 = Regex.Matches(data, datesReg1);
 *          var datesRes2 = Regex.Matches(data, datesReg2);
 *          foreach(Match res in datesRes1)
 *              Console.WriteLine("value: {0}, index: {1}, length: {2}",  res.Value, res.Index, res.Length);
 *          foreach (Match res in datesRes2)
 *              Console.WriteLine("value: {0}, index: {1}, length: {2}", res.Value, res.Index, res.Length);
 */

            var blocks = new List <RulesBlock>();
            //blocks.Add(new RulesBlock(blocks.Count+1, ));
        }
Example #27
0
 protected ParserResult(ParserResult.Internal* native, bool isInternalImpl = false)
 {
     __Instance = new global::System.IntPtr(native);
 }
Example #28
0
        public void Invoking_RenderParsingErrorsText_returns_appropriate_formatted_text()
        {
            // Fixture setup
            var fakeResult = new ParserResult<NullInstance>(
                ParserResultType.Options,
                new NullInstance(),
                new Error[]
                    {
                        new BadFormatTokenError("badtoken"),
                        new MissingValueOptionError(new NameInfo("x", "switch")),
                        new UnknownOptionError("unknown"),
                        new MissingRequiredOptionError(new NameInfo("", "missing")),
                        new MutuallyExclusiveSetError(new NameInfo("z", "")),
                        new SequenceOutOfRangeError(new NameInfo("s", "sequence")),
                        new NoVerbSelectedError(),
                        new BadVerbSelectedError("badverb"),
                        new HelpRequestedError(), // should be ignored
                        new HelpVerbRequestedError(null, null, false), // should be ignored 
                    },
                Maybe.Nothing<IEnumerable<Type>>());
            Func<Error, string> fakeRenderer = err =>
                {
                    switch (err.Tag)
                    {
                        case ErrorType.BadFormatTokenError:
                            return "ERR " + ((BadFormatTokenError)err).Token;
                        case ErrorType.MissingValueOptionError:
                            return "ERR " + ((MissingValueOptionError)err).NameInfo.NameText;
                        case ErrorType.UnknownOptionError:
                            return "ERR " + ((UnknownOptionError)err).Token;
                        case ErrorType.MissingRequiredOptionError:
                            return "ERR " + ((MissingRequiredOptionError)err).NameInfo.NameText;
                        case ErrorType.MutuallyExclusiveSetError:
                            return "ERR " + ((MutuallyExclusiveSetError)err).NameInfo.NameText;
                        case ErrorType.SequenceOutOfRangeError:
                            return "ERR " + ((SequenceOutOfRangeError)err).NameInfo.NameText;
                        case ErrorType.NoVerbSelectedError:
                            return "ERR no-verb-selected";
                        case ErrorType.BadVerbSelectedError:
                            return "ERR " + ((BadVerbSelectedError)err).Token;
                        default:
                            throw new InvalidOperationException();
                    }
                };

            // Exercize system
            var errorsText = HelpText.RenderParsingErrorsText(fakeResult, fakeRenderer, 2);

            // Verify outcome
            var lines = errorsText.ToNotEmptyLines();

            Assert.Equal("  ERR badtoken", lines[0]);
            Assert.Equal("  ERR x, switch", lines[1]);
            Assert.Equal("  ERR unknown", lines[2]);
            Assert.Equal("  ERR missing", lines[3]);
            Assert.Equal("  ERR z", lines[4]);
            Assert.Equal("  ERR s, sequence", lines[5]);
            Assert.Equal("  ERR no-verb-selected", lines[6]);
            Assert.Equal("  ERR badverb", lines[7]);
            // Teardown
        }
Example #29
0
        void OnFileParsed(string file, ParserResult result)
        {
            switch (result.Kind)
            {
                case ParserResultKind.Success:
                    Diagnostics.Message("Parsed '{0}'", file);
                    break;
                case ParserResultKind.Error:
                    Diagnostics.Error("Error parsing '{0}'", file);
                    break;
                case ParserResultKind.FileNotFound:
                    Diagnostics.Error("File '{0}' was not found", file);
                    break;
            }

            for (uint i = 0; i < result.DiagnosticsCount; ++i)
            {
                var diag = result.getDiagnostics(i);

                if (Options.IgnoreParseWarnings
                    && diag.Level == ParserDiagnosticLevel.Warning)
                    continue;

                if (diag.Level == ParserDiagnosticLevel.Note)
                    continue;

                Diagnostics.Message("{0}({1},{2}): {3}: {4}",
                    diag.FileName, diag.LineNumber, diag.ColumnNumber,
                    diag.Level.ToString().ToLower(), diag.Message);
            }
        }
Example #30
0
        public void Invoke_AutoBuild_for_Options_returns_appropriate_formatted_text()
        {
            // Fixture setup
            var fakeResult = new ParserResult<FakeOptions>(
                ParserResultType.Options,
                new FakeOptions(),
                new Error[]
                    {
                        new BadFormatTokenError("badtoken"),
                        new SequenceOutOfRangeError(new NameInfo("i", ""))
                    },
                Maybe.Nothing<IEnumerable<Type>>());

            // Exercize system
            var helpText = HelpText.AutoBuild(fakeResult);

            // Verify outcome
            var lines = helpText.ToString().ToNotEmptyLines().TrimStringArray();

            Assert.True(lines[0].StartsWith("CommandLine", StringComparison.Ordinal));
            Assert.True(lines[1].StartsWith("Copyright (c)", StringComparison.Ordinal));
            Assert.Equal("ERROR(S):", lines[2]);
            Assert.Equal("Token 'badtoken' is not recognized.", lines[3]);
            Assert.Equal("A sequence option 'i' is defined with few items than required.", lines[4]);
            Assert.Equal("--stringvalue    Define a string value here.", lines[5]);
            Assert.Equal("-i               Define a int sequence here.", lines[6]);
            Assert.Equal("-x               Define a boolean or switch value here.", lines[7]);
            Assert.Equal("--help           Display this help screen.", lines[8]);
            // Teardown
        }
Example #31
0
 internal ParserResult(ParserResult.Internal native)
     : this(__CopyValue(native))
 {
 }
Example #32
0
        public void Invoke_AutoBuild_for_Verbs_with_specific_verb_returns_appropriate_formatted_text()
        {
            // Fixture setup
            var fakeResult = new ParserResult<object>(
                ParserResultType.Verbs,
                new NullInstance(),
                new Error[]
                    {
                        new HelpVerbRequestedError("commit", typeof(CommitOptions), true)
                    },
                Maybe.Nothing<IEnumerable<Type>>());

            // Exercize system
            var helpText = HelpText.AutoBuild(fakeResult);

            // Verify outcome
            var lines = helpText.ToString().ToNotEmptyLines().TrimStringArray();

            Assert.True(lines[0].StartsWith("CommandLine", StringComparison.Ordinal));
            Assert.True(lines[1].StartsWith("Copyright (c)", StringComparison.Ordinal));
            Assert.Equal("-p, --patch    Use the interactive patch selection interface to chose which", lines[2]);
            Assert.Equal("changes to commit.", lines[3]);
            Assert.Equal("--amend        Used to amend the tip of the current branch.", lines[4]);
            Assert.Equal("--help         Display this help screen.", lines[5]);
            // Teardown
        }
Example #33
0
        /// <summary>
        /// Main entry point to the sample.
        /// </summary>
        public static async Task Main(string[] args)
        {
            // Parse and validate parameters

            CommandLineOptions options = null;
            ParserResult <CommandLineOptions> result = Parser.Default.ParseArguments <CommandLineOptions>(args)
                                                       .WithParsed(parsedOptions =>
            {
                options = parsedOptions;
            })
                                                       .WithNotParsed(errors =>
            {
                Environment.Exit(1);
            });

            // Instantiate the client

            #region Snippet:IotHubServiceClientInitializeWithIotHubSasCredential

            // Create an IotHubSasCredential type to use sas tokens to authenticate against your IoT Hub instance.
            // The default lifespan of the sas token is 30 minutes, and it is set to be renewed when at 15% or less of its lifespan.
            var credential = new IotHubSasCredential(options.IotHubSharedAccessPolicy, options.IotHubSharedAccessKey);

            IotHubServiceClient hubClient = new IotHubServiceClient(options.Endpoint, credential);

            #endregion Snippet:IotHubServiceClientInitializeWithIotHubSasCredential

            // Run the samples

            var deviceIdentityLifecycleSamples = new DeviceIdentityLifecycleSample(hubClient);
            await deviceIdentityLifecycleSamples.RunSampleAsync();

            var moduleIdentityLifecycleSamples = new ModuleIdentityLifecycleSample(hubClient);
            await moduleIdentityLifecycleSamples.RunSampleAsync();

            var bulkDeviceIdentityLifecycleSamples = new BulkDeviceIdentityLifecycleSample(hubClient);
            await bulkDeviceIdentityLifecycleSamples.RunSampleAsync();

            var bulkModuledentityLifecycleSamples = new BulkModuleIdentityLifecycleSample(hubClient);
            await bulkModuledentityLifecycleSamples.RunSampleAsync();

            var querySamples = new QueryTwinSample(hubClient);
            await querySamples.RunSampleAsync();

            var statisticsSample = new StatisticsSample(hubClient);
            await statisticsSample.RunSampleAsync();

            var configurationsSample = new ConfigurationSample(hubClient);
            await configurationsSample.RunSampleAsync();

            // Get SAS token to 'jobs' container in the  storage account.
            Uri containerSasUri = await GetSasUriAsync(options.StorageAccountConnectionString, "jobs").ConfigureAwait(false);

            var jobsSample = new JobsSample(hubClient, containerSasUri);
            await jobsSample.RunSampleAsync();

            // Run samples that require the device sample to be running.
            if (options.IsDeviceSampleRunning == true)
            {
                // This sample requires the device sample to be running so that it can connect to the device.
                var methodInvocationSamples = new MethodInvocationSamples(hubClient);
                await methodInvocationSamples.RunSampleAsync();
            }
        }
Example #34
0
        public void Invoke_AutoBuild_for_Verbs_with_unknown_verb_returns_appropriate_formatted_text()
        {
            // Fixture setup
            var verbTypes = Enumerable.Empty<Type>().Concat(
                new[] { typeof(AddOptions), typeof(CommitOptions), typeof(CloneOptions) });
            var fakeResult = new ParserResult<object>(
                ParserResultType.Verbs,
                new NullInstance(),
                new Error[]
                    {
                        new HelpVerbRequestedError(null, null, false)
                    },
                Maybe.Just(verbTypes));

            // Exercize system
            var helpText = HelpText.AutoBuild(fakeResult);

            // Verify outcome
            var lines = helpText.ToString().ToNotEmptyLines().TrimStringArray();

            Assert.True(lines[0].StartsWith("CommandLine", StringComparison.Ordinal));
            Assert.True(lines[1].StartsWith("Copyright (c)", StringComparison.Ordinal));
            Assert.Equal("add       Add file contents to the index.", lines[2]);
            Assert.Equal("commit    Record changes to the repository.", lines[3]);
            Assert.Equal("clone     Clone a repository into a new directory.", lines[4]);
            Assert.Equal("help      Display more information on a specific command.", lines[5]);
            // Teardown
        }
Example #35
0
 void OnFileParsed(string file, ParserResult result)
 {
     OnFileParsed(new[] { file }, result);
 }
        /// <inheritdoc />
        protected override void OnStartup(StartupEventArgs e)
        {
            // Setup
            JsonConvert.DefaultSettings = () => JsonHelper.CreateSettings();
            string basePath       = Assembly.GetExecutingAssembly().GetDirectoryPath();
            bool   consoleCreated = false;

            if (e.Args.Length > 0)
            {
                ConsoleHelper.AttachConsole(out consoleCreated);

                if (ConsoleHelper.HasConsole)
                {
                    ConsoleHelper.Show();
                }
                else
                {
                    Logger.LogError("Could not create Writer window.");
                    Shutdown();
                    return;
                }
            }

            // Configuration
            Logger.LogInformation("Loading configuration.");
            IConfiguration configuration = IConfigurationBuilderHelper.CreateConfiguration(basePath)
                                           .AddConfigurationFiles(basePath, EnvironmentHelper.GetEnvironmentName())
                                           .AddEnvironmentVariables()
                                           .AddUserSecrets()
                                           .AddArguments(e.Args)
                                           .Build();

            Parser           parser = null;
            StartupArguments args;

            try
            {
                // Command line
                Logger.LogInformation("Processing command line.");
                parser = new Parser(settings =>
                {
                    settings.CaseSensitive             = false;
                    settings.CaseInsensitiveEnumValues = true;
                });

                ParserResult <StartupArguments> result = parser.ParseArguments <StartupArguments>(e.Args);

                if (result.Tag == ParserResultType.NotParsed)
                {
                    Logger.LogError(StartupArguments.GetUsage(result));
                    Shutdown();
                    return;
                }

                args = ((Parsed <StartupArguments>)result).Value;
            }
            catch (Exception ex)
            {
                Logger.LogError(ex.CollectMessages());
                Shutdown();
                return;
            }
            finally
            {
                // in case an error occurred and the parser was not disposed
                ObjectHelper.Dispose(ref parser);
            }

            // Logging
            Logger.LogInformation("Configuring logging.");

            if (configuration.GetValue <bool>("Logging:Enabled") && args.LogLevel < LogLevel.None)
            {
                LoggerConfiguration loggerConfiguration = new();
                loggerConfiguration.ReadFrom.Configuration(configuration);
                loggerConfiguration.MinimumLevel.Is(args.LogLevel switch
                {
                    LogLevel.Trace => LogEventLevel.Verbose,
                    LogLevel.Debug => LogEventLevel.Debug,
                    LogLevel.Information => LogEventLevel.Information,
                    LogLevel.Warning => LogEventLevel.Warning,
                    LogLevel.Error => LogEventLevel.Error,
                    _ => LogEventLevel.Fatal
                });
Example #37
0
        static async Task Main(string[] args)
        {
            Stopwatch watch = new Stopwatch();

            watch.Start();

            // Parse arguments passed
            Parser parser = new Parser(with =>
            {
                with.CaseInsensitiveEnumValues = true;
                with.CaseSensitive             = false;
                with.HelpWriter = null;
            });

            ParserResult <Options> parserResult = parser.ParseArguments <Options>(args);

            parserResult.WithParsed <Options>(o => { Options.Instance = o; })
            .WithNotParsed(errs => DisplayHelp(parserResult, errs));
            Options options = Options.Instance;

            try
            {
                smithy = new Smithy();

                if (options.Quiet)
                {
                    Log.Logger = new LoggerConfiguration()
                                 .MinimumLevel.Error()
                                 .WriteTo.Console()
                                 .CreateLogger();
                }

                else
                {
                    Log.Logger = new LoggerConfiguration()
                                 .MinimumLevel.Information()
                                 .WriteTo.Console()
                                 .CreateLogger();
                }

                await DoCrawl(smithy);

                Uri    uri     = new Uri(smithy.Url);
                string safeUri = uri.Authority;
                safeUri = safeUri.Replace('.', '_');

                if (string.IsNullOrEmpty(smithy.Output))
                {
                    smithy.Output = "wordlist_" + safeUri + DateTime.Now.ToString("_HH-mm-ss") + ".txt";

                    if (smithy.Output.Length > 250)
                    {
                        smithy.Output = "wordlist_" + DateTime.Now.ToString("M-dd-yyyy_HH-mm-ss") + ".txt";
                    }
                }

                Console.WriteLine($"\n[+] Crawl finished, writing to file: {smithy.Output}\n");

                using (StreamWriter outfile = new StreamWriter(smithy.Output))
                {
                    foreach (var word in wordlist)
                    {
                        await outfile.WriteLineAsync(word);
                    }
                }

                watch.Stop();
                Console.WriteLine("Execution time: " + watch.ElapsedMilliseconds / 1000 + " Seconds");
            }

            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Example #38
0
        private static int Main(string[] args)
        {
#if DEBUG
            if (args.LastOrDefault() == "--debug")
            {
                WriteArgs(args.Take(args.Length - 1).ToArray(), Verbosity.Quiet);
                return(ExitCodes.NotSuccess);
            }
#endif
            Parser parser = null;
            try
            {
                parser = CreateParser(ignoreUnknownArguments: true);

                if (args == null ||
                    args.Length == 0)
                {
                    HelpCommand.WriteCommandsHelp();
                    return(ExitCodes.Success);
                }

                bool?success = null;

                ParserResult <BaseCommandLineOptions> defaultResult = parser
                                                                      .ParseArguments <BaseCommandLineOptions>(args)
                                                                      .WithParsed(options =>
                {
                    if (!options.Help)
                    {
                        return;
                    }

                    string commandName = args?.FirstOrDefault();
                    Command command    = (commandName != null)
                            ? CommandLoader.LoadCommand(typeof(Program).Assembly, commandName)
                            : null;

                    if (!ParseVerbosityAndOutput(options))
                    {
                        success = false;
                        return;
                    }

                    WriteArgs(args, Verbosity.Diagnostic);

                    if (command != null)
                    {
                        HelpCommand.WriteCommandHelp(command);
                    }
                    else
                    {
                        HelpCommand.WriteCommandsHelp();
                    }

                    success = true;
                });

                if (success == false)
                {
                    return(ExitCodes.Error);
                }

                if (success == true)
                {
                    return(ExitCodes.Success);
                }

                parser = CreateParser();

                ParserResult <object> parserResult = parser.ParseArguments(
                    args,
                    new Type[]
                {
                    typeof(AnalyzeCommandLineOptions),
                    typeof(FixCommandLineOptions),
                    typeof(FormatCommandLineOptions),
                    typeof(GenerateDocCommandLineOptions),
                    typeof(GenerateDocRootCommandLineOptions),
                    typeof(HelpCommandLineOptions),
                    typeof(ListSymbolsCommandLineOptions),
                    typeof(LogicalLinesOfCodeCommandLineOptions),
                    typeof(MigrateCommandLineOptions),
                    typeof(PhysicalLinesOfCodeCommandLineOptions),
                    typeof(RenameSymbolCommandLineOptions),
                    typeof(SpellcheckCommandLineOptions),
#if DEBUG
                    typeof(AnalyzeAssemblyCommandLineOptions),
                    typeof(FindSymbolsCommandLineOptions),
                    typeof(GenerateSourceReferencesCommandLineOptions),
                    typeof(ListVisualStudioCommandLineOptions),
                    typeof(ListReferencesCommandLineOptions),
                    typeof(SlnListCommandLineOptions),
#endif
                });

                parserResult.WithNotParsed(e =>
                {
                    if (e.Any(f => f.Tag == ErrorType.VersionRequestedError))
                    {
                        Console.WriteLine(typeof(Program).GetTypeInfo().Assembly.GetName().Version);
                        success = false;
                        return;
                    }

                    var helpText = new HelpText(SentenceBuilder.Create(), HelpCommand.GetHeadingText());

                    helpText = HelpText.DefaultParsingErrorsHandler(parserResult, helpText);

                    VerbAttribute verbAttribute = parserResult.TypeInfo.Current.GetCustomAttribute <VerbAttribute>();

                    if (verbAttribute != null)
                    {
                        helpText.AddPreOptionsText(Environment.NewLine + HelpCommand.GetFooterText(verbAttribute.Name));
                    }

                    Console.Error.WriteLine(helpText);

                    success = false;
                });

                if (success == true)
                {
                    return(ExitCodes.Success);
                }

                if (success == false)
                {
                    return(ExitCodes.Error);
                }

                parserResult.WithParsed <AbstractCommandLineOptions>(
                    options =>
                {
                    if (ParseVerbosityAndOutput(options))
                    {
                        WriteArgs(args, Verbosity.Diagnostic);
                    }
                    else
                    {
                        success = false;
                    }
                });

                if (success == false)
                {
                    return(ExitCodes.Error);
                }

                return(parserResult.MapResult(
                           (MSBuildCommandLineOptions options) =>
                {
                    switch (options)
                    {
                    case AnalyzeCommandLineOptions analyzeCommandLineOptions:
                        return AnalyzeAsync(analyzeCommandLineOptions).Result;

                    case FixCommandLineOptions fixCommandLineOptions:
                        return FixAsync(fixCommandLineOptions).Result;

                    case FormatCommandLineOptions formatCommandLineOptions:
                        return FormatAsync(formatCommandLineOptions).Result;

                    case GenerateDocCommandLineOptions generateDocCommandLineOptions:
                        return GenerateDocAsync(generateDocCommandLineOptions).Result;

                    case GenerateDocRootCommandLineOptions generateDocRootCommandLineOptions:
                        return GenerateDocRootAsync(generateDocRootCommandLineOptions).Result;

                    case ListSymbolsCommandLineOptions listSymbolsCommandLineOptions:
                        return ListSymbolsAsync(listSymbolsCommandLineOptions).Result;

                    case LogicalLinesOfCodeCommandLineOptions logicalLinesOfCodeCommandLineOptions:
                        return LogicalLinesOrCodeAsync(logicalLinesOfCodeCommandLineOptions).Result;

                    case PhysicalLinesOfCodeCommandLineOptions physicalLinesOfCodeCommandLineOptions:
                        return PhysicalLinesOfCodeAsync(physicalLinesOfCodeCommandLineOptions).Result;

                    case RenameSymbolCommandLineOptions renameSymbolCommandLineOptions:
                        return RenameSymbolAsync(renameSymbolCommandLineOptions).Result;

                    case SpellcheckCommandLineOptions spellcheckCommandLineOptions:
                        return SpellcheckAsync(spellcheckCommandLineOptions).Result;

#if DEBUG
                    case FindSymbolsCommandLineOptions findSymbolsCommandLineOptions:
                        return FindSymbolsAsync(findSymbolsCommandLineOptions).Result;

                    case GenerateSourceReferencesCommandLineOptions generateSourceReferencesCommandLineOptions:
                        return GenerateSourceReferencesAsync(generateSourceReferencesCommandLineOptions).Result;

                    case ListReferencesCommandLineOptions listReferencesCommandLineOptions:
                        return ListReferencesAsync(listReferencesCommandLineOptions).Result;

                    case SlnListCommandLineOptions slnListCommandLineOptions:
                        return SlnListAsync(slnListCommandLineOptions).Result;
#endif
                    default:
                        throw new InvalidOperationException();
                    }
                },
                           (AbstractCommandLineOptions options) =>
                {
                    switch (options)
                    {
                    case HelpCommandLineOptions helpCommandLineOptions:
                        return Help(helpCommandLineOptions);

                    case MigrateCommandLineOptions migrateCommandLineOptions:
                        return Migrate(migrateCommandLineOptions);

#if DEBUG
                    case AnalyzeAssemblyCommandLineOptions analyzeAssemblyCommandLineOptions:
                        return AnalyzeAssembly(analyzeAssemblyCommandLineOptions);

                    case ListVisualStudioCommandLineOptions listVisualStudioCommandLineOptions:
                        return ListVisualStudio(listVisualStudioCommandLineOptions);
#endif
                    default:
                        throw new InvalidOperationException();
                    }
                },
                           _ => ExitCodes.Error));
            }
            catch (Exception ex) when(ex is AggregateException ||
                                      ex is FileNotFoundException ||
                                      ex is InvalidOperationException)
            {
                WriteError(ex);
            }
            finally
            {
                parser?.Dispose();
                Out?.Dispose();
                Out = null;
            }

            return(ExitCodes.Error);
        }
Example #39
0
        protected bool FunctionalTest()
        {
            ParserResult root = ((T)Activator.CreateInstance(typeof(T), "HTTP/1.1 404 Not found\r\nHeader1: data1\r\nErrorHeader\r\nHeader2: data2\r\nHeader3: data3\r\nHeader4: data4\r\nErrorHeaderFinal\r\n\r\nHello! This is the body!"))
                                .Until("version", " ")
                                .Until("code", " ", converter: s => int.Parse(s))
                                .Until("message", "\r\n")
                                .RepeatUntil("headers", "\r\n\r\n", b => b
                                             .Or(bb => bb
                                                 .Until("name", ":", validator: s => !s.Contains("\r\n"))
                                                 .Until("value", "\r\n", converter: s => s.Trim()),
                                                 bb => bb
                                                 .Until("error", "\r\n"),
                                                 bb => bb
                                                 .ToEnd("final", converter: bs => bs.GetString())))
                                .ToEnd("body", converter: bs => bs.GetString())
                                .Close();

            if (IsVerbose)
            {
                Console.WriteLine(":: FunctionalTest");

                Console.WriteLine("Version :");
                Console.WriteLine(root["version"]);
                Console.WriteLine("Code :");
                Console.WriteLine(root["code"]);
                Console.WriteLine("Message :");
                Console.WriteLine(root["message"]);

                Console.WriteLine("Headers :");
                foreach (var e in root.GetList("headers"))
                {
                    if (e.ContainsKey("final"))
                    {
                        Console.WriteLine(e["final"] + "|");
                    }
                    else if (e.ContainsKey("error"))
                    {
                        Console.WriteLine(e["error"] + "|");
                    }
                    else
                    {
                        Console.WriteLine(e["name"] + " = " + e["value"] + "|");
                    }
                }

                Console.WriteLine("Body :");
                Console.WriteLine(root["body"]);
            }

            if (!root["version"].Equals("HTTP/1.1"))
            {
                return(false);
            }

            if (!root["code"].Equals(404))
            {
                return(false);
            }

            if (!root["message"].Equals("Not found"))
            {
                return(false);
            }

            if (!root["headers.<0>.name"].Equals("Header1"))
            {
                return(false);
            }
            if (!root["headers.<0>.value"].Equals("data1"))
            {
                return(false);
            }

            if (!root["headers.<1>.error"].Equals("ErrorHeader"))
            {
                return(false);
            }

            if (!root["headers.<2>.name"].Equals("Header2"))
            {
                return(false);
            }
            if (!root["headers.<2>.value"].Equals("data2"))
            {
                return(false);
            }

            if (!root["headers.<3>.name"].Equals("Header3"))
            {
                return(false);
            }
            if (!root["headers.<3>.value"].Equals("data3"))
            {
                return(false);
            }

            if (!root["headers.<4>.name"].Equals("Header4"))
            {
                return(false);
            }
            if (!root["headers.<4>.value"].Equals("data4"))
            {
                return(false);
            }

            if (!root["headers.<5>.final"].Equals("ErrorHeaderFinal"))
            {
                return(false);
            }

            if (!root["body"].Equals("Hello! This is the body!"))
            {
                return(false);
            }

            return(true);
        }
Example #40
0
        /// <summary>
        /// Entry point method for CLI.
        /// </summary>
        public static int Main(string[] args)
        {
            // Interactive mode: commands separated by line
            if (args.Length == 0)
            {
                while (true)
                {
                    Console.Write("$ ");
                    args = Console.ReadLine()?.Split(' ');
                    ParserResult <object> parseInteractiveResult = Parser.Default.ParseArguments <RunCommand,
                                                                                                  ExtractCommand,
                                                                                                  TestCommand,
                                                                                                  GenerateCommand,
                                                                                                  HeadersCommand,
                                                                                                  CsvConvertCommand,
                                                                                                  ExitCommand,
                                                                                                  WriteSchemaCommand>(args);

                    if (parseInteractiveResult is Parsed <object> parsedInteractive)
                    {
                        switch (parsedInteractive.Value)
                        {
                        case RunCommand runOptions:
                            runOptions.Execute();
                            break;

                        case ExtractCommand extractOptions:
                            extractOptions.Execute();
                            break;

                        case TestCommand testOptions:
                            testOptions.Execute();
                            break;

                        case GenerateCommand generateOptions:
                            generateOptions.Execute();
                            break;

                        case HeadersCommand headersOptions:
                            headersOptions.Execute();
                            break;

                        case CsvConvertCommand convertOptions:
                            convertOptions.Execute();
                            break;

                        case WriteSchemaCommand writeSchemaOptions:
                            writeSchemaOptions.Execute();
                            break;

                        case ExitCommand _:
                            return(0);

                        default:
                            return(-1);
                        }
                    }
                    // Exit and show help if command is not recognized
                    else if (parseInteractiveResult is NotParsed <object> )
                    {
                        return(-1);
                    }
                }
            }

            // Single command mode
            ParserResult <object> parseResult = Parser.Default.ParseArguments <RunCommand,
                                                                               ExtractCommand,
                                                                               TestCommand,
                                                                               GenerateCommand,
                                                                               HeadersCommand,
                                                                               CsvConvertCommand,
                                                                               WriteSchemaCommand,
                                                                               ExitCommand>(args);

            if (parseResult is Parsed <object> parsed)
            {
                switch (parsed.Value)
                {
                case RunCommand runOptions:
                    runOptions.Execute();
                    break;

                case ExtractCommand extractOptions:
                    extractOptions.Execute();
                    break;

                case TestCommand testOptions:
                    testOptions.Execute();
                    break;

                case GenerateCommand generateOptions:
                    generateOptions.Execute();
                    break;

                case HeadersCommand headersOptions:
                    headersOptions.Execute();
                    break;

                case CsvConvertCommand convertOptions:
                    convertOptions.Execute();
                    break;

                case WriteSchemaCommand writeSchemaOptions:
                    writeSchemaOptions.Execute();
                    break;

                case ExitCommand _:
                    return(0);
                }
            }

            return(-1);
        }
Example #41
0
 /// <summary>
 /// Creates a default instance of the <see cref="CommandLine.Text.HelpText"/> class,
 /// automatically handling verbs or options scenario.
 /// </summary>
 /// <param name='parserResult'>The <see cref="CommandLine.ParserResult{T}"/> containing the instance that collected command line arguments parsed with <see cref="CommandLine.Parser"/> class.</param>
 /// <param name="maxDisplayWidth">The maximum width of the display.</param>
 /// <returns>
 /// An instance of <see cref="CommandLine.Text.HelpText"/> class.
 /// </returns>
 /// <remarks>This feature is meant to be invoked automatically by the parser, setting the HelpWriter property
 /// of <see cref="CommandLine.ParserSettings"/>.</remarks>
 public static HelpText AutoBuild <T>(ParserResult <T> parserResult, int maxDisplayWidth = DefaultMaximumLength)
 {
     return(AutoBuild <T>(parserResult, h => h, maxDisplayWidth));
 }
Example #42
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SummaryResult" /> class.
 /// </summary>
 /// <param name="parserResult">The parser result.</param>
 public SummaryResult(ParserResult parserResult)
     : this(parserResult.Assemblies, parserResult.ParserName, parserResult.SupportsBranchCoverage, parserResult.SourceDirectories)
 {
 }
Example #43
0
        /// <summary>
        /// Creates a new instance of the <see cref="CommandLine.Text.HelpText"/> class using common defaults.
        /// </summary>
        /// <returns>
        /// An instance of <see cref="CommandLine.Text.HelpText"/> class.
        /// </returns>
        /// <param name='parserResult'>The <see cref="CommandLine.ParserResult{T}"/> containing the instance that collected command line arguments parsed with <see cref="CommandLine.Parser"/> class.</param>
        /// <param name='onError'>A delegate used to customize the text block of reporting parsing errors text block.</param>
        /// <param name='onExample'>A delegate used to customize <see cref="CommandLine.Text.Example"/> model used to render text block of usage examples.</param>
        /// <param name="verbsIndex">If true the output style is consistent with verb commands (no dashes), otherwise it outputs options.</param>
        /// <param name="maxDisplayWidth">The maximum width of the display.</param>
        /// <remarks>The parameter <paramref name="verbsIndex"/> is not ontly a metter of formatting, it controls whether to handle verbs or options.</remarks>
        public static HelpText AutoBuild <T>(
            ParserResult <T> parserResult,
            Func <HelpText, HelpText> onError,
            Func <Example, Example> onExample,
            bool verbsIndex     = false,
            int maxDisplayWidth = DefaultMaximumLength)
        {
            var auto = new HelpText
            {
                Heading   = HeadingInfo.Empty,
                Copyright = CopyrightInfo.Empty,
                AdditionalNewLineAfterOption = true,
                AddDashesToOption            = !verbsIndex,
                MaximumDisplayWidth          = maxDisplayWidth
            };

            try
            {
                auto.Heading   = HeadingInfo.Default;
                auto.Copyright = CopyrightInfo.Default;
            }
            catch (Exception)
            {
                auto = onError(auto);
            }

            var errors = Enumerable.Empty <Error>();

            if (onError != null && parserResult.Tag == ParserResultType.NotParsed)
            {
                errors = ((NotParsed <T>)parserResult).Errors;

                if (errors.OnlyMeaningfulOnes().Any())
                {
                    auto = onError(auto);
                }
            }

            ReflectionHelper.GetAttribute <AssemblyLicenseAttribute>()
            .Do(license => license.AddToHelpText(auto, true));

            var usageAttr  = ReflectionHelper.GetAttribute <AssemblyUsageAttribute>();
            var usageLines = HelpText.RenderUsageTextAsLines(parserResult, onExample).ToMaybe();

            if (usageAttr.IsJust() || usageLines.IsJust())
            {
                var heading = auto.SentenceBuilder.UsageHeadingText();
                if (heading.Length > 0)
                {
                    auto.AddPreOptionsLine(heading);
                }
            }

            usageAttr.Do(
                usage => usage.AddToHelpText(auto, true));

            usageLines.Do(
                lines => auto.AddPreOptionsLines(lines));

            if ((verbsIndex && parserResult.TypeInfo.Choices.Any()) ||
                errors.Any(e => e.Tag == ErrorType.NoVerbSelectedError))
            {
                auto.AddDashesToOption = false;
                auto.AddVerbs(parserResult.TypeInfo.Choices.ToArray());
            }
            else
            {
                auto.AddOptions(parserResult);
            }

            return(auto);
        }
Example #44
0
 protected abstract void Handle([NotNull] TContext context, [NotNull] ParserResult result);
Example #45
0
        public virtual void Calculate(DateTime t1, DateTime t2)
        {
            var t1a = t1;
            var t2a = t2;

            Logger.OnLogEvent += Logger_OnLogEvent;

            var seriesBeforeCalc = this.Clone();

            //if( this.TimeInterval == TimeSeries.TimeInterval.Irregular)
            t2a = t2.AddDays(1);    // we may need midnight value in the next day.

            if (this.TimeInterval == TimeSeries.TimeInterval.Daily)
            {
                // daily_wrdo_pu needs AdjustStartingDate
                t1a = this.AdjustStartingDateFromProperties(t1, t2a);   // DO DO??? needed??
            }

            Exception error = new Exception();

            if (Expression != null && Expression.Trim() != "")
            {
                string tmpExpression = Expression;
                Logger.WriteLine("begin Calculate()");
                Expression = ExpressionPreProcessor();
                ParserResult result = null;
                try
                {
                    result = Parser.Evaluate(this.Expression, t1a, t2a, this.TimeInterval);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    Logger.WriteLine(e.Message, "ui");
                    Messages.Add(e.Message);
                    error  = e;
                    result = null;
                }

                if (result != null && (result.IsDouble || result.IsInteger))
                { // constant expression, need to convert to a Series.
                    Series constant = new Series();
                    constant.TimeInterval = this.TimeInterval;
                    constant = Math.FillMissingWithZero(constant, t1, t2);
                    if (result.IsDouble)
                    {
                        constant = Math.Add(constant, result.Double);
                    }
                    else
                    {
                        constant = Math.Add(constant, result.Integer);
                    }
                    result = new ParserResult(constant);
                }

                if (result != null && result.IsSeries)
                {
                    result.Series.Trim(t1, t2);
                    //var s = result.Series;
                    //result.Series = Math.Subset(s, t1, t2); // trim extra data used for calculations

                    Logger.WriteLine("Calculation result has " + result.Series.Count + " rows");
                    this.TimeInterval = result.Series.TimeInterval;
                    string tableName = this.Table.TableName;

                    this.Table           = result.Series.Table;
                    this.Table.TableName = tableName;
                    if (m_db != null)
                    {
                        // Logger.WriteLine("Setting Flags");
                        m_db.Quality.SetFlags(this);
                    }

                    this.Table.AcceptChanges();// prevents error releated to Deleted rows from Trim() above.
                    foreach (DataRow row in this.Table.Rows)
                    {
                        row.SetAdded(); // so database will insert these rows.
                    }
                    if (m_db != null)   // database is not required for calculations.
                    {
                        //bool canSave = m_db.Server.HasSavePrivilge(this.Table.TableName);
                        //  if(canSave)
                        m_db.SaveTimeSeriesTable(this.ID, this, DatabaseSaveOptions.UpdateExisting);
                        Expression = tmpExpression;

                        if (seriesBeforeCalc.TimeInterval != this.TimeInterval ||
                            seriesBeforeCalc.Units != this.Units)
                        {
                            Logger.WriteLine("Warning Units or interval has changed.");
                            //if(canSave)
                            m_db.SaveProperties(this); // time interval, units, are dependent on calculation.
                        }
                    }
                }
                else
                {
                    Clear();
                    Console.WriteLine(error.Message);
                    Logger.WriteLine(error.Message);
                }

                Logger.WriteLine("Calculate() completed");
                Logger.OnLogEvent -= Logger_OnLogEvent;
            }
        }
Example #46
0
 public CommandLineParsingException(ParserResult <object> parserResult)
 {
     ParserResult = parserResult;
 }
        static async Task <int> Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                         .WriteTo.Console()
                         .CreateLogger();

            ParserResult <CommandlineArgs> argsResult = Parser.Default.ParseArguments <CommandlineArgs>(args);

            if (argsResult is NotParsed <CommandlineArgs> )
            {
                Log.Logger.Error("Unable to parse arguments, be sure to include the path to the 'repos.json' file");

                return(1);
            }

            CommandlineArgs parsedArgs = ((Parsed <CommandlineArgs>)argsResult).Value;

            if (!File.Exists(parsedArgs.RepositoryJson))
            {
                Log.Logger.Error($"Unable to locate {parsedArgs.RepositoryJson}");
                return(2);
            }

            RepositoryRoot configRoot = JsonConvert.DeserializeObject <RepositoryRoot>(await File.ReadAllTextAsync(parsedArgs.RepositoryJson));

            IHost host = new HostBuilder()
                         .ConfigureLogging(loggingBuilder =>
            {
                loggingBuilder.AddSerilog(Log.Logger);
            })
                         .ConfigureServices(services =>
            {
                if (!string.IsNullOrEmpty(parsedArgs.ProxyUrl))
                {
                    services.AddSingleton <IWebProxy>(_ => new WebProxy(parsedArgs.ProxyUrl));
                }

                services.AddSingleton <IGitHubClient>(provider =>
                {
                    IWebProxy proxy = provider.GetService <IWebProxy>();
                    SimpleJsonSerializer jsonSerializer = new SimpleJsonSerializer();

                    return(new GitHubClient(new Connection(new ProductHeaderValue(ClientName), new Uri(parsedArgs.GithubApi),
                                                           new InMemoryCredentialStore(new Credentials(parsedArgs.GithubToken)), new HttpClientAdapter(
                                                               () => new HttpClientHandler
                    {
                        Proxy = proxy
                    }), jsonSerializer)));
                });

                services
                .AddSingleton(parsedArgs)
                .AddSingleton(configRoot)
                .AddSingleton(x => new GhStandardFileSetFactory(x.GetRequiredService <RepositoryRoot>(), parsedArgs.RepositoryJson))
                .AddSingleton <GhStandardContentApplier>();
            })
                         .Build();

            GhStandardFileSetFactory fileSetFactory = host.Services.GetRequiredService <GhStandardFileSetFactory>();
            GhStandardContentApplier applier        = host.Services.GetRequiredService <GhStandardContentApplier>();

            IEnumerable <KeyValuePair <string, JObject> > repos;

            if (!string.IsNullOrEmpty(parsedArgs.Repository) &&
                configRoot.Repositories.TryGetValue(parsedArgs.Repository, out var singleRepo))
            {
                repos = new[] { KeyValuePair.Create(parsedArgs.Repository, singleRepo) };
            }
            else if (!string.IsNullOrEmpty(parsedArgs.Repository))
            {
                // Try looking for a partial match
                var match = configRoot.Repositories.Keys.FirstOrDefault(s =>
                                                                        s.Split('/').Last().Equals(parsedArgs.Repository, StringComparison.OrdinalIgnoreCase));

                if (match == null)
                {
                    Log.Error("Unable to run for {Repository} alone", parsedArgs.Repository);
                    return(3);
                }

                repos = new[] { KeyValuePair.Create(match, configRoot.Repositories[match]) };
            }
            else
            {
                repos = configRoot.Repositories;
            }

            foreach ((string repository, JObject config) in repos)
            {
                GhStandardFileSet fileSet = fileSetFactory.GetFileSet(config);
                if (fileSet.Count == 0)
                {
                    Log.Debug("Skipping {Repository}, no files to manage", repository);
                    continue;
                }

                string[] repoParts = repository.Split('/');

                string repoOrg  = repoParts[0];
                string repoName = repoParts[1];

                Log.Information("Applying {Count} files to {Organization} / {Repository}", fileSet.Count, repoOrg, repoName);

                await applier.Apply(repoOrg, repoName, fileSet);
            }

            return(0);
        }
        public IEnumerable <CodeSpecificException> InitializeCodeModel(CppCodeModel codeModel, IncludeManagerParameter parameter)
        {
            HashSet <string>             parsedIncludes         = new HashSet <string>(parameter.KnownIncludes);
            List <CodeSpecificException> codeSpecificExceptions = new List <CodeSpecificException>();
            VirtualFile cacheFile = fileSystem.GetFile(IncludeFilePath.CleanPath().ResolvePathName(environmentService.PathNames));

            includeCache.LoadCache(cacheFile);

            UpdateCache();

            codeModel.IncludeDirectories = parameter.IncludeDirectories;

            codeModel.RegisterIncludeTypeFinder(s => FindIncludeType(s, parameter.IncludeDirectories));
            this.codeModel = codeModel;

            return(codeSpecificExceptions);

            void UpdateCache()
            {
                log.LogVerbose("Start updating the include cache.");
                Stopwatch loadWatch = new Stopwatch();

                loadWatch.Start();
                using (IIncludeCacheTransaction cacheTransaction = includeCache.StartTransaction())
                {
                    Stopwatch checkWatch = new Stopwatch();
                    checkWatch.Start();
                    foreach (IncludeCacheEntry staleEntry in FindStaleAndOutdatedEntries().ToArray())
                    {
                        cacheTransaction.DeleteEntry(staleEntry);
                    }
                    checkWatch.Stop();
                    log.LogVerbose($"Checked files in {checkWatch.ElapsedMilliseconds} ms.");

                    AddOrUpdate(parameter.IncludeDefinitions, cacheTransaction);
                }
                loadWatch.Stop();
                log.LogVerbose($"Finished updating the include cache in {loadWatch.ElapsedMilliseconds} ms.");

                IEnumerable <IncludeCacheEntry> FindStaleAndOutdatedEntries()
                {
                    return(includeCache.Entries.Where(e => !fileSystem.FileExists(e.File) ||
                                                      fileSystem.GetLastWriteTime(e.File) != e.LastWriteTime));
                }

                void AddOrUpdate(IEnumerable <IncludeDefinition> includes, IIncludeCacheTransaction cacheTransaction)
                {
                    Stack <IncludeDefinition> unvisited = new Stack <IncludeDefinition>(includes);

                    while (unvisited.Any())
                    {
                        IncludeDefinition include = unvisited.Pop();
                        if (TryFindInclude(include, out IncludeFindResult findResult))
                        {
                            IEnumerable <IncludeDefinition> childDefinitions;
                            if (findResult.IsInCache)
                            {
                                VirtualFile      cacheSourceFile    = fileSystem.GetFile(findResult.IncludeCacheEntry.File);
                                VirtualDirectory cacheBaseDirectory = fileSystem.GetDirectory(findResult.IncludeCacheEntry.BaseDirectory);
                                parsedIncludes.Add(cacheSourceFile.GetRelativePath(cacheBaseDirectory));
                                childDefinitions = findResult.IncludeCacheEntry.Includes
                                                   .Select(i => new IncludeDefinition(i, cacheSourceFile,
                                                                                      cacheBaseDirectory));
                            }
                            else
                            {
                                parsedIncludes.Add(findResult.IncludeFile.GetRelativePath(findResult.IncludeBaseDirectory));
                                childDefinitions = ProcessInclude(findResult.IncludeFile, findResult.IncludeBaseDirectory);
                            }

                            foreach (IncludeDefinition childDefinition in childDefinitions)
                            {
                                unvisited.Push(childDefinition);
                            }
                        }
                    }

                    IEnumerable <IncludeDefinition> ProcessInclude(VirtualFile findResultIncludeFile, VirtualDirectory findResultIncludeBaseDirectory)
                    {
                        ParserResult parserResult = fileParser.Parse(findResultIncludeFile);

                        if (!parserResult.Success)
                        {
                            codeSpecificExceptions.AddRange(parserResult.Exceptions);
                            cacheTransaction.AddEntry(new IncludeCacheEntry(findResultIncludeFile.FullName,
                                                                            false,
                                                                            findResultIncludeFile.LastWriteTime,
                                                                            findResultIncludeBaseDirectory.FullName,
                                                                            Enumerable.Empty <string>(),
                                                                            Enumerable.Empty <string>()));
                            return(Enumerable.Empty <IncludeDefinition>());
                        }

                        foreach (IType type in parserResult.Types.Keys)
                        {
                            codeModel.AddType(type, findResultIncludeFile, findResultIncludeBaseDirectory);
                        }

                        codeSpecificExceptions.AddRange(parserResult.Exceptions);
                        cacheTransaction.AddEntry(new IncludeCacheEntry(findResultIncludeFile.FullName,
                                                                        true,
                                                                        findResultIncludeFile.LastWriteTime,
                                                                        findResultIncludeBaseDirectory.FullName,
                                                                        parserResult.Types.Keys.Select(t => t.FullName),
                                                                        parserResult.Includes));
                        return(parserResult.Includes.Select(
                                   i => new IncludeDefinition(
                                       i, findResultIncludeFile, findResultIncludeBaseDirectory)));
                    }

                    bool TryFindInclude(IncludeDefinition current, out IncludeFindResult result)
                    {
                        if (current.Include.Trim().StartsWith("<", StringComparison.Ordinal))
                        {
                            //system includes in form <algorithms> are ignored
                            result = null;
                            return(false);
                        }

                        //Try parse relative to source
                        if (current.DefinitionSourceFile.Parent.TryGetFileFromPath(current.Include, out VirtualFile file))
                        {
                            if (parsedIncludes.Contains(file.GetRelativePath(current.DefinitionSourceBaseDirectory)))
                            {
                                result = null;
                                return(false);
                            }

                            result = includeCache.TryGetCacheEntry(file.FullName, out IncludeCacheEntry cacheEntry)
                                         ? new IncludeFindResult(cacheEntry)
                                         : new IncludeFindResult(file, current.DefinitionSourceBaseDirectory);
                            return(true);
                        }

                        //Parse relative to include path
                        foreach (VirtualDirectory includeDirectory in parameter.IncludeDirectories.Values.Where(v => v != null))
                        {
                            if (includeDirectory.TryGetFileFromPath(current.Include, out file))
                            {
                                if (parsedIncludes.Contains(file.GetRelativePath(includeDirectory)))
                                {
                                    result = null;
                                    return(false);
                                }

                                result = includeCache.TryGetCacheEntry(file.FullName, out IncludeCacheEntry cacheEntry)
                                             ? new IncludeFindResult(cacheEntry)
                                             : new IncludeFindResult(file, includeDirectory);
                                return(true);
                            }
                        }

                        log.LogWarning($"Could not find include {current.Include}. Possible types from these files will not be parsed.");
                        result = null;
                        return(false);
                    }
                }
            }
        }
Example #49
0
        public bool AcceptLine (SubString ss)
        {
            Result = ParserResult.Continue;
            CurrentLine = ss;

            Partial_BeginLine ();

            var bs = ss.BaseString;
            var begin = ss.Begin;
            var end = ss.End;

            for (var iter = begin; iter < end; ++iter)
            {
                CurrentCharacter = bs[iter];
apply:
                if (Result != ParserResult.Continue)
                {
                    break;
                }

                switch (State)
                {
                case ParserState.Error:
                    switch (CurrentCharacter)
                    {
                    default:
                            Partial_StateTransition__From_Error ();
                            Partial_StateTransition__From_Error__To_Error ();
                            Partial_StateTransition__To_Error ();
                        break;
    
                    }
                    break;
                case ParserState.WrongTagError:
                    switch (CurrentCharacter)
                    {
                    default:
                        State = ParserState.Error; 
                            Partial_StateTransition__From_WrongTagError ();
                            Partial_StateTransition__From_WrongTagError__To_Error ();
                            Partial_StateTransition__To_Error ();
                        break;
    
                    }
                    break;
                case ParserState.NonEmptyTagError:
                    switch (CurrentCharacter)
                    {
                    default:
                        State = ParserState.Error; 
                            Partial_StateTransition__From_NonEmptyTagError ();
                            Partial_StateTransition__From_NonEmptyTagError__To_Error ();
                            Partial_StateTransition__To_Error ();
                        break;
    
                    }
                    break;
                case ParserState.PreProcessing:
                    switch (CurrentCharacter)
                    {
                    case '!':
                        State = ParserState.PreProcessorTag; 
                            Partial_StateTransition__From_PreProcessing ();
                            Partial_StateTransition__From_PreProcessing__To_PreProcessorTag ();
                            Partial_StateTransition__To_PreProcessorTag ();
                        break;
                    default:
                        State = ParserState.Indention; 
                            Partial_StateTransition__From_PreProcessing ();
                            Partial_StateTransition__From_PreProcessing__To_Indention ();
                            Partial_StateTransition__To_Indention ();
                        goto apply;
                        break;
    
                    }
                    break;
                case ParserState.Indention:
                    switch (CurrentCharacter)
                    {
                    case '\t':
                            Partial_StateTransition__From_Indention ();
                            Partial_StateTransition__From_Indention__To_Indention ();
                            Partial_StateTransition__To_Indention ();
                        break;
                    default:
                    Partial_StateChoice__From_Indention__Choose_TagExpected_NoContentTagExpected_ValueLine_Error ();

                        switch (State)
                        {
                        case ParserState.TagExpected:
                            Partial_StateTransition__From_Indention ();
                            Partial_StateTransition__From_Indention__To_TagExpected ();
                            Partial_StateTransition__To_TagExpected ();
                            break;
                        case ParserState.NoContentTagExpected:
                            Partial_StateTransition__From_Indention ();
                            Partial_StateTransition__From_Indention__To_NoContentTagExpected ();
                            Partial_StateTransition__To_NoContentTagExpected ();
                            break;
                        case ParserState.ValueLine:
                            Partial_StateTransition__From_Indention ();
                            Partial_StateTransition__From_Indention__To_ValueLine ();
                            Partial_StateTransition__To_ValueLine ();
                            break;
                        case ParserState.Error:
                            Partial_StateTransition__From_Indention ();
                            Partial_StateTransition__From_Indention__To_Error ();
                            Partial_StateTransition__To_Error ();
                            break;
                        default:
                            Result = ParserResult.Error;
                            break;
                    }
                        goto apply;
                        break;
    
                    }
                    break;
                case ParserState.TagExpected:
                    switch (CurrentCharacter)
                    {
                    case '@':
                        State = ParserState.ObjectTag; 
                            Partial_StateTransition__From_TagExpected ();
                            Partial_StateTransition__From_TagExpected__To_ObjectTag ();
                            Partial_StateTransition__To_ObjectTag ();
                        break;
                    case '=':
                        State = ParserState.ValueTag; 
                            Partial_StateTransition__From_TagExpected ();
                            Partial_StateTransition__From_TagExpected__To_ValueTag ();
                            Partial_StateTransition__To_ValueTag ();
                        break;
                    case '#':
                        State = ParserState.CommentTag; 
                            Partial_StateTransition__From_TagExpected ();
                            Partial_StateTransition__From_TagExpected__To_CommentTag ();
                            Partial_StateTransition__To_CommentTag ();
                        break;
                    case '\t':
                    case ' ':
                        State = ParserState.EmptyTag; 
                            Partial_StateTransition__From_TagExpected ();
                            Partial_StateTransition__From_TagExpected__To_EmptyTag ();
                            Partial_StateTransition__To_EmptyTag ();
                        break;
                    default:
                        State = ParserState.WrongTagError; 
                            Partial_StateTransition__From_TagExpected ();
                            Partial_StateTransition__From_TagExpected__To_WrongTagError ();
                            Partial_StateTransition__To_WrongTagError ();
                        break;
    
                    }
                    break;
                case ParserState.NoContentTagExpected:
                    switch (CurrentCharacter)
                    {
                    case '#':
                        State = ParserState.CommentTag; 
                            Partial_StateTransition__From_NoContentTagExpected ();
                            Partial_StateTransition__From_NoContentTagExpected__To_CommentTag ();
                            Partial_StateTransition__To_CommentTag ();
                        break;
                    case '\t':
                    case ' ':
                        State = ParserState.EmptyTag; 
                            Partial_StateTransition__From_NoContentTagExpected ();
                            Partial_StateTransition__From_NoContentTagExpected__To_EmptyTag ();
                            Partial_StateTransition__To_EmptyTag ();
                        break;
                    default:
                        State = ParserState.WrongTagError; 
                            Partial_StateTransition__From_NoContentTagExpected ();
                            Partial_StateTransition__From_NoContentTagExpected__To_WrongTagError ();
                            Partial_StateTransition__To_WrongTagError ();
                        break;
    
                    }
                    break;
                case ParserState.PreProcessorTag:
                    switch (CurrentCharacter)
                    {
                    default:
                            Partial_StateTransition__From_PreProcessorTag ();
                            Partial_StateTransition__From_PreProcessorTag__To_PreProcessorTag ();
                            Partial_StateTransition__To_PreProcessorTag ();
                        break;
    
                    }
                    break;
                case ParserState.ObjectTag:
                    switch (CurrentCharacter)
                    {
                    default:
                            Partial_StateTransition__From_ObjectTag ();
                            Partial_StateTransition__From_ObjectTag__To_ObjectTag ();
                            Partial_StateTransition__To_ObjectTag ();
                        break;
    
                    }
                    break;
                case ParserState.ValueTag:
                    switch (CurrentCharacter)
                    {
                    default:
                            Partial_StateTransition__From_ValueTag ();
                            Partial_StateTransition__From_ValueTag__To_ValueTag ();
                            Partial_StateTransition__To_ValueTag ();
                        break;
    
                    }
                    break;
                case ParserState.EmptyTag:
                    switch (CurrentCharacter)
                    {
                    case '\t':
                    case ' ':
                            Partial_StateTransition__From_EmptyTag ();
                            Partial_StateTransition__From_EmptyTag__To_EmptyTag ();
                            Partial_StateTransition__To_EmptyTag ();
                        break;
                    default:
                        State = ParserState.NonEmptyTagError; 
                            Partial_StateTransition__From_EmptyTag ();
                            Partial_StateTransition__From_EmptyTag__To_NonEmptyTagError ();
                            Partial_StateTransition__To_NonEmptyTagError ();
                        break;
    
                    }
                    break;
                case ParserState.CommentTag:
                    switch (CurrentCharacter)
                    {
                    default:
                            Partial_StateTransition__From_CommentTag ();
                            Partial_StateTransition__From_CommentTag__To_CommentTag ();
                            Partial_StateTransition__To_CommentTag ();
                        break;
    
                    }
                    break;
                case ParserState.EndOfPreProcessorTag:
                    switch (CurrentCharacter)
                    {
                    default:
                        State = ParserState.PreProcessing; 
                            Partial_StateTransition__From_EndOfPreProcessorTag ();
                            Partial_StateTransition__From_EndOfPreProcessorTag__To_PreProcessing ();
                            Partial_StateTransition__To_PreProcessing ();
                        goto apply;
                        break;
    
                    }
                    break;
                case ParserState.EndOfObjectTag:
                    switch (CurrentCharacter)
                    {
                    default:
                        State = ParserState.Indention; 
                            Partial_StateTransition__From_EndOfObjectTag ();
                            Partial_StateTransition__From_EndOfObjectTag__To_Indention ();
                            Partial_StateTransition__To_Indention ();
                        goto apply;
                        break;
    
                    }
                    break;
                case ParserState.EndOfEmptyTag:
                    switch (CurrentCharacter)
                    {
                    default:
                        State = ParserState.Indention; 
                            Partial_StateTransition__From_EndOfEmptyTag ();
                            Partial_StateTransition__From_EndOfEmptyTag__To_Indention ();
                            Partial_StateTransition__To_Indention ();
                        goto apply;
                        break;
    
                    }
                    break;
                case ParserState.EndOfValueTag:
                    switch (CurrentCharacter)
                    {
                    default:
                        State = ParserState.Indention; 
                            Partial_StateTransition__From_EndOfValueTag ();
                            Partial_StateTransition__From_EndOfValueTag__To_Indention ();
                            Partial_StateTransition__To_Indention ();
                        goto apply;
                        break;
    
                    }
                    break;
                case ParserState.EndOfCommentTag:
                    switch (CurrentCharacter)
                    {
                    default:
                        State = ParserState.Indention; 
                            Partial_StateTransition__From_EndOfCommentTag ();
                            Partial_StateTransition__From_EndOfCommentTag__To_Indention ();
                            Partial_StateTransition__To_Indention ();
                        goto apply;
                        break;
    
                    }
                    break;
                case ParserState.ValueLine:
                    switch (CurrentCharacter)
                    {
                    default:
                            Partial_StateTransition__From_ValueLine ();
                            Partial_StateTransition__From_ValueLine__To_ValueLine ();
                            Partial_StateTransition__To_ValueLine ();
                        break;
    
                    }
                    break;
                case ParserState.EndOfValueLine:
                    switch (CurrentCharacter)
                    {
                    default:
                        State = ParserState.Indention; 
                            Partial_StateTransition__From_EndOfValueLine ();
                            Partial_StateTransition__From_EndOfValueLine__To_Indention ();
                            Partial_StateTransition__To_Indention ();
                        goto apply;
                        break;
    
                    }
                    break;
                default:
                    Result = ParserResult.Error;
                    break;
                }
            }

            if (Result == ParserResult.Error)
            {
                return false;
            }

            // EndOfLine
            CurrentCharacter = EndOfStream;

            {
                switch (State)
                {
                case ParserState.Indention:
                    State = ParserState.EndOfEmptyTag; 
                            Partial_StateTransition__From_Indention ();
                            Partial_StateTransition__From_Indention__To_EndOfEmptyTag ();
                            Partial_StateTransition__To_EndOfEmptyTag ();
                    break;
                case ParserState.TagExpected:
                    State = ParserState.EndOfEmptyTag; 
                            Partial_StateTransition__From_TagExpected ();
                            Partial_StateTransition__From_TagExpected__To_EndOfEmptyTag ();
                            Partial_StateTransition__To_EndOfEmptyTag ();
                    break;
                case ParserState.NoContentTagExpected:
                    State = ParserState.EndOfEmptyTag; 
                            Partial_StateTransition__From_NoContentTagExpected ();
                            Partial_StateTransition__From_NoContentTagExpected__To_EndOfEmptyTag ();
                            Partial_StateTransition__To_EndOfEmptyTag ();
                    break;
                case ParserState.PreProcessorTag:
                    State = ParserState.EndOfPreProcessorTag; 
                            Partial_StateTransition__From_PreProcessorTag ();
                            Partial_StateTransition__From_PreProcessorTag__To_EndOfPreProcessorTag ();
                            Partial_StateTransition__To_EndOfPreProcessorTag ();
                    break;
                case ParserState.ObjectTag:
                    State = ParserState.EndOfObjectTag; 
                            Partial_StateTransition__From_ObjectTag ();
                            Partial_StateTransition__From_ObjectTag__To_EndOfObjectTag ();
                            Partial_StateTransition__To_EndOfObjectTag ();
                    break;
                case ParserState.ValueTag:
                    State = ParserState.EndOfValueTag; 
                            Partial_StateTransition__From_ValueTag ();
                            Partial_StateTransition__From_ValueTag__To_EndOfValueTag ();
                            Partial_StateTransition__To_EndOfValueTag ();
                    break;
                case ParserState.EmptyTag:
                    State = ParserState.EndOfEmptyTag; 
                            Partial_StateTransition__From_EmptyTag ();
                            Partial_StateTransition__From_EmptyTag__To_EndOfEmptyTag ();
                            Partial_StateTransition__To_EndOfEmptyTag ();
                    break;
                case ParserState.CommentTag:
                    State = ParserState.EndOfCommentTag; 
                            Partial_StateTransition__From_CommentTag ();
                            Partial_StateTransition__From_CommentTag__To_EndOfCommentTag ();
                            Partial_StateTransition__To_EndOfCommentTag ();
                    break;
                case ParserState.ValueLine:
                    State = ParserState.EndOfValueLine; 
                            Partial_StateTransition__From_ValueLine ();
                            Partial_StateTransition__From_ValueLine__To_EndOfValueLine ();
                            Partial_StateTransition__To_EndOfValueLine ();
                    break;
                }
            }

            Partial_EndLine ();

            return Result != ParserResult.Error;
        }
 public abstract void Register(ref ParserResult <object> parserResult);
Example #51
0
 public static ParserResult __CreateInstance(ParserResult.Internal native)
 {
     return new ParserResult(native);
 }
Example #52
0
        static void Main(string[] args)
        {
            int           threads      = 1;
            int           timeout      = 30;
            string        fileName     = "";
            FileType      fileType     = FileType.HostFile;
            bool          appendPorts  = false;
            bool          prependHttps = false;
            List <string> hostList     = null;

            //Parse command line arguments
            ParserResult <Options> argResults = Parser.Default.ParseArguments <Options>(args);
            ParserResult <Options> res        = argResults.WithParsed <Options>(o =>
            {
                appendPorts  = o.AppendPorts;
                prependHttps = o.PrependHTTPS;
                threads      = o.NumThreads;
                timeout      = o.Timeout;

                if (o.FileName == "")
                {
                    System.Console.WriteLine("Please provide the name of a host file or a Nessus file");
                    System.Environment.Exit(1);
                }

                fileName = o.FileName;

                //Automatically determine file type
                try
                {
                    System.IO.StreamReader file = new System.IO.StreamReader(fileName);
                    string line = file.ReadLine();

                    if (line != null)
                    {
                        if (line.Contains("xml version"))
                        {
                            fileType = FileType.Nessus;
                        }
                        else
                        {
                            fileType = FileType.HostFile;
                        }
                    }

                    file.Close();
                }
                catch
                {
                    System.Console.WriteLine(string.Format("Could not open file: {0}", fileName));
                    System.Environment.Exit(1);
                }
            });

            //This takes care of if the --help option was used
            if (argResults.Tag == CommandLine.ParserResultType.NotParsed)
            {
                System.Environment.Exit(1);
            }

            //Get hosts
            if (fileType == FileType.HostFile)
            {
                FileParser fParser = new FileParser();
                hostList = fParser.Parse(fileName, prependHttps, appendPorts);
            }
            else if (fileType == FileType.Nessus)
            {
                NessusParser nParser = new NessusParser();
                hostList = nParser.Parse(fileName);
            }

            if (hostList == null)
            {
                System.Environment.Exit(1);
            }

            foreach (string host in hostList)
            {
                System.Console.WriteLine(host);
            }

            //Create a new WebShot object for screenshotting.
            WebShot webshot = new WebShot(threads, timeout);


            //Some examples of screenshotting for now...
            //webshot.ScreenShot("https://google.com");
            //webshot.ScreenShot("https://www.blackhillsinfosec.com");
            //webshot.ScreenShot("http://www.reddit.com");
        }
Example #53
0
 private ParserResult(ParserResult.Internal native)
     : this(__CopyValue(native))
 {
     __ownsNativeInstance = true;
     NativeToManagedMap[__Instance] = this;
 }
        static void Main(string[] args)
        {
            ParserResult <Arguments> parseResult = Parser.Default.ParseArguments <Arguments>(args);

            if (parseResult.Errors.Any())
            {
                return;
            }

            Arguments arguments = parseResult.Value;

            // Создаем коллекцию всех существительных.
            CyrNounCollection nouns = new CyrNounCollection();

            // Создаем коллекцию всех прилагательных.
            CyrAdjectiveCollection adjectives = new CyrAdjectiveCollection();

            // Создаем фразу с использование созданных коллекций.
            CyrPhrase phrase = new CyrPhrase(nouns, adjectives);

            InjectionAnalyzer analyzer = new InjectionAnalyzer();

            HashSet <string> defTypes = new HashSet <string>(arguments.DefsTypes.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries));

            HashSet <string> ignoredInjections = File.Exists(arguments.IgnoreFile)
                                ? new HashSet <string>(File.ReadAllLines(arguments.IgnoreFile))
                                : new HashSet <string>();

            HashSet <string> pluralizedLabels = File.Exists(arguments.Output)
                                ? new HashSet <string>(File.ReadAllLines(arguments.Output).Select(line => new string(line.TakeWhile(c => c != ';').ToArray())))
                                : new HashSet <string>();

            Injection[] allLabels = analyzer
                                    .ReadInjections(arguments.DefsPath)
                                    .Where(inj => defTypes.Contains(inj.DefType))
                                    .Where(inj => GetLastPart(inj).ToLowerInvariant().Contains("label"))
                                    .Distinct(new InjectionTypeTranslationComparer())
                                    .Where(inj =>
                                           !ignoredInjections.Contains(FormInjectionLine(inj)) &&
                                           !pluralizedLabels.Contains(inj.Translation))
                                    .ToArray();

            Console.WriteLine($"Check plural forms for {allLabels.Length} labels.");

            List <Option> history = new List <Option>();

            string prevDefType = "";

            PluralPair pluralPair = null;

            for (int labelIndex = 0; labelIndex < allLabels.Length;)
            {
                Injection injection = allLabels[labelIndex];
                string    label     = injection.Translation;

                Console.WriteLine();
                Console.WriteLine($"{labelIndex + 1}/{allLabels.Length} {injection.DefType} <{injection.DefPath}> \"{label}\":");

                if (pluralPair == null)
                {
                    pluralPair = PluralizeIgnoreSuffix(phrase, label, " (", " из ", " для ", " с ", " в ");
                }

                if (pluralPair == null)
                {
                    Console.WriteLine($"	Failed to pluralize");
                }
                else
                {
                    WritePluralization(pluralPair);
                }

                Console.Write("<Enter> - accept; <Space> - edit; <Backspace> - back; <Delete> - ignore");
                ConsoleKey key = Console.ReadKey().Key;
                Console.WriteLine();

                switch (key)
                {
                case ConsoleKey.Escape:
                    return;

                case ConsoleKey.Spacebar:
                    if (pluralPair == null)
                    {
                        pluralPair = new PluralPair(label, label);
                    }

                    pluralPair = EditPluralization(pluralPair);

                    if (injection.DefType != prevDefType)
                    {
                        FileUtil.PushLine(arguments.Output, string.Empty);
                        FileUtil.PushLine(arguments.Output, "// " + injection.DefType);
                    }
                    FileUtil.PushLine(arguments.Output, ToLine(pluralPair));
                    pluralPair = null;
                    history.Add(Option.Accept);
                    labelIndex++;
                    break;

                case ConsoleKey.Enter:
                    if (pluralPair != null)
                    {
                        if (injection.DefType != prevDefType)
                        {
                            FileUtil.PushLine(arguments.Output, string.Empty);
                            FileUtil.PushLine(arguments.Output, "// " + injection.DefType);
                        }
                        FileUtil.PushLine(arguments.Output, ToLine(pluralPair));
                        pluralPair = null;
                        history.Add(Option.Accept);
                        labelIndex++;
                    }
                    break;

                case ConsoleKey.Delete:
                    FileUtil.PushLine(arguments.IgnoreFile, FormInjectionLine(injection));
                    pluralPair = null;
                    history.Add(Option.Ignore);
                    labelIndex++;
                    break;

                case ConsoleKey.Backspace:
                    Option prevOption = history[labelIndex - 1];
                    history.RemoveAt(labelIndex - 1);
                    labelIndex--;

                    if (prevOption == Option.Accept)
                    {
                        string prevDeclinationLine = FileUtil.PopLine(arguments.Output);
                        pluralPair = FromLine(prevDeclinationLine);
                    }
                    else if (prevOption == Option.Ignore)
                    {
                        FileUtil.PopLine(arguments.IgnoreFile);
                        pluralPair = null;
                    }
                    break;

                default:
                    break;
                }

                prevDefType = injection.DefType;
            }
        }
Example #55
0
 public static ParserResult __CreateInstance(ParserResult.__Internal native, bool skipVTables = false)
 {
     return new ParserResult(native, skipVTables);
 }
Example #56
0
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            LConfig = new LoggerConfiguration()
                      .Enrich.FromLogContext()
                      .MinimumLevel.Debug()
                      .WriteTo.Console(outputTemplate: "{Timestamp:HH:mm:ss}<{ThreadId:d2}> [{Level:u3}] {Message}{NewLine}{Exception}");
            L = Log.Logger = LConfig.CreateLogger();
            Type[]     BindOptionTypes      = Assembly.GetExecutingAssembly().GetTypes().Where(t => t == typeof(Options) || t.IsSubclassOf(typeof(Options))).ToArray();
            MethodInfo parseArgumentsMethod = typeof(ParserExtensions).GetMethods().Where(m => m.IsGenericMethod && m.Name == "ParseArguments" &&
                                                                                          m.GetGenericArguments().Count() == BindOptionTypes.Count()).First();
            Parser p = new Parser();
            ParserResult <object> result = (ParserResult <object>)parseArgumentsMethod.MakeGenericMethod(BindOptionTypes).Invoke(p, new object[] { p, args });

            result.WithNotParsed((IEnumerable <Error> errors) =>
            {
                HelpText help            = GetAutoBuiltHelpText(result);
                help.MaximumDisplayWidth = Console.WindowWidth;
                help.Copyright           = string.Empty;
                help.Heading             = new HeadingInfo("Sylvester Bindings CLI", Version.ToString(3));
                help.AddPreOptionsLine(string.Empty);
                if (errors.Any(e => e.Tag == ErrorType.VersionRequestedError))
                {
                    Log.Information(help);
                    Exit(ExitResult.SUCCESS);
                }
                else if (errors.Any(e => e.Tag == ErrorType.HelpVerbRequestedError))
                {
                    HelpVerbRequestedError error = (HelpVerbRequestedError)errors.First(e => e.Tag == ErrorType.HelpVerbRequestedError);
                    if (error.Type != null)
                    {
                        help.AddVerbs(error.Type);
                    }
                    else
                    {
                        help.AddVerbs(BindOptionTypes);
                    }
                    Log.Information(help);
                    Exit(ExitResult.SUCCESS);
                }
                else if (errors.Any(e => e.Tag == ErrorType.HelpRequestedError))
                {
                    help.AddOptions(result);
                    L.Information(help);
                    Exit(ExitResult.SUCCESS);
                }
                else if (errors.Any(e => e.Tag == ErrorType.NoVerbSelectedError))
                {
                    help.AddVerbs(BindOptionTypes);
                    help.AddPreOptionsLine("No library selected. Select a library or verb from the options below:");
                    L.Information(help);
                    Exit(ExitResult.INVALID_OPTIONS);
                }
                else if (errors.Any(e => e.Tag == ErrorType.MissingRequiredOptionError))
                {
                    MissingRequiredOptionError error = (MissingRequiredOptionError)errors.First(e => e is MissingRequiredOptionError);
                    help.AddOptions(result);
                    help.AddPreOptionsLine($"A required option or value is missing: {error.NameInfo.NameText} The options and values for this benchmark category are: ");
                    L.Information(help);
                    Exit(ExitResult.INVALID_OPTIONS);
                }
                else if (errors.Any(e => e.Tag == ErrorType.MissingValueOptionError))
                {
                    MissingValueOptionError error = (MissingValueOptionError)errors.First(e => e.Tag == ErrorType.MissingValueOptionError);
                    help.AddOptions(result);
                    help.AddPreOptionsLine($"A required option or value is missing. The options and values for this category are: ");
                    L.Information(help);
                    Exit(ExitResult.INVALID_OPTIONS);
                }
                else if (errors.Any(e => e.Tag == ErrorType.UnknownOptionError))
                {
                    UnknownOptionError error = (UnknownOptionError)errors.First(e => e.Tag == ErrorType.UnknownOptionError);
                    help.AddOptions(result);
                    help.AddPreOptionsLine($"Unknown option: {error.Token}.");
                    L.Information(help);
                    Exit(ExitResult.INVALID_OPTIONS);
                }
                else
                {
                    help.AddPreOptionsLine($"An error occurred parsing the program options: {string.Join(" ", errors.Select(e => e.Tag.ToString()).ToArray())}");
                    help.AddVerbs(BindOptionTypes);
                    L.Information(help);
                    Exit(ExitResult.INVALID_OPTIONS);
                }
            })
            .WithParsed <Options>(o =>
            {
                if (string.IsNullOrEmpty(o.ModuleName))
                {
                    Log.Error($"You must select a module to create bindings for. Use the --help option to get the list of available modules.");
                    Exit(ExitResult.INVALID_OPTIONS);
                }

                if (!string.IsNullOrEmpty(o.Root) && !Directory.Exists(o.Root))
                {
                    Log.Error($"The library root directory specified {o.Root} does not exist.");
                    Exit(ExitResult.INVALID_OPTIONS);
                }
                else if (!string.IsNullOrEmpty(o.Root))
                {
                    ProgramOptions.Add("RootDirectory", new DirectoryInfo(o.Root));
                }
                foreach (PropertyInfo prop in o.GetType().GetProperties())
                {
                    ProgramOptions.Add(prop.Name, prop.GetValue(o));
                }
            })
            .WithParsed <PlaidMLOptions>(o =>
            {
                if (!File.Exists(Path.Combine(AssemblyDirectory.FullName, "plaidml", "base.h")))
                {
                    L.Error($"The PlaidML header file {Path.Combine(AssemblyDirectory.FullName, "plaidml", "base.h")} was not found.");
                    Exit(ExitResult.FILE_MISSING);
                }
                else if (!File.Exists(Path.Combine(AssemblyDirectory.FullName, "plaidml", "plaidml.h")))
                {
                    L.Error($"The PlaidML header file {Path.Combine(AssemblyDirectory.FullName, "plaidml", "plaidml.h")} was not found.");
                    Exit(ExitResult.FILE_MISSING);
                }
                ProgramLibrary = new PlaidML(ProgramOptions);
                ConsoleDriver.Run(ProgramLibrary);
                if (ProgramLibrary.CleanAndFixup())
                {
                    Exit(ExitResult.SUCCESS);
                }
                else
                {
                    Exit(ExitResult.ERROR_DURING_CLEANUP);
                }
            })
            .WithParsed <TensorFlowOptions>(o =>
            {
                if (!File.Exists(Path.Combine(AssemblyDirectory.FullName, "tf", "c_api.h")))
                {
                    L.Error($"The TensorFlow header file {Path.Combine(AssemblyDirectory.FullName, "tf", "c_api.h")} was not found.");
                    Exit(ExitResult.FILE_MISSING);
                }
                ProgramLibrary = new TensorFlow(ProgramOptions);
                ConsoleDriver.Run(ProgramLibrary);
                if (ProgramLibrary.CleanAndFixup())
                {
                    Exit(ExitResult.SUCCESS);
                }
                else
                {
                    Exit(ExitResult.ERROR_DURING_CLEANUP);
                }
            });
        }
Example #57
0
 private ParserResult(ParserResult.__Internal native, bool skipVTables = false)
     : this(__CopyValue(native), skipVTables)
 {
     __ownsNativeInstance = true;
     NativeToManagedMap[__Instance] = this;
 }
Example #58
0
        /// <summary>
        /// Méthode de parsing d'une expression.
        /// </summary>
        /// <param name="expression">Expression à parser.</param>
        /// <param name="year">Année.</param>
        /// <returns>Un <see cref="ParserResult"/> correspondant.</returns>
        public override ParserResult Parse(string expression, int year)
        {
            var result = new ParserResult();
            var regex  = new Regex(Pattern.ToString());
            var match  = regex.Match(expression);

            if (match.Success)
            {
                var calendar = Parser.GetCalendar(match.Groups["Calendar"].Value);

                if (!(calendar is System.Globalization.GregorianCalendar))
                {
                    year = calendar.GetYear(DateTime.Today.Of(year));
                }

                var date = new DateTime(year, int.Parse(match.Groups["month"].Value), int.Parse(match.Groups["day"].Value), calendar);
                if (match.Groups["year"].Value.IsNotNullOrEmpty())
                {
                    date = date.SetYear(int.Parse(match.Groups["year"].Value));
                }

                if (match.Groups["StartHours"].Value.IsNotNullOrEmpty() && match.Groups["StartMinutes"].Value.IsNotNullOrEmpty())
                {
                    date = date.SetTime(int.Parse(match.Groups["StartHours"].Value), int.Parse(match.Groups["StartMinutes"].Value));
                }

                if (match.Groups["Expected"].Value.IsNotNullOrEmpty())
                {
                    if (date.DayOfWeek.ToString().ToUpper() == match.Groups["Expected"].Value)
                    {
                        if (match.Groups["NewHours"].Value.IsNotNullOrEmpty() && match.Groups["NewMinutes"].Value.IsNotNullOrEmpty())
                        {
                            date = date.SetTime(int.Parse(match.Groups["NewHours"].Value), int.Parse(match.Groups["NewMinutes"].Value));
                        }
                    }
                }

                if (match.Groups["RepeatEndYear"].Value.IsNotNullOrEmpty())
                {
                    if (date.Year > int.Parse(match.Groups["RepeatEndYear"].Value))
                    {
                        return(result);
                    }
                }

                var isYearTypeOk = false;
                if (match.Groups["YearType"].Value.IsNotNullOrEmpty())
                {
                    switch ((YearType)Enum.Parse(typeof(YearType), match.Groups["YearType"].Value, true))
                    {
                    case Even:
                        if (date.Year % 2 == 0)
                        {
                            isYearTypeOk = true;
                        }

                        break;

                    case Odd:
                        if (date.Year % 2 != 0)
                        {
                            isYearTypeOk = true;
                        }

                        break;

                    case Leap:
                        if (DateTime.IsLeapYear(date.Year))
                        {
                            isYearTypeOk = true;
                        }

                        break;

                    case NonLeap:
                        if (!DateTime.IsLeapYear(date.Year))
                        {
                            isYearTypeOk = true;
                        }

                        break;

                    default:
                        isYearTypeOk = false;
                        break;
                    }
                }
                else
                {
                    isYearTypeOk = true;
                }

                var isYearRecursOk = false;
                if (match.Groups["RepeatYear"].Value.IsNotNullOrEmpty() && match.Groups["RepeatStartYear"].Value.IsNotNullOrEmpty())
                {
                    var numberYear = int.Parse(match.Groups["RepeatYear"].Value);
                    var startYear  = int.Parse(match.Groups["RepeatStartYear"].Value);
                    if (date.Year >= startYear && ((date.Year - startYear) % numberYear) == 0)
                    {
                        isYearRecursOk = true;
                    }
                }
                else
                {
                    isYearRecursOk = true;
                }

                if (isYearTypeOk && isYearRecursOk && (match.Groups["year"].Value.IsNotNullOrEmpty() ? date.Year == year : true))
                {
                    result.DatesToAdd.Add(date);
                    if (match.Groups["DurationDays"].Value.IsNotNullOrEmpty())
                    {
                        var number = int.Parse(match.Groups["DurationDays"].Value);
                        for (var i = 1; i < number; i++)
                        {
                            result.DatesToAdd.Add(i.Days().After(date.Midnight()));
                        }
                    }
                }
            }
            return(result);
        }
Example #59
0
 void OnSourceFileParsed(SourceFile file, ParserResult result)
 {
     OnFileParsed(file.Path, result);
 }
Example #60
0
 internal ParserResult(ParserResult.Internal* native)
     : this(new global::System.IntPtr(native))
 {
 }