public void Config()
		{

            JsLintConfiguration config = new JsLintConfiguration();

            Assert.AreEqual("maxerr: 50", config.OptionsToString(), "Default has no options set.");
            Assert.AreEqual(String.Empty, config.GlobalsToString(), "Default has no globals set.");
            Assert.AreEqual(50, config.MaxErrors, "Maxerrors=99999");
            Assert.AreEqual(true, config.ErrorOnUnused, "Unused default");
            Assert.AreEqual(config.MaxErrors,config.GetOption<int>("maxerr") , config.MaxErrors, "Maxerrors = options(maxerr)");
            
            config.SetOption("unused");
            config.SetOption("evil");
            config.SetOption("maxerr", 50);
            config.SetOption("immed");

            Assert.AreEqual("maxerr: 50, unused: true, evil: true, immed: true", config.OptionsToString(), "Basic option setting worked.");

            JsLintConfiguration config2 = new JsLintConfiguration();
            config2.SetOption("eqeqeq", true);
            config2.SetOption("maxerr", 25);
            config2.SetOption("immed", false);

            config.MergeOptions(config2);

            Assert.AreEqual("maxerr: 25, unused: true, evil: true, immed: false, eqeqeq: true", config.OptionsToString(), "Basic option setting worked.");

        }
        public void Config()
        {
            JsLintConfiguration config = new JsLintConfiguration();

            Assert.AreEqual("maxerr: 50", config.OptionsToString(), "Default has no options set.");
            Assert.AreEqual(String.Empty, config.GlobalsToString(), "Default has no globals set.");
            Assert.AreEqual(50, config.MaxErrors, "Maxerrors=99999");
            Assert.AreEqual(true, config.ErrorOnUnused, "Unused default");
            Assert.AreEqual(config.MaxErrors, config.GetOption <int>("maxerr"), config.MaxErrors, "Maxerrors = options(maxerr)");

            config.SetOption("unused");
            config.SetOption("evil");
            config.SetOption("maxerr", 50);
            config.SetOption("immed");

            Assert.AreEqual("maxerr: 50, unused: true, evil: true, immed: true", config.OptionsToString(), "Basic option setting worked.");

            JsLintConfiguration config2 = new JsLintConfiguration();

            config2.SetOption("eqeqeq", true);
            config2.SetOption("maxerr", 25);
            config2.SetOption("immed", false);

            config.MergeOptions(config2);

            Assert.AreEqual("maxerr: 25, unused: true, evil: true, immed: false, eqeqeq: true", config.OptionsToString(), "Basic option setting worked.");
        }
Beispiel #3
0
        public void TestMultipleDifferentOptions()
        {
            JsLintConfiguration config = new JsLintConfiguration();
            SharpLinter         lint   = new SharpLinter(config);

            config.SetOption("eqeqeq", true);
            config.SetOption("plusplus", true);

            JsLintResult result = lint.Lint(
                @"function annon() { var i, number, x; for (i = 0; i == 5; i++) { number += ++i; } }"
                );

            Assert.AreEqual(3, result.Errors.Count);

            config = new JsLintConfiguration();
            config.SetOption("unused", false);

            // should fail on ++ since "plusplus=true" -- note that we are testing with JSHINT so the
            // behavior is opposite of JSLINT for this options

            JsLintResult result2 = lint.Lint(
                @"function annon() { var i, number; for (i = 0; i === 5; i++) { number += i; } }");

            Assert.AreEqual(1, result2.Errors.Count);
        }
Beispiel #4
0
		public void TestMultipleDifferentOptions()
		{
            JsLintConfiguration config = new JsLintConfiguration();
			SharpLinter lint = new SharpLinter(config);
            
            config.SetOption("eqeqeq",true);
            config.SetOption("plusplus",true);
            
            JsLintResult result = lint.Lint(
							@"function annon() { var i, number, x; for (i = 0; i == 5; i++) { number += ++i; } }"							
                            );

			Assert.AreEqual(3, result.Errors.Count);

            config = new JsLintConfiguration();
            config.SetOption("unused", false);

            // should fail on ++ since "plusplus=true" -- note that we are testing with JSHINT so the
            // behavior is opposite of JSLINT for this options

			JsLintResult result2 = lint.Lint(
							@"function annon() { var i, number; for (i = 0; i === 5; i++) { number += i; } }");

			Assert.AreEqual(1, result2.Errors.Count);
		}
