void ConfigRules()
        {
            if (!_arg_ignoreDefaultRules)
            {
                _rules = Utils.GetDefaultRuleSet(_arg_logger);
            }

            if (!string.IsNullOrEmpty(_arg_customRulesPath))
            {
                if (_rules == null)
                {
                    _rules = new RuleSet(_arg_logger);
                }

                if (Directory.Exists(_arg_customRulesPath))
                {
                    _rules.AddDirectory(_arg_customRulesPath);
                }
                else if (File.Exists(_arg_customRulesPath))
                {
                    _rules.AddFile(_arg_customRulesPath);
                }
                else
                {
                    throw new OpException(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_RULE_PATH, _arg_customRulesPath));
                }
            }

            //error check based on ruleset not path enumeration
            if (_rules == null || _rules.Count() == 0)
            {
                throw new OpException(ErrMsg.GetString(ErrMsg.ID.CMD_NORULES_SPECIFIED));
            }
        }
        public void ConfigureRules()
        {
            List <string> rulePaths = new List <string>();

            if (!string.IsNullOrEmpty(_arg_customRulesPath))
            {
                rulePaths.Add(_arg_customRulesPath);
            }

            foreach (string rulePath in rulePaths)
            {
                if (Directory.Exists(rulePath))
                {
                    _rulesSet.AddDirectory(rulePath);
                }
                else if (File.Exists(rulePath))
                {
                    _rulesSet.AddFile(rulePath);
                }
                else
                {
                    throw new OpException(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_RULE_PATH, rulePath));
                }
            }

            //error check based on ruleset not path enumeration
            if (_rulesSet.Count() == 0)
            {
                throw new OpException(ErrMsg.GetString(ErrMsg.ID.CMD_NORULES_SPECIFIED));
            }
        }
Exemple #3
0
        private bool LoadFile(string file)
        {
            RuleSet rules     = new RuleSet();
            bool    noProblem = true;

            rules.OnDeserializationError += delegate(object?sender, Newtonsoft.Json.Serialization.ErrorEventArgs e)
            {
                ErrorMessage message = new ErrorMessage(File: file,
                                                        Message: e.ErrorContext.Error.Message,
                                                        Path: e.ErrorContext.Path);

                if (e.ErrorContext.OriginalObject is Rule r && !string.IsNullOrEmpty(r.Id))
                {
                    message.RuleID = r.Id;
                }

                // Newtonsoft json throws some errors twice
                if (_messages.FirstOrDefault(x => (x.Message == message.Message && x.File == file)) == null)
                {
                    _messages.Add(message);
                }

                noProblem = false;
                e.ErrorContext.Handled = true;
            };

            rules.AddFile(file, null);

            if (noProblem)
            {
                _rules.AddRange(rules.AsEnumerable());
            }

            return(noProblem);
        }
Exemple #4
0
        private void ConfigRules()
        {
            _logger.LogTrace("ExportTagsCommand::ConfigRules");
            _rules = new RuleSet(_loggerFactory);
            if (!_options.IgnoreDefaultRules)
            {
                _rules = RuleSetUtils.GetDefaultRuleSet(_loggerFactory);
            }

            if (!string.IsNullOrEmpty(_options?.CustomRulesPath))
            {
                if (Directory.Exists(_options.CustomRulesPath))
                {
                    _rules.AddDirectory(_options.CustomRulesPath);
                }
                else if (File.Exists(_options.CustomRulesPath))
                {
                    _rules.AddFile(_options.CustomRulesPath);
                }
                else
                {
                    throw new OpException(MsgHelp.FormatString(MsgHelp.ID.CMD_INVALID_RULE_PATH, _options.CustomRulesPath));
                }
            }

            //error check based on ruleset not path enumeration
            if (_rules == null || !_rules.Any())
            {
                throw new OpException(MsgHelp.GetString(MsgHelp.ID.CMD_NORULES_SPECIFIED));
            }
        }
 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));
     }
 }
