Exemplo n.º 1
0
        string _arg_fileExclusionList;//see exclusion list

        /// Compares a set of rules against a source path...
        /// Used for both RulesPresent and RulesNotePresent options
        /// Focus is pass/fail not detailed comparison output -see Tagdiff for more
        public TagTestCommand(TagTestCommandOptions opt)
        {
            _arg_srcPath               = opt.SourcePath;
            _arg_customRulesPath       = opt.CustomRulesPath;
            _arg_outputFile            = opt.OutputFilePath;
            _arg_consoleVerbosityLevel = opt.ConsoleVerbosityLevel ?? "medium";
            _arg_tag_test_type_raw     = opt.TestType ?? "RulesPresent";
            _arg_logger            = opt.Log;
            _arg_log_file_path     = opt.LogFilePath;
            _arg_log_level         = opt.LogFileLevel;
            _arg_close_log_on_exit = Utils.CLIExecutionContext ? true : opt.CloseLogOnCommandExit;
            _arg_fileExclusionList = opt.FilePathExclusions;

            _arg_logger ??= Utils.SetupLogging(opt);
            WriteOnce.Log ??= _arg_logger;
            _rulesSet = new RuleSet(_arg_logger);

            try
            {
                ConfigureConsoleOutput();
                ConfigureCompareTest();
                ConfigureRules();
            }
            catch (Exception e) //group error handling
            {
                WriteOnce.Error(e.Message);
                if (_arg_close_log_on_exit)
                {
                    Utils.Logger  = null;
                    WriteOnce.Log = null;
                }
                throw;
            }
        }
