public AssemblyInfoFileUpdate(Arguments args, string workingDirectory, VersionVariables variables, IFileSystem fileSystem)
        {
            if (!args.UpdateAssemblyInfo) return;

            if (args.Output != OutputType.Json)
                Console.WriteLine("Updating assembly info files");

            var assemblyInfoFiles = GetAssemblyInfoFiles(workingDirectory, args, fileSystem);

            foreach (var assemblyInfoFile in assemblyInfoFiles)
            {
                var backupAssemblyInfo = assemblyInfoFile + ".bak";
                var localAssemblyInfo = assemblyInfoFile;
                fileSystem.Copy(assemblyInfoFile, backupAssemblyInfo, true);
                restoreBackupTasks.Add(() =>
                {
                    if (fileSystem.Exists(localAssemblyInfo))
                        fileSystem.Delete(localAssemblyInfo);
                    fileSystem.Move(backupAssemblyInfo, localAssemblyInfo);
                });
                cleanupBackupTasks.Add(() => fileSystem.Delete(backupAssemblyInfo));

                var assemblyVersion = variables.AssemblySemVer;
                var assemblyInfoVersion = variables.InformationalVersion;
                var assemblyFileVersion = variables.MajorMinorPatch + ".0";
                var fileContents = fileSystem.ReadAllText(assemblyInfoFile)
                    .RegexReplace(@"AssemblyVersion\(""\d+.\d+.\d+(.(\d+|\*))?""\)", string.Format("AssemblyVersion(\"{0}\")", assemblyVersion))
                    .RegexReplace(@"AssemblyInformationalVersion\(""\d+.\d+.\d+(.(\d+|\*))?""\)", string.Format("AssemblyInformationalVersion(\"{0}\")", assemblyInfoVersion))
                    .RegexReplace(@"AssemblyFileVersion\(""\d+.\d+.\d+(.(\d+|\*))?""\)", string.Format("AssemblyFileVersion(\"{0}\")", assemblyFileVersion));

                fileSystem.WriteAllText(assemblyInfoFile, fileContents);
            }
        }
Example #2
0
        internal override void ManageFolders(IFileSystem fileSystem)
        {
            if (Folders != null)
            {
                // helper list to be able to modify Folders property inside the loop
                var iterate = new List<FolderInfo>(Folders);

                foreach (var folder in iterate)
                {
                    if (fileSystem.Exists(this, folder))
                    {
                        var directoryInfos = fileSystem.GetFolders(this, folder);
                        foreach (var directoryInfo in directoryInfos.OrderByDescending(x => x.Name))
                        {
                            var newFolder = new FolderInfo
                            {
                                Absolute = folder.Absolute,
                                Filter = folder.Filter,
                                Levels = new List<LogLevel>(folder.Levels),
                                Name = $"{folder.Name}_{directoryInfo.Name}",
                                Path = fileSystem.CombinePath(folder.Path, directoryInfo.Name),
                                OpeningLinePattern = folder.OpeningLinePattern
                            };

                            Folders.Insert(Folders.IndexOf(folder) + 1, newFolder);
                        }
                    }
                    else
                    {
                        Folders.Remove(folder);
                    }
                }
            }
        }
        public void builder()
        {
            _filesystem = Substitute.For<IFileSystem>();
            _filesystem.GetPlatformRoot().Returns(The.Root);

            _filesystem.Exists(null).ReturnsForAnyArgs(true);

            _modules = Substitute.For<IModules>();
            _modules.Paths.Returns(new[] { "group1/proj1", "group1/proj2", "group2/proj3" });
            _modules.Repos.Returns(new[] { "p1Repo", "p2Repo", "p3Repo" });
            _locks = new List<AutoResetEvent> { new AutoResetEvent(true), new AutoResetEvent(true), new AutoResetEvent(true) };
            _modules.CreateAndSetLocks().Returns(_locks);

            _patterns = new Patterns
            {
                DependencyPattern = "*.dll",
                DependencyPath = (FilePath)"lib",
                Masters = new FilePath[] { }
            };

            _git = Substitute.For<IGit>();
            _depMgr = Substitute.For<IDependencyManager>();
            _ruleFac = Substitute.For<IRuleFactory>();
            _ruleFac.GetModules().Returns(_modules);
            _ruleFac.GetRulePatterns().Returns(_patterns);

            _buildCmd = Substitute.For<IBuildCmd>();

            _subject = new Builder(_filesystem, _git, _depMgr, _ruleFac, _buildCmd);
            _subject.Prepare();
            _subject.GetDependenciesAndBuild();
        }