Beispiel #5
0
        public void TestArgumentParsing2()
        {
            JsLintConfiguration config = JsLintConfiguration.ParseString("  maxerr : 400,eqeqeq : true,unused :    FALSE,predef : 1 window alert,evil:true , browser : false", LinterType.JSHint);

            Assert.AreEqual(400, config.MaxErrors);
            Assert.AreEqual("maxerr: 400, eqeqeq: true, unused: false, evil: true, browser: false", config.OptionsToString());
            Assert.AreEqual(false, config.ErrorOnUnused);
            Assert.AreEqual(3, config.Globals.Count());
            Assert.AreEqual("1", config.Globals.ElementAt(0));
        }
Beispiel #6
0
        public void TestArgumentParsing()
        {
            JsLintConfiguration config = JsLintConfiguration.ParseString("  maxerr : 2,eqeqeq,unused :    TRUE,predef : test1 TEST2   3 ,evil:false , browser : true", LinterType.JSHint);

            Assert.AreEqual(2, config.MaxErrors);
            Assert.AreEqual("maxerr: 2, eqeqeq: true, unused: true, evil: false, browser: true", config.OptionsToString());
            Assert.AreEqual(true, config.ErrorOnUnused);
            Assert.AreEqual(3, config.Globals.Count());
            Assert.AreEqual("test1", config.Globals.ElementAt(0));
            Assert.AreEqual("TEST2", config.Globals.ElementAt(1));
            Assert.AreEqual("3", config.Globals.ElementAt(2));
        }
        public void ConfigFile()
        {
            string configFile = TestResources.GetAppRootedPath("resources\\jslint.test.conf");

            JsLintConfiguration config = new JsLintConfiguration();

            config.MergeOptions(configFile);

            Assert.AreEqual("maxerr: 50, browser: false, nomen: false, plusplus: false, forin: false, wsh: true, laxbreak: true", config.OptionsToString(), "Got lint options from conf file");

            Assert.AreEqual("jQuery, HTMLElement, $", config.GlobalsToString());
            Assert.AreEqual(config.ExcludeFiles.Count, 2, "Got 2 files");
            Assert.AreEqual("*.min.js", config.ExcludeFiles.ElementAt(0), "First file was right");
        }
        public void ConfigFile()
        {
            string configFile = TestResources.GetAppRootedPath("resources\\jslint.test.conf");
      
            JsLintConfiguration config = new JsLintConfiguration();

            config.MergeOptions(configFile);

            Assert.AreEqual("maxerr: 50, browser: false, nomen: false, plusplus: false, forin: false, wsh: true, laxbreak: true", config.OptionsToString(), "Got lint options from conf file");

            Assert.AreEqual("jQuery, HTMLElement, $", config.GlobalsToString());
            Assert.AreEqual(config.ExcludeFiles.Count, 2, "Got 2 files");
            Assert.AreEqual("*.min.js", config.ExcludeFiles.ElementAt(0), "First file was right");
        }
        public void ConfigFile()
        {
            string configFile = Directory.GetCurrentDirectory().BeforeIncluding("\\source\\") + "SharpLinter.Test\\jslint.test.conf";

            JsLintConfiguration config = new JsLintConfiguration();

            config.MergeOptions(configFile);

            Assert.AreEqual("browser: false, nomen: false, plusplus: false, forin: false, wsh: true, laxbreak: true", config.OptionsToString(), "Got lint options from conf file");

            Assert.AreEqual("jQuery, HTMLElement, $", config.GlobalsToString());
            Assert.AreEqual(config.ExcludeFiles.Count, 2, "Got 2 files");
            Assert.AreEqual("*.min.js", config.ExcludeFiles.ElementAt(0), "First file was right");
        }
    public override PolicyFailure[] Evaluate()
    {
        JsLintConfiguration finalConfig = new JsLintConfiguration();
        SharpLinter lint = new SharpLinter(finalConfig);
        List<JsLintData> allErrors = new List<JsLintData>();

        StringCollection policyFailureMessages = new StringCollection();

        PendingChange[] changes = PendingCheckin.PendingChanges.CheckedPendingChanges;
        foreach (PendingChange pendingChange in changes)
        {
            if ((pendingChange.ChangeType.HasFlag(ChangeType.Add) ||
                  pendingChange.ChangeType.HasFlag(ChangeType.Edit)) &&
                  pendingChange.FileName.EndsWith(".js") && !ShouldIgnore(pendingChange.LocalItem))
            {
                allErrors.AddRange(LintFile(pendingChange.LocalItem, lint));
            }
        }

        if (allErrors.Count > 0)
        {
            List<PolicyFailure> policyFailures = new List<PolicyFailure>();

            foreach (JsLintData error in allErrors)
            {
                string character = error.Character.ToString();
                character = error.Character >= 0 ? "at character " + error.Character : String.Empty;
                policyFailures.Add(new PolicyFailure(string.Format(OutputFormat, error.FilePath, error.Line, error.Source, error.Reason, character)));
                //Console.WriteLine(string.Format(OutputFormat, error.FilePath, error.Line, error.Source, error.Reason, character));
            }

            //List<PolicyFailure> policyFailures = new List<PolicyFailure>();

            //foreach (string message in policyFailureMessages)
            //{
            //    policyFailures.Add(new PolicyFailure(message, this));
            //}

            return policyFailures.ToArray();
        }
        else
        {
            return new PolicyFailure[0];
        }
    }
 public SharpLinterBatch(JsLintConfiguration configuration)
 {
     Configuration = configuration;
     OutputFormat = "{0}({1}): ({2}) {3} {4}";
 }
Beispiel #12
0
        static int Main(string[] args)
        {
           
            bool readKey = false;
            int errorCount = 0;
            try
            {
                Lazy<JsLintConfiguration> _Configuration = new Lazy<JsLintConfiguration>();
                Func<JsLintConfiguration> Configuration = () => { return _Configuration.Value; };

                if (args.Length == 0)
                {
                    Console.WriteLine("SharpLinter [-[r]f /path/*.js] [-o options] ");
                    Console.WriteLine("            [-c sharplinter.conf] [-j jslint.js] [-y]");
                    Console.WriteLine("            [-v[1|2|3]] [--noglobal]");
                    Console.WriteLine("            [-p[h] yui|packer|best mask] [-k] ");
                    Console.WriteLine("            [-i ignore-start ignore-end] [-if text] [-of \"format\"] [file]");
                    Console.WriteLine();
                    Console.WriteLine(("Options: \n\n" +
                                    "-[r]f c:\\scripts\\*.js     parse all files matching \"*.js\" in \"c:\\scripts\"\n" +
                                    "                          if called with \"r\", will recurse subfolders\n" +
                                    "-o \"option option ...\"    set jslint/jshint options specified, separated by\n" +
                                    "                          spaces, in format \"option\" or \"option: true|false\"\n" +
                                    "-v[1|2|3]                 be [terse][verbose-default][really verbose]\n" +
                                    "\n" +
                                    "-k                        Wait for a keytroke when done\n" +
                                    "-c c:\\sharplinter.conf   load config options from file specified\n" +
                                    "--noglobal                ignore global config file\n" +
                                    "-j jslint.js              use file specified to parse files instead of embedded\n" +
                                    "                          (probably old) script\n" +
                                    "-y                        Also run the script through YUI compressor to look\n" +
                                    "                          forerrors\n" +
                                    "\n" +
                                    "-i text-start text-end    Ignore blocks bounded by /*text-start*/ and\n" +
                                    "                          /*text-end*/\n" +
                                    "-if text-skip             Ignore files that contain /*text-skip*/ anywhere\n" +
                                    "-of \"output format\"       Use the string as a format for the error output. The\n" +
                                    "                          default is:\n" +
                                    "                          \"{0}({1}): ({2}) {3} at character {4}\". The parms are\n" +
                                    "                          {0}: full file path, {1}: line number, {2}: source\n" +
                                    "                          (lint or yui), {4}: character\n" +
                                    "\n" +
                                    "-p[h] yui|packer|best *.min.js      Pack/minimize valid input using YUI\n" +
                                    "                                    Compressor, Dean Edwards' JS Packer, or \n" +
                                    "                          whichever produces the smallest file. Output to a\n" +
                                    "                          file \"filename.min.js\". If validation fails, \n" +
                                    "                          the output file will be deleted (if exists)\n" +
                                    "                          to ensure no version mismatch. If  -h is specified,\n" +
                                    "                          the first comment block in the file /* ... */\n" +
                                    "                          will be passed uncompressed at the beginning of the\n" +
                                    "                          output.\n")
                                    .Replace("\n", Environment.NewLine));




                    Console.Write("Options Format:");
                    Console.WriteLine(JsLintConfiguration.GetParseOptions());

                    Console.WriteLine();
                    Console.WriteLine("E.g.");
                    Console.WriteLine("JsLint -f input.js -f input2.js");
                    Console.WriteLine("JsLint -f input.js -o \"evil=False,eqeqeq,predef=Microsoft System\"");
                    return 0;
                }

                //string commandlineConfig = String.Empty;
                string commandLineOptions = String.Empty;
                string globalConfigFile = "";
                string excludeFiles = "";
                string jsLintSource = "";

                HashSet<PathInfo> filePaths = new HashSet<PathInfo>();

 
                bool recurse = false;
                bool noGlobal = false;

                LinterType linterType = 0;

                CompressorType compressorType = 0;

                JsLintConfiguration finalConfig = new JsLintConfiguration();


                for (int i = 0; i < args.Length; i++)
                {
                    string arg = args[i].Trim().ToLower();
                    string value = args.Length > i + 1 ? args[i + 1] : String.Empty;
                    string value2 = args.Length > i + 2 ? args[i + 2] : String.Empty;
                    //string filter = null;
                    switch (arg)
                    {
                        case "-of":
                            finalConfig.OutputFormat = value.Replace("\\r", "\r").Replace("\\n", "\n");
                            i++;
                            break;
                        case "-i":
                            finalConfig.IgnoreStart = value;
                            finalConfig.IgnoreFile = value2;
                            break;
                        case "-ie":
                            finalConfig.IgnoreEnd = value;
                            break;

                        case "-p":
                        case "-ph":

                            if (!Enum.TryParse<CompressorType>(value, out compressorType))
                            {
                                Console.WriteLine(String.Format("Unknown pack option {0}", value));
                                goto exit;
                            }
                            finalConfig.MinimizeOnSuccess = true;
                            finalConfig.MinimizeFilenameMask = value2;
                            if (arg == "-ph")
                            {
                                finalConfig.MinimizeKeepHeader = true;
                            }
                            finalConfig.CompressorType = compressorType;
                            i += 2;
                            break;
                        case "-y":
                            finalConfig.YUIValidation = true;
                            break;
                        case "-c":
                            globalConfigFile = value;
                            i++;
                            break;
                        case "-j":

                            if (File.Exists(value))
                            {
                                jsLintSource = value;
                            }
                            else
                            {
                                Console.WriteLine(String.Format("Cannot find JSLint source file {0}", value));
                                goto exit;
                            }
                            i++;
                            break;
                        case "-k":
                            readKey = true;
                            break;
                        case "-f":
                        case "-rf":
                            filePaths.Add(new PathInfo(value, arg == "-rf"));
                            i++;
                            break;
                        case "-r":
                            recurse = true;
                            break;
                        case "-o":
                            commandLineOptions = commandLineOptions.AddListItem(value, " ");
                            i++;
                            break;
                        case "-x":
                            excludeFiles = excludeFiles.AddListItem(value, " ");
                            i++;
                            break;
                        case "-v":
                        case "-v1":
                        case "-v2":
                        case "-v3":
                            finalConfig.Verbosity = arg.Length == 2 ? Verbosity.Debugging :
                                (Verbosity)Convert.ToInt32(arg.Substring(2, 1));

                            break;
                        case "--noglobal":
                            noGlobal = true;
                            break;
                        default:
                            if (arg[0] == '-')
                            {
                                throw new Exception("Unrecognized command line option \"" + arg + "\"");
                            }
                            filePaths.Add(new PathInfo(arg, recurse));
                            break;
                    }
                }
                // Done parsing options.. look for linter

                string lintSourcePath = "";
                string lintSource = GetLinter(jsLintSource, out lintSourcePath);
                if (!string.IsNullOrEmpty(lintSource))
                {
                    finalConfig.JsLintCode = lintSource;
                    finalConfig.JsLintFilePath = lintSourcePath;
                }

                if (!string.IsNullOrEmpty(excludeFiles))
                {
                    foreach (string file in excludeFiles.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        finalConfig.SetFileExclude(file);
                    }
                }

                // Get global config options
                if (!noGlobal)
                {
                    string globalConfigPath;
                    string config = GetConfig(globalConfigFile, out globalConfigPath);
                    if (!string.IsNullOrEmpty(config))
                    {
                        try
                        {
                            finalConfig.MergeOptions(JsLintConfiguration.ParseConfigFile(config, linterType));
                            finalConfig.GlobalConfigFilePath = globalConfigPath;
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e.Message);
                            goto exit;
                        }
                    }
                }


                // add the basic config we built so far
                finalConfig.MergeOptions(Configuration());

                // Overlay any command line options
                if (commandLineOptions != null)
                {
                    try
                    {
                        finalConfig.MergeOptions(JsLintConfiguration.ParseString(commandLineOptions, linterType));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                        goto exit;
                    }

                }

                try
                {
                    SharpLinterBatch batch = new SharpLinterBatch(finalConfig);
                    batch.FilePaths = filePaths;
                    errorCount = batch.Process();
                }
                catch (Exception e)
                {
                    Console.WriteLine("Parser error: " + e.Message +
                        (finalConfig.Verbosity == Verbosity.Debugging ?
                            ". Stack trace (verbose mode): " + e.StackTrace :
                            ""));
                    goto exit;
                }

            }
            catch(Exception e) {
                Console.WriteLine(e.Message);

            }

            exit:
            if (readKey)
            {
                Console.ReadKey();
            }

            return errorCount == 0 ? 0 : 1;
        }
Beispiel #13
0
 public SharpLinter(JsLintConfiguration config)
 {
     Configuration = config;
     Initialize();
 }
Beispiel #14
0
 public SharpLinter(JsLintConfiguration config)
 {
     Configuration = config;
     Initialize();
 }
Beispiel #15
0
        static int Main(string[] args)
        {
            bool readKey    = false;
            int  errorCount = 0;

            try
            {
                Lazy <JsLintConfiguration> _Configuration = new Lazy <JsLintConfiguration>();
                Func <JsLintConfiguration> Configuration  = () => { return(_Configuration.Value); };

                if (args.Length == 0)
                {
                    Console.WriteLine("SharpLinter [-[r]f /path/*.js] [-o options] ");
                    Console.WriteLine("            [-c sharplinter.conf] [-j jslint.js] [-y]");
                    Console.WriteLine("            [-v[1|2|3]] [--noglobal]");
                    Console.WriteLine("            [-p[h] yui|packer|best mask] [-k] ");
                    Console.WriteLine("            [-i ignore-start ignore-end] [-if text] [-of \"format\"] [file]");
                    Console.WriteLine();
                    Console.WriteLine(("Options: \n\n" +
                                       "-[r]f c:\\scripts\\*.js     parse all files matching \"*.js\" in \"c:\\scripts\"\n" +
                                       "                          if called with \"r\", will recurse subfolders\n" +
                                       "-o \"option option ...\"    set jslint/jshint options specified, separated by\n" +
                                       "                          spaces, in format \"option\" or \"option: true|false\"\n" +
                                       "-v[1|2|3]                 be [terse][verbose-default][really verbose]\n" +
                                       "\n" +
                                       "-k                        Wait for a keytroke when done\n" +
                                       "-c c:\\sharplinter.conf   load config options from file specified\n" +
                                       "--noglobal                ignore global config file\n" +
                                       "-j jslint.js              use file specified to parse files instead of embedded\n" +
                                       "                          (probably old) script\n" +
                                       "-y                        Also run the script through YUI compressor to look\n" +
                                       "                          forerrors\n" +
                                       "\n" +
                                       "-i text-start text-end    Ignore blocks bounded by /*text-start*/ and\n" +
                                       "                          /*text-end*/\n" +
                                       "-if text-skip             Ignore files that contain /*text-skip*/ anywhere\n" +
                                       "-of \"output format\"       Use the string as a format for the error output. The\n" +
                                       "                          default is:\n" +
                                       "                          \"{0}({1}): ({2}) {3} at character {4}\". The parms are\n" +
                                       "                          {0}: full file path, {1}: line number, {2}: source\n" +
                                       "                          (lint or yui), {4}: character\n" +
                                       "\n" +
                                       "-p[h] yui|packer|best *.min.js      Pack/minimize valid input using YUI\n" +
                                       "                                    Compressor, Dean Edwards' JS Packer, or \n" +
                                       "                          whichever produces the smallest file. Output to a\n" +
                                       "                          file \"filename.min.js\". If validation fails, \n" +
                                       "                          the output file will be deleted (if exists)\n" +
                                       "                          to ensure no version mismatch. If  -h is specified,\n" +
                                       "                          the first comment block in the file /* ... */\n" +
                                       "                          will be passed uncompressed at the beginning of the\n" +
                                       "                          output.\n")
                                      .Replace("\n", Environment.NewLine));



                    Console.Write("Options Format:");
                    Console.WriteLine(JsLintConfiguration.GetParseOptions());

                    Console.WriteLine();
                    Console.WriteLine("E.g.");
                    Console.WriteLine("JsLint -f input.js -f input2.js");
                    Console.WriteLine("JsLint -f input.js -o \"evil=False,eqeqeq,predef=Microsoft System\"");
                    return(0);
                }

                //string commandlineConfig = String.Empty;
                string commandLineOptions = String.Empty;
                string globalConfigFile   = "";
                string excludeFiles       = "";
                string jsLintSource       = "";

                HashSet <PathInfo> filePaths = new HashSet <PathInfo>();


                bool recurse  = false;
                bool noGlobal = false;

                LinterType linterType = 0;

                CompressorType compressorType = 0;

                JsLintConfiguration finalConfig = new JsLintConfiguration();


                for (int i = 0; i < args.Length; i++)
                {
                    string arg    = args[i].Trim().ToLower();
                    string value  = args.Length > i + 1 ? args[i + 1] : String.Empty;
                    string value2 = args.Length > i + 2 ? args[i + 2] : String.Empty;
                    //string filter = null;
                    switch (arg)
                    {
                    case "-of":
                        finalConfig.OutputFormat = value.Replace("\\r", "\r").Replace("\\n", "\n");
                        i++;
                        break;

                    case "-i":
                        finalConfig.IgnoreStart = value;
                        finalConfig.IgnoreFile  = value2;
                        break;

                    case "-ie":
                        finalConfig.IgnoreEnd = value;
                        break;

                    case "-p":
                    case "-ph":

                        if (!Enum.TryParse <CompressorType>(value, out compressorType))
                        {
                            Console.WriteLine(String.Format("Unknown pack option {0}", value));
                            goto exit;
                        }
                        finalConfig.MinimizeOnSuccess    = true;
                        finalConfig.MinimizeFilenameMask = value2;
                        if (arg == "-ph")
                        {
                            finalConfig.MinimizeKeepHeader = true;
                        }
                        finalConfig.CompressorType = compressorType;
                        i += 2;
                        break;

                    case "-y":
                        finalConfig.YUIValidation = true;
                        break;

                    case "-c":
                        globalConfigFile = value;
                        i++;
                        break;

                    case "-j":

                        if (File.Exists(value))
                        {
                            jsLintSource = value;
                        }
                        else
                        {
                            Console.WriteLine(String.Format("Cannot find JSLint source file {0}", value));
                            goto exit;
                        }
                        i++;
                        break;

                    case "-k":
                        readKey = true;
                        break;

                    case "-f":
                    case "-rf":
                        filePaths.Add(new PathInfo(value, arg == "-rf"));
                        i++;
                        break;

                    case "-r":
                        recurse = true;
                        break;

                    case "-o":
                        commandLineOptions = commandLineOptions.AddListItem(value, " ");
                        i++;
                        break;

                    case "-x":
                        excludeFiles = excludeFiles.AddListItem(value, " ");
                        i++;
                        break;

                    case "-v":
                    case "-v1":
                    case "-v2":
                    case "-v3":
                        finalConfig.Verbosity = arg.Length == 2 ? Verbosity.Debugging :
                                                (Verbosity)Convert.ToInt32(arg.Substring(2, 1));

                        break;

                    case "--noglobal":
                        noGlobal = true;
                        break;

                    default:
                        if (arg[0] == '-')
                        {
                            throw new Exception("Unrecognized command line option \"" + arg + "\"");
                        }
                        filePaths.Add(new PathInfo(arg, recurse));
                        break;
                    }
                }
                // Done parsing options.. look for linter

                string lintSourcePath = "";
                string lintSource     = GetLinter(jsLintSource, out lintSourcePath);
                if (!string.IsNullOrEmpty(lintSource))
                {
                    finalConfig.JsLintCode     = lintSource;
                    finalConfig.JsLintFilePath = lintSourcePath;
                }

                if (!string.IsNullOrEmpty(excludeFiles))
                {
                    foreach (string file in excludeFiles.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        finalConfig.SetFileExclude(file);
                    }
                }

                // Get global config options
                if (!noGlobal)
                {
                    string globalConfigPath;
                    string config = GetConfig(globalConfigFile, out globalConfigPath);
                    if (!string.IsNullOrEmpty(config))
                    {
                        try
                        {
                            finalConfig.MergeOptions(JsLintConfiguration.ParseConfigFile(config, linterType));
                            finalConfig.GlobalConfigFilePath = globalConfigPath;
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e.Message);
                            goto exit;
                        }
                    }
                }


                // add the basic config we built so far
                finalConfig.MergeOptions(Configuration());

                // Overlay any command line options
                if (commandLineOptions != null)
                {
                    try
                    {
                        finalConfig.MergeOptions(JsLintConfiguration.ParseString(commandLineOptions, linterType));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                        goto exit;
                    }
                }

                try
                {
                    SharpLinterBatch batch = new SharpLinterBatch(finalConfig);
                    batch.FilePaths = filePaths;
                    errorCount      = batch.Process();
                }
                catch (Exception e)
                {
                    Console.WriteLine("Parser error: " + e.Message +
                                      (finalConfig.Verbosity == Verbosity.Debugging ?
                                       ". Stack trace (verbose mode): " + e.StackTrace :
                                       ""));
                    goto exit;
                }
            }
            catch (Exception e) {
                Console.WriteLine(e.Message);
            }

exit:
            if (readKey)
            {
                Console.ReadKey();
            }

            return(errorCount == 0 ? 0 : 1);
        }
Beispiel #16
0
        static void Main(string[] args)
        {
            Lazy<JsLintConfiguration> _Configuration = new Lazy<JsLintConfiguration>();
            Func<JsLintConfiguration> Configuration = () => { return _Configuration.Value; };

            if (args.Length == 0)
            {
                Console.WriteLine("SharpLinter [-[r]f /path/*.js] [-o options] [-v] ");
                Console.WriteLine("            [-c sharplinter.conf] [-j jslint.js] [-y]");
                Console.WriteLine("            [-p[h] yui|packer|best mask] [-k] ");
                Console.WriteLine("            [-i ignore-start ignore-end] [-if text] [-of \"format\"]");
                Console.WriteLine();
                Console.WriteLine(("Options: \n\n" +
                                "-[r]f c:\\scripts\\*.js     parse all files matching \"*.js\" in \"c:\\scripts\"\n" +
                                "                          if called with \"r\", will recurse subfolders\n" +
                                "-o \"option option ...\"    set jslint/jshint options specified, separated by\n"+
                                "                          spaces, in format \"option\" or \"option: true|false\"\n" +
                                "-v                        be verbose (report information other than errors)\n" +
                                "\n" +
                                "-k                        Wait for a keytroke when done\n" +
                                "-c c:\\sharplinter.conf    load config options from file specified\n" +
                                "-j jslint.js              use file specified to parse files instead of embedded\n"+
                                "                          (probably old) script\n" +
                                "-y                        Also run the script through YUI compressor to look\n"+
                                "                          forerrors\n" +
                                "\n"+
                                "-i text-start text-end    Ignore blocks bounded by /*text-start*/ and\n"+
                                "                          /*text-end*/\n" +
                                "-if text-skip             Ignore files that contain /*text-skip*/ anywhere\n" +
                                "-of \"output format\"       Use the string as a format for the error output. The\n"+
                                "                          default is:\n" +
                                "                          \"{0}({1}): ({2}) {3} at character {4}\". The parms are\n" +
                                "                          {0}: full file path, {1}: line number, {2}: source\n" +
                                "                          (lint or yui), {4}: character\n" +
                                "\n" +
                                "-p[h] yui|packer|best *.min.js      Pack/minimize valid input using YUI\n"+
                                "                                    Compressor, Dean Edwards' JS Packer, or \n" +
                                "                          whichever produces the smallest file. Output to a\n" +
                                "                          file \"filename.min.js\". If validation fails, \n" +
                                "                          the output file will be deleted (if exists)\n" +
                                "                          to ensure no version mismatch. If  -h is specified,\n" +
                                "                          the first comment block in the file /* ... */\n" +
                                "                          will be passed uncompressed at the beginning of the\n"+
                                "                          output.\n")
                                .Replace("\n", Environment.NewLine));

                Console.Write("Options Format:");
                Console.WriteLine(JsLintConfiguration.GetParseOptions());

                Console.WriteLine();
                Console.WriteLine("E.g.");
                Console.WriteLine("JsLint -f input.js -f input2.js");
                Console.WriteLine("JsLint -f input.js -o \"evil=False,eqeqeq,predef=Microsoft System\"");
                return;
            }

            //string commandlineConfig = String.Empty;
            string commandLineOptions = String.Empty;
            string globalConfigFile = "sharplinter.conf";
            string defaultGlobalConfigFile = globalConfigFile;
            string excludeFiles = String.Empty;
            string jsLintSource = "jslint.js";
            string defaultJsLintSource = jsLintSource;

            HashSet<PathInfo> filePaths = new HashSet<PathInfo>();

            bool readKey = false;
            bool recurse  = false;

            LinterType linterType = 0;

            CompressorType compressorType = 0;

            JsLintConfiguration finalConfig = new JsLintConfiguration();

            for (int i = 0; i < args.Length; i++ )
            {
                string arg = args[i].Trim().ToLower();
                string value = args.Length > i+1 ? args[i + 1] : String.Empty;
                string value2 = args.Length > i+2 ? args[i + 2] : String.Empty;
                //string filter = null;
                switch (arg)
                {
                    case "-of":
                        finalConfig.OutputFormat = value.Replace("\\r", "\r").Replace("\\n", "\n");
                        break;
                    case "-i":
                        finalConfig.IgnoreStart = value;
                        finalConfig.IgnoreFile = value2;
                        break;
                    case "-ie":
                        finalConfig.IgnoreEnd = value;
                        break;
                    case "-p":
                    case "-ph":

                        if (!Enum.TryParse<CompressorType>(value, out compressorType))
                        {
                            Console.WriteLine(String.Format("Unknown pack option {0}", value));
                            goto exit;
                        }
                        finalConfig.MinimizeOnSuccess = true;
                        finalConfig.MinimizeFilenameMask = value2;
                        if (arg=="-ph") {
                            finalConfig.MinimizeKeepHeader = true;
                        }
                        finalConfig.CompressorType = compressorType;
                        i+=2;
                        break;
                    case "-y":
                        finalConfig.YUIValidation = true;
                        break;
                    case "-c":
                        globalConfigFile = value;
                        i++;
                        break;
                    case "-j":

                        if (File.Exists(value)) {
                            jsLintSource = value;
                        } else {
                            Console.WriteLine(String.Format("Cannot find JSLint source file {0}",value));
                            goto exit;
                        }
                        i++;
                        break;
                    case "-k":
                        readKey = true;
                        break;
                    case "-f":
                    case "-rf":
                        filePaths.Add(new PathInfo(value, arg == "-rf"));
                        i++;
                        break;
                    case "-r":
                        recurse = true;
                        break;
                    case "-o":
                        commandLineOptions = commandLineOptions.AddListItem(value, " ");
                        i++;
                        break;
                    case "-x":
                       excludeFiles = excludeFiles.AddListItem(value," ");
                        i++;
                        break;
                    case "-v":
                        finalConfig.Verbose = true;
                        break;
                    default:
                        if (arg[0] == '-')
                        {
                            throw new Exception("Unrecognized command line option \"" + arg + "\"");
                        }
                        filePaths.Add(new PathInfo(arg, recurse));
                        break;
                }
            }
            // Done parsing options

            if (!String.IsNullOrEmpty(jsLintSource))
            {

                jsLintSource = Utility.ResolveRelativePath_AppRoot(jsLintSource);
                if (File.Exists(jsLintSource))
                {
                    try
                    {
                        finalConfig.JsLintCode = File.ReadAllText(jsLintSource);
                    }
                    catch
                    {
                        Console.WriteLine(String.Format("The JSLINT/JSHINT file \"{0}\" appears to be invalid.", jsLintSource));
                        goto exit;
                    }
                }
                else
                {
                    if (jsLintSource != defaultJsLintSource)
                    {
                        Console.WriteLine(String.Format("The JSLINT/JSHINT file \"{0}\" does not exist.", jsLintSource));
                        goto exit;
                    }
                }
            }
            else
            {
                // See if there's a default linter

                string defaultLint = Path.GetDirectoryName(Assembly.GetAssembly(typeof(JTC.SharpLinter.SharpLinterExe)).Location) + "\\jslint.js";

                if (File.Exists(defaultLint))
                {
                    finalConfig.JsLintCode = File.ReadAllText(defaultLint);
                }
            }

            if (!string.IsNullOrEmpty(excludeFiles))
            {
                foreach (string file in excludeFiles.Split(new char[] {' '},StringSplitOptions.RemoveEmptyEntries))
                {
                    finalConfig.SetFileExclude(file);
                }

            }
            // Get global config first.
            if (!String.IsNullOrEmpty(globalConfigFile))
            {
                globalConfigFile = Utility.ResolveRelativePath_AppRoot(globalConfigFile);
                if (File.Exists(globalConfigFile))
                {
                    try
                    {
                        finalConfig.MergeOptions(JsLintConfiguration.ParseConfigFile(File.ReadAllText(globalConfigFile), linterType));
                        finalConfig.GlobalConfigFile = globalConfigFile;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                        goto exit;
                    }
                }
                else
                {
                    if (globalConfigFile != defaultGlobalConfigFile)
                    {
                        Console.WriteLine(String.Format("Cannot find global configuration file {0}", globalConfigFile));
                        goto exit;
                    }
                }
            }

            // add the basic config we built so far
            finalConfig.MergeOptions(Configuration());

            // Overlay any command line options
            if (commandLineOptions != null)
            {
                try
                {
                   finalConfig.MergeOptions(JsLintConfiguration.ParseString(commandLineOptions, linterType));
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    goto exit;
                }

            }

            try
            {
                SharpLinterBatch batch = new SharpLinterBatch(finalConfig);
                batch.FilePaths = filePaths;
                batch.Process();
            }
            catch(Exception e)
            {
                Console.WriteLine("Everything was looking good on your command line, but the parser threw an error: "+ e.Message +" , " + e.StackTrace );
                goto exit;
            }

            exit:
            if (readKey)
            {
                Console.ReadKey();
            }
        }