Exemplo n.º 2
0
        void WritePartialRuleDetails(RuleSet rules)
        {
            WriteOnce.Result("RuleId,Rulename,RuleDesc,Tags,AppliesToLanguage", true, WriteOnce.ConsoleVerbosity.High);

            //option to write out partial rule data
            foreach (Rule r in rules)
            {
                string tags      = "";
                string languages = "";
                foreach (string tag in r.Tags)
                {
                    tags += tag + ",";
                }

                tags = tags.Remove(tags.Length - 1);

                if (r.AppliesTo != null && r.AppliesTo.Length > 0)
                {
                    foreach (string lang in r.AppliesTo)
                    {
                        languages += lang + ",";
                    }

                    languages = languages.Remove(languages.Length - 1);
                }
                else
                {
                    languages = "Not-specified-so-all";
                }

                WriteOnce.Result(string.Format("{0},{1},{2},{3},{4}", r.Id, r.Name, r.Description, tags, languages), true, WriteOnce.ConsoleVerbosity.High);
            }
        }
        public void ConfigureRules()
        {
            WriteOnce.SafeLog("TagTestCommand::ConfigRules", LogLevel.Trace);

            if (string.IsNullOrEmpty(_options.CustomRulesPath))
            {
                throw new OpException(MsgHelp.GetString(MsgHelp.ID.CMD_NORULES_SPECIFIED));
            }

            RulesVerifier verifier = new RulesVerifier(_options.CustomRulesPath, _options.Log);

            verifier.Verify();
            if (!verifier.IsVerified)
            {
                throw new OpException(MsgHelp.GetString(MsgHelp.ID.VERIFY_RULES_RESULTS_FAIL));
            }

            _rulesSet = verifier.CompiledRuleset ?? new RuleSet(null);

            //error check based on ruleset not path enumeration
            if (!_rulesSet.Any())
            {
                throw new OpException(MsgHelp.GetString(MsgHelp.ID.CMD_NORULES_SPECIFIED));
            }
        }
        public void ConfigureRules()
        {
            WriteOnce.SafeLog("TagTestCommand::ConfigRules", LogLevel.Trace);

            if (string.IsNullOrEmpty(_options.CustomRulesPath))
            {
                throw new OpException(MsgHelp.GetString(MsgHelp.ID.CMD_NORULES_SPECIFIED));
            }

            try
            {
                RulesVerifier verifier = new RulesVerifier(_options.CustomRulesPath, _options.Log);
                verifier.Verify();

                _rulesSet = verifier.CompiledRuleset;
            }
            catch (Exception e)
            {
                WriteOnce.SafeLog(e.Message + "\n" + e.StackTrace, NLog.LogLevel.Error);
                throw new OpException(MsgHelp.FormatString(MsgHelp.ID.VERIFY_RULE_FAILED, _options.CustomRulesPath));
            }

            //error check based on ruleset not path enumeration
            if (_rulesSet.Count() == 0)
            {
                throw new OpException(MsgHelp.GetString(MsgHelp.ID.CMD_NORULES_SPECIFIED));
            }
        }
        /// <summary>
        /// Intentional as no identified value in calling from DLL at this time
        /// </summary>
        /// <returns></returns>
        public PackRulesResult GetResult()
        {
            WriteOnce.SafeLog("PackRules::Run", LogLevel.Trace);
            WriteOnce.Operation(MsgHelp.FormatString(MsgHelp.ID.CMD_RUNNING, "Pack Rules"));

            PackRulesResult packRulesResult = new()
            {
                AppVersion = Common.Utils.GetVersionString()
            };

            try
            {
                RulesVerifier verifier = new(_rules_path, _options?.Log);
                if (_options?.PackEmbeddedRules ?? false)
                {
                    verifier.LoadRuleSet(RuleSetUtils.GetDefaultRuleSet());
                }
                verifier.Verify();
                if (!verifier.IsVerified)
                {
                    throw new OpException(MsgHelp.GetString(MsgHelp.ID.VERIFY_RULES_RESULTS_FAIL));
                }
                packRulesResult.Rules      = verifier.CompiledRuleset?.GetAppInspectorRules().ToList() ?? new List <Rule>();
                packRulesResult.ResultCode = PackRulesResult.ExitCode.Success;
            }
            catch (OpException e)
            {
                WriteOnce.Error(e.Message);
                //caught for CLI callers with final exit msg about checking log or throws for DLL callers
                throw;
            }

            return(packRulesResult);
        }
    }
        /// <summary>
        /// Option for DLL use as alternate to Run which only outputs a file to return results as string
        /// CommandOption defaults will not have been set when used as DLL via CLI processing so some checks added
        /// </summary>
        /// <returns>output results</returns>
        public VerifyRulesResult GetResult()
        {
            WriteOnce.SafeLog("VerifyRulesCommand::Run", LogLevel.Trace);
            WriteOnce.Operation(MsgHelp.FormatString(MsgHelp.ID.CMD_RUNNING, "Verify Rules"));

            VerifyRulesResult verifyRulesResult = new VerifyRulesResult()
            {
                AppVersion = Utils.GetVersionString()
            };

            try
            {
                RulesVerifier verifier = new RulesVerifier(_rules_path, _options.Log);
                verifyRulesResult.ResultCode     = VerifyRulesResult.ExitCode.Verified;
                verifyRulesResult.RuleStatusList = verifier.Verify();
                verifyRulesResult.ResultCode     = verifier.IsVerified ? VerifyRulesResult.ExitCode.Verified : VerifyRulesResult.ExitCode.NotVerified;
            }
            catch (OpException e)
            {
                WriteOnce.Error(e.Message);
                //caught for CLI callers with final exit msg about checking log or throws for DLL callers
                throw;
            }

            return(verifyRulesResult);
        }
        public void FlushAll()
        {
            if (_outputWriter != null)
            {
                _outputWriter.WriteApp(_appProfile);

                if (_outputWriter.TextWriter != null && _arg_fileFormat != "html")
                {
                    _outputWriter.FlushAndClose();//not required for html formal i.e. multiple files already closed
                    _outputWriter = null;

                    //Special case to avoid writing tmp file path to output file for TagTest,TagDiff or when called as a DLL since unnecessary
                    if (_arg_consoleVerbosityLevel.ToLower() != "none")
                    {
                        if (!String.IsNullOrEmpty(_arg_outputFile))
                        {
                            WriteOnce.Any(ErrMsg.FormatString(ErrMsg.ID.ANALYZE_OUTPUT_FILE, _arg_outputFile), true, ConsoleColor.Gray, WriteOnce.ConsoleVerbosity.Medium);
                        }
                        else
                        {
                            WriteOnce.NewLine();
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Main entry from CLI
        /// </summary>
        /// <returns></returns>
        public override int Run()
        {
            bool issues = false;

            WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_RUNNING, "Verify Rules"));

            RulesVerifier verifier = new RulesVerifier(_arg_customRulesPath);

            if (!verifier.Verify())
            {
                return((int)ExitCode.NotVerified);
            }

            RuleSet rules = verifier.CompiledRuleset;

            //report each add
            foreach (Rule rule in rules)
            {
                WriteOnce.Result(string.Format("Rule {0}-{1} verified", rule.Id, rule.Name), true, WriteOnce.ConsoleVerbosity.High);
            }

            WriteOnce.Any(ErrMsg.GetString(ErrMsg.ID.VERIFY_RULES_RESULTS_SUCCESS), true, ConsoleColor.Green, WriteOnce.ConsoleVerbosity.Low);
            WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_COMPLETED, "Verify Rules"));

            WriteOnce.FlushAll();
            if (!String.IsNullOrEmpty(_arg_outputFile))
            {
                WriteOnce.Any(ErrMsg.FormatString(ErrMsg.ID.ANALYZE_OUTPUT_FILE, _arg_outputFile), true, ConsoleColor.Gray, WriteOnce.ConsoleVerbosity.Low);
            }

            return(issues ? (int)ExitCode.NotVerified : (int)ExitCode.Verified);
        }
Exemplo n.º 9
0
        string _arg_fileExclusionList;//see exclusion list

        public TagDiffCommand(TagDiffCommandOptions opt)
        {
            _arg_src1                  = opt.SourcePath1;
            _arg_src2                  = opt.SourcePath2;
            _arg_customRulesPath       = opt.CustomRulesPath;
            _arg_consoleVerbosityLevel = opt.ConsoleVerbosityLevel ?? "medium";
            _arg_ignoreDefault         = opt.IgnoreDefaultRules;
            _arg_outputFile            = opt.OutputFilePath;
            _arg_test_type_raw         = opt.TestType ?? "Equality";
            _arg_logger                = opt.Log;
            _arg_log_file_path         = opt.LogFilePath;
            _arg_close_log_on_exit     = Utils.CLIExecutionContext ? true : opt.CloseLogOnCommandExit;
            _arg_fileExclusionList     = opt.FilePathExclusions;

            _arg_logger ??= Utils.SetupLogging(opt);
            WriteOnce.Log ??= _arg_logger;

            try
            {
                ConfigureConsoleOutput();
                ConfigureCompareType();
                ConfigSourceToScan();
            }
            catch (Exception e) //group error handling
            {
                WriteOnce.Error(e.Message);
                if (_arg_close_log_on_exit)
                {
                    Utils.Logger  = null;
                    WriteOnce.Log = null;
                }
                throw;
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// After verifying rules are valid syntax and load; combines into a single .json file
        /// for ease in distribution including this application's defaultset which are
        /// added to the manifest as an embedded resource (see AppInspector.Commands.csproj)
        /// </summary>
        /// <returns></returns>
        public override int Run()
        {
            WriteOnce.SafeLog("PackRules::Run", LogLevel.Trace);
            WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_RUNNING, "PackRules"));
            RulesVerifier verifier = new RulesVerifier(_path);

            if (!verifier.Verify())//throws anyway
            {
                return((int)ExitCode.CriticalError);
            }

            List <Rule> list = new List <Rule>(verifier.CompiledRuleset.AsEnumerable());

            JsonSerializerSettings settings = new JsonSerializerSettings();

            settings.Formatting = (_indent) ? Formatting.Indented : Formatting.None;

            using (FileStream fs = File.Open(_outputfile, FileMode.Create, FileAccess.Write))
            {
                StreamWriter sw = new StreamWriter(fs);
                sw.Write(JsonConvert.SerializeObject(list, settings));
                sw.Close();
                fs.Close();
            }

            WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_COMPLETED, "PackRules"));
            WriteOnce.Any(ErrMsg.FormatString(ErrMsg.ID.ANALYZE_OUTPUT_FILE, _outputfile), true, ConsoleColor.Gray, WriteOnce.ConsoleVerbosity.Medium);

            return((int)ExitCode.NoIssues);
        }
        public ExportTagsCommand(ExportTagsCommandOptions opt)
        {
            _rules = new RuleSet(WriteOnce.Log);
            _arg_customRulesPath       = opt.CustomRulesPath;
            _arg_outputFile            = opt.OutputFilePath;
            _arg_ignoreDefaultRules    = opt.IgnoreDefaultRules;
            _arg_consoleVerbosityLevel = opt.ConsoleVerbosityLevel ?? "medium";
            _arg_logger            = opt.Log;
            _arg_log_file_path     = opt.LogFilePath;
            _arg_log_level         = opt.LogFileLevel;
            _arg_close_log_on_exit = Utils.CLIExecutionContext ? true : opt.CloseLogOnCommandExit;

            _arg_logger ??= Utils.SetupLogging(opt);
            WriteOnce.Log ??= _arg_logger;

            try
            {
                ConfigureConsoleOutput();
                ConfigFileOutput();
                ConfigRules();
            }
            catch (Exception e)
            {
                WriteOnce.Error(e.Message);
                if (_arg_close_log_on_exit)
                {
                    Utils.Logger  = null;
                    WriteOnce.Log = null;
                }
                throw;
            }
        }
 /// <summary>
 /// Expects user to supply all that apply
 /// </summary>
 void ConfigConfidenceFilters()
 {
     WriteOnce.SafeLog("AnalyzeCommand::ConfigConfidenceFilters", LogLevel.Trace);
     //parse and verify confidence values
     if (String.IsNullOrEmpty(_arg_confidenceFilters))
     {
         _arg_confidence = Confidence.High | Confidence.Medium; //excludes low by default
     }
     else
     {
         string[] confidences = _arg_confidenceFilters.Split(',');
         foreach (string confidence in confidences)
         {
             Confidence single;
             if (Enum.TryParse(confidence, true, out single))
             {
                 _arg_confidence |= single;
             }
             else
             {
                 throw new Exception(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_ARG_VALUE, "x"));
             }
         }
     }
 }
        /// <summary>
        /// Intentional as no identified value in calling from DLL at this time
        /// </summary>
        /// <returns></returns>
        public PackRulesResult GetResult()
        {
            WriteOnce.SafeLog("PackRules::Run", LogLevel.Trace);
            WriteOnce.Operation(MsgHelp.FormatString(MsgHelp.ID.CMD_RUNNING, "Pack Rules"));

            if (!Utils.CLIExecutionContext)
            { //requires output format and filepath only supported via CLI use
                WriteOnce.Error("Command not supported for DLL calls");
                throw new Exception("Command not supported for DLL calls");
            }

            PackRulesResult packRulesResult = new PackRulesResult()
            {
                AppVersion = Utils.GetVersionString()
            };

            try
            {
                RulesVerifier verifier = new RulesVerifier(_rules_path, _options.Log);
                verifier.Verify();
                packRulesResult.Rules = new List <Rule>(verifier.CompiledRuleset.AsEnumerable());

                packRulesResult.ResultCode = PackRulesResult.ExitCode.Success;
            }
            catch (OpException e)
            {
                WriteOnce.Error(e.Message);
                //caught for CLI callers with final exit msg about checking log or throws for DLL callers
                throw;
            }

            return(packRulesResult);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Simple validation on source path provided for scanning and preparation
        /// </summary>
        void ConfigSourcetoScan()
        {
            WriteOnce.SafeLog("AnalyzeCommand::ConfigSourcetoScan", LogLevel.Trace);

            if (Directory.Exists(_arg_sourcePath))
            {
                try
                {
                    _srcfileList = Directory.EnumerateFiles(_arg_sourcePath, "*.*", SearchOption.AllDirectories);
                    if (_srcfileList.Count() == 0)
                    {
                        throw new OpException(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_FILE_OR_DIR, _arg_sourcePath));
                    }
                }
                catch (Exception)
                {
                    throw new OpException(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_FILE_OR_DIR, _arg_sourcePath));
                }
            }
            else if (File.Exists(_arg_sourcePath)) //not a directory but make one for single flow
            {
                _srcfileList = new List <string>()
                {
                    _arg_sourcePath
                }
            }
            ;
            else
            {
                throw new OpException(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_FILE_OR_DIR, _arg_sourcePath));
            }
        }