Example #4
0
        public void builder()
        {
            _filesystem = Substitute.For<IFileSystem>();
            _filesystem.GetPlatformRoot().Returns(The.Root);

            var dbpath = The.Root.Navigate((FilePath)"group1/proj2/DatabaseScripts");
            _filesystem.Exists(null).ReturnsForAnyArgs(c=> c.Args()[0] as FilePath == dbpath);
            _filesystem.SortedDescendants(null,null).ReturnsForAnyArgs(new [] {(FilePath)"one",(FilePath)"two"});

            _modules = Substitute.For<IModules>();
            _modules.Paths.Returns(new[] {"group1/proj1", "group1/proj2", "group2/proj3"});
            _modules.Repos.Returns(new[] {"p1Repo", "p2Repo", "p3Repo"});
            _locks = new List<AutoResetEvent> { new AutoResetEvent(true), new AutoResetEvent(true), new AutoResetEvent(true) };
            _modules.CreateAndSetLocks().Returns(_locks);

            _git = Substitute.For<IGit>();
            _depMgr = Substitute.For<IDependencyManager>();
            _ruleFac = Substitute.For<IRuleFactory>();
            _ruleFac.GetModules().Returns(_modules);

            _buildCmd = Substitute.For<IBuildCmd>();

            _subject = new Builder(_filesystem, _git, _depMgr, _ruleFac, _buildCmd);
            _subject.Prepare();
            _subject.RebuildDatabases();
        }
        public StaticFileRouteHandler(string basePath, IReadOnlyDictionary<string, string> extensionsToMimeTypes, IFileSystem fileSystem)
        {
            _basePath = basePath.GetAbsoluteBasePathUri();
            _fileSystem = fileSystem ?? new PhysicalFileSystem();
            _mimeTypeProvider = new MimeTypeProvider(extensionsToMimeTypes ?? MimeTypeProvider.DefaultMimeTypesByExtension);

            if (!_fileSystem.Exists(_basePath))
            {
                throw new Exception($"Path at {_basePath} could not be found.");
            }
        }
        static IEnumerable<string> GetAssemblyInfoFiles(string workingDirectory, Arguments args, IFileSystem fileSystem)
        {
            if (args.UpdateAssemblyInfoFileName != null)
            {
                var fullPath = Path.Combine(workingDirectory, args.UpdateAssemblyInfoFileName);

                if (fileSystem.Exists(fullPath))
                {
                    return new[] { fullPath };
                }
            }

            return fileSystem.DirectoryGetFiles(workingDirectory, "AssemblyInfo.cs", SearchOption.AllDirectories);
        }
        public AssemblyInfoFileUpdate(Arguments args, string workingDirectory, VersionVariables variables, IFileSystem fileSystem)
        {
            if (!args.UpdateAssemblyInfo) return;

            if (args.Output != OutputType.Json)
                Logger.WriteInfo("Updating assembly info files");

            var assemblyInfoFiles = GetAssemblyInfoFiles(workingDirectory, args, fileSystem).ToList();
            Logger.WriteInfo(string.Format("Found {0} files", assemblyInfoFiles.Count));

            var assemblyVersion = variables.AssemblySemVer;
            var assemblyVersionRegex = new Regex(@"AssemblyVersion\s*\(\s*""[^""]*""\s*\)");
            var assemblyVersionString = !string.IsNullOrWhiteSpace(assemblyVersion) ? string.Format("AssemblyVersion(\"{0}\")", assemblyVersion) : null;
            var assemblyInfoVersion = variables.InformationalVersion;
            var assemblyInfoVersionRegex = new Regex(@"AssemblyInformationalVersion\s*\(\s*""[^""]*""\s*\)");
            var assemblyInfoVersionString = string.Format("AssemblyInformationalVersion(\"{0}\")", assemblyInfoVersion);
            var assemblyFileVersion = variables.MajorMinorPatch + ".0";
            var assemblyFileVersionRegex = new Regex(@"AssemblyFileVersion\s*\(\s*""[^""]*""\s*\)");
            var assemblyFileVersionString = string.Format("AssemblyFileVersion(\"{0}\")", assemblyFileVersion);

            foreach (var assemblyInfoFile in assemblyInfoFiles)
            {
                var backupAssemblyInfo = assemblyInfoFile.FullName + ".bak";
                var localAssemblyInfo = assemblyInfoFile.FullName;
                fileSystem.Copy(assemblyInfoFile.FullName, backupAssemblyInfo, true);
                restoreBackupTasks.Add(() =>
                {
                    if (fileSystem.Exists(localAssemblyInfo))
                        fileSystem.Delete(localAssemblyInfo);
                    fileSystem.Move(backupAssemblyInfo, localAssemblyInfo);
                });
                cleanupBackupTasks.Add(() => fileSystem.Delete(backupAssemblyInfo));

                var fileContents = fileSystem.ReadAllText(assemblyInfoFile.FullName);
                var appendedAttributes = false;
                if (!string.IsNullOrWhiteSpace(assemblyVersion))
                {
                    fileContents = ReplaceOrAppend(assemblyVersionRegex, fileContents, assemblyVersionString, assemblyInfoFile.Extension, ref appendedAttributes);
                }
                fileContents = ReplaceOrAppend(assemblyInfoVersionRegex, fileContents, assemblyInfoVersionString, assemblyInfoFile.Extension, ref appendedAttributes);
                fileContents = ReplaceOrAppend(assemblyFileVersionRegex, fileContents, assemblyFileVersionString, assemblyInfoFile.Extension, ref appendedAttributes);

                if (appendedAttributes)
                {
                    // If we appended any attributes, put a new line after them
                    fileContents += Environment.NewLine;
                }
                fileSystem.WriteAllText(assemblyInfoFile.FullName, fileContents);
            }
        }
        public static Config Provide(string gitDirectory, IFileSystem fileSystem)
        {
            var configFilePath = GetConfigFilePath(gitDirectory);

            if (fileSystem.Exists(configFilePath))
            {
                var readAllText = fileSystem.ReadAllText(configFilePath);
                LegacyConfigNotifier.Notify(new StringReader(readAllText));

                return ConfigSerialiser.Read(new StringReader(readAllText));
            }

            return new Config();
        }
        static IEnumerable<string> GetAssemblyInfoFiles(string workingDirectory, Arguments args, IFileSystem fileSystem)
        {
            if (args.UpdateAssemblyInfoFileName != null)
            {
                var fullPath = Path.Combine(workingDirectory, args.UpdateAssemblyInfoFileName);

                if (fileSystem.Exists(fullPath))
                {
                    return new[] { fullPath };
                }
            }

            return fileSystem.DirectoryGetFiles(workingDirectory, "AssemblyInfo.*", SearchOption.AllDirectories)
                .Where(f => f.EndsWith(".cs", StringComparison.OrdinalIgnoreCase) || f.EndsWith(".vb", StringComparison.OrdinalIgnoreCase));
        }
        public static void WriteSample(string gitDirectory, IFileSystem fileSystem)
        {
            var configFilePath = GetConfigFilePath(gitDirectory);

            if (!fileSystem.Exists(configFilePath))
            {
                using (var stream = fileSystem.OpenWrite(configFilePath))
                using (var writer = new StreamWriter(stream))
                {
                    ConfigSerialiser.WriteSample(writer);
                }
            }
            else
            {
                Logger.WriteError("Cannot write sample, GitVersionConfig.yaml already exists");
            }
        }
        public static Config Provide(string gitDirectory, IFileSystem fileSystem)
        {
            if (fileSystem == null)
            {
                throw new ArgumentNullException("fileSystem");
            }

            var configFilePath = GetConfigFilePath(gitDirectory);

            if (fileSystem.Exists(configFilePath))
            {
                var readAllText = fileSystem.ReadAllText(configFilePath);

                return ConfigSerializer.Read(new StringReader(readAllText));
            }

            return new Config();
        }
        public void builder()
        {
            _filesystem = Substitute.For<IFileSystem>();
            _filesystem.GetPlatformRoot().Returns(The.Root);
            _missingRepo = The.Root.Append((FilePath)"/group1/proj2");

            _filesystem.Exists(null).ReturnsForAnyArgs(c=> (c.Args()[0] as FilePath !=_missingRepo));

            _modules = Substitute.For<IModules>();
            _modules.Paths.Returns(new[] {"group1/proj1", "group1/proj2", "group2/proj3"});
            _modules.Repos.Returns(new[] {"p1Repo", "p2Repo", "p3Repo"});

            _git = Substitute.For<IGit>();
            _depMgr = Substitute.For<IDependencyManager>();
            _ruleFac = Substitute.For<IRuleFactory>();
            _ruleFac.GetModules().Returns(_modules);

            _subject = new Builder(_filesystem, _git, _depMgr, _ruleFac, null);
            _subject.Prepare();
        }
        public AssemblyInfoFileUpdate(Arguments args, string workingDirectory, VersionVariables variables, IFileSystem fileSystem)
        {
            if (!args.UpdateAssemblyInfo) return;

            if (args.Output != OutputType.Json)
                Logger.WriteInfo("Updating assembly info files");

            var assemblyInfoFiles = GetAssemblyInfoFiles(workingDirectory, args, fileSystem);
            Logger.WriteInfo(string.Format("Found {0} files", assemblyInfoFiles.Count()));

            var assemblyVersion = variables.AssemblySemVer;
            var assemblyVersionRegex = new Regex(@"AssemblyVersion\(""[^""]*""\)");
            var assemblyVersionString = string.Format("AssemblyVersion(\"{0}\")", assemblyVersion);
            var assemblyInfoVersion = variables.InformationalVersion;
            var assemblyInfoVersionRegex = new Regex(@"AssemblyInformationalVersion\(""[^""]*""\)");
            var assemblyInfoVersionString = string.Format("AssemblyInformationalVersion(\"{0}\")", assemblyInfoVersion);
            var assemblyFileVersion = variables.MajorMinorPatch + ".0";
            var assemblyFileVersionRegex = new Regex(@"AssemblyFileVersion\(""[^""]*""\)");
            var assemblyFileVersionString = string.Format("AssemblyFileVersion(\"{0}\")", assemblyFileVersion);

            foreach (var assemblyInfoFile in assemblyInfoFiles.Select(f => new FileInfo(f)))
            {
                var backupAssemblyInfo = assemblyInfoFile.FullName + ".bak";
                var localAssemblyInfo = assemblyInfoFile.FullName;
                fileSystem.Copy(assemblyInfoFile.FullName, backupAssemblyInfo, true);
                restoreBackupTasks.Add(() =>
                {
                    if (fileSystem.Exists(localAssemblyInfo))
                        fileSystem.Delete(localAssemblyInfo);
                    fileSystem.Move(backupAssemblyInfo, localAssemblyInfo);
                });
                cleanupBackupTasks.Add(() => fileSystem.Delete(backupAssemblyInfo));

                var fileContents = fileSystem.ReadAllText(assemblyInfoFile.FullName);
                fileContents = ReplaceOrAppend(assemblyVersionRegex, fileContents, assemblyVersionString);
                fileContents = ReplaceOrAppend(assemblyInfoVersionRegex, fileContents, assemblyInfoVersionString);
                fileContents = ReplaceOrAppend(assemblyFileVersionRegex, fileContents, assemblyFileVersionString);

                fileSystem.WriteAllText(assemblyInfoFile.FullName, fileContents);
            }
        }
        public static void WriteSample(string targetDirectory, IFileSystem fileSystem)
        {
            if (fileSystem == null)
            {
                throw new ArgumentNullException("fileSystem");
            }

            var configFilePath = GetConfigFilePath(targetDirectory);

            if (!fileSystem.Exists(configFilePath))
            {
                using (var stream = fileSystem.OpenWrite(configFilePath))
                using (var writer = new StreamWriter(stream))
                {
                    ConfigSerializer.WriteSample(writer);
                }
            }
            else
            {
                Logger.WriteError("Cannot write sample, GitReleaseManager.yaml already exists");
            }
        }
Example #15
0
        public void builder()
        {
            _filesystem = Substitute.For<IFileSystem>();
            _filesystem.GetPlatformRoot().Returns(The.Root);

            _filesystem.Exists(null).ReturnsForAnyArgs(c=> (c.Args()[0] as FilePath != (FilePath)"group1/proj2"));

            _modules = Substitute.For<IModules>();
            _modules.Paths.Returns(new[] {"group1/proj1", "group1/proj2", "group2/proj3"});
            _modules.Repos.Returns(new[] {"p1Repo", "p2Repo", "p3Repo"});
            _locks = new List<AutoResetEvent> { new AutoResetEvent(false), new AutoResetEvent(false), new AutoResetEvent(false) };
            _modules.CreateAndSetLocks().Returns(_locks);

            _git = Substitute.For<IGit>();
            _depMgr = Substitute.For<IDependencyManager>();
            _ruleFac = Substitute.For<IRuleFactory>();
            _ruleFac.GetModules().Returns(_modules);

            _subject = new Builder(_filesystem, _git, _depMgr, _ruleFac, null);
            _subject.Prepare();
            _subject.PullRepos();
        }
        static bool EnsureVersionAssemblyInfoFile(Arguments arguments, IFileSystem fileSystem, string fullPath)
        {
            if (fileSystem.Exists(fullPath)) return true;

            if (!arguments.EnsureAssemblyInfo) return false;

            var assemblyInfoSource = AssemblyVersionInfoTemplates.GetAssemblyInfoTemplateFor(fullPath);
            if (!string.IsNullOrWhiteSpace(assemblyInfoSource))
            {
                var fileInfo = new FileInfo(fullPath);
                if (!fileSystem.DirectoryExists(fileInfo.Directory.FullName))
                {
                    fileSystem.CreateDirectory(fileInfo.Directory.FullName);
                }
                fileSystem.WriteAllText(fullPath, assemblyInfoSource);
                return true;
            }
            Logger.WriteWarning(string.Format("No version assembly info template available to create source file '{0}'", arguments.UpdateAssemblyInfoFileName));
            return false;
        }
Example #17
0
 private void MakeRemoteTestFile(IFileSystem fs, Uri path)
 {
     if (fs.Exists(path))
     {
         fs.Delete(path);
     }
     using (var s = fs.Create(path))
     {
         s.WriteByte(TestByte);
     }
 }
        public override bool Execute()
        {
            try
            {
                Console.WriteLine("\nCalculating coverage result...");

                IFileSystem fileSystem = DependencyInjection.Current.GetService <IFileSystem>();
                if (InstrumenterState is null || !fileSystem.Exists(InstrumenterState.ItemSpec))
                {
                    _logger.LogError("Result of instrumentation task not found");
                    return(false);
                }

                Coverage coverage = null;
                using (Stream instrumenterStateStream = fileSystem.NewFileStream(InstrumenterState.ItemSpec, FileMode.Open))
                {
                    var instrumentationHelper = DependencyInjection.Current.GetService <IInstrumentationHelper>();
                    // Task.Log is teared down after a task and thus the new MSBuildLogger must be passed to the InstrumentationHelper
                    // https://github.com/microsoft/msbuild/issues/5153
                    instrumentationHelper.SetLogger(_logger);
                    coverage = new Coverage(CoveragePrepareResult.Deserialize(instrumenterStateStream), this._logger, DependencyInjection.Current.GetService <IInstrumentationHelper>(), fileSystem);
                }

                try
                {
                    fileSystem.Delete(InstrumenterState.ItemSpec);
                }
                catch (Exception ex)
                {
                    // We don't want to block coverage for I/O errors
                    _logger.LogWarning($"Exception during instrument state deletion, file name '{InstrumenterState.ItemSpec}' exception message '{ex.Message}'");
                }

                CoverageResult result = coverage.GetCoverageResult();

                var directory = Path.GetDirectoryName(_output);
                if (directory == string.Empty)
                {
                    directory = Directory.GetCurrentDirectory();
                }
                else if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                var formats = _format.Split(',');
                foreach (var format in formats)
                {
                    var reporter = new ReporterFactory(format).CreateReporter();
                    if (reporter == null)
                    {
                        throw new Exception($"Specified output format '{format}' is not supported");
                    }

                    if (reporter.OutputType == ReporterOutputType.Console)
                    {
                        // Output to console
                        Console.WriteLine("  Outputting results to console");
                        Console.WriteLine(reporter.Report(result));
                    }
                    else
                    {
                        ReportWriter writer = new ReportWriter(_coverletMultiTargetFrameworksCurrentTFM,
                                                               directory,
                                                               _output,
                                                               reporter,
                                                               fileSystem,
                                                               DependencyInjection.Current.GetService <IConsole>(),
                                                               result);
                        writer.WriteReport();
                    }
                }

                var thresholdTypeFlags = ThresholdTypeFlags.None;
                var thresholdStat      = ThresholdStatistic.Minimum;

                foreach (var thresholdType in _thresholdType.Split(',').Select(t => t.Trim()))
                {
                    if (thresholdType.Equals("line", StringComparison.OrdinalIgnoreCase))
                    {
                        thresholdTypeFlags |= ThresholdTypeFlags.Line;
                    }
                    else if (thresholdType.Equals("branch", StringComparison.OrdinalIgnoreCase))
                    {
                        thresholdTypeFlags |= ThresholdTypeFlags.Branch;
                    }
                    else if (thresholdType.Equals("method", StringComparison.OrdinalIgnoreCase))
                    {
                        thresholdTypeFlags |= ThresholdTypeFlags.Method;
                    }
                }

                if (_thresholdStat.Equals("average", StringComparison.OrdinalIgnoreCase))
                {
                    thresholdStat = ThresholdStatistic.Average;
                }
                else if (_thresholdStat.Equals("total", StringComparison.OrdinalIgnoreCase))
                {
                    thresholdStat = ThresholdStatistic.Total;
                }

                var coverageTable = new ConsoleTable("Module", "Line", "Branch", "Method");
                var summary       = new CoverageSummary();
                int numModules    = result.Modules.Count;

                var linePercentCalculation   = summary.CalculateLineCoverage(result.Modules);
                var branchPercentCalculation = summary.CalculateBranchCoverage(result.Modules);
                var methodPercentCalculation = summary.CalculateMethodCoverage(result.Modules);

                var totalLinePercent   = linePercentCalculation.Percent;
                var totalBranchPercent = branchPercentCalculation.Percent;
                var totalMethodPercent = methodPercentCalculation.Percent;

                var averageLinePercent   = linePercentCalculation.AverageModulePercent;
                var averageBranchPercent = branchPercentCalculation.AverageModulePercent;
                var averageMethodPercent = methodPercentCalculation.AverageModulePercent;

                foreach (var module in result.Modules)
                {
                    var linePercent   = summary.CalculateLineCoverage(module.Value).Percent;
                    var branchPercent = summary.CalculateBranchCoverage(module.Value).Percent;
                    var methodPercent = summary.CalculateMethodCoverage(module.Value).Percent;

                    coverageTable.AddRow(Path.GetFileNameWithoutExtension(module.Key), $"{linePercent}%", $"{branchPercent}%", $"{methodPercent}%");
                }

                Console.WriteLine();
                Console.WriteLine(coverageTable.ToStringAlternative());

                coverageTable.Columns.Clear();
                coverageTable.Rows.Clear();

                coverageTable.AddColumn(new[] { "", "Line", "Branch", "Method" });
                coverageTable.AddRow("Total", $"{totalLinePercent}%", $"{totalBranchPercent}%", $"{totalMethodPercent}%");
                coverageTable.AddRow("Average", $"{averageLinePercent}%", $"{averageBranchPercent}%", $"{averageMethodPercent}%");

                Console.WriteLine(coverageTable.ToStringAlternative());

                thresholdTypeFlags = result.GetThresholdTypesBelowThreshold(summary, _threshold, thresholdTypeFlags, thresholdStat);
                if (thresholdTypeFlags != ThresholdTypeFlags.None)
                {
                    var exceptionMessageBuilder = new StringBuilder();
                    if ((thresholdTypeFlags & ThresholdTypeFlags.Line) != ThresholdTypeFlags.None)
                    {
                        exceptionMessageBuilder.AppendLine($"The {thresholdStat.ToString().ToLower()} line coverage is below the specified {_threshold}");
                    }

                    if ((thresholdTypeFlags & ThresholdTypeFlags.Branch) != ThresholdTypeFlags.None)
                    {
                        exceptionMessageBuilder.AppendLine($"The {thresholdStat.ToString().ToLower()} branch coverage is below the specified {_threshold}");
                    }

                    if ((thresholdTypeFlags & ThresholdTypeFlags.Method) != ThresholdTypeFlags.None)
                    {
                        exceptionMessageBuilder.AppendLine($"The {thresholdStat.ToString().ToLower()} method coverage is below the specified {_threshold}");
                    }

                    throw new Exception(exceptionMessageBuilder.ToString());
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex);
                return(false);
            }

            return(true);
        }
Example #19
0
        /// <summary>
        /// Checks if a certain resource does exist under a certain file system.
        /// </summary>
        /// <param name="system"></param>
        /// <param name="pather"></param>
        /// <param name="magicChecked"></param>
        /// <returns></returns>
        private static bool Exists(IFileSystem system, Pather pather, bool magicChecked)
        {
            // If said file exists, good
            if (system.Exists(pather.RootlessPath))
                return true;

            // If we already tried our magic
            if (magicChecked)
            {
                // Pop the magic again.
                pather.Pop();

                // Second-to-last resort: Extension is .lua, so there might be a luac somewhere.
                if (pather.Last.EndsWith(".lua") && system.Exists(pather.RootlessPath + "c"))
                    return true;

                // Last resort: .lua or .luac extension
                if (system.Exists(pather.RootlessPath + ".lua") || system.Exists(pather.RootlessPath + ".luac"))
                {
                    string script = pather.Last;
                    pather.Pop();
                    script += system.Exists(script + ".lua") ? ".lua" : ".luac";
                    pather.Add(script);
                    return true;
                }

                return false;
            }
            else
            {
                // Try it for an alias
                if (ParseAlias(pather.ToString()) != null)
                    return true;
            }

            // Since we can't check for zip files, try this.
            // It's not exactly a beautiful approach but it's an allnighter here, so \o/
            pather.Add(pather.Last + ".json");

            // Just call us again, this time without magic. If we ever redo this part, this would be nice.
            return Exists(system, pather, true);
        }
        static string GetConfigFilePath(string workingDirectory, IFileSystem fileSystem)
        {
            var ymlPath = Path.Combine(workingDirectory, "GitVersion.yml");
            if (fileSystem.Exists(ymlPath))
            {
                return ymlPath;
            }

            var deprecatedPath = Path.Combine(workingDirectory, "GitVersionConfig.yaml");
            if (fileSystem.Exists(deprecatedPath))
            {
                Logger.WriteWarning("'GitVersionConfig.yaml' is deprecated, use 'GitVersion.yml' instead.");

                return deprecatedPath;
            }

            return ymlPath;
        }
Example #21
0
 static bool AppVeyorConfigExists(string workingDirectory, IFileSystem fileSystem)
 {
     return fileSystem.Exists(Path.Combine(workingDirectory, "appveyor.yml"));
 }
    protected internal static bool IsResource(IFileSystem diskFileSystem, string providerPath)
    {
      if (providerPath == "/")
        return true;
      string isoPath = ToIsoPath(providerPath);

      return diskFileSystem.Exists(isoPath);
    }
Example #23
0
        string GetOutputFilename(string workingDirectory, IFileSystem fileSystem)
        {
            if (AppVeyorConfigExists(workingDirectory, fileSystem))
            {
                var count = 0;
                do
                {
                    var path = Path.Combine(workingDirectory, string.Format("appveyor.gitversion{0}.yml", count == 0 ? string.Empty : "." + count));

                    if (!fileSystem.Exists(path))
                    {
                        return path;
                    }

                    count++;
                } while (count < 10);
                throw new Exception("appveyor.gitversion.yml -> appveyor.gitversion.9.yml all exist. Pretty sure you have enough templates");
            }

            return Path.Combine(workingDirectory, "appveyor.yml");
        }
        static void WarnAboutObsoleteConfigFile(string workingDirectory, IFileSystem fileSystem)
        {
            var deprecatedConfigFilePath = Path.Combine(workingDirectory, ObsoleteConfigFileName);
            if (!fileSystem.Exists(deprecatedConfigFilePath))
            {
                return;
            }

            var defaultConfigFilePath = Path.Combine(workingDirectory, DefaultConfigFileName);
            if (fileSystem.Exists(defaultConfigFilePath))
            {
                Logger.WriteWarning(string.Format("Ambiguous config files at '{0}': '{1}' (deprecated) and '{2}'. Will be used '{2}'", workingDirectory, ObsoleteConfigFileName, DefaultConfigFileName));
                return;
            }

            Logger.WriteWarning(string.Format("'{0}' is deprecated, use '{1}' instead.", deprecatedConfigFilePath, DefaultConfigFileName));
        }
        static void WarnAboutAmbiguousConfigFileSelection(string workingDirectory, string projectRootDirectory, IFileSystem fileSystem)
        {
            var workingConfigFile = GetConfigFilePath(workingDirectory, fileSystem);
            var projectRootConfigFile = GetConfigFilePath(projectRootDirectory, fileSystem);

            bool hasConfigInWorkingDirectory = fileSystem.Exists(workingConfigFile);
            bool hasConfigInProjectRootDirectory = fileSystem.Exists(projectRootConfigFile);
            if (hasConfigInProjectRootDirectory && hasConfigInWorkingDirectory)
            {
                throw new WarningException(string.Format("Ambiguous config file selection from '{0}' and '{1}'", workingConfigFile, projectRootConfigFile));
            }
        }
        static bool HasConfigFileAt(string workingDirectory, IFileSystem fileSystem)
        {
            var defaultConfigFilePath = Path.Combine(workingDirectory, DefaultConfigFileName);
            if (fileSystem.Exists(defaultConfigFilePath))
            {
                return true;
            }

            var deprecatedConfigFilePath = Path.Combine(workingDirectory, ObsoleteConfigFileName);
            if (fileSystem.Exists(deprecatedConfigFilePath))
            {
                return true;
            }

            return false;
        }
Example #27
0
        public CoverageResult GetCoverageResult()
        {
            CalculateCoverage();

            Modules modules = new Modules();

            foreach (var result in _results)
            {
                Documents documents = new Documents();
                foreach (var doc in result.Documents.Values)
                {
                    // Construct Line Results
                    foreach (var line in doc.Lines.Values)
                    {
                        if (documents.TryGetValue(doc.Path, out Classes classes))
                        {
                            if (classes.TryGetValue(line.Class, out Methods methods))
                            {
                                if (methods.TryGetValue(line.Method, out Method method))
                                {
                                    documents[doc.Path][line.Class][line.Method].Lines.Add(line.Number, line.Hits);
                                }
                                else
                                {
                                    documents[doc.Path][line.Class].Add(line.Method, new Method());
                                    documents[doc.Path][line.Class][line.Method].Lines.Add(line.Number, line.Hits);
                                }
                            }
                            else
                            {
                                documents[doc.Path].Add(line.Class, new Methods());
                                documents[doc.Path][line.Class].Add(line.Method, new Method());
                                documents[doc.Path][line.Class][line.Method].Lines.Add(line.Number, line.Hits);
                            }
                        }
                        else
                        {
                            documents.Add(doc.Path, new Classes());
                            documents[doc.Path].Add(line.Class, new Methods());
                            documents[doc.Path][line.Class].Add(line.Method, new Method());
                            documents[doc.Path][line.Class][line.Method].Lines.Add(line.Number, line.Hits);
                        }
                    }

                    // Construct Branch Results
                    foreach (var branch in doc.Branches.Values)
                    {
                        if (documents.TryGetValue(doc.Path, out Classes classes))
                        {
                            if (classes.TryGetValue(branch.Class, out Methods methods))
                            {
                                if (methods.TryGetValue(branch.Method, out Method method))
                                {
                                    method.Branches.Add(new BranchInfo
                                    {
                                        Line = branch.Number, Hits = branch.Hits, Offset = branch.Offset, EndOffset = branch.EndOffset, Path = branch.Path, Ordinal = branch.Ordinal
                                    }
                                                        );
                                }
                                else
                                {
                                    documents[doc.Path][branch.Class].Add(branch.Method, new Method());
                                    documents[doc.Path][branch.Class][branch.Method].Branches.Add(new BranchInfo
                                    {
                                        Line = branch.Number, Hits = branch.Hits, Offset = branch.Offset, EndOffset = branch.EndOffset, Path = branch.Path, Ordinal = branch.Ordinal
                                    }
                                                                                                  );
                                }
                            }
                            else
                            {
                                documents[doc.Path].Add(branch.Class, new Methods());
                                documents[doc.Path][branch.Class].Add(branch.Method, new Method());
                                documents[doc.Path][branch.Class][branch.Method].Branches.Add(new BranchInfo
                                {
                                    Line = branch.Number, Hits = branch.Hits, Offset = branch.Offset, EndOffset = branch.EndOffset, Path = branch.Path, Ordinal = branch.Ordinal
                                }
                                                                                              );
                            }
                        }
                        else
                        {
                            documents.Add(doc.Path, new Classes());
                            documents[doc.Path].Add(branch.Class, new Methods());
                            documents[doc.Path][branch.Class].Add(branch.Method, new Method());
                            documents[doc.Path][branch.Class][branch.Method].Branches.Add(new BranchInfo
                            {
                                Line = branch.Number, Hits = branch.Hits, Offset = branch.Offset, EndOffset = branch.EndOffset, Path = branch.Path, Ordinal = branch.Ordinal
                            }
                                                                                          );
                        }
                    }
                }

                modules.Add(Path.GetFileName(result.ModulePath), documents);
                _instrumentationHelper.RestoreOriginalModule(result.ModulePath, _identifier);
            }

            // In case of anonymous delegate compiler generate a custom class and passes it as type.method delegate.
            // If in delegate method we've a branches we need to move these to "actual" class/method that use it.
            // We search "method" with same "Line" of closure class method and add missing branches to it,
            // in this way we correctly report missing branch inside compiled generated anonymous delegate.
            List <string> compileGeneratedClassToRemove = null;

            foreach (var module in modules)
            {
                foreach (var document in module.Value)
                {
                    foreach (var @class in document.Value)
                    {
                        // We fix only lamda generated class
                        // https://github.com/dotnet/roslyn/blob/master/src/Compilers/CSharp/Portable/Symbols/Synthesized/GeneratedNameKind.cs#L18
                        if ([email protected]("<>c"))
                        {
                            continue;
                        }

                        foreach (var method in @class.Value)
                        {
                            foreach (var branch in method.Value.Branches)
                            {
                                if (BranchInCompilerGeneratedClass(method.Key))
                                {
                                    Method actualMethod = GetMethodWithSameLineInSameDocument(document.Value, @class.Key, branch.Line);

                                    if (actualMethod is null)
                                    {
                                        continue;
                                    }

                                    actualMethod.Branches.Add(branch);

                                    if (compileGeneratedClassToRemove is null)
                                    {
                                        compileGeneratedClassToRemove = new List <string>();
                                    }

                                    if (!compileGeneratedClassToRemove.Contains(@class.Key))
                                    {
                                        compileGeneratedClassToRemove.Add(@class.Key);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // After method/branches analysis of compiled generated class we can remove noise from reports
            if (!(compileGeneratedClassToRemove is null))
            {
                foreach (var module in modules)
                {
                    foreach (var document in module.Value)
                    {
                        foreach (var classToRemove in compileGeneratedClassToRemove)
                        {
                            document.Value.Remove(classToRemove);
                        }
                    }
                }
            }

            var coverageResult = new CoverageResult {
                Identifier = _identifier, Modules = modules, InstrumentedResults = _results, UseSourceLink = _useSourceLink
            };

            if (!string.IsNullOrEmpty(_mergeWith) && !string.IsNullOrWhiteSpace(_mergeWith) && _fileSystem.Exists(_mergeWith))
            {
                string json = _fileSystem.ReadAllText(_mergeWith);
                coverageResult.Merge(JsonConvert.DeserializeObject <Modules>(json));
            }

            return(coverageResult);
        }
        private static string GetConfigFileHash(IFileSystem fileSystem, GitPreparer gitPreparer)
        {
            // will return the same hash even when config file will be moved
            // from workingDirectory to rootProjectDirectory. It's OK. Config essentially is the same.
            var configFilePath = ConfigurationProvider.SelectConfigFilePath(gitPreparer, fileSystem);
            if (!fileSystem.Exists(configFilePath))
            {
                return string.Empty;
            }

            var configFileContent = fileSystem.ReadAllText(configFilePath);
            return GetHash(configFileContent);
        }
        static string GetConfigFilePath(string workingDirectory, IFileSystem fileSystem)
        {
            var ymlPath = Path.Combine(workingDirectory, DefaultConfigFileName);
            if (fileSystem.Exists(ymlPath))
            {
                return ymlPath;
            }

            var deprecatedPath = Path.Combine(workingDirectory, ObsoleteConfigFileName);
            if (fileSystem.Exists(deprecatedPath))
            {
                return deprecatedPath;
            }

            return ymlPath;
        }
Example #30
0
        public async Task Delete(string orgSlug, string dsSlug, string path)
        {
            var ds = await _utils.GetDataset(orgSlug, dsSlug);

            _logger.LogInformation("In Delete('{OrgSlug}/{DsSlug}')", orgSlug, dsSlug);

            if (!await _authManager.IsOwnerOrAdmin(ds))
            {
                throw new UnauthorizedException("The current user is not allowed to edit dataset");
            }

            if (IsReservedPath(path))
            {
                throw new InvalidOperationException($"'{path}' is a reserved path");
            }

            var ddb = _ddbManager.Get(orgSlug, ds.InternalRef);

            if (!await ddb.EntryExistsAsync(path))
            {
                throw new BadRequestException($"Path '{path}' not found in dataset");
            }

            var objs = (await ddb.SearchAsync(path, true)).ToArray();

            foreach (var obj in objs.Where(item => item.Type != EntryType.Directory))
            {
                _logger.LogInformation("Deleting '{ObjPath}'", obj.Path);

                var objLocalPath = ddb.GetLocalPath(obj.Path);

                try
                {
                    if (!_fs.Exists(objLocalPath))
                    {
                        throw new InvalidOperationException(
                                  $"Cannot find local file '{objLocalPath}' for object '{obj.Path}'");
                    }

                    _fs.Delete(objLocalPath);

                    await _cacheManager.Clear(MagicStrings.ThumbnailCacheSeed, obj.Hash);

                    await _cacheManager.Clear(MagicStrings.TileCacheSeed, obj.Hash);
                }
                catch (Exception ex)
                {
                    // We basically ignore this error, it's not critical. We should perform a cleanup later
                    _logger.LogWarning("Cannot delete local file '{ObjPath}': {Reason}", objLocalPath, ex.Message);
                }
            }

            try
            {
                _logger.LogInformation("Removing from DDB");
                await ddb.RemoveAsync(path);
            }
            catch (Exception ex)
            {
                _logger.LogWarning("Cannot delete '{ObjPath}' from DDB: {Reason}", path, ex.Message);
                throw new InvalidOperationException("Cannot delete object from database", ex);
            }

            _logger.LogInformation("Deletion complete");
        }