Exemple #6
0
        public void AddRuleFromStringAndFile()
        {
            StreamReader fs   = File.OpenText(Path.Combine("rules", "custom", "quickfix.json"));
            string       rule = fs.ReadToEnd();

            // From String
            RuleSet testRules = RuleSet.FromString(rule, "string", null);

            Assert.AreEqual(1, testRules.Count(), "FromString Count should be 1");

            // From File
            testRules.AddFile(Path.Combine("rules", "custom", "quickfix.json"), null);
            Assert.AreEqual(2, testRules.Count(), "FromFile Count should be 2");
        }
        private void LoadFile(string file)
        {
            RuleSet rules = new RuleSet();

            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 Exception(ErrMsg.FormatString(ErrMsg.ID.VERIFY_RULE_FAILED, file));
            }

            _rules.AddRange(rules.AsEnumerable());
        }
Exemple #8
0
        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);

                //allow caller to specify whether to continue
                if (fail_fast)
                {
                    throw new OpException(MsgHelp.FormatString(MsgHelp.ID.VERIFY_RULE_FAILED, file));
                }
            }
        }
        private bool LoadFile(string file)
        {
            RuleSet rules     = new RuleSet();
            bool    noProblem = true;

            rules.OnDeserializationError += delegate(object sender, Newtonsoft.Json.Serialization.ErrorEventArgs e)
            {
                throw new Exception(String.Format("Error packing rule file: {0}", file));
            };

            rules.AddFile(file, null);

            if (noProblem)
            {
                _rules.AddRange(rules.AsEnumerable());
            }

            return(noProblem);
        }
        void ConfigRules()
        {
            List <string> rulePaths = new List <string>();

            if (!_arg_ignoreDefaultRules)
            {
                Assembly assembly     = Assembly.GetExecutingAssembly();
                string[] resourceName = assembly.GetManifestResourceNames();
                string   filePath     = "Microsoft.ApplicationInspector.Commands.defaultRules.json";
                Stream   resource     = assembly.GetManifestResourceStream(filePath);
                using (StreamReader file = new StreamReader(resource))
                {
                    _rules.AddString(file.ReadToEnd(), filePath, null);
                }
            }

            if (!string.IsNullOrEmpty(_arg_customRulesPath))
            {
                rulePaths.Add(_arg_customRulesPath);
            }

            foreach (string rulePath in rulePaths)
            {
                if (Directory.Exists(rulePath))
                {
                    _rules.AddDirectory(rulePath);
                }
                else if (File.Exists(rulePath))
                {
                    _rules.AddFile(rulePath);
                }
                else
                {
                    throw new OpException(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_RULE_PATH, rulePath));
                }
            }

            //error check based on ruleset not path enumeration
            if (_rules.Count() == 0)
            {
                throw new OpException(ErrMsg.GetString(ErrMsg.ID.CMD_NORULES_SPECIFIED));
            }
        }
Exemple #11
0
        /// <summary>
        /// Reloads rules based on settings
        /// </summary>
        private void LoadRules()
        {
            Settings set = Settings.GetSettings();

            ruleset = new RuleSet();
            string rulesFile = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            rulesFile = Path.Combine(Path.Combine(rulesFile, "Content"), "devskim-rules.json");
            if (set.UseDefaultRules)
            {
                ruleset.AddFile(rulesFile, null);
            }

            if (set.UseCustomRules)
            {
                ruleset.AddDirectory(set.CustomRulesPath, "custom");
            }

            processor.Rules = ruleset;

            processor.SeverityLevel = Severity.Critical;

            if (set.EnableImportantRules)
            {
                processor.SeverityLevel |= Severity.Important;
            }
            if (set.EnableModerateRules)
            {
                processor.SeverityLevel |= Severity.Moderate;
            }
            if (set.EnableBestPracticeRules)
            {
                processor.SeverityLevel |= Severity.BestPractice;
            }
            if (set.EnableManualReviewRules)
            {
                processor.SeverityLevel |= Severity.ManualReview;
            }
        }
Exemple #12
0
        private void ConfigRules()
        {
            WriteOnce.SafeLog("ExportTagsCommand::ConfigRules", LogLevel.Trace);

            if (!_options.IgnoreDefaultRules)
            {
                _rules = Utils.GetDefaultRuleSet(_options.Log);
            }

            if (!string.IsNullOrEmpty(_options.CustomRulesPath))
            {
                if (_rules == null)
                {
                    _rules = new RuleSet(_options.Log);
                }

                if (Directory.Exists(_options.CustomRulesPath))
                {
                    _rules.AddDirectory(_options.CustomRulesPath);
                }
                else if (File.Exists(_options.CustomRulesPath))
                {
                    _rules.AddFile(_options.CustomRulesPath);
                }
                else
                {
                    throw new OpException(MsgHelp.FormatString(MsgHelp.ID.CMD_INVALID_RULE_PATH, _options.CustomRulesPath));
                }
            }

            //error check based on ruleset not path enumeration
            if (_rules == null || _rules.Count() == 0)
            {
                throw new OpException(MsgHelp.GetString(MsgHelp.ID.CMD_NORULES_SPECIFIED));
            }
        }
Exemple #13
0
        /// <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"));

            //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.ToLower() == "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);
        }
Exemple #14
0
        /// <summary>
        /// Add default and/or custom rules paths
        /// Iterate paths and add to ruleset
        /// </summary>
        void ConfigRules()
        {
            WriteOnce.SafeLog("AnalyzeCommand::ConfigRules", LogLevel.Trace);

            RuleSet       rulesSet  = new RuleSet(_arg_logger);
            List <string> rulePaths = new List <string>();

            if (!_arg_ignoreDefaultRules)
            {
                rulePaths.Add(Utils.GetPath(Utils.AppPath.defaultRules));
            }

            if (!string.IsNullOrEmpty(_arg_customRulesPath))
            {
                rulePaths.Add(_arg_customRulesPath);
            }

            foreach (string rulePath in rulePaths)
            {
                if (Directory.Exists(rulePath))
                {
                    rulesSet.AddDirectory(rulePath);
                }
                else if (File.Exists(rulePath))
                {
                    rulesSet.AddFile(rulePath);
                }
                else
                {
                    throw new OpException(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_RULE_PATH, rulePath));
                }
            }

            //error check based on ruleset not path enumeration
            if (rulesSet.Count() == 0)
            {
                throw new OpException(ErrMsg.GetString(ErrMsg.ID.CMD_NORULES_SPECIFIED));
            }

            //instantiate a RuleProcessor with the added rules and exception for dependency
            _rulesProcessor = new RuleProcessor(rulesSet, _arg_confidence, _arg_outputUniqueTagsOnly, _arg_simpleTagsOnly, _arg_logger);

            if (_arg_outputUniqueTagsOnly)
            {
                List <TagException> tagExceptions;
                if (File.Exists(Utils.GetPath(Utils.AppPath.tagCounterPref)))
                {
                    tagExceptions = JsonConvert.DeserializeObject <List <TagException> >(File.ReadAllText(Utils.GetPath(Utils.AppPath.tagCounterPref)));
                    string[] exceptions = new string[tagExceptions.Count];
                    for (int i = 0; i < tagExceptions.Count; i++)
                    {
                        exceptions[i] = tagExceptions[i].Tag;
                    }
                    _rulesProcessor.UniqueTagExceptions = exceptions;
                }
            }

            _appProfile      = new AppProfile(_arg_sourcePath, rulePaths, false, _arg_simpleTagsOnly, _arg_outputUniqueTagsOnly, _arg_autoBrowserOpen);
            _appProfile.Args = "analyze -f " + _arg_fileFormat + " -u " + _arg_outputUniqueTagsOnly.ToString().ToLower() + " -v " +
                               WriteOnce.Verbosity.ToString() + " -x " + _arg_confidence + " -i " + _arg_ignoreDefaultRules.ToString().ToLower();
        }