コード例 #1
0
        internal static string FindVcsRootPath()
        {
            try
            {
                Assembly ncrunchAssembly = AppDomain.CurrentDomain.Load("NCrunch.Framework");

                Type ncrunchType =
                    ncrunchAssembly.GetTypes()
                    .FirstOrDefault(
                        type => type.Name.Equals("NCrunchEnvironment", StringComparison.InvariantCultureIgnoreCase));

                MethodInfo method = ncrunchType?.GetMethod("GetOriginalSolutionPath");

                string originalSolutionPath = method?.Invoke(null, null) as string;
                if (!string.IsNullOrWhiteSpace(originalSolutionPath))
                {
                    DirectoryInfo parent = new DirectoryInfo(originalSolutionPath).Parent;
                    return(VcsPathHelper.FindVcsRootPath(parent.FullName));
                }
            }
            catch (Exception)
            {
                // ignored
            }
            return(VcsPathHelper.FindVcsRootPath());
        }
コード例 #2
0
        private async Task <string> GetBaseDirectoryAsync(BootstrapStartOptions startOptions)
        {
            string baseDir;

            if (!string.IsNullOrWhiteSpace(startOptions.BaseDir) && Directory.Exists(startOptions.BaseDir))
            {
                _logger.Write($"Using base directory '{startOptions.BaseDir}' from start options", _Prefix);

                baseDir = startOptions.BaseDir;
            }
            else
            {
                if (IsBetterRunOnLocalTempStorage() && await IsCurrentDirectoryClonableAsync())
                {
                    string clonedDirectory = await CloneDirectoryAsync();

                    baseDir = clonedDirectory;
                }
                else
                {
                    baseDir = VcsPathHelper.FindVcsRootPath();
                }
            }

            return(baseDir);
        }
コード例 #3
0
        private async Task <ExitCode> ExecuteAsync(ImmutableArray <string> args)
        {
            bool whatIf = args.Any(arg => arg.Equals(ConfigurationKeys.WhatIf, StringComparison.OrdinalIgnoreCase));

            bool deleteEmptyDirectories = args.Any(arg => arg.Equals(
                                                       ConfigurationKeys.DeleteEmptyDirectories,
                                                       StringComparison.OrdinalIgnoreCase));

            ImmutableArray <string> exclusions = new[] { ".git", ".vs" }.ToImmutableArray();

            ImmutableArray <string> targets = new[] { "obj", "bin", "temp", "tmp", "artifacts", "arbor.x" }
            .ToImmutableArray();

            string baseDirectory = args.FirstOrDefault(arg => !arg.StartsWith(
                                                           "-",
                                                           StringComparison.OrdinalIgnoreCase)) ??
                                   VcsPathHelper.FindVcsRootPath(Directory.GetCurrentDirectory());

            ImmutableArray <string> fileExtensionsToDelete = new[] { ".tmp", ".cache", ".orig" }.ToImmutableArray();

            var options = new Options(
                baseDirectory,
                exclusions,
                targets,
                fileExtensionsToDelete,
                whatIf,
                deleteEmptyDirectories);

            return(await ExecuteAsync(options));
        }
コード例 #4
0
        private async Task <BootstrapStartOptions> StartWithDebuggerAsync([NotNull] string[] args)
        {
            if (args == null)
            {
                throw new ArgumentNullException(nameof(args));
            }

            string baseDir = VcsPathHelper.FindVcsRootPath(AppDomain.CurrentDomain.BaseDirectory);

            var tempDirectory = new DirectoryInfo(Path.Combine(
                                                      Path.GetTempPath(),
                                                      $"{DefaultPaths.TempPathPrefix}_Boot_Debug",
                                                      DateTime.Now.ToString("yyyyMMddHHmmssfff")));

            tempDirectory.EnsureExists();

            WriteDebug($"Using temp directory '{tempDirectory}'");

            await DirectoryCopy.CopyAsync(baseDir, tempDirectory.FullName);

            Environment.SetEnvironmentVariable(WellKnownVariables.BranchNameVersionOverrideEnabled, "true");
            Environment.SetEnvironmentVariable(WellKnownVariables.VariableOverrideEnabled, "true");

            var bootstrapStartOptions = new BootstrapStartOptions(
                tempDirectory.FullName,
                true,
                "refs/heads/develop/12.34.56");

            WriteDebug("Starting with debugger attached");

            return(bootstrapStartOptions);
        }
コード例 #5
0
        public static string FindVcsRootPath()
        {
            try
            {
                Assembly ncrunchAssembly = AppDomain.CurrentDomain.Load("NCrunch.Framework");

                Type ncrunchType =
                    ncrunchAssembly.GetTypes()
                    .FirstOrDefault(
                        type => type.Name.Equals("NCrunchEnvironment",
                                                 StringComparison.InvariantCultureIgnoreCase));

                MethodInfo method = ncrunchType?.GetMethod("GetOriginalSolutionPath");

                string originalSolutionPath = method?.Invoke(null, null) as string;

                if (!string.IsNullOrWhiteSpace(originalSolutionPath))
                {
                    DirectoryInfo parent = new DirectoryInfo(originalSolutionPath).Parent;
                    if (parent != null)
                    {
                        return(VcsPathHelper.FindVcsRootPath(parent.FullName));
                    }
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                Console.WriteLine("Could not find NCrunch original solution path, {0}", ex);
#endif
            }

            return(VcsPathHelper.FindVcsRootPath());
        }
コード例 #6
0
        private async Task <bool> IsCurrentDirectoryClonableAsync()
        {
            if (!_directoryCloneEnabled)
            {
                _logger.WriteVerbose("Directory clone is disabled");
                return(false);
            }

            _logger.WriteVerbose("Directory clone is enabled");

            string sourceRoot = VcsPathHelper.TryFindVcsRootPath();

            if (string.IsNullOrWhiteSpace(sourceRoot))
            {
                _logger.WriteWarning("Could not find source root", _Prefix);
                return(false);
            }

            bool isClonable = false;

            string gitExePath = GitHelper.GetGitExePath(_logger);

            if (!string.IsNullOrWhiteSpace(gitExePath))
            {
                string gitDir = Path.Combine(sourceRoot, ".git");

                var statusAllArguments = new[]
                {
                    $"--git-dir={gitDir}",
                    $"--work-tree={sourceRoot}",
                    "status"
                };

                var argumentVariants = new List <string[]> {
                    new[] { "status" }, statusAllArguments
                };

                foreach (string[] argumentVariant in argumentVariants)
                {
                    ExitCode statusExitCode = await ProcessRunner.ExecuteAsync(
                        gitExePath,
                        arguments : argumentVariant,
                        standardOutLog : _logger.WriteVerbose,
                        standardErrorAction : _logger.WriteVerbose,
                        toolAction : _logger.Write,
                        verboseAction : _logger.WriteVerbose);

                    if (statusExitCode.IsSuccess)
                    {
                        isClonable = true;
                        break;
                    }
                }
            }

            _logger.WriteVerbose($"Is directory clonable: {isClonable}");

            return(isClonable);
        }
コード例 #7
0
        public static string?TryFindVcsRootPath(Action <string>?logger = null)
        {
            if (NCrunchEnvironment.NCrunchIsResident())
            {
                var originalSolutionFileInfo = new FileInfo(NCrunchEnvironment.GetOriginalSolutionPath());
                return(VcsPathHelper.TryFindVcsRootPath(originalSolutionFileInfo.Directory?.FullName, logger));
            }

            return(VcsPathHelper.TryFindVcsRootPath(logger: logger));
        }
コード例 #8
0
        public static string FindVcsRootPath()
        {
            if (NCrunchEnvironment.NCrunchIsResident())
            {
                var directory = new FileInfo(NCrunchEnvironment.GetOriginalSolutionPath()).Directory;

                return(VcsPathHelper.FindVcsRootPath(directory?.FullName));
            }

            return(VcsPathHelper.FindVcsRootPath());
        }
コード例 #9
0
        public static string FindVcsRootPath(string baseDir = null)
        {
            if (NCrunchEnvironment.NCrunchIsResident())
            {
                var fileInfo = new FileInfo(NCrunchEnvironment.GetOriginalSolutionPath());

                return(VcsPathHelper.FindVcsRootPath(fileInfo.Directory?.FullName));
            }

            return(VcsPathHelper.FindVcsRootPath(baseDir));
        }
コード例 #10
0
        public Task <IEnumerable <IVariable> > GetEnvironmentVariablesAsync(
            ILogger logger,
            IReadOnlyCollection <IVariable> buildVariables,
            CancellationToken cancellationToken)
        {
            string existingSourceRoot =
                buildVariables.GetVariableValueOrDefault(WellKnownVariables.SourceRoot, string.Empty);

            string existingToolsDirectory =
                buildVariables.GetVariableValueOrDefault(WellKnownVariables.ExternalTools, string.Empty);
            string sourceRoot;

            if (!string.IsNullOrWhiteSpace(existingSourceRoot))
            {
                if (!Directory.Exists(existingSourceRoot))
                {
                    throw new InvalidOperationException(
                              $"The defined variable {WellKnownVariables.SourceRoot} has value set to '{existingSourceRoot}' but the directory does not exist");
                }

                sourceRoot = existingSourceRoot;
            }
            else
            {
                sourceRoot = VcsPathHelper.FindVcsRootPath();
            }

            DirectoryInfo tempPath = new DirectoryInfo(Path.Combine(sourceRoot, "temp")).EnsureExists();

            var variables = new List <IVariable>
            {
                new EnvironmentVariable(
                    WellKnownVariables.TempDirectory,
                    tempPath.FullName)
            };

            if (string.IsNullOrWhiteSpace(existingSourceRoot))
            {
                variables.Add(new EnvironmentVariable(WellKnownVariables.SourceRoot, sourceRoot));
            }

            if (string.IsNullOrWhiteSpace(existingToolsDirectory))
            {
                DirectoryInfo externalTools =
                    new DirectoryInfo(Path.Combine(sourceRoot, "build", "Arbor.X", "tools", "external")).EnsureExists();

                variables.Add(new EnvironmentVariable(
                                  WellKnownVariables.ExternalTools,
                                  externalTools.FullName));
            }

            return(Task.FromResult <IEnumerable <IVariable> >(variables));
        }
コード例 #11
0
        public static string GetRootDirectory(string?basePath = null)
        {
            string originalSolutionPath = NCrunchEnvironment.GetOriginalSolutionPath();

            if (!string.IsNullOrWhiteSpace(originalSolutionPath))
            {
                var fileInfo = new FileInfo(originalSolutionPath);
                return(VcsPathHelper.FindVcsRootPath(fileInfo.Directory?.FullName ?? Directory.GetCurrentDirectory()));
            }

            return(VcsPathHelper.FindVcsRootPath(basePath ?? new FileInfo(typeof(VcsTestPathHelper).Assembly.Location).DirectoryName ?? Directory.GetCurrentDirectory()));
        }
コード例 #12
0
        public static string GetRootDirectory()
        {
            string originalSolutionPath = NCrunch.Framework.NCrunchEnvironment.GetOriginalSolutionPath();

            if (!string.IsNullOrWhiteSpace(originalSolutionPath))
            {
                var fileInfo = new FileInfo(originalSolutionPath);
                return(VcsPathHelper.FindVcsRootPath(fileInfo.Directory?.FullName ?? Directory.GetCurrentDirectory()));
            }

            return(VcsPathHelper.FindVcsRootPath(Directory.GetCurrentDirectory()));
        }
コード例 #13
0
        private async Task <string> CloneDirectoryAsync()
        {
            string targetDirectoryPath = Path.Combine(
                Path.GetTempPath(),
                DefaultPaths.TempPathPrefix,
                "R",
                Guid.NewGuid().ToString().Substring(0, 8));

            var targetDirectory = new DirectoryInfo(targetDirectoryPath);

            targetDirectory.EnsureExists();

            string gitExePath = GitHelper.GetGitExePath(_logger);

            string sourceRoot = VcsPathHelper.TryFindVcsRootPath();

            IEnumerable <string> cloneArguments = new List <string>
            {
                "clone",
                sourceRoot,
                targetDirectory.FullName
            };

            _logger.WriteVerbose($"Using temp storage to clone: '{targetDirectory.FullName}'", _Prefix);

            ExitCode cloneExitCode = await ProcessHelper.ExecuteAsync(
                gitExePath,
                cloneArguments,
                _logger,
                addProcessNameAsLogCategory : true,
                addProcessRunnerCategory : true,
                parentPrefix : _Prefix);

            if (!cloneExitCode.IsSuccess)
            {
                throw new InvalidOperationException(
                          $"Could not clone directory '{sourceRoot}' to '{targetDirectory.FullName}'");
            }

            return(targetDirectory.FullName);
        }
コード例 #14
0
        public static ExitCode SetEnvironmentVariablesFromFile([NotNull] ILogger logger, string fileName)
        {
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            string currentDirectory = VcsPathHelper.FindVcsRootPath();

            if (currentDirectory == null)
            {
                logger.WriteError("Could not find source root");
                return(ExitCode.Failure);
            }

            var fileInfo = new FileInfo(Path.Combine(currentDirectory, fileName));

            if (!fileInfo.Exists)
            {
                logger.WriteWarning(
                    $"The environment variable file '{fileInfo}' does not exist, skipping setting environment variables from file '{fileName}'");
                return(ExitCode.Success);
            }

            ConfigurationItems configurationItems;

            try
            {
                configurationItems = new KVConfiguration.JsonConfiguration.JsonFileReader(fileInfo.FullName)
                                     .GetConfigurationItems();
            }
            catch (Exception ex) when(!ex.IsFatal())
            {
                logger.WriteError($"Could not parse key value pairs in file '{fileInfo.FullName}', {ex}");
                return(ExitCode.Failure);
            }

            if (configurationItems == null)
            {
                logger.WriteError($"Could not parse key value pairs in file '{fileInfo.FullName}'");
                return(ExitCode.Failure);
            }

            foreach (KeyValue keyValuePair in configurationItems.Keys)
            {
                try
                {
                    Environment.SetEnvironmentVariable(keyValuePair.Key, keyValuePair.Value);
                    logger.WriteDebug(
                        $"Set environment variable with key '{keyValuePair.Key}' and value '{keyValuePair.Value}' from file '{fileName}'");
                }
                catch (Exception ex) when(!ex.IsFatal())
                {
                    logger.WriteError(
                        $"Could not set environment variable with key '{keyValuePair.Key}' and value '{keyValuePair.Value}' from file '{fileName}'");
                    return(ExitCode.Failure);
                }
            }

            logger.Write($"Used configuration values from file '{fileName}'");

            return(ExitCode.Success);
        }