Exemple #1
0
        public static VersionVariables ExecuteGitVersion(IFileSystem fileSystem, string targetUrl, string dynamicRepositoryLocation, Authentication authentication, string targetBranch, bool noFetch, string workingDirectory, string commitId)
        {
            // Normalise if we are running on build server
            var gitPreparer = new GitPreparer(targetUrl, dynamicRepositoryLocation, authentication, noFetch, workingDirectory);
            var applicableBuildServers = BuildServerList.GetApplicableBuildServers();
            var buildServer = applicableBuildServers.FirstOrDefault();
            var currentBranch = buildServer == null ? null : buildServer.GetCurrentBranch();
            if (!string.IsNullOrEmpty(currentBranch))
            {
                Logger.WriteInfo("Branch from build environment: " + currentBranch);
            }
            gitPreparer.Initialise(buildServer != null, currentBranch ?? targetBranch);
            var dotGitDirectory = gitPreparer.GetDotGitDirectory();
            var projectRoot = gitPreparer.GetProjectRootDirectory();
            Logger.WriteInfo(string.Format("Project root is: " + projectRoot));
            if (string.IsNullOrEmpty(dotGitDirectory) || string.IsNullOrEmpty(projectRoot))
            {
                // TODO Link to wiki article
                throw new Exception(string.Format("Failed to prepare or find the .git directory in path '{0}'.", workingDirectory));
            }
            VersionVariables variables;
            var versionFinder = new GitVersionFinder();
            var configuration = ConfigurationProvider.Provide(projectRoot, fileSystem);

            using (var repo = RepositoryLoader.GetRepo(dotGitDirectory))
            {
                var gitVersionContext = new GitVersionContext(repo, configuration, commitId: commitId);
                var semanticVersion = versionFinder.FindVersion(gitVersionContext);
                var config = gitVersionContext.Configuration;
                variables = VariableProvider.GetVariablesFor(semanticVersion, config.AssemblyVersioningScheme, config.VersioningMode, config.ContinuousDeploymentFallbackTag, gitVersionContext.IsCurrentCommitTagged);
            }

            return variables;
        }
Exemple #2
0
 public Arguments()
 {
     Authentication = new Authentication();
     OverrideConfig = new Config();
     Output = OutputType.Json;
     UpdateAssemblyInfoFileName = new HashSet<string>();
 }
        public VersionVariables ExecuteGitVersion(string targetUrl, string dynamicRepositoryLocation, Authentication authentication, string targetBranch, bool noFetch, string workingDirectory, string commitId)
        {
            // Normalise if we are running on build server
            var applicableBuildServers = BuildServerList.GetApplicableBuildServers();
            var buildServer = applicableBuildServers.FirstOrDefault();
            var fetch = noFetch || (buildServer != null && buildServer.PreventFetch());
            var gitPreparer = new GitPreparer(targetUrl, dynamicRepositoryLocation, authentication, fetch, workingDirectory);
            var dotGitDirectory = gitPreparer.GetDotGitDirectory();
            var projectRoot = gitPreparer.GetProjectRootDirectory();
            Logger.WriteInfo(string.Format("Project root is: " + projectRoot));
            if (string.IsNullOrEmpty(dotGitDirectory) || string.IsNullOrEmpty(projectRoot))
            {
                // TODO Link to wiki article
                throw new Exception(string.Format("Failed to prepare or find the .git directory in path '{0}'.", workingDirectory));
            }
            
            using (var repo = GetRepository(dotGitDirectory))
            {
                var versionVariables = gitVersionCache.LoadVersionVariablesFromDiskCache(repo, dotGitDirectory);
                if (versionVariables == null)
                {
                    versionVariables = ExecuteInternal(targetBranch, commitId, repo, gitPreparer, projectRoot, buildServer);
                    gitVersionCache.WriteVariablesToDiskCache(repo, dotGitDirectory, versionVariables);
                }

                return versionVariables;
            }
        }
