public static CommandResultsWriter GetExportWriter(CLIExportTagsCmdOptions options)
        {
            CommandResultsWriter?writer;

            switch (options.OutputFileFormat.ToLower())
            {
            case "_dummy":
                writer = new ExportDummyWriter();
                break;

            case "json":
                writer = new JsonWriter();
                break;

            case "text":
                writer = new ExportTextWriter();
                break;

            default:
                WriteOnce.Error(MsgHelp.FormatString(MsgHelp.ID.CMD_INVALID_ARG_VALUE, "-f"));
                throw new OpException((MsgHelp.FormatString(MsgHelp.ID.CMD_INVALID_ARG_VALUE, "-f")));
            }

            //assign the stream as a file or console
            writer.OutputFileName = options.OutputFilePath;
            writer.TextWriter     = GetTextWriter(writer.OutputFileName);

            return(writer);
        }
        private string MergeResourceFiles(string inputPath)
        {
            StringBuilder stringBuilder = new();

            if (Directory.Exists(inputPath))
            {
                try
                {
                    IEnumerable <string> srcfileList = Directory.EnumerateFiles(inputPath, "*.*", SearchOption.AllDirectories);
                    if (!srcfileList.Any())
                    {
                        throw new OpException(MsgHelp.FormatString(MsgHelp.ID.CMD_INVALID_FILE_OR_DIR, inputPath));
                    }

                    foreach (string fileName in srcfileList)
                    {
                        stringBuilder.Append(string.Format("\n\n/*FILE: {0}*/\n\n", fileName));
                        stringBuilder.Append(File.ReadAllText(fileName));
                    }
                }
                catch (Exception)
                {
                    throw new OpException(MsgHelp.FormatString(MsgHelp.ID.CMD_INVALID_FILE_OR_DIR, inputPath));
                }
            }

            return(stringBuilder.ToString());
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Only AnalyzeResultsWriter supports an html option
        /// </summary>
        /// <param name="options"></param>
        /// <returns></returns>
        private static CommandResultsWriter GetAnalyzeWriter(CLIAnalyzeCmdOptions options)
        {
            CommandResultsWriter?writer;

            switch (options.OutputFileFormat.ToLower())
            {
            case "json":
                writer = new AnalyzeJsonWriter();
                break;

            case "text":
                writer = new AnalyzeTextWriter(options.TextOutputFormat);
                break;

            case "html":
                writer = new AnalyzeHtmlWriter();
                break;

            case "sarif":
                writer = new AnalyzeSarifWriter();
                break;

            default:
                WriteOnce.Error(MsgHelp.FormatString(MsgHelp.ID.CMD_INVALID_ARG_VALUE, "-f"));
                throw new OpException((MsgHelp.FormatString(MsgHelp.ID.CMD_INVALID_ARG_VALUE, "-f")));
            }

            //assign the stream as a file or console
            writer.OutputFileName = options.OutputFilePath;
            writer.TextWriter     = GetTextWriter(writer.OutputFileName);

            return(writer);
        }
        public override void WriteResults(Result result, CLICommandOptions commandOptions, bool autoClose = true)
        {
            TagDiffResult        tagDiffResult        = (TagDiffResult)result;
            CLITagDiffCmdOptions cLITagDiffCmdOptions = (CLITagDiffCmdOptions)commandOptions;

            TextWriter.WriteLine(MsgHelp.FormatString(MsgHelp.ID.TAGTEST_RESULTS_TEST_TYPE, cLITagDiffCmdOptions.TestType));

            if (tagDiffResult.ResultCode == TagDiffResult.ExitCode.TestFailed)
            {
                TextWriter.WriteLine(MsgHelp.GetString(MsgHelp.ID.TAGTEST_RESULTS_FAIL));
            }
            else
            {
                TextWriter.WriteLine(MsgHelp.GetString(MsgHelp.ID.TAGTEST_RESULTS_SUCCESS));
            }

            //Results list
            if (tagDiffResult.TagDiffList.Count > 0)
            {
                TextWriter.WriteLine("Differences");
                foreach (TagDiff tagDiff in tagDiffResult.TagDiffList)
                {
                    TextWriter.WriteLine(string.Format("Tag: {0}, Only found in file: {1}", tagDiff.Tag, tagDiff.Source));
                }
            }

            if (autoClose)
            {
                FlushAndClose();
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Checks that either output filepath is valid or console verbosity is not visible to ensure
        /// some output can be achieved...other command specific inputs that are relevant to both CLI
        /// and NuGet callers are checked by the commands themselves
        /// </summary>
        /// <param name="options"></param>
        private static void CommonOutputChecks(CLICommandOptions options)
        {
            //validate requested format
            string fileFormatArg = options.OutputFileFormat;

            string[] validFormats =
            {
                "html",
                "text",
                "json",
                "sarif"
            };

            string[] checkFormats;
            if (options is CLIAnalyzeCmdOptions cliAnalyzeOptions)
            {
                checkFormats  = validFormats;
                fileFormatArg = cliAnalyzeOptions.OutputFileFormat;
            }
            else if (options is CLIPackRulesCmdOptions cliPackRulesOptions)
            {
                checkFormats  = validFormats.Skip(2).Take(1).ToArray();
                fileFormatArg = cliPackRulesOptions.OutputFileFormat;
            }
            else
            {
                checkFormats = validFormats.Skip(1).Take(2).ToArray();
            }

            bool isValidFormat = checkFormats.Any(v => v.Equals(fileFormatArg.ToLower()));

            if (!isValidFormat)
            {
                WriteOnce.Error(MsgHelp.FormatString(MsgHelp.ID.CMD_INVALID_ARG_VALUE, "-f"));
                throw new OpException(MsgHelp.FormatString(MsgHelp.ID.CMD_INVALID_ARG_VALUE, "-f"));
            }

            //validate output is not empty if no file output specified
            if (string.IsNullOrEmpty(options.OutputFilePath))
            {
                if (string.Equals(options.ConsoleVerbosityLevel, "none", StringComparison.OrdinalIgnoreCase))
                {
                    WriteOnce.Error(MsgHelp.GetString(MsgHelp.ID.CMD_NO_OUTPUT));
                    throw new Exception(MsgHelp.GetString(MsgHelp.ID.CMD_NO_OUTPUT));
                }
                else if (string.Equals(options.ConsoleVerbosityLevel, "low", StringComparison.OrdinalIgnoreCase))
                {
                    WriteOnce.SafeLog("Verbosity set low.  Detailed output limited.", NLog.LogLevel.Info);
                }
            }
            else
            {
                ValidFileWritePath(options.OutputFilePath);
            }
        }
Ejemplo n.º 6
0
 /// <summary>
 /// Ensure output file path can be written to
 /// </summary>
 /// <param name="filePath"></param>
 private static void ValidFileWritePath(string filePath)
 {
     try
     {
         File.WriteAllText(filePath, "");//verify ability to write to location
     }
     catch (Exception)
     {
         WriteOnce.Error(MsgHelp.FormatString(MsgHelp.ID.CMD_INVALID_FILE_OR_DIR, filePath));
         throw new OpException(MsgHelp.FormatString(MsgHelp.ID.CMD_INVALID_FILE_OR_DIR, filePath));
     }
 }
Ejemplo n.º 7
0
        /// <summary>
        /// CLI program entry point which defines command verbs and options to running
        /// </summary>
        /// <param name="args"></param>
        private static int Main(string[] args)
        {
            int finalResult = (int)Utils.ExitCode.CriticalError;

            Utils.CLIExecutionContext = true;//set manually at start from CLI

            WriteOnce.Verbosity = WriteOnce.ConsoleVerbosity.Medium;
            try
            {
                var argsResult = Parser.Default.ParseArguments <CLIAnalyzeCmdOptions,
                                                                CLITagDiffCmdOptions,
                                                                CLITagTestCmdOptions,
                                                                CLIExportTagsCmdOptions,
                                                                CLIVerifyRulesCmdOptions,
                                                                CLIPackRulesCmdOptions>(args)
                                 .MapResult(
                    (CLIAnalyzeCmdOptions cliOptions) => VerifyOutputArgsRun(cliOptions),
                    (CLITagDiffCmdOptions cliOptions) => VerifyOutputArgsRun(cliOptions),
                    (CLITagTestCmdOptions cliOptions) => VerifyOutputArgsRun(cliOptions),
                    (CLIExportTagsCmdOptions cliOptions) => VerifyOutputArgsRun(cliOptions),
                    (CLIVerifyRulesCmdOptions cliOptions) => VerifyOutputArgsRun(cliOptions),
                    (CLIPackRulesCmdOptions cliOptions) => VerifyOutputArgsRun(cliOptions),
                    errs => 1
                    );

                finalResult = argsResult;
            }
            catch (OpException)
            {
                //log, output file and console have already been written to ensure all are updated for NuGet and CLI callers
                //that may exit at different call points
            }
            catch (Exception e)
            {
                //unlogged exception so report out for CLI callers
                WriteOnce.SafeLog(e.Message + "\n" + e.StackTrace, NLog.LogLevel.Error);
            }

            //final exit msg to review log
            if (finalResult == (int)Utils.ExitCode.CriticalError)
            {
                if (!String.IsNullOrEmpty(Utils.LogFilePath))
                {
                    WriteOnce.Info(MsgHelp.FormatString(MsgHelp.ID.RUNTIME_ERROR_UNNAMED, Utils.LogFilePath), true, WriteOnce.ConsoleVerbosity.Low, false);
                }
                else
                {
                    WriteOnce.Info(MsgHelp.GetString(MsgHelp.ID.RUNTIME_ERROR_PRELOG), true, WriteOnce.ConsoleVerbosity.Medium, false);
                }
            }

            return(finalResult);
        }
        public override void WriteResults(Result result, CLICommandOptions commandOptions, bool autoClose = true)
        {
            CLITagTestCmdOptions cLITagTestCmdOptions = (CLITagTestCmdOptions)commandOptions;
            TagTestResult        tagTestResult        = (TagTestResult)result;

            //For console output, update write once for same results to console or file
            WriteOnce.TextWriter = TextWriter;

            if (string.IsNullOrEmpty(commandOptions.OutputFilePath))
            {
                WriteOnce.Result("Results");
            }

            WriteOnce.General(MsgHelp.FormatString(MsgHelp.ID.TAGTEST_RESULTS_TEST_TYPE, cLITagTestCmdOptions.TestType), false, WriteOnce.ConsoleVerbosity.Low);

            if (tagTestResult.ResultCode == TagTestResult.ExitCode.TestFailed)
            {
                WriteOnce.Any(MsgHelp.GetString(MsgHelp.ID.TAGTEST_RESULTS_FAIL), true, ConsoleColor.Red, WriteOnce.ConsoleVerbosity.Low);
            }
            else
            {
                WriteOnce.Any(MsgHelp.GetString(MsgHelp.ID.TAGTEST_RESULTS_SUCCESS), true, ConsoleColor.Green, WriteOnce.ConsoleVerbosity.Low);
            }

            if (tagTestResult.TagsStatusList.Count > 0)
            {
                WriteOnce.Result("Test results:");

                foreach (TagStatus tag in tagTestResult.TagsStatusList)
                {
                    WriteOnce.General(string.Format("Tag: {0}, Detected: {1}", tag.Tag, tag.Detected));
                }
            }

            WriteOnce.NewLine();

            if (autoClose)
            {
                FlushAndClose();
            }
        }
Ejemplo n.º 9
0
        public override void WriteResults(Result result, CLICommandOptions commandOptions, bool autoClose = true)
        {
            TagDiffResult        tagDiffResult        = (TagDiffResult)result;
            CLITagDiffCmdOptions cLITagDiffCmdOptions = (CLITagDiffCmdOptions)commandOptions;

            //For console output, update write once for same results to console or file
            WriteOnce.TextWriter = TextWriter;

            if (string.IsNullOrEmpty(commandOptions.OutputFilePath))
            {
                WriteOnce.Result("Results");
            }

            WriteOnce.General(MsgHelp.FormatString(MsgHelp.ID.TAGTEST_RESULTS_TEST_TYPE, cLITagDiffCmdOptions.TestType), false, WriteOnce.ConsoleVerbosity.Low);

            if (tagDiffResult.ResultCode == TagDiffResult.ExitCode.TestFailed)
            {
                WriteOnce.Any(MsgHelp.GetString(MsgHelp.ID.TAGTEST_RESULTS_FAIL), true, ConsoleColor.Red, WriteOnce.ConsoleVerbosity.Low);
            }
            else
            {
                WriteOnce.Any(MsgHelp.GetString(MsgHelp.ID.TAGTEST_RESULTS_SUCCESS), true, ConsoleColor.Green, WriteOnce.ConsoleVerbosity.Low);
            }

            //Results list
            if (tagDiffResult.TagDiffList.Count > 0)
            {
                WriteOnce.Result("Differences");
                foreach (TagDiff tagDiff in tagDiffResult.TagDiffList)
                {
                    WriteOnce.General(string.Format("Tag: {0}, Only found in file: {1}", tagDiff.Tag, tagDiff.Source));
                }
            }

            if (autoClose)
            {
                FlushAndClose();
            }
        }
        private static TextWriter GetTextWriter(string?outputFileName)
        {
            TextWriter textWriter;

            if (String.IsNullOrEmpty(outputFileName))
            {
                textWriter = Console.Out;
            }
            else
            {
                try
                {
                    textWriter = File.CreateText(outputFileName);
                }
                catch (Exception e)
                {
                    WriteOnce.Error(MsgHelp.FormatString(MsgHelp.ID.CMD_INVALID_FILE_OR_DIR, outputFileName));
                    throw new OpException(e.Message);
                }
            }

            return(textWriter);
        }