Exemplo n.º 15
0
        public VerifyRulesCommand(VerifyRulesCommandOptions opt)
        {
            _arg_verify_default_rules  = opt.VerifyDefaultRules;
            _arg_custom_rules_path     = opt.CustomRulesPath;
            _arg_outputFile            = opt.OutputFilePath;
            _arg_consoleVerbosityLevel = opt.ConsoleVerbosityLevel ?? "medium";
            _arg_logger            = opt.Log;
            _arg_log_file_path     = opt.LogFilePath;
            _arg_log_level         = opt.LogFileLevel;
            _arg_close_log_on_exit = Utils.CLIExecutionContext ? true : opt.CloseLogOnCommandExit;

            _rules_path = _arg_verify_default_rules ? Utils.GetPath(Utils.AppPath.defaultRulesSrc) : _arg_custom_rules_path;

            _arg_logger ??= Utils.SetupLogging(opt);
            WriteOnce.Log ??= _arg_logger;

            try
            {
                ConfigureConsoleOutput();
                ConfigFileOutput();
                ConfigRules();
            }
            catch (Exception e) //group error handling
            {
                WriteOnce.Error(e.Message);
                if (_arg_close_log_on_exit)
                {
                    Utils.Logger  = null;
                    WriteOnce.Log = null;
                }
                throw;
            }
        }