Exemple #4
0
        public static void NormalizeGitDirectory(string gitDirectory, Authentication authentication, string branch = null)
        {
            using (var repo = new Repository(gitDirectory))
            {
                var remote = EnsureOnlyOneRemoteIsDefined(repo);

                AddMissingRefSpecs(repo, remote);

                Logger.WriteInfo(string.Format("Fetching from remote '{0}' using the following refspecs: {1}.",
                    remote.Name, string.Join(", ", remote.FetchRefSpecs.Select(r => r.Specification))));

                var fetchOptions = BuildFetchOptions(authentication.Username, authentication.Password);
                repo.Network.Fetch(remote, fetchOptions);

                CreateMissingLocalBranchesFromRemoteTrackingOnes(repo, remote.Name);

                if (!repo.Info.IsHeadDetached)
                {
                    Logger.WriteInfo(string.Format("HEAD points at branch '{0}'.", repo.Refs.Head.TargetIdentifier));
                    return;
                }

                Logger.WriteInfo(string.Format("HEAD is detached and points at commit '{0}'.", repo.Refs.Head.TargetIdentifier));

                if (branch != null)
                {
                    Logger.WriteInfo(string.Format("Checking out local branch 'refs/heads/{0}'.", branch));
                    repo.Checkout("refs/heads/" + branch);
                }
                else
                {
                    CreateFakeBranchPointingAtThePullRequestTip(repo, authentication);
                }
            }
        }
Exemple #5
0
        static IEnumerable<IBuildServer> DefaultSelector(Authentication authentication)
        {
            if (BuildServers == null)
            {
                BuildServers = new List<IBuildServer>
                {
                    new ContinuaCi(authentication),
                    new TeamCity(authentication),
                    new AppVeyor(authentication)
                };
            }

            var buildServices = new List<IBuildServer>();

            foreach (var buildServer in BuildServers)
            {
                try
                {
                    if (buildServer.CanApplyToCurrentContext())
                    {
                        Logger.WriteInfo(string.Format("Applicable build agent found: '{0}'.", buildServer.GetType().Name));
                        buildServices.Add(buildServer);
                    }
                }
                catch (Exception ex)
                {
                    Logger.WriteWarning(string.Format("Failed to check build server '{0}': {1}", buildServer.GetType().Name, ex.Message));
                }
            }

            return buildServices;
        }
 public GitPreparer(string targetUrl, string dynamicRepositoryLocation, Authentication authentication, bool noFetch, string targetPath)
 {
     this.targetUrl = targetUrl;
     this.dynamicRepositoryLocation = dynamicRepositoryLocation;
     this.authentication = authentication;
     this.noFetch = noFetch;
     this.targetPath = targetPath.TrimEnd('/', '\\');
 }
