private static void CloneRespository(EscrowElement element, string elementPath, List <GitCredential> credentialList)
 {
     if (!string.IsNullOrWhiteSpace(element.VersionControlHash))
     {
         var uriBuilder = new UriBuilder(element.VersionControlServer);
         uriBuilder.Path = GetFixedVersionControlPath(element) + ".git";
         var gitRepo = new GitRepositoryHttp(uriBuilder.Uri.ToString(), elementPath, string.Empty,
                                             credentialList);
         try
         {
             gitRepo.Clone(new CloneOptions {
                 RecurseSubmodules = true, BranchName = element.VersionControlBranch
             });
         }
         catch (Exception ex)
         {
             Log.Error($"Failure during cloning: Exception: {ex} \nStackTrace: \n{ex.StackTraceEx()}");
             var checkoutFolder = new DirectoryInfo(elementPath);
             checkoutFolder.Delete(true);
             gitRepo.Clone(new CloneOptions {
                 RecurseSubmodules = false, BranchName = element.VersionControlBranch
             });
         }
         gitRepo.AddBranch($"Escrow-{element.Number}", element.VersionControlHash);
         gitRepo.CheckoutBranch($"Escrow-{element.Number}");
     }
 }
        private async Task ResolveDependenciesInternal(string buildConfigId, EscrowElement escrowElement)
        {
            Log.Info("Resolving dependencies for: {0} : {1}", buildConfigId, escrowElement.Number);

            BuildConfig buildConfig = await _client.BuildConfigs.GetByConfigurationId(buildConfigId);

            var tasks = buildConfig.ArtifactDependencies.Select(ad => ResolveDependency(ad, escrowElement));

            await Task.WhenAll(tasks);
        }
        public async Task <bool> ResolveDependencies(string id, EscrowElement escrowElement)
        {
            await ResolveDependenciesInternal(id, escrowElement);

            _downloadDataFlow.Complete();

            await _downloadDataFlow.Completion;

            return(true);
        }
        private async Task ResolveDependency(DependencyDefinition dependency, EscrowElement escrowElement)
        {
            Log.Debug("Trying to fetch dependency: {0}", dependency.SourceBuildConfig.Id);

            if (_builds.ContainsKey(dependency.SourceBuildConfig.Id))
            {
                Log.Info("Dependency already fetched. Skipping: {0}", dependency.SourceBuildConfig.Id);
                return;
            }

            EscrowArtifactDependency escrowArtifact =
                escrowElement.ArtifactDependencies.FirstOrDefault(x => x.BuildTypeId == dependency.SourceBuildConfig.Id);

            if (escrowArtifact == null)
            {
                Log.Info("Cannot find dependency defined in escrow docucment: {0}", dependency.SourceBuildConfig.Id);
                return;
            }

            Build build = await _client.Builds.ById(escrowArtifact.Id);

            lock (_builds)
            {
                _builds.Add(build.BuildTypeId, BuildInfo.FromBuild(build));
            }

            Log.Debug("Downloading artifacts from: {0}-{1}", build.BuildTypeId, build.Number);

            List <ArtifactRule> artifactRules = GetArtifactRules(dependency);

            string basePath = _fileSystem.GetWorkingDirectory();

            if (string.IsNullOrWhiteSpace(basePath))
            {
                basePath = ".";
            }

            List <PathFilePair> files = new List <PathFilePair>();

            foreach (ArtifactRule artifactRule in artifactRules)
            {
                files.AddRange(await FetchFileListForArtifactRule(artifactRule, build, basePath));
            }

            DownloadFiles(files);

            Log.Debug("Done fetching dependency for: {0}", dependency.SourceBuildConfig.Id);
        }
        private static string GetFixedVersionControlPath(EscrowElement element)
        {
            if (element.VersionControlPath.Contains("%system.teamcity.projectName%"))
            {
                string[] projectNameParts;
                if (element.ProjectName.Contains("::"))
                {
                    projectNameParts = element.ProjectName.Split(new string[] { "::" }, StringSplitOptions.None);
                }
                else
                {
                    projectNameParts = element.ProjectName.Split(new string[] { "/" }, StringSplitOptions.None);
                }

                element.VersionControlPath = element.VersionControlPath.Replace("%system.teamcity.projectName%", projectNameParts[projectNameParts.Length - 1].Replace(" ", "").Trim());
                return(element.VersionControlPath);
            }
            return(element.VersionControlPath);
        }
        private async Task FetchArtifactDependencies(string elementPath, EscrowElement element)
        {
            _downloadDataFlow = new DownloadDataFlow(_downloader);
            _builds.Clear();
            var currentDirectory = Directory.GetCurrentDirectory();

            try
            {
                if (!Directory.Exists(elementPath))
                {
                    Directory.CreateDirectory(elementPath);
                }

                Directory.SetCurrentDirectory(elementPath);
                await ResolveDependencies(element.BuildTypeId, element);
            }
            finally
            {
                Directory.SetCurrentDirectory(currentDirectory);
            }
        }
        private void FetchNuGetPackages(string outputPath, string elementPath, EscrowElement element)
        {
            var directoryInfo = new DirectoryInfo(elementPath);

            foreach (var solutionFile in directoryInfo.EnumerateFiles("*.sln", SearchOption.AllDirectories))
            {
                System.Diagnostics.Process          process   = new System.Diagnostics.Process();
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                startInfo.FileName    = Path.Combine(outputPath, "nuget.exe");

                startInfo.Arguments = $"restore \"{solutionFile.FullName}\"";
                startInfo.RedirectStandardOutput = true;
                startInfo.UseShellExecute        = false;
                process.StartInfo = startInfo;
                process.Start();
                var output = process.StandardOutput.ReadToEnd();
                Log.Info(output);
                process.WaitForExit();
            }
        }
        private async Task FetchBuildArtifacts(EscrowElement element, string elementPath)
        {
            Log.Info($"Fetch build Artifacts: for {element.BuildTypeId}");
            var directoryInfo = new DirectoryInfo(elementPath);

            if (directoryInfo.Exists == false)
            {
                _fileSystem.CreateDirectory(elementPath);
            }

            string artifactOutputPath = _fileSystem.CombinePath(elementPath, "build");

            _fileSystem.EnsureDirectoryExists(artifactOutputPath);
            await
            _downloadCommand.Execute(new GetArtifactOptions
            {
                BuildConfigId   = element.BuildTypeId,
                BuildId         = element.Id,
                Tag             = string.Empty,
                OutputDirectory = artifactOutputPath
            });
        }