Exemplo n.º 16
0
 void ConfigureCompareType()
 {
     if (!Enum.TryParse(_arg_test_type_raw, true, out _arg_tagTestType))
     {
         WriteOnce.Error((ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_ARG_VALUE, _arg_test_type_raw)));
         throw new Exception(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_ARG_VALUE, _arg_test_type_raw));
     }
 }
        void ConfigFileOutput()
        {
            WriteOnce.SafeLog("PackRulesCommand::ConfigOutput", LogLevel.Trace);

            if (string.IsNullOrEmpty(_arg_outputfile))
            {
                throw new Exception(ErrMsg.FormatString(ErrMsg.ID.PACK_MISSING_OUTPUT_ARG));
            }
        }
Exemplo n.º 18
0
        private void ConfigSourceToScan()
        {
            WriteOnce.SafeLog("TagDiff::ConfigRules", LogLevel.Trace);

            if ((!_options?.SourcePath1.Any() ?? true) || (!_options?.SourcePath2.Any() ?? true))
            {
                throw new OpException(MsgHelp.GetString(MsgHelp.ID.CMD_INVALID_ARG_VALUE));
            }
        }
        List <string> _fileExclusionList;//see exclusion list

        public AnalyzeCommand(AnalyzeCommandOptions opt)
        {
            _arg_sourcePath            = opt.SourcePath;
            _arg_outputFile            = opt.OutputFilePath;
            _arg_fileFormat            = opt.OutputFileFormat ?? "html";
            _arg_outputTextFormat      = opt.TextOutputFormat;
            _arg_outputUniqueTagsOnly  = !opt.AllowDupTags;
            _arg_customRulesPath       = opt.CustomRulesPath;
            _arg_confidenceFilters     = opt.ConfidenceFilters ?? "high,medium";
            _arg_consoleVerbosityLevel = opt.ConsoleVerbosityLevel ?? "medium";
            _arg_suppressBrowserOpen   = opt.SuppressBrowserOpen;
            _arg_ignoreDefaultRules    = opt.IgnoreDefaultRules;
            _arg_simpleTagsOnly        = opt.SimpleTagsOnly;
            _arg_logger            = opt.Log;
            _arg_log_file_path     = opt.LogFilePath;
            _arg_log_level         = opt.LogFileLevel;
            _arg_close_log_on_exit = Utils.CLIExecutionContext ? true : opt.CloseLogOnCommandExit;

            opt.FilePathExclusions ??= "sample,example,test,docs,.vs,.git";
            if (!string.IsNullOrEmpty(opt.FilePathExclusions))
            {
                _fileExclusionList = opt.FilePathExclusions.ToLower().Split(",").ToList <string>();
                if (_fileExclusionList != null && (_fileExclusionList.Contains("none") || _fileExclusionList.Contains("None")))
                {
                    _fileExclusionList.Clear();
                }
            }

            _arg_logger ??= Utils.SetupLogging(opt);
            WriteOnce.Log ??= _arg_logger;

            LastUpdated = DateTime.MinValue;
            DateScanned = DateTime.Now;

            try
            {
                ConfigureConsoleOutput();
                ConfigFileOutput();
                ConfigSourcetoScan();
                ConfigConfidenceFilters();
                ConfigRules();
            }
            catch (Exception e) //group error handling
            {
                WriteOnce.Error(e.Message);
                if (_arg_close_log_on_exit)
                {
                    Utils.Logger  = null;
                    WriteOnce.Log = null;
                }
                throw;
            }

            _uniqueTagsControl = new HashSet <string>();
        }
        private void ConfigRules()
        {
            WriteOnce.SafeLog("VerifyRulesCommand::ConfigRules", LogLevel.Trace);

            if (!_options.VerifyDefaultRules && string.IsNullOrEmpty(_options.CustomRulesPath))
            {
                throw new OpException(MsgHelp.GetString(MsgHelp.ID.CMD_NORULES_SPECIFIED));
            }

            _rules_path = _options.VerifyDefaultRules ? null : _options.CustomRulesPath;
        }
        void UnZipAndProcess(string filename, ArchiveFileType archiveFileType)
        {
            // zip itself may be in excluded list i.e. sample, test or similar unless ignore filter requested
            if (_fileExclusionList != null && _fileExclusionList.Any(v => filename.ToLower().Contains(v)))
            {
                WriteOnce.SafeLog(ErrMsg.FormatString(ErrMsg.ID.ANALYZE_EXCLUDED_TYPE_SKIPPED, filename), LogLevel.Warn);
                _appProfile.MetaData.FilesSkipped++;
                return;
            }

            //zip itself may be too huge for timely processing
            if (new FileInfo(filename).Length > WARN_ZIP_FILE_SIZE)
            {
                WriteOnce.General(ErrMsg.FormatString(ErrMsg.ID.ANALYZE_COMPRESSED_FILESIZE_WARN));
            }
            else
            {
                WriteOnce.General(ErrMsg.FormatString(ErrMsg.ID.ANALYZE_COMPRESSED_PROCESSING));
            }

            LastUpdated = File.GetLastWriteTime(filename);
            _appProfile.MetaData.PackageTypes.Add(ErrMsg.GetString(ErrMsg.ID.ANALYZE_COMPRESSED_FILETYPE));

            try
            {
                IEnumerable <FileEntry> files = Extractor.ExtractFile(filename);

                if (files.Count() > 0)
                {
                    _appProfile.MetaData.TotalFiles += files.Count();//additive in case additional child zip files processed

                    foreach (FileEntry file in files)
                    {
                        //check uncompressed file passes standard checks
                        LanguageInfo languageInfo = new LanguageInfo();
                        if (FileChecksPassed(file.FullPath, ref languageInfo, file.Content.Length))
                        {
                            byte[] streamByteArray = file.Content.ToArray();
                            ProcessInMemory(file.FullPath, Encoding.UTF8.GetString(streamByteArray, 0, streamByteArray.Length), languageInfo);
                        }
                    }
                }
                else
                {
                    WriteOnce.SafeLog(string.Format("Decompression found no files in {0}", filename), LogLevel.Warn);//zero results can be valid
                }
            }
            catch (Exception)
            {
                string errmsg = ErrMsg.FormatString(ErrMsg.ID.ANALYZE_COMPRESSED_ERROR, filename);
                WriteOnce.Error(errmsg);
                throw;
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// Main entry from CLI
        /// </summary>
        /// <returns></returns>
        public override int Run()
        {
            WriteOnce.SafeLog("VerifyRulesCommand::Run", LogLevel.Trace);
            WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_RUNNING, "verifyrules"));

            ExitCode exitCode = ExitCode.CriticalError;

            try
            {
                RulesVerifier verifier = new RulesVerifier(_rules_path);
                verifier.Verify();
                exitCode = ExitCode.Verified;

                RuleSet rules = verifier.CompiledRuleset;

                //report each add to console if desired
                foreach (Rule rule in rules)
                {
                    WriteOnce.Result(string.Format("Rule {0}-{1} verified", rule.Id, rule.Name), true, WriteOnce.ConsoleVerbosity.High);
                }

                WriteOnce.Any(ErrMsg.GetString(ErrMsg.ID.VERIFY_RULES_RESULTS_SUCCESS), true, ConsoleColor.Green, WriteOnce.ConsoleVerbosity.Low);
                WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_COMPLETED, "verifyrules"));
                if (!String.IsNullOrEmpty(_arg_outputFile) && Utils.CLIExecutionContext)
                {
                    WriteOnce.Any(ErrMsg.FormatString(ErrMsg.ID.ANALYZE_OUTPUT_FILE, _arg_outputFile), true, ConsoleColor.Gray, WriteOnce.ConsoleVerbosity.Low);
                }
                WriteOnce.FlushAll();
            }
            catch (Exception e)
            {
                WriteOnce.Error(e.Message);
                //exit normaly for CLI callers and throw for DLL callers
                if (Utils.CLIExecutionContext)
                {
                    return((int)ExitCode.CriticalError);
                }
                else
                {
                    throw;
                }
            }
            finally
            {
                if (_arg_close_log_on_exit)
                {
                    Utils.Logger  = null;
                    WriteOnce.Log = null;
                }
            }

            return((int)exitCode);
        }
Exemplo n.º 23
0
        public static void OpenBrowser(string?url)
        {
            if (string.IsNullOrEmpty(url))
            {
                WriteOnce.Log?.Error("Bad url for OpenBrowser method");
                return;
            }

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                try
                {
                    Process.Start(new ProcessStartInfo("cmd", $"/c start {url}"));
                    WriteOnce.General(MsgHelp.GetString(MsgHelp.ID.BROWSER_START_SUCCESS));
                }
                catch (Exception)
                {
                    WriteOnce.General(MsgHelp.GetString(MsgHelp.ID.BROWSER_START_FAIL));//soft error
                }
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("BROWSER")))
                {
                    try
                    {
                        Process.Start("xdg-open", "\"" + url + "\"");
                        WriteOnce.General(MsgHelp.GetString(MsgHelp.ID.BROWSER_START_SUCCESS));
                    }
                    catch (Exception)
                    {
                        WriteOnce.General(MsgHelp.GetString(MsgHelp.ID.BROWSER_START_FAIL));//soft error
                    }
                }
                else
                {
                    WriteOnce.General(MsgHelp.GetString(MsgHelp.ID.BROWSER_ENVIRONMENT_VAR));
                }
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                try
                {
                    Process.Start("open", "\"" + url + "\"");
                    WriteOnce.General(MsgHelp.GetString(MsgHelp.ID.BROWSER_START_SUCCESS));
                }
                catch (Exception)
                {
                    WriteOnce.General(MsgHelp.GetString(MsgHelp.ID.BROWSER_START_FAIL));//soft error
                }
            }
        }
 private void LoadFile(string file)
 {
     try
     {
         _rules?.AddFile(file, null);
     }
     catch (Exception e)
     {
         Debug.Write(e.Message);//Ensure console message indicates problem for Build process
         WriteOnce.SafeLog(e.Message, NLog.LogLevel.Error);
         throw new OpException(MsgHelp.FormatString(MsgHelp.ID.VERIFY_RULE_LOADFILE_FAILED, file));
     }
 }
Exemplo n.º 25
0
        void ConfigSourceToScan()
        {
            WriteOnce.SafeLog("TagDiff::ConfigRules", LogLevel.Trace);

            if (_arg_src1 == _arg_src2)
            {
                throw new Exception(ErrMsg.GetString(ErrMsg.ID.TAGDIFF_SAME_FILE_ARG));
            }
            else if (string.IsNullOrEmpty(_arg_src1) || string.IsNullOrEmpty(_arg_src2))
            {
                throw new Exception(ErrMsg.GetString(ErrMsg.ID.CMD_INVALID_ARG_VALUE));
            }
        }
        private void ConfigSourceToScan()
        {
            WriteOnce.SafeLog("TagDiff::ConfigRules", LogLevel.Trace);

            if (_options.SourcePath1 == _options.SourcePath2)
            {
                throw new OpException(MsgHelp.GetString(MsgHelp.ID.TAGDIFF_SAME_FILE_ARG));
            }
            else if (string.IsNullOrEmpty(_options.SourcePath1) || string.IsNullOrEmpty(_options.SourcePath2))
            {
                throw new OpException(MsgHelp.GetString(MsgHelp.ID.CMD_INVALID_ARG_VALUE));
            }
        }
        /// <summary>
        /// After verifying rules are valid syntax and load; combines into a single .json file
        /// for ease in distribution including this application's defaultset which are
        /// added to the manifest as an embedded resource (see AppInspector.Commands.csproj)
        /// </summary>
        /// <returns></returns>
        public override int Run()
        {
            WriteOnce.SafeLog("PackRules::Run", LogLevel.Trace);
            WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_RUNNING, "packrules"));

            try
            {
                RulesVerifier verifier = new RulesVerifier(_rules_path);
                verifier.Verify();

                List <Rule> list = new List <Rule>(verifier.CompiledRuleset.AsEnumerable());

                JsonSerializerSettings settings = new JsonSerializerSettings();
                settings.Formatting = (_arg_indent) ? Formatting.Indented : Formatting.None;

                using (FileStream fs = File.Open(_arg_outputfile, FileMode.Create, FileAccess.Write))
                {
                    StreamWriter sw = new StreamWriter(fs);
                    sw.Write(JsonConvert.SerializeObject(list, settings));
                    sw.Close();
                    fs.Close();
                }

                WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_COMPLETED, "packrules"));
                WriteOnce.Any(ErrMsg.FormatString(ErrMsg.ID.ANALYZE_OUTPUT_FILE, _arg_outputfile), true, ConsoleColor.Gray, WriteOnce.ConsoleVerbosity.Medium);
                WriteOnce.FlushAll();
            }
            catch (Exception e)
            {
                WriteOnce.Error(e.Message);
                //exit normaly for CLI callers and throw for DLL callers
                if (Utils.CLIExecutionContext)
                {
                    return((int)ExitCode.CriticalError);
                }
                else
                {
                    throw;
                }
            }
            finally
            {
                if (_arg_close_log_on_exit)
                {
                    Utils.Logger  = null;
                    WriteOnce.Log = null;
                }
            }

            return((int)ExitCode.NoIssues);
        }
        void ConfigRules()
        {
            WriteOnce.SafeLog("PackRulesCommand::ConfigRules", LogLevel.Trace);

            if (_arg_repack_default_rules && !Utils.CLIExecutionContext)
            {
                throw new Exception(ErrMsg.GetString(ErrMsg.ID.VERIFY_RULES_NO_CLI_DEFAULT));
            }

            if (!_arg_repack_default_rules && string.IsNullOrEmpty(_arg_custom_rules_path))
            {
                throw new Exception(ErrMsg.GetString(ErrMsg.ID.CMD_NORULES_SPECIFIED));
            }
        }
        public ExportTagsResult GetResult()
        {
            WriteOnce.SafeLog("ExportTagsCommand::Run", LogLevel.Trace);
            WriteOnce.Operation(MsgHelp.FormatString(MsgHelp.ID.CMD_RUNNING, "Export Tags"));

            ExportTagsResult exportTagsResult = new()
            {
                AppVersion = Common.Utils.GetVersionString()
            };

            SortedDictionary <string, string> uniqueTags = new();

            try
            {
                foreach (Rule?r in _rules)
                {
                    //builds a list of unique tags
                    foreach (string t in r?.Tags ?? Array.Empty <string>())
                    {
                        if (uniqueTags.ContainsKey(t))
                        {
                            continue;
                        }
                        else
                        {
                            uniqueTags.Add(t, t);
                        }
                    }
                }

                //generate results list
                foreach (string s in uniqueTags.Values)
                {
                    exportTagsResult.TagsList.Add(s);
                }

                exportTagsResult.ResultCode = ExportTagsResult.ExitCode.Success;
            }
            catch (OpException e)
            {
                WriteOnce.Error(e.Message);
                //caught for CLI callers with final exit msg about checking log or throws for DLL callers
                throw;
            }

            return(exportTagsResult);
        }
    }
        private void ConfigRules()
        {
            WriteOnce.SafeLog("PackRulesCommand::ConfigRules", LogLevel.Trace);

            if (_options.RepackDefaultRules && !Utils.CLIExecutionContext)
            {
                throw new OpException(MsgHelp.GetString(MsgHelp.ID.VERIFY_RULES_NO_CLI_DEFAULT));
            }

            if (!_options.RepackDefaultRules && string.IsNullOrEmpty(_options.CustomRulesPath))
            {
                throw new OpException(MsgHelp.GetString(MsgHelp.ID.CMD_NORULES_SPECIFIED));
            }

            _rules_path = _options.RepackDefaultRules ? Utils.GetPath(Utils.AppPath.defaultRulesSrc) : _options.CustomRulesPath;
        }