Exemple #7
0
        public static void NormalizeGitDirectory(string gitDirectory, Authentication authentication, bool noFetch)
        {
            //If noFetch is enabled, then GitVersion will assume that the git repository is normalized before execution, so that fetching from remotes is not required.
            if (noFetch)
            {
                Logger.WriteInfo("Skipping fetching");
                return;
            }

            using (var repo = new Repository(gitDirectory))
            {
                var remote = EnsureOnlyOneRemoteIsDefined(repo);

                AddMissingRefSpecs(repo, remote);

                Logger.WriteInfo(string.Format("Fetching from remote '{0}' using the following refspecs: {1}.",
                    remote.Name, string.Join(", ", remote.FetchRefSpecs.Select(r => r.Specification))));

                var fetchOptions = BuildFetchOptions(authentication.Username, authentication.Password);
                repo.Network.Fetch(remote, fetchOptions);

                CreateMissingLocalBranchesFromRemoteTrackingOnes(repo, remote.Name);

                var headSha = repo.Refs.Head.TargetIdentifier;

                if (!repo.Info.IsHeadDetached)
                {
                    Logger.WriteInfo(string.Format("HEAD points at branch '{0}'.", headSha));
                    return;
                }

                Logger.WriteInfo(string.Format("HEAD is detached and points at commit '{0}'.", headSha));

                // In order to decide whether a fake branch is required or not, first check to see if any local branches have the same commit SHA of the head SHA.
                // If they do, go ahead and checkout that branch
                // If no, go ahead and check out a new branch, using the known commit SHA as the pointer
                var localBranchesWhereCommitShaIsHead = repo.Branches.Where(b => !b.IsRemote && b.Tip.Sha == headSha).ToList();

                if (localBranchesWhereCommitShaIsHead.Count > 1)
                {
                    var names = string.Join(", ", localBranchesWhereCommitShaIsHead.Select(r => r.CanonicalName));
                    var message = string.Format("Found more than one local branch pointing at the commit '{0}'. Unable to determine which one to use ({1}).", headSha, names);
                    throw new WarningException(message);
                }

                if (localBranchesWhereCommitShaIsHead.Count == 0)
                {
                    Logger.WriteInfo(string.Format("No local branch pointing at the commit '{0}'. Fake branch needs to be created.", headSha));
                    CreateFakeBranchPointingAtThePullRequestTip(repo, authentication);
                }
                else
                {
                    Logger.WriteInfo(string.Format("Checking out local branch 'refs/heads/{0}'.", localBranchesWhereCommitShaIsHead[0].Name));
                    repo.Branches[localBranchesWhereCommitShaIsHead[0].Name].Checkout();
                }
            }
        }
        public void InnerExecute()
        {
            SemanticVersion semanticVersion;
            if (!VersionAndBranchFinder.TryGetVersion(SolutionDirectory, out semanticVersion))
            {
                return;
            }

            var authentication = new Authentication();
            WriteIntegrationParameters(semanticVersion, BuildServerList.GetApplicableBuildServers(authentication));
        }
        public VersionVariables ExecuteGitVersion(string targetUrl, string dynamicRepositoryLocation, Authentication authentication, string targetBranch, bool noFetch, string workingDirectory, string commitId, Config overrideConfig = null, bool noCache = false)
        {
            // Normalise if we are running on build server
            var applicableBuildServers = BuildServerList.GetApplicableBuildServers();
            var buildServer = applicableBuildServers.FirstOrDefault();
            var fetch = noFetch || (buildServer != null && buildServer.PreventFetch());
            var gitPreparer = new GitPreparer(targetUrl, dynamicRepositoryLocation, authentication, fetch, workingDirectory);
            gitPreparer.Initialise(buildServer != null, ResolveCurrentBranch(buildServer, targetBranch, !string.IsNullOrWhiteSpace(dynamicRepositoryLocation)));
            var dotGitDirectory = gitPreparer.GetDotGitDirectory();
            var projectRoot = gitPreparer.GetProjectRootDirectory();

            // TODO Can't use this, it still needs work
            //var gitRepository = GitRepositoryFactory.CreateRepository(new RepositoryInfo
            //{
            //    Url = targetUrl,
            //    Branch = targetBranch,
            //    Authentication = new AuthenticationInfo
            //    {
            //        Username = authentication.Username,
            //        Password = authentication.Password
            //    },
            //    Directory = workingDirectory
            //});
            Logger.WriteInfo(string.Format("Project root is: {0}", projectRoot));
            Logger.WriteInfo(string.Format("DotGit directory is: {0}", dotGitDirectory));
            if (string.IsNullOrEmpty(dotGitDirectory) || string.IsNullOrEmpty(projectRoot))
            {
                // TODO Link to wiki article
                throw new Exception(string.Format("Failed to prepare or find the .git directory in path '{0}'.", workingDirectory));
            }

            var cacheKey = GitVersionCacheKeyFactory.Create(fileSystem, gitPreparer, overrideConfig);
            var versionVariables = noCache ? default(VersionVariables) : gitVersionCache.LoadVersionVariablesFromDiskCache(gitPreparer, cacheKey);
            if (versionVariables == null)
            {
                versionVariables = ExecuteInternal(targetBranch, commitId, gitPreparer, buildServer, overrideConfig);

                if (!noCache)
                {
                    try
                    {
                        gitVersionCache.WriteVariablesToDiskCache(gitPreparer, cacheKey, versionVariables);
                    }
                    catch (AggregateException e)
                    {
                        Logger.WriteWarning(string.Format("One or more exceptions during cache write:{0}{1}", Environment.NewLine, e));
                    }
                }
            }

            return versionVariables;
        }
        public void InnerExecute()
        {
            CachedVersion semanticVersion;
            var gitDirectory = GitDirFinder.TreeWalkForGitDir(SolutionDirectory);
            var configuration = ConfigurationProvider.Provide(gitDirectory, fileSystem);
            if (!VersionAndBranchFinder.TryGetVersion(SolutionDirectory, out semanticVersion, configuration))
            {
                return;
            }

            var authentication = new Authentication();
            WriteIntegrationParameters(semanticVersion, BuildServerList.GetApplicableBuildServers(authentication));
        }
 public bool TryGetVersion(string directory, out VersionVariables versionVariables, bool noFetch, Authentication authentication)
 {
     try
     {
         versionVariables = ExecuteGitVersion(null, null, authentication, null, noFetch, directory, null);
         return true;
     }
     catch (Exception ex)
     {
         Logger.WriteWarning("Could not determine assembly version: " + ex);
         versionVariables = null;
         return false;
     }
 }
Exemple #12
0
 public GitPreparer(string targetUrl, string dynamicRepositoryLocation, Authentication authentication, bool noFetch, string targetPath)
 {
     this.targetUrl = targetUrl;
     this.dynamicRepositoryLocation = dynamicRepositoryLocation;
     this.authentication = authentication == null ?
         null :
         new AuthenticationInfo
         {
             Username = authentication.Username,
             Password = authentication.Password
         };
     this.noFetch = noFetch;
     this.targetPath = targetPath.TrimEnd('/', '\\');
 }
Exemple #13
0
        public static int Main(string[] args)
        {
            Logger.SetLoggers(
                Console.WriteLine,
                Console.WriteLine,
                Console.WriteLine);

            var options = Options.Parse(args);

            if (options.Help)
            {
                Console.WriteLine(Options.GetHelpMessage());
                return(0);
            }

            if (options.NoFilesSpecified && !TryFindNetCoreProject(out options))
            {
                Console.Error.WriteLine($"Could not locate {ProjectJsonFile} or {CsprojFile} in current directory and no command line arguments were specified.");
                Console.WriteLine(Options.GetHelpMessage());
                return(-1);
            }

            var fs   = new FileSystem();
            var gv   = new GitVersion.ExecuteCore(fs);
            var auth = new GitVersion.Authentication();

            var version = gv.ExecuteGitVersion(null, null, auth, null, false, ".", null);

            Console.WriteLine($"Setting version: {version.LegacySemVerPadded}");

            if (!string.IsNullOrEmpty(options.ProjectJson))
            {
                UpdateProjectJson(options.ProjectJson, version.LegacySemVerPadded);
            }

            if (!string.IsNullOrEmpty(options.CsProj))
            {
                UpdateCsproj(options.CsProj, version.LegacySemVerPadded);
            }

            return(0);
        }
Exemple #14
0
        public VersionVariables ExecuteGitVersion(string targetUrl, string dynamicRepositoryLocation, Authentication authentication, string targetBranch, bool noFetch, string workingDirectory, string commitId, Config overrideConfig = null)
        {
            // Normalise if we are running on build server
            var applicableBuildServers = BuildServerList.GetApplicableBuildServers();
            var buildServer = applicableBuildServers.FirstOrDefault();
            var fetch = noFetch || (buildServer != null && buildServer.PreventFetch());
            var gitPreparer = new GitPreparer(targetUrl, dynamicRepositoryLocation, authentication, fetch, workingDirectory);
            var dotGitDirectory = gitPreparer.GetDotGitDirectory();
            var projectRoot = gitPreparer.GetProjectRootDirectory();

            // TODO Can't use this, it still needs work
            //var gitRepository = GitRepositoryFactory.CreateRepository(new RepositoryInfo
            //{
            //    Url = targetUrl,
            //    Branch = targetBranch,
            //    Authentication = new AuthenticationInfo
            //    {
            //        Username = authentication.Username,
            //        Password = authentication.Password
            //    },
            //    Directory = workingDirectory
            //});
            Logger.WriteInfo(string.Format("Project root is: " + projectRoot));
            if (string.IsNullOrEmpty(dotGitDirectory) || string.IsNullOrEmpty(projectRoot))
            {
                // TODO Link to wiki article
                throw new Exception(string.Format("Failed to prepare or find the .git directory in path '{0}'.", workingDirectory));
            }

            using (var repo = GetRepository(dotGitDirectory))
            {
                var versionVariables = gitVersionCache.LoadVersionVariablesFromDiskCache(repo, dotGitDirectory);
                if (versionVariables == null)
                {
                    versionVariables = ExecuteInternal(targetBranch, commitId, repo, gitPreparer, projectRoot, buildServer, overrideConfig: overrideConfig);
                    gitVersionCache.WriteVariablesToDiskCache(repo, dotGitDirectory, versionVariables);
                }

                return versionVariables;
            }
        }
Exemple #15
0
 public ContinuaCi(Authentication authentication)
 {
     this.authentication = authentication;
 }
        static string CreateDynamicRepository(string targetPath, Authentication authentication, string repositoryUrl, string targetBranch, bool noFetch)
        {
            if (string.IsNullOrWhiteSpace(targetBranch))
            {
                throw new Exception("Dynamic Git repositories must have a target branch (/b)");
            }
            Logger.WriteInfo(string.Format("Creating dynamic repository at '{0}'", targetPath));

            var gitDirectory = Path.Combine(targetPath, ".git");
            if (Directory.Exists(targetPath))
            {
                Logger.WriteInfo("Git repository already exists");
                GitHelper.NormalizeGitDirectory(gitDirectory, authentication, noFetch, targetBranch);

                return gitDirectory;
            }

            CloneRepository(repositoryUrl, gitDirectory, authentication);

            // Normalize (download branches) before using the branch
            GitHelper.NormalizeGitDirectory(gitDirectory, authentication, noFetch, targetBranch);

            return gitDirectory;
        }
        static void CloneRepository(string repositoryUrl, string gitDirectory, Authentication authentication)
        {
            Credentials credentials = null;
            if (!string.IsNullOrWhiteSpace(authentication.Username) && !string.IsNullOrWhiteSpace(authentication.Password))
            {
                Logger.WriteInfo(string.Format("Setting up credentials using name '{0}'", authentication.Username));

                credentials = new UsernamePasswordCredentials
                {
                    Username = authentication.Username,
                    Password = authentication.Password
                };
            }

            Logger.WriteInfo(string.Format("Retrieving git info from url '{0}'", repositoryUrl));

            try
            {
                var cloneOptions = new CloneOptions
                {
                    Checkout = false,
                    CredentialsProvider = (url, usernameFromUrl, types) => credentials
                };
                Repository.Clone(repositoryUrl, gitDirectory, cloneOptions);
            }
            catch (LibGit2SharpException ex)
            {
                var message = ex.Message;
                if (message.Contains("401"))
                {
                    throw new Exception("Unauthorised: Incorrect username/password");
                }
                if (message.Contains("403"))
                {
                    throw new Exception("Forbidden: Possbily Incorrect username/password");
                }
                if (message.Contains("404"))
                {
                    throw new Exception("Not found: The repository was not found");
                }

                throw new Exception("There was an unknown problem with the Git repository you provided");
            }
        }
 static IEnumerable<IBuildServer> GetApplicableBuildServers(Authentication authentication)
 {
     return BuildServerList.GetApplicableBuildServers(authentication);
 }
Exemple #19
0
        private static DirectReference GetRemoteReference(Repository repository, string branchName, string repositoryUrl, Authentication authentication)
        {
            var targetBranchName = branchName.GetCanonicalBranchName();

            var remoteReferences = GitHelper.GetRemoteTipsUsingUsernamePasswordCredentials(repository, repositoryUrl, authentication.Username, authentication.Password);
            return remoteReferences.FirstOrDefault(remoteRef => string.Equals(remoteRef.CanonicalName, targetBranchName));
        }
Exemple #20
0
        public static void NormalizeGitDirectory(string gitDirectory, Authentication authentication, bool noFetch, string currentBranch)
        {
            using (var repo = new Repository(gitDirectory))
            {
                var remote = EnsureOnlyOneRemoteIsDefined(repo);

                AddMissingRefSpecs(repo, remote);

                //If noFetch is enabled, then GitVersion will assume that the git repository is normalized before execution, so that fetching from remotes is not required.
                if (noFetch)
                {
                    Logger.WriteInfo("Skipping fetching, if GitVersion does not calculate your version as expected you might need to allow fetching or use dynamic repositories");
                }
                else
                {
                    Logger.WriteInfo(string.Format("Fetching from remote '{0}' using the following refspecs: {1}.",
                        remote.Name, string.Join(", ", remote.FetchRefSpecs.Select(r => r.Specification))));
                    var fetchOptions = BuildFetchOptions(authentication.Username, authentication.Password);
                    repo.Network.Fetch(remote, fetchOptions);
                }

                EnsureLocalBranchExistsForCurrentBranch(repo, currentBranch);
                CreateOrUpdateLocalBranchesFromRemoteTrackingOnes(repo, remote.Name);

                var headSha = repo.Refs.Head.TargetIdentifier;

                if (!repo.Info.IsHeadDetached)
                {
                    Logger.WriteInfo(string.Format("HEAD points at branch '{0}'.", headSha));
                    return;
                }

                Logger.WriteInfo(string.Format("HEAD is detached and points at commit '{0}'.", headSha));
                Logger.WriteInfo(string.Format("Local Refs:\r\n" + string.Join(Environment.NewLine, repo.Refs.FromGlob("*").Select(r => string.Format("{0} ({1})", r.CanonicalName, r.TargetIdentifier)))));

                // In order to decide whether a fake branch is required or not, first check to see if any local branches have the same commit SHA of the head SHA.
                // If they do, go ahead and checkout that branch
                // If no, go ahead and check out a new branch, using the known commit SHA as the pointer
                var localBranchesWhereCommitShaIsHead = repo.Branches.Where(b => !b.IsRemote && b.Tip.Sha == headSha).ToList();

                var matchingCurrentBranch = !string.IsNullOrEmpty(currentBranch)
                    ? localBranchesWhereCommitShaIsHead.SingleOrDefault(b => b.CanonicalName.Replace("/heads/", "/") == currentBranch.Replace("/heads/", "/"))
                    : null;
                if (matchingCurrentBranch != null)
                {
                    Logger.WriteInfo(string.Format("Checking out local branch '{0}'.", currentBranch));
                    repo.Checkout(matchingCurrentBranch);
                }
                else if (localBranchesWhereCommitShaIsHead.Count > 1)
                {
                    var branchNames = localBranchesWhereCommitShaIsHead.Select(r => r.CanonicalName);
                    var csvNames = string.Join(", ", branchNames);
                    const string moveBranchMsg = "Move one of the branches along a commit to remove warning";

                    Logger.WriteWarning(string.Format("Found more than one local branch pointing at the commit '{0}' ({1}).", headSha, csvNames));
                    var master = localBranchesWhereCommitShaIsHead.SingleOrDefault(n => n.Name == "master");
                    if (master != null)
                    {
                        Logger.WriteWarning("Because one of the branches is 'master', will build master." + moveBranchMsg);
                        repo.Checkout(master);
                    }
                    else
                    {
                        var branchesWithoutSeparators = localBranchesWhereCommitShaIsHead.Where(b => !b.Name.Contains('/') && !b.Name.Contains('-')).ToList();
                        if (branchesWithoutSeparators.Count == 1)
                        {
                            var branchWithoutSeparator = branchesWithoutSeparators[0];
                            Logger.WriteWarning(string.Format("Choosing {0} as it is the only branch without / or - in it. " + moveBranchMsg, branchWithoutSeparator.CanonicalName));
                            repo.Checkout(branchWithoutSeparator);
                        }
                        else
                        {
                            throw new WarningException("Failed to try and guess branch to use. " + moveBranchMsg);
                        }
                    }
                }
                else if (localBranchesWhereCommitShaIsHead.Count == 0)
                {
                    Logger.WriteInfo(string.Format("No local branch pointing at the commit '{0}'. Fake branch needs to be created.", headSha));
                    CreateFakeBranchPointingAtThePullRequestTip(repo, authentication);
                }
                else
                {
                    Logger.WriteInfo(string.Format("Checking out local branch 'refs/heads/{0}'.", localBranchesWhereCommitShaIsHead[0].Name));
                    repo.Checkout(repo.Branches[localBranchesWhereCommitShaIsHead[0].Name]);
                }
            }
        }
Exemple #21
0
 public TeamCity(Authentication authentication)
 {
     this.authentication = authentication;
 }
Exemple #22
0
        static string CreateDynamicRepository(string targetPath, Authentication authentication, string repositoryUrl, string targetBranch, bool noFetch)
        {
            Logger.WriteInfo(string.Format("Creating dynamic repository at '{0}'", targetPath));

            var gitDirectory = Path.Combine(targetPath, ".git");
            if (Directory.Exists(targetPath))
            {
                Logger.WriteInfo("Git repository already exists");
                GitHelper.NormalizeGitDirectory(gitDirectory, authentication, noFetch);
                Logger.WriteInfo(string.Format("Updating branch '{0}'", targetBranch));
                using (var repo = new Repository(targetPath))
                {
                    if (string.IsNullOrWhiteSpace(targetBranch))
                    {
                        throw new Exception("Dynamic Git repositories must have a target branch (/b)");
                    }
                    var targetGitBranch = repo.Branches[targetBranch];
                    var trackedBranch = targetGitBranch.TrackedBranch;
                    if (trackedBranch == null)
                        throw new InvalidOperationException(string.Format("Expecting {0} to have a remote tracking branch", targetBranch));

                    targetGitBranch.Checkout();
                    repo.Reset(ResetMode.Hard, trackedBranch.Tip);
                }

                return gitDirectory;
            }

            Credentials credentials = null;
            if (!string.IsNullOrWhiteSpace(authentication.Username) && !string.IsNullOrWhiteSpace(authentication.Password))
            {
                Logger.WriteInfo(string.Format("Setting up credentials using name '{0}'", authentication.Username));

                credentials = new UsernamePasswordCredentials
                {
                    Username = authentication.Username,
                    Password = authentication.Password
                };
            }

            Logger.WriteInfo(string.Format("Retrieving git info from url '{0}'", repositoryUrl));

            CloneRepository(repositoryUrl, gitDirectory, credentials);

            // Normalize (download branches) before using the branch
            GitHelper.NormalizeGitDirectory(gitDirectory, authentication, noFetch);

            using (var repository = new Repository(gitDirectory))
            {
                if (string.IsNullOrWhiteSpace(targetBranch))
                {
                    targetBranch = repository.Head.Name;
                }

                Reference newHead = null;

                var localReference = GetLocalReference(repository, targetBranch);
                if (localReference != null)
                {
                    newHead = localReference;
                }

                if (newHead == null)
                {
                    var remoteReference = GetRemoteReference(repository, targetBranch, repositoryUrl, authentication);
                    if (remoteReference != null)
                    {
                        repository.Network.Fetch(repositoryUrl, new[]
                            {
                                string.Format("{0}:{1}", remoteReference.CanonicalName, targetBranch)
                            });

                        newHead = repository.Refs[string.Format("refs/heads/{0}", targetBranch)];
                    }
                }

                if (newHead != null)
                {
                    Logger.WriteInfo(string.Format("Switching to branch '{0}'", targetBranch));

                    repository.Refs.UpdateTarget(repository.Refs.Head, newHead);
                }
            }

            return gitDirectory;
        }
Exemple #23
0
 public AppVeyor(Authentication authentication)
 {
     this.authentication = authentication;
 }
Exemple #24
0
        static void CreateFakeBranchPointingAtThePullRequestTip(Repository repo, Authentication authentication)
        {
            var remote = repo.Network.Remotes.Single();

            var remoteTips = string.IsNullOrEmpty(authentication.Username) ?
                GetRemoteTipsForAnonymousUser(repo, remote) :
                GetRemoteTipsUsingUsernamePasswordCredentials(repo, remote, authentication.Username, authentication.Password);

            var headTipSha = repo.Head.Tip.Sha;

            var refs = remoteTips.Where(r => r.TargetIdentifier == headTipSha).ToList();

            if (refs.Count == 0)
            {
                var message = string.Format("Couldn't find any remote tips from remote '{0}' pointing at the commit '{1}'.", remote.Url, headTipSha);
                throw new WarningException(message);
            }

            if (refs.Count > 1)
            {
                var names = string.Join(", ", refs.Select(r => r.CanonicalName));
                var message = string.Format("Found more than one remote tip from remote '{0}' pointing at the commit '{1}'. Unable to determine which one to use ({2}).", remote.Url, headTipSha, names);
                throw new WarningException(message);
            }

            var canonicalName = refs[0].CanonicalName;
            Logger.WriteInfo(string.Format("Found remote tip '{0}' pointing at the commit '{1}'.", canonicalName, headTipSha));

            if (!canonicalName.StartsWith("refs/pull/") && !canonicalName.StartsWith("refs/pull-requests/"))
            {
                var message = string.Format("Remote tip '{0}' from remote '{1}' doesn't look like a valid pull request.", canonicalName, remote.Url);
                throw new WarningException(message);
            }

            var fakeBranchName = canonicalName.Replace("refs/pull/", "refs/heads/pull/").Replace("refs/pull-requests/", "refs/heads/pull-requests/");

            Logger.WriteInfo(string.Format("Creating fake local branch '{0}'.", fakeBranchName));
            repo.Refs.Add(fakeBranchName, new ObjectId(headTipSha));

            Logger.WriteInfo(string.Format("Checking local branch '{0}' out.", fakeBranchName));
            repo.Checkout(fakeBranchName);
        }
Exemple #25
0
        static string CreateDynamicRepository(string targetPath, Authentication authentication, string repositoryUrl, string targetBranch, bool noFetch)
        {
            var gitDirectory = Path.Combine(targetPath, ".git");
            if (Directory.Exists(targetPath))
            {
                Logger.WriteInfo("Git repository already exists at {0}, skipping clone");

                return gitDirectory;
            }

            Credentials credentials = null;
            if (!string.IsNullOrWhiteSpace(authentication.Username) && !string.IsNullOrWhiteSpace(authentication.Password))
            {
                Logger.WriteInfo(string.Format("Setting up credentials using name '{0}'", authentication.Username));

                credentials = new UsernamePasswordCredentials
                {
                    Username = authentication.Username,
                    Password = authentication.Password
                };
            }

            Logger.WriteInfo(string.Format("Retrieving git info from url '{0}'", repositoryUrl));

            Repository.Clone(repositoryUrl, gitDirectory,
                new CloneOptions
                {
                    IsBare = true,
                    Checkout = false,
                    CredentialsProvider = (url, usernameFromUrl, types) => credentials
                });

            // Normalize (download branches) before using the branch
            GitHelper.NormalizeGitDirectory(gitDirectory, authentication, noFetch);

            using (var repository = new Repository(gitDirectory))
            {
                if (string.IsNullOrWhiteSpace(targetBranch))
                {
                    targetBranch = repository.Head.Name;
                }

                Reference newHead = null;

                var localReference = GetLocalReference(repository, targetBranch);
                if (localReference != null)
                {
                    newHead = localReference;
                }

                if (newHead == null)
                {
                    var remoteReference = GetRemoteReference(repository, targetBranch, repositoryUrl);
                    if (remoteReference != null)
                    {
                        repository.Network.Fetch(repositoryUrl, new[]
                            {
                                string.Format("{0}:{1}", remoteReference.CanonicalName, targetBranch)
                            });

                        newHead = repository.Refs[string.Format("refs/heads/{0}", targetBranch)];
                    }
                }

                if (newHead != null)
                {
                    Logger.WriteInfo(string.Format("Switching to branch '{0}'", targetBranch));

                    repository.Refs.UpdateTarget(repository.Refs.Head, newHead);
                }
            }

            return gitDirectory;
        }
Exemple #26
0
 public static IEnumerable<IBuildServer> GetApplicableBuildServers(Authentication authentication)
 {
     return Selector(authentication);
 }
Exemple #27
0
 public MyGet(Authentication authentication)
 {
     this.authentication = authentication;
 }