/// <summary> /// Creates an instance of the AnalysisService class. /// </summary> /// <param name="consoleHost">An object that implements IConsoleHost in which to write errors/warnings /// from analyzer.</param> /// <param name="settingsPath">Path to a PSScriptAnalyzer settings file.</param> public AnalysisService(IConsoleHost consoleHost, string settingsPath = null) { try { // Attempt to create a ScriptAnalyzer instance first // just in case the assembly can't be found and we // can skip creating an extra runspace. this.scriptAnalyzer = new ScriptAnalyzer(); this.analysisRunspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault2()); this.analysisRunspace.ApartmentState = ApartmentState.STA; this.analysisRunspace.ThreadOptions = PSThreadOptions.ReuseThread; this.analysisRunspace.Open(); this.scriptAnalyzer.Initialize( this.analysisRunspace, new AnalysisOutputWriter(consoleHost), includeRuleNames: settingsPath == null ? IncludedRules : null, includeDefaultRules: true, profile: settingsPath); } catch (FileNotFoundException) { Logger.Write( LogLevel.Warning, "Script Analyzer binaries not found, AnalysisService will be disabled."); } }
public ScriptRunnerFixture(string fileName = "/Working/build.cake") { Script = fileName; Source = "Hello World"; AssemblyLoader = Substitute.For <IAssemblyLoader>(); Environment = FakeEnvironment.CreateUnixEnvironment(); FileSystem = new FakeFileSystem(Environment); FileSystem.CreateFile(Script.MakeAbsolute(Environment)).SetContent(Source); Globber = Substitute.For <IGlobber>(); Configuration = Substitute.For <ICakeConfiguration>(); AliasFinder = Substitute.For <IScriptAliasFinder>(); Log = Substitute.For <ICakeLog>(); Session = Substitute.For <IScriptSession>(); ArgumentDictionary = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase); Engine = Substitute.For <IScriptEngine>(); Engine.CreateSession(Arg.Any <IScriptHost>(), ArgumentDictionary).Returns(Session); ScriptAnalyzer = new ScriptAnalyzer(FileSystem, Environment, Log, new[] { new FileLoadDirectiveProvider() }); ScriptProcessor = Substitute.For <IScriptProcessor>(); ScriptConventions = new ScriptConventions(FileSystem, AssemblyLoader, Log); var context = Substitute.For <ICakeContext>(); context.Environment.Returns(c => Environment); context.FileSystem.Returns(c => FileSystem); Host = Substitute.For <IScriptHost>(); Host.Context.Returns(context); }
public void TestAnalyzeClass() { string code1 = @"class TestClass { public void TestMethod( int test = 0; test = 1;){}}"; SyntaxTree tree1 = CSharpSyntaxTree.ParseText(code1); ClassDeclarationSyntax classNode = tree1.GetRootAsync().Result.DescendantNodes().OfType <ClassDeclarationSyntax>().First(); List <SyntaxTree> trees1 = new List <SyntaxTree> { tree1 }; Compilation comp1 = CSharpCompilation.Create("TestCompilation1", trees1); ScriptAnalyzer analyzer = this.createAnalyzer(comp1); TaggedSyntaxLibrary lib = analyzer.AnalyzeNode(classNode); Assert.IsNotNull(lib, "Library defined"); Assert.AreEqual(1, lib.TaggedSyntaxTrees.Count(), "Has one tree"); TaggedSyntaxTree tree = lib.TaggedSyntaxTrees.First(); CollectionAssert.Contains(tree.TaggedNodes, classNode, "Tree contains class node"); IEnumerable <SyntaxNode> nodes = classNode.DescendantNodes(); foreach (SyntaxNode node in nodes) { CollectionAssert.DoesNotContain(tree.TaggedNodes, node, "SubNode is not added to tree"); } }
public void TestAnalyzeForEach() { string code1 = @"class MainClass {public int MainMethod(){ TestClass[] testClasses = new TestClass[] { new TestClass(1), new TestClass(2) };int count = 0; foreach (TestClass testclass in testClasses){count += testclass.GetInt()} return count;}};}"; string code2 = @"class TestClass{ int counter; public TestClass(int param}{this.counter = param} public int GetInt(){return this.counter}"; SyntaxTree tree1 = CSharpSyntaxTree.ParseText(code1); SyntaxTree tree2 = CSharpSyntaxTree.ParseText(code2); ForEachStatementSyntax forEachNode = tree1.GetRootAsync().Result.DescendantNodes().OfType <ForEachStatementSyntax>().First(); List <SyntaxTree> trees1 = new List <SyntaxTree> { tree1, tree2 }; Compilation comp1 = CSharpCompilation.Create("TestCompilation1", trees1); ScriptAnalyzer analyzer = this.createAnalyzer(comp1); TaggedSyntaxLibrary lib = analyzer.AnalyzeNode(forEachNode); //Assert.IsNotNull(lib, "Library defined"); //Assert.AreEqual(1, lib.TaggedSyntaxTrees.Count(), "Has one tree"); //TaggedSyntaxTree tree = lib.TaggedSyntaxTrees.First(); //CollectionAssert.Contains(tree.TaggedNodes, varDeclartionNode, "Tree contains variable declaration node"); //IEnumerable<SyntaxNode> nodes = varDeclartionNode.DescendantNodes(); //foreach (SyntaxNode node in nodes) //{ // CollectionAssert.Contains(tree.TaggedNodes, node, "SubNode is added to tree: " + node.ToString()); //} }
public void TestAnalyzeOverrideMethodFromVirtual() { string code1 = @"class TestClass { public void MainMethod(){ SubClass test = new SubClass(); test.TestMethod();}}"; string code2 = @"class SuperClass { public void TestMethod(){this.TestMethod2();} public virtual void TestMethod2(){}}"; string code3 = @"class SubClass:SuperClass { public override void TestMethod2(){}}"; SyntaxTree tree1 = CSharpSyntaxTree.ParseText(code1); SyntaxTree tree2 = CSharpSyntaxTree.ParseText(code2); SyntaxTree tree3 = CSharpSyntaxTree.ParseText(code3); MethodDeclarationSyntax mainNode = tree1.GetRootAsync().Result.DescendantNodes().OfType <MethodDeclarationSyntax>().First(); MethodDeclarationSyntax superNode1 = tree2.GetRootAsync().Result.DescendantNodes().OfType <MethodDeclarationSyntax>().First(); MethodDeclarationSyntax superNode2 = tree2.GetRootAsync().Result.DescendantNodes().OfType <MethodDeclarationSyntax>().Last(); MethodDeclarationSyntax subNode = tree3.GetRootAsync().Result.DescendantNodes().OfType <MethodDeclarationSyntax>().First(); List <SyntaxTree> trees1 = new List <SyntaxTree> { tree1, tree2, tree3 }; Compilation comp1 = CSharpCompilation.Create("TestCompilation1", trees1); ScriptAnalyzer analyzer = this.createAnalyzer(comp1); TaggedSyntaxLibrary lib = analyzer.AnalyzeNode(mainNode); Assert.IsNotNull(lib, "Library defined"); Assert.AreEqual(3, lib.TaggedSyntaxTrees.Count(), "Has three trees"); TaggedSyntaxTree rTree1 = lib.TaggedSyntaxTrees.First(); TaggedSyntaxTree rTree2 = lib.TaggedSyntaxTrees.ElementAt(1); TaggedSyntaxTree rTree3 = lib.TaggedSyntaxTrees.ElementAt(2); CollectionAssert.Contains(rTree1.TaggedNodes, mainNode, "Main tree contains main method"); CollectionAssert.Contains(rTree3.TaggedNodes, superNode1, "Super tree contains first method"); CollectionAssert.Contains(rTree3.TaggedNodes, superNode2, "Super tree contains first method"); CollectionAssert.Contains(rTree2.TaggedNodes, subNode, "Sub tree contains sub method"); }
public void Test_Analyze() { var httpClientMock = new Mock<IHttpClient>(); httpClientMock.Setup(it => it.DownloadString(It.IsAny<string>())) .Returns<string>((url) => { return "script"; }); var siteFileProviderMock = new Mock<ISiteFileProvider>(); Dictionary<string, string> styles = new Dictionary<string, string>(); siteFileProviderMock.Setup(it => it.AddFile(It.IsAny<Site>(), It.IsAny<string>(), It.IsAny<string>())) .Callback<Site, string, string>((site1, path, content) => { styles.Add(path, content); }); var scriptAnalyzer = new ScriptAnalyzer(httpClientMock.Object, siteFileProviderMock.Object); var pageHtml = @"<html> <head> <script src=""/script1.js"" type=""text/javascript""></script> <script src=""/script2.js"" type=""text/javascript""></script> </head> <body> </body> </html>"; SiteDownloadContext siteDownloadContext = new SiteDownloadContext(null, new DownloadOptions() { SiteName = "Test_Analyze", Url = "localhost", Pages = 20, Deep = 1 }, null, null); PageDownloadContext pageDownloadContext = new PageDownloadContext(siteDownloadContext, new PageLevel("http://localhost", 1), pageHtml); scriptAnalyzer.Analyze(pageDownloadContext); Assert.AreEqual(2, styles.Count()); Assert.AreEqual("script", styles["\\Scripts\\script1.js"]);
private ScriptAnalyzer createAnalyzer(Compilation[] comps) { ScriptAnalyzerSymbolHelper sHelper = new ScriptAnalyzerSymbolHelper(comps); ScriptAnalyzerResourceHelper rHelper = new ScriptAnalyzerResourceHelper(sHelper); ScriptAnalyzer analyzer = new ScriptAnalyzer(rHelper); return(analyzer); }
public void TestConstructor() { Compilation comp = CSharpCompilation.Create("test"); ScriptAnalyzerSymbolHelper sHelper = new ScriptAnalyzerSymbolHelper(new Compilation[] { comp }); ScriptAnalyzerResourceHelper rHelper = new ScriptAnalyzerResourceHelper(sHelper); ScriptAnalyzer analyzer = new ScriptAnalyzer(rHelper); Assert.AreEqual(rHelper, analyzer.ResourceHelper, "Resource helper gest set"); }
public Dictionary <string, AnalyzedQuery> Visit(string script) { var patternInterpreterLexer = new PageInterpreterLexer(new AntlrInputStream(script)); var patternInterpreterParser = new PageInterpreterParser(new CommonTokenStream(patternInterpreterLexer)); patternInterpreterParser.AddErrorListener(new ErrorListener()); var visitor = new ScriptAnalyzer(); visitor.Visit(patternInterpreterParser.compileUnit()); return(visitor.ResultCountByQuery); }
/// <summary> /// Creates an instance of the AnalysisService class. /// </summary> public AnalysisService() { this.analysisRunspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault2()); this.analysisRunspace.ApartmentState = ApartmentState.STA; this.analysisRunspace.ThreadOptions = PSThreadOptions.ReuseThread; this.analysisRunspace.Open(); this.scriptAnalyzer = new ScriptAnalyzer(); this.scriptAnalyzer.Initialize( this.analysisRunspace, new AnalysisOutputWriter(), null, IncludedRules); }
/// <summary> /// Creates an instance of the AnalysisService class. /// </summary> public AnalysisService() { // TODO: Share runspace with PowerShellContext? Probably should always // run analysis in a local session. this.analysisRunspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault2()); this.analysisRunspace.ApartmentState = ApartmentState.STA; this.analysisRunspace.ThreadOptions = PSThreadOptions.ReuseThread; this.analysisRunspace.Open(); this.scriptAnalyzer = new ScriptAnalyzer(); this.scriptAnalyzer.Initialize( this.analysisRunspace, new AnalysisOutputWriter(), null, null, new string[] { "DscTestsPresent", "DscExamplesPresent" }); }
public void Test_Analyze() { var httpClientMock = new Mock <IHttpClient>(); httpClientMock.Setup(it => it.DownloadString(It.IsAny <string>())) .Returns <string>((url) => { return("script"); }); var siteFileProviderMock = new Mock <ISiteFileProvider>(); Dictionary <string, string> styles = new Dictionary <string, string>(); siteFileProviderMock.Setup(it => it.AddFile(It.IsAny <Site>(), It.IsAny <string>(), It.IsAny <string>())) .Callback <Site, string, string>((site1, path, content) => { styles.Add(path, content); }); var scriptAnalyzer = new ScriptAnalyzer(httpClientMock.Object, siteFileProviderMock.Object); var pageHtml = @"<html> <head> <script src=""/script1.js"" type=""text/javascript""></script> <script src=""/script2.js"" type=""text/javascript""></script> </head> <body> </body> </html>"; SiteDownloadContext siteDownloadContext = new SiteDownloadContext(null, new DownloadOptions() { SiteName = "Test_Analyze", Url = "localhost", Pages = 20, Deep = 1 }, null, null); PageDownloadContext pageDownloadContext = new PageDownloadContext(siteDownloadContext, new PageLevel("http://localhost", 1), pageHtml); scriptAnalyzer.Analyze(pageDownloadContext); Assert.AreEqual(2, styles.Count()); Assert.AreEqual("script", styles["\\Scripts\\script1.js"]); Assert.AreEqual("script", styles["\\Scripts\\script2.js"]); }
///--------------------------------------------------------------------- protected override BuildResult DoApplyValidTemplate(ref FileData fileData) { Profiler.BeginSample($"DoApplyValidTemplate()"); if (fileData.source.extension != Glossary.importExtension) { Profiler.EndSample(); return(BuildResult.ValueType.Success | BuildResult.ValueType.Ignored); } var registry = new PrateekScriptSymbolRegistry(); var analyzer = new ScriptAnalyzer(registry); var activeCodeFile = (CodeFile)null; var activeScope = string.Empty; var codeFiles = new List <CodeFile>(); var codeDepth = 0; var args = new List <string>(); analyzer.Init(fileData.source.content); { analyzer.FindAllSymbols(); analyzer.BuildCodeCommands(); return(BuildResult.ValueType.LoadingFailed); var rootScope = analyzer.ContentRootScope; foreach (var codeCommand in rootScope.innerCommands) { Profiler.BeginSample($"foreach (var codeCommand in rootScope.commands)"); if (!(codeCommand is CodeKeyword codeKeyword)) { Profiler.EndSample(); continue; } var codeFile = RetrieveCodeFile(codeKeyword, codeFiles); if (codeFile == null) { Profiler.EndSample(); continue; } var result = FeedCodeFile(ref fileData, codeFile, codeKeyword, string.Empty); Profiler.EndSample(); if (!result) { return(Error(result, ref fileData)); } } //return BuildResult.ValueType.LoadingFailed; } //code files have been filled for (var f = 0; f < codeFiles.Count; f++) { var codeFile = codeFiles[f]; Profiler.BeginSample($"for (var f = 0; f < codeFiles.Count; f++)"); //{ // Log shit // var log = String.Format("FOUND: {0}.{1}\n", codeFile.fileName, codeFile.fileExtension); // for (int d = 0; d < codeFile.DataCount; d++) // { // var codeData = codeFile[d]; // for (int i = 0; i < codeData.classInfos.Count; i++) // { // var info = codeData.classInfos[i]; // log += String.Format(" - CLASS: {0} ", info.name); // for (int v = 0; v < info.variables.Count; v++) // { // log += " " + info.variables[v]; // } // log += "\n"; // } // log += String.Format(" - TYPE: {0} = {1}\n", codeData.classContentType, codeData.classContentValue); // log += String.Format(" - CODE PREFIX:\n > {0}\n", codeData.codePrefix.Replace("\n", "\n> ")); // log += String.Format(" - CODE MAIN:\n > {0}\n", codeData.codeMain.Replace("\n", "\n> ")); // log += String.Format(" - CODE POSTFIX:\n > {0}\n", codeData.codePostfix.Replace("\n", "\n> ")); // } // UnityEngine.Debug.Log(log); //} var newData = fileData; newData.destination.name = codeFile.fileName.Extension(newData.source.extension); newData.destination.extension = codeFile.fileExtension; newData.source.extension = newData.source.extension.Extension(codeFile.fileExtension); var applyResult = base.DoApplyValidTemplate(ref newData); if (applyResult.Is(BuildResult.ValueType.NoMatchingTemplate)) { Profiler.EndSample(); Profiler.EndSample(); return(Error(applyResult, ref newData)); } var genStart = Glossary.Macros.scriptStartTag; var genStartIndex = newData.destination.content.IndexOf(genStart); if (genStartIndex < 0) { Profiler.EndSample(); Profiler.EndSample(); return(Error(BuildResult.ValueType.PrateekScriptSourceStartTagInvalid, ref newData)); } var genHeader = newData.destination.content.Substring(0, genStartIndex); var genCode = newData.destination.content.Substring(genStartIndex + genStart.Length); // Build the actual code var result = codeFile.Generate(genHeader, genCode); if (!result) { Profiler.EndSample(); Profiler.EndSample(); return(Error(result, ref newData)); } foreach (var codeGenerated in codeFile.CodeGenerated) { Profiler.BeginSample($"foreach (var codeGenerated in codeFile.CodeGenerated)"); var workData = newData; if (!string.IsNullOrEmpty(codeGenerated.className)) { workData.destination.name = codeGenerated.className + workData.destination.name; } workData.destination.content = codeGenerated.code; workData.destination.SetupFileInfo(); AddWorkFile(workData); Profiler.EndSample(); } //{ // Log shit // for (int i = 0; i < codeFile.DataCount; i++) // { // var code = codeFile[i]; // UnityEngine.Debug.Log(code.codeGenerated); // } // UnityEngine.Debug.Log(codeFile.CodeGenerated); //} Profiler.EndSample(); } Profiler.EndSample(); return(BuildResult.ValueType.Ignored); }