/// <summary> /// Main entry point to start analysis; handles setting up rules, directory enumeration /// file type detection and handoff /// Pre: All Configure Methods have been called already and we are ready to SCAN /// </summary> /// <returns></returns> public int Run() { WriteOnce.SafeLog("AnalyzeCommand::Run", LogLevel.Trace); DateTime start = DateTime.Now; WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_RUNNING, "Analyze")); _appProfile.MetaData.TotalFiles = _srcfileList.Count();//updated for zipped files later // Iterate through all files and process against rules foreach (string filename in _srcfileList) { var fileExtension = new FileInfo(filename).Extension; if (COMPRESSED_EXTENSIONS.Any(fileExtension.Contains)) { UnZipAndProcess(filename); //determine if file is a compressed item to unpackage for processing } else { ProcessAsFile(filename); } } WriteOnce.General("\r" + ErrMsg.FormatString(ErrMsg.ID.ANALYZE_FILES_PROCESSED_PCNT, 100)); WriteOnce.Operation(ErrMsg.GetString(ErrMsg.ID.CMD_PREPARING_REPORT)); //Prepare report results _appProfile.MetaData.LastUpdated = LastUpdated.ToString(); _appProfile.DateScanned = DateScanned.ToString(); _appProfile.PrepareReport(); TimeSpan timeSpan = start - DateTime.Now; WriteOnce.SafeLog(String.Format("Processing time: seconds:{0}", timeSpan.TotalSeconds * -1), LogLevel.Trace); FlushAll(); //wrapup result status if (_appProfile.MetaData.TotalFiles == _appProfile.MetaData.FilesSkipped) { WriteOnce.Error(ErrMsg.GetString(ErrMsg.ID.ANALYZE_NOSUPPORTED_FILETYPES)); } else if (_appProfile.MatchList.Count == 0) { WriteOnce.Error(ErrMsg.GetString(ErrMsg.ID.ANALYZE_NOPATTERNS)); } else { WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_COMPLETED, "Analyze")); } //html report size warning if (_arg_fileFormat == "html" && new FileInfo("output.html").Length > MAX_HTML_REPORT_FILE_SIZE) { WriteOnce.Info(ErrMsg.GetString(ErrMsg.ID.ANALYZE_REPORTSIZE_WARN)); } return(_appProfile.MatchList.Count() == 0 ? (int)ExitCode.NoMatches : (int)ExitCode.MatchesFound); }
/// <summary> /// Program entry point which defines command verbs and options to running /// </summary> /// <param name="args"></param> static int Main(string[] args) { int finalResult = -1; WriteOnce.Verbosity = WriteOnce.ConsoleVerbosity.Medium; try { WriteOnce.Info(GetVersionString()); var argsResult = Parser.Default.ParseArguments <AnalyzeCommandOptions, TagDiffCommandOptions, TagTestCommandOptions, ExportTagsCommandOptions, VerifyRulesCommandOptions>(args) .MapResult( (AnalyzeCommandOptions opts) => RunAnalyzeCommand(opts), (TagDiffCommandOptions opts) => RunTagDiffCommand(opts), (TagTestCommandOptions opts) => RunTagTestCommand(opts), (ExportTagsCommandOptions opts) => RunExportTagsCommand(opts), (VerifyRulesCommandOptions opts) => RunVerifyRulesCommand(opts), errs => 1 ); finalResult = argsResult; } catch (OpException e) { if (Logger != null) { WriteOnce.Error(ErrMsg.FormatString(ErrMsg.ID.RUNTIME_ERROR_NAMED, e.Message)); Logger.Error($"Runtime error: {e.StackTrace}"); } else { WriteOnce.Error(ErrMsg.FormatString(ErrMsg.ID.RUNTIME_ERROR_PRELOG, e.Message)); } } catch (Exception e) { if (Logger != null) { WriteOnce.Error(ErrMsg.FormatString(ErrMsg.ID.RUNTIME_ERROR_UNNAMED)); Logger.Error($"Runtime error: {e.StackTrace}"); } else { WriteOnce.Error(ErrMsg.FormatString(ErrMsg.ID.RUNTIME_ERROR_PRELOG, e.Message)); } } return(finalResult); }
void ConfigOutput() { WriteOnce.SafeLog("AnalyzeCommand::ConfigOutput", LogLevel.Trace); //Set output type, format and outstream _outputWriter = WriterFactory.GetWriter(_arg_fileFormat ?? "text", (string.IsNullOrEmpty(_arg_outputFile)) ? null : "text", _arg_outputTextFormat); if (_arg_fileFormat == "html") { if (!string.IsNullOrEmpty(_arg_outputFile)) { WriteOnce.Info("output file ignored for html format"); } _outputWriter.TextWriter = Console.Out; } else if (!string.IsNullOrEmpty(_arg_outputFile)) { _outputWriter.TextWriter = File.CreateText(_arg_outputFile);//not needed if html output since application controlled } else { _outputWriter.TextWriter = Console.Out; } }
public int Run() { bool issues = false; WriteOnce.Operation(ErrMsg.FormatString(ErrMsg.ID.CMD_RUNNING, "Verify Rules")); //load [each] rules file separately to report out where a failure is happening RuleSet rules = new RuleSet(WriteOnce.Log); IEnumerable <string> fileListing = new List <string>(); foreach (string rulePath in _rulePaths) { if (Directory.Exists(rulePath)) { fileListing = Directory.EnumerateFiles(rulePath, "*.json", SearchOption.AllDirectories); } else if (File.Exists(rulePath) && Path.GetExtension(rulePath) == ".json") { fileListing = new List <string>() { new string(rulePath) } } ; else { throw new OpException(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_RULE_PATH, rulePath)); } //test loading each file foreach (string filename in fileListing) { try { rules.AddFile(filename); WriteOnce.Info(string.Format("Rule file added {0}", filename), true, WriteOnce.ConsoleVerbosity.High); } catch (Exception e) { WriteOnce.Error(string.Format("Rule file add failed {0}", filename)); WriteOnce.SafeLog(e.Message + "\n" + e.StackTrace, NLog.LogLevel.Error); issues = true; } } } //option to write validating data if (_arg_consoleVerbosityLevel == WriteOnce.ConsoleVerbosity.High) { WritePartialRuleDetails(rules); } //final status report if (issues) { WriteOnce.Any(ErrMsg.GetString(ErrMsg.ID.VERIFY_RULES_RESULTS_FAIL), true, ConsoleColor.Red, WriteOnce.ConsoleVerbosity.Low); } else { 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); }
readonly int MAX_HTML_REPORT_FILE_SIZE = 1024 * 1000 * 3; //warn about potential slow rendering /// <summary> /// Registers datatypes with html framework liquid and sets up data for use within it and used /// with html partial.liquid files that are embedded as resources /// </summary> /// <param name="app"></param> public override void WriteApp(AppProfile app) { var htmlTemplateText = File.ReadAllText(Path.Combine(Utils.GetPath(Utils.AppPath.basePath), "html/index.html")); Assembly test = Assembly.GetEntryAssembly(); Template.FileSystem = new EmbeddedFileSystem(Assembly.GetEntryAssembly(), "ApplicationInspector.html.partials"); RegisterSafeType(typeof(AppProfile)); RegisterSafeType(typeof(AppMetaData)); var htmlTemplate = Template.Parse(htmlTemplateText); var data = new Dictionary <string, object>(); data["AppProfile"] = app; //matchitems rather than records created to exclude full rule/patterns/cond. List <MatchItems> matches = new List <MatchItems>(); foreach (MatchRecord match in app.MatchList) { MatchItems matchItem = new MatchItems(match); matches.Add(matchItem); } data["matchDetails"] = matches; var hashData = new Hash(); hashData["json"] = JsonConvert.SerializeObject(data, Formatting.Indented); hashData["application_version"] = Program.GetVersionString(); //add dynamic sets of groups of taginfo read from preferences for Profile page List <TagGroup> tagGroupList = app.GetCategoryTagGroups("profile"); hashData["groups"] = tagGroupList; //add summary values for sorted tags lists of taginfo foreach (string outerKey in app.KeyedSortedTagInfoLists.Keys) { hashData.Add(outerKey, app.KeyedSortedTagInfoLists[outerKey]); } //add summary metadata lists hashData["cputargets"] = app.MetaData.CPUTargets; hashData["apptypes"] = app.MetaData.AppTypes; hashData["packagetypes"] = app.MetaData.PackageTypes; hashData["ostargets"] = app.MetaData.OSTargets; hashData["outputs"] = app.MetaData.Outputs; hashData["filetypes"] = app.MetaData.FileExtensions; hashData["tagcounters"] = app.MetaData.TagCountersUI; var htmlResult = htmlTemplate.Render(hashData); string htmlOutputFilePath = Path.Combine(Utils.GetPath(Utils.AppPath.basePath), "output.html"); File.WriteAllText(htmlOutputFilePath, htmlResult); //writes out json report for convenience and linking to from report page(s) String jsonReportPath = Path.Combine(Utils.GetPath(Utils.AppPath.basePath), "output.json"); Writer jsonWriter = WriterFactory.GetWriter("json", jsonReportPath); jsonWriter.TextWriter = File.CreateText(jsonReportPath); jsonWriter.WriteApp(app); jsonWriter.FlushAndClose(); //html report size warning string outputHTMLPath = Path.Combine(Utils.GetPath(Utils.AppPath.basePath), "output.html"); if (File.Exists(outputHTMLPath) && new FileInfo(outputHTMLPath).Length > MAX_HTML_REPORT_FILE_SIZE) { WriteOnce.Info(ErrMsg.GetString(ErrMsg.ID.ANALYZE_REPORTSIZE_WARN)); } Utils.OpenBrowser(htmlOutputFilePath); }