public bool Process(AnalyserResult analyserResult, string line, int lineIndex)
        {
            if (!line.TrimStart().StartsWith("//#nuget", StringComparison.OrdinalIgnoreCase))
            {
                return(false);
            }

            int nugetIndex = line.IndexOf(" ", StringComparison.Ordinal);

            if (nugetIndex < 0)
            {
                return(true);
            }

            string nugetPackage = line.Substring(nugetIndex);

            var nugetInfos = nugetPackage.Split(',');

            if (nugetInfos.Length != 2)
            {
                throw new ScriptException("Invalid nuget package directive. Example of valid directive: '//#nuget: FlubuCore, 2.8.0'");
            }

            analyserResult.NugetPackages.Add(new NugetPackageReference {
                Id = nugetInfos[0].Trim(), Version = nugetInfos[1].Trim()
            });
            return(true);
        }
Exemplo n.º 2
0
        private void AddOtherCsFilesToBuildScriptCode(AnalyserResult analyserResult, List <string> assemblyReferenceLocations, List <string> code)
        {
            foreach (var file in analyserResult.CsFiles)
            {
                if (_file.Exists(file))
                {
                    _log.LogInformation($"File found: {file}");
                    List <string> additionalCode = _file.ReadAllLines(file);

                    AnalyserResult additionalCodeAnalyserResult = _analyser.Analyze(additionalCode);
                    if (additionalCodeAnalyserResult.CsFiles.Count > 0)
                    {
                        throw new NotSupportedException("//#imp is only supported in main buildscript .cs file.");
                    }

                    var usings = additionalCode.Where(x => x.StartsWith("using"));

                    assemblyReferenceLocations.AddRange(additionalCodeAnalyserResult.References);
                    code.InsertRange(1, usings);
                    code.AddRange(additionalCode.Where(x => !x.StartsWith("using")));
                }
                else
                {
                    _log.LogInformation($"File was not found: {file}");
                }
            }
        }
Exemplo n.º 3
0
        public bool Process(AnalyserResult analyserResult, string line, int lineIndex)
        {
            if (!line.TrimStart().StartsWith("//#ass", StringComparison.OrdinalIgnoreCase))
            {
                return(false);
            }

            int dllIndex = line.IndexOf(" ", StringComparison.Ordinal);

            if (dllIndex < 0)
            {
                return(true);
            }

            string dll       = line.Substring(dllIndex);
            string pathToDll = Path.GetFullPath(dll.Trim());
            string extension = _pathWrapper.GetExtension(pathToDll);

            if (!extension.Equals(".dll", StringComparison.OrdinalIgnoreCase))
            {
                if (!extension.Equals(".exe", StringComparison.OrdinalIgnoreCase))
                {
                    throw new ScriptException($"File doesn't have dll extension. {pathToDll}");
                }
            }

            if (!_file.Exists(pathToDll))
            {
                throw new ScriptException($"Assembly not found at location: {pathToDll}");
            }

            analyserResult.References.Add(pathToDll);
            return(true);
        }
Exemplo n.º 4
0
        public async Task <IBuildScript> FindAndCreateBuildScriptInstanceAsync(CommandArguments args)
        {
            string buildScriptFilePath     = _buildScriptLocator.FindBuildScript(args);
            var    buildScriptAssemblyPath = Path.Combine("bin", Path.GetFileName(buildScriptFilePath));

            buildScriptAssemblyPath = Path.ChangeExtension(buildScriptAssemblyPath, "dll");

            List <string>  code           = _file.ReadAllLines(buildScriptFilePath);
            AnalyserResult analyserResult = _analyser.Analyze(code);
            bool           oldWay         = false;

#if NET462
            oldWay = true;
#endif
            var references = GetBuildScriptReferences(args, analyserResult, code, oldWay, buildScriptFilePath);

            if (oldWay)
            {
                return(await CreateBuildScriptInstanceOldWay(buildScriptFilePath, references, code, analyserResult));
            }

            var assembly = TryLoadBuildScriptFromAssembly(buildScriptAssemblyPath, buildScriptFilePath);

            if (assembly != null)
            {
                return(CreateBuildScriptInstance(assembly, buildScriptFilePath));
            }

            code.Insert(0, $"#line 1 \"{buildScriptFilePath}\"");
            assembly = CompileBuildScriptToAssembly(buildScriptAssemblyPath, buildScriptFilePath, references, string.Join("\r\n", code));
            return(CreateBuildScriptInstance(assembly, buildScriptFilePath));
        }
Exemplo n.º 5
0
        public void GetClassNameFromBuildScriptCodeTest(string code, string expectedClassName)
        {
            ClassDirectiveProcessor pr  = new ClassDirectiveProcessor();
            AnalyserResult          res = new AnalyserResult();

            pr.Process(res, code, 1);
            Assert.Equal(expectedClassName, res.ClassName);
        }
Exemplo n.º 6
0
        public void ParseDll(string line, string expected)
        {
            AssemblyDirectiveProcessor pr  = new AssemblyDirectiveProcessor();
            AnalyserResult             res = new AnalyserResult();

            pr.Process(res, line, 1);
            Assert.Equal(expected, res.References.First());
        }
Exemplo n.º 7
0
        public void ParseCs(string line, string expected)
        {
            CsDirectiveProcessor pr  = new CsDirectiveProcessor();
            AnalyserResult       res = new AnalyserResult();

            pr.Process(res, line, 1);
            Assert.Equal(expected, res.CsFiles.First());
        }
Exemplo n.º 8
0
        public void NugetRefrence(string line, string expectedId, string expectedVersion)
        {
            NugetPackageDirectirveProcessor pr = new NugetPackageDirectirveProcessor();
            AnalyserResult res = new AnalyserResult();

            pr.Process(res, line, 1);
            Assert.Equal(expectedId, res.NugetPackages.First().Id);
            Assert.Equal(expectedVersion, res.NugetPackages.First().Version);
        }
        public bool Process(AnalyserResult analyserResult, string line, int lineIndex)
        {
            if (line.TrimStart().StartsWith("namespace"))
            {
                analyserResult.NamespaceIndex = lineIndex;
                return(false);
            }

            return(false);
        }
Exemplo n.º 10
0
        public void ParseDll(string line, string expected)
        {
            AssemblyDirectiveProcessor pr = new AssemblyDirectiveProcessor(_fileWrapper.Object, _pathWrapper.Object);

            _pathWrapper.Setup(x => x.GetExtension(expected)).Returns(".dll");
            _fileWrapper.Setup(x => x.Exists(expected)).Returns(true);
            AnalyserResult res = new AnalyserResult();

            pr.Process(res, line, 1);
            Assert.Equal(expected, res.References.First());
        }
Exemplo n.º 11
0
        private IEnumerable <MetadataReference> GetBuildScriptReferences(CommandArguments args,
                                                                         AnalyserResult analyserResult, List <string> code, bool oldWay, string pathToBuildScript)
        {
            var coreDir           = Path.GetDirectoryName(typeof(object).GetTypeInfo().Assembly.Location);
            var flubuCoreAssembly = typeof(DefaultBuildScript).GetTypeInfo().Assembly;
            var flubuPath         = flubuCoreAssembly.Location;

            //// Default assemblies that should be referenced.
            var assemblyReferenceLocations = oldWay
                ? GetBuildScriptReferencesForOldWayBuildScriptCreation()
                : GetDefaultReferences(coreDir, flubuPath);

            // Enumerate all assemblies referenced by FlubuCore
            // and provide them as references to the build script we're about to
            // compile.
            AssemblyName[] referencedAssemblies = flubuCoreAssembly.GetReferencedAssemblies();
            foreach (var referencedAssembly in referencedAssemblies)
            {
                Assembly loadedAssembly = Assembly.Load(referencedAssembly);
                if (string.IsNullOrEmpty(loadedAssembly.Location))
                {
                    continue;
                }

                assemblyReferenceLocations.Add(loadedAssembly.Location);
            }

            assemblyReferenceLocations.AddRange(analyserResult.References);
            assemblyReferenceLocations.AddRange(
                _nugetPackageResolver.ResolveNugetPackages(analyserResult.NugetPackages, pathToBuildScript));
            AddOtherCsFilesToBuildScriptCode(analyserResult, assemblyReferenceLocations, code);
            assemblyReferenceLocations.AddRange(FindAssemblyReferencesInDirectories(args.AssemblyDirectories));
            assemblyReferenceLocations =
                assemblyReferenceLocations.Distinct().Where(x => !string.IsNullOrEmpty(x)).ToList();
            IEnumerable <PortableExecutableReference> references = null;

            references = assemblyReferenceLocations.Select(i =>
            {
                return(MetadataReference.CreateFromFile(i));
            });
#if !NET462
            foreach (var assemblyReferenceLocation in assemblyReferenceLocations)
            {
                try
                {
                    AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyReferenceLocation);
                }
                catch (Exception ex)
                {
                }
            }
#endif
            return(references);
        }
Exemplo n.º 12
0
        public bool Process(AnalyserResult analyserResult, string line, int lineIndex)
        {
            if (!line.StartsWith("//#imp"))
            {
                return(false);
            }

            int index = line.IndexOf(" ", StringComparison.Ordinal);

            if (index < 0)
            {
                return(true);
            }

            string file = line.Substring(index);

            analyserResult.CsFiles.Add(Path.GetFullPath(file.Trim()));
            return(true);
        }
Exemplo n.º 13
0
        public bool Process(AnalyserResult analyserResult, string line, int lineIndex)
        {
            if (!line.StartsWith("//#ass"))
            {
                return(false);
            }

            int dllIndex = line.IndexOf(" ", StringComparison.Ordinal);

            if (dllIndex < 0)
            {
                return(true);
            }

            string dll = line.Substring(dllIndex);

            analyserResult.References.Add(Path.GetFullPath(dll.Trim()));
            return(true);
        }
        public bool Process(AnalyserResult analyserResult, string line, int lineIndex)
        {
            if (!line.StartsWith("//#ref"))
            {
                return(false);
            }

            int dllIndex = line.IndexOf(" ", StringComparison.Ordinal);

            if (dllIndex < 0)
            {
                return(true);
            }

            string dll  = line.Substring(dllIndex);
            var    type = Type.GetType(dll, true);

            analyserResult.References.Add(type.GetTypeInfo().Assembly.Location);
            return(true);
        }
Exemplo n.º 15
0
        public bool Process(AnalyserResult analyserResult, string line, int lineIndex)
        {
            var i = line.IndexOf("class", StringComparison.Ordinal);

            if (i < 0)
            {
                return(false);
            }

            var tmp = line.Substring(i + 6);

            tmp = tmp.TrimStart();
            i   = tmp.IndexOf(" ", StringComparison.Ordinal);
            if (i == -1)
            {
                i = tmp.Length;
            }

            analyserResult.ClassName = tmp.Substring(0, i);
            return(true);
        }
Exemplo n.º 16
0
        public async Task <IBuildScript> FindAndCreateBuildScriptInstanceAsync(CommandArguments args)
        {
            var           coreDir   = Path.GetDirectoryName(typeof(object).GetTypeInfo().Assembly.Location);
            var           flubuPath = typeof(DefaultBuildScript).GetTypeInfo().Assembly.Location;
            List <string> assemblyReferenceLocations = new List <string>
            {
                Path.Combine(coreDir, "mscorlib.dll"),
                typeof(object).GetTypeInfo().Assembly.Location,
                flubuPath,
                typeof(File).GetTypeInfo().Assembly.Location,
                typeof(ILookup <string, string>).GetTypeInfo().Assembly.Location,
                typeof(Expression).GetTypeInfo().Assembly.Location,
            };

            List <MetadataReference> references = new List <MetadataReference>();

#if NETSTANDARD2_0
            assemblyReferenceLocations.Add(typeof(Console).GetTypeInfo().Assembly.Location);
#endif

            // Enumerate all assemblies referenced by this executing assembly
            // and provide them as references to the build script we're about to
            // compile.
            AssemblyName[] referencedAssemblies = Assembly.GetEntryAssembly().GetReferencedAssemblies();
            foreach (var referencedAssembly in referencedAssemblies)
            {
                Assembly loadedAssembly = Assembly.Load(referencedAssembly);
                if (string.IsNullOrEmpty(loadedAssembly.Location))
                {
                    continue;
                }

                assemblyReferenceLocations.Add(loadedAssembly.Location);
            }

            string fileName = _buildScriptLocator.FindBuildScript(args);

            List <string> code = _file.ReadAllLines(fileName);

            AnalyserResult analyserResult = _analyser.Analyze(code);
            assemblyReferenceLocations.AddRange(analyserResult.References);

            foreach (var file in analyserResult.CsFiles)
            {
                if (_file.Exists(file))
                {
                    _log.LogInformation($"File found: {file}");
                    List <string> additionalCode = _file.ReadAllLines(file);

                    AnalyserResult additionalCodeAnalyserResult = _analyser.Analyze(additionalCode);
                    if (additionalCodeAnalyserResult.CsFiles.Count > 0)
                    {
                        throw new NotSupportedException("//#imp is only supported in main buildscript .cs file.");
                    }

                    var usings = additionalCode.Where(x => x.StartsWith("using"));

                    assemblyReferenceLocations.AddRange(additionalCodeAnalyserResult.References);
                    code.InsertRange(0, usings);
                    code.AddRange(additionalCode.Where(x => !x.StartsWith("using")));
                }
                else
                {
                    _log.LogInformation($"File was not found: {file}");
                }
            }

            assemblyReferenceLocations.AddRange(FindAssemblyReferencesInDirectories(args.AssemblyDirectories));

            assemblyReferenceLocations = assemblyReferenceLocations.Distinct().ToList();
            references.AddRange(assemblyReferenceLocations.Select(i => MetadataReference.CreateFromFile(i)));
            var opts = ScriptOptions.Default
                       .WithReferences(references);

            Script script = CSharpScript
                            .Create(string.Join("\r\n", code), opts)
                            .ContinueWith(string.Format("var sc = new {0}();", analyserResult.ClassName));

            try
            {
                ScriptState result = await script.RunAsync();

                var buildScript = result.Variables[0].Value as IBuildScript;

                if (buildScript == null)
                {
                    throw new ScriptLoaderExcetpion($"Class in file: {fileName} must inherit from DefaultBuildScript or implement IBuildScipt interface. See getting started on https://github.com/flubu-core/flubu.core/wiki");
                }

                return(buildScript);
            }
            catch (CompilationErrorException e)
            {
                if (e.Message.Contains("CS0234"))
                {
                    throw new ScriptLoaderExcetpion($"Csharp source code file: {fileName} has some compilation errors. {e.Message}. If u are using flubu script correctly you have to add assembly reference with #ref directive in build script. See build script fundamentals section 'Referencing other assemblies in build script' in https://github.com/flubu-core/flubu.core/wiki for more details.Otherwise if u think u are not using flubu correctly see Getting started section in wiki.", e);
                }

                throw new ScriptLoaderExcetpion($"Csharp source code file: {fileName} has some compilation errors. {e.Message}. See getting started and build script fundamentals in https://github.com/flubu-core/flubu.core/wiki", e);
            }
        }
Exemplo n.º 17
0
        private async Task <IBuildScript> CreateBuildScriptInstanceOldWay(string buildScriptFIlePath, IEnumerable <MetadataReference> references, List <string> code, AnalyserResult analyserResult)
        {
            ScriptOptions opts = ScriptOptions.Default
                                 .WithEmitDebugInformation(true)
                                 .WithFilePath(buildScriptFIlePath)
                                 .WithFileEncoding(Encoding.UTF8)
                                 .WithReferences(references);

            Script script = CSharpScript
                            .Create(string.Join("\r\n", code), opts)
                            .ContinueWith(string.Format("var sc = new {0}();", analyserResult.ClassName));

            try
            {
                ScriptState result = await script.RunAsync();

                var buildScript = result.Variables[0].Value as IBuildScript;

                if (buildScript == null)
                {
                    throw new ScriptLoaderExcetpion($"Class in file: {buildScriptFIlePath} must inherit from DefaultBuildScript or implement IBuildScipt interface. See getting started on https://github.com/flubu-core/flubu.core/wiki");
                }

                return(buildScript);
            }
            catch (CompilationErrorException e)
            {
                if (e.Message.Contains("CS0234"))
                {
                    throw new ScriptLoaderExcetpion($"Csharp source code file: {buildScriptFIlePath} has some compilation errors. {e.Message}. If your script doesnt have compilation errors in VS or VSCode you are probably missing assembly directive in build script. You have to add reference to all assemblies that flubu doesn't add by default with #ass, #nuget or #ref directive in build script. See build script fundamentals section 'Referencing other assemblies in build script' in https://github.com/flubu-core/flubu.core/wiki/2-Build-script-fundamentals#Referencing-other-assemblies-in-build-script for more details.", e);
                }

                throw new ScriptLoaderExcetpion($"Csharp source code file: {buildScriptFIlePath} has some compilation errors. {e.Message}.", e);
            }
        }