Example #1
0
        /// <summary>
        /// Initializes endpoints in the supplied <paramref name="configuration"/> based on the
        /// properties of the specified <paramref name="configSection"/>
        /// </summary>
        /// <param name="configuration">The configuration to initialize</param>
        /// <param name="configSection">The configuration section containing the endpoint
        /// properties</param>
        protected virtual void InitializeEndpoints(TConfiguration configuration, PlatibusConfigurationSection configSection)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }
            if (configSection == null)
            {
                throw new ArgumentNullException(nameof(configSection));
            }

            IEnumerable <EndpointElement> endpoints = configSection.Endpoints;

            foreach (var endpointConfig in endpoints)
            {
                IEndpointCredentials credentials = null;
                switch (endpointConfig.CredentialType)
                {
                case ClientCredentialType.Basic:
                    var un = endpointConfig.Username;
                    var pw = endpointConfig.Password;
                    credentials = new BasicAuthCredentials(un, pw);
                    break;

                case ClientCredentialType.Windows:
                case ClientCredentialType.NTLM:
                    credentials = new DefaultCredentials();
                    break;
                }

                var endpoint = new Endpoint(endpointConfig.Address, credentials);
                configuration.AddEndpoint(endpointConfig.Name, endpoint);
            }
        }
            public string Update()
            {
                try
                {
                    GitCredentials = new DefaultCredentials();

                    using (var repo = new Repository(Path))
                    {
                        var gitSignature = new Signature(GitUsername, GitEmail, DateTimeOffset.Now);

                        // FETCH
                        Commands.Fetch(repo, "origin", new string[0], new FetchOptions {
                            CredentialsProvider = (_url, _user, _cred) => GitCredentials, TagFetchMode = TagFetchMode.All
                        }, null);

                        // MERGE
                        MergeResult result = repo.MergeFetchedRefs(gitSignature, new MergeOptions());
                    }
                }
                catch (Exception e)
                {
                    return(System.Web.HttpContext.Current.Request.IsLocal ? e.ToString() : "Failed");
                }

                return("Success");
            }
Example #3
0
        public void TestConstructor_ResetsCredentialsFromDefault()
        {
            const string account1Name      = "Account1";
            const string account1FilePath  = "c:\\account1.json";
            const string expectedProjectId = "Expected Project Id";
            var          account1          = new UserAccount {
                AccountName = account1Name
            };
            var defaultCredentials =
                new DefaultCredentials {
                AccountName = account1Name, ProjectId = expectedProjectId
            };

            _fileSystemMock.Setup(fs => fs.Directory.Exists(It.IsAny <string>())).Returns(true);
            _fileSystemMock.Setup(fs => fs.Directory.EnumerateFiles(It.IsAny <string>()))
            .Returns(new[] { account1FilePath });
            _fileSystemMock.Setup(fs => fs.File.ReadAllText(account1FilePath))
            .Returns(JsonConvert.SerializeObject(account1));
            _fileSystemMock.Setup(fs => fs.File.Exists(It.IsAny <string>())).Returns(true);
            _fileSystemMock
            .Setup(
                fs => fs.File.ReadAllText(
                    It.Is <string>(
                        s => s.EndsWith(CredentialsStore.DefaultCredentialsFileName, StringComparison.Ordinal))))
            .Returns(
                JsonConvert.SerializeObject(
                    defaultCredentials));

            _objectUnderTest = new CredentialsStore(_fileSystemMock.ToLazy());

            Assert.AreEqual(account1.AccountName, _objectUnderTest.CurrentAccount.AccountName);
            Assert.AreEqual(expectedProjectId, _objectUnderTest.CurrentProjectId);
        }
Example #4
0
        public void CanGetRemoteRepoContextWithHeadAtBranchName(string branchName)
        {
            // Arrange
            // Create a local repo to serve as the origin for our clone.

            var originRepoDir = TestGitRepoUtils.GetUniqueTempFolder("testOriginGitRepo");

            //Path.Combine(currentDir, "", Guid.NewGuid().ToString("N"));

            using (var testOriginRepo = TestGitRepoUtils.CreateRepoWithBranch(originRepoDir, branchName))
            {
                // Construct the arguments necessary for cloning this origin repo.
                var remoteArgs = new GitRemoteRepositoryContextFactory.RemoteRepoArgs();
                var creds      = new DefaultCredentials();
                remoteArgs.Credentials = creds;

                var desinationDirForClone = TestGitRepoUtils.GetUniqueTempFolder("testClonedGitRepo"); // Path.Combine(currentDir, "testClonedGitRepo", Guid.NewGuid().ToString("N"));
                remoteArgs.DestinationPath = desinationDirForClone;

                remoteArgs.Url = testOriginRepo.Info.Path; // This could be the Url of the git repo, but as this is a unit test, we are using a local file path.

                // This is the sut.
                var remoteRepoContextFactory = new GitRemoteRepositoryContextFactory(remoteArgs);

                using (var repoContext = remoteRepoContextFactory.GetRepositoryContext())
                {
                    // Act
                    repoContext.PrepareRemoteRepoForUse(branchName);

                    // The cloned repo should now be set to the specified branch name.
                    var currentBranch = repoContext.Repository.Head.CanonicalName;
                    currentBranch.ShouldEndWith(branchName);
                }
            }
        }
Example #5
0
        public void CanGetRemoteRepoContext()
        {
            // Arrange
            // 1. Create a local repo to serve as the source / origin for our clone.
            var          originRepoDir             = TestGitRepoUtils.GetUniqueTempFolder("testOriginGitRepo");
            var          testOriginRepo            = TestGitRepoUtils.CreateEmptyTestRepo(originRepoDir);
            const string expectedDefaultBranchName = "master";

            // Construct the arguments necessary for cloning the origin repo.
            var remoteArgs = new GitRemoteRepositoryContextFactory.RemoteRepoArgs();
            var creds      = new DefaultCredentials();

            remoteArgs.Credentials = creds;
            var desinationDirForClone = TestGitRepoUtils.GetUniqueTempFolder("testClonedGitRepo"); // Path.Combine(currentDir, "testClonedGitRepo", Guid.NewGuid().ToString("N"));

            remoteArgs.DestinationPath = desinationDirForClone;
            remoteArgs.Url             = testOriginRepo.Info.Path; // This could be the Url of the git repo, but as this is a unit test, we are using a local file path.

            var remoteRepoContextFactory = new GitRemoteRepositoryContextFactory(remoteArgs);

            // Act
            using (var repoContext = remoteRepoContextFactory.GetRepositoryContext())
            {
                // Assert
                repoContext.IsRemote.ShouldBe(true);
                Directory.Exists(Path.Combine(desinationDirForClone, ".git")).ShouldBe(true);

                var currentBranch = repoContext.Repository.Head.CanonicalName;
                currentBranch.ShouldEndWith(expectedDefaultBranchName); // cloned repo should default to master branch.
            }
        }
 public void Visit(DefaultCredentials credentials)
 {
     if (_newHandler)
     {
         // We can only modify the handler if it has not started (i.e. no requests have
         // been sent)
         _clientHandler.UseDefaultCredentials = true;
     }
 }
Example #7
0
 public bool GetCredentials(string url, string user, SupportedCredentialTypes supportedCredentials, out Credentials credentials, out string message)
 {
     try
     {
         credentials = GetCredentialsFromTerminal(url);
         message     = "[WindowsCredentialManager] Recieved credentials";
         return(true);
     }
     catch (Exception e)
     {
         credentials = new DefaultCredentials();
         //This is a hack to get the exception information out. since Lib2GitSharp keeps eating it!
         message = "[WindowsCredentialManager] Exception getting credentials: " + e.Message;
         return(false);
     }
 }
Example #8
0
        public void CanGetRemoteRepoContextAndCheckoutReleaseNotesIfExists(string branchName, bool shouldHaveReleaseNotesFile)
        {
            // Arrange
            // Create a local repo to serve as the origin for our clone, - with a release notes file.
            var currentDir    = Environment.CurrentDirectory;
            var originRepoDir = TestGitRepoUtils.GetUniqueTempFolder("testOriginGitRepo");

            using (var testOriginRepo = TestGitRepoUtils.CreateRepoWithBranch(originRepoDir, branchName))
            {
                string releaseNotesFileName = Guid.NewGuid().ToString();
                // If a release notes file should be added, switch to the branch and add one.
                if (shouldHaveReleaseNotesFile)
                {
                    // switch head to the branch.
                    var branchInfo       = new GitBranchNameInfo(branchName);
                    var targetBranchName = branchInfo.GetCanonicalBranchName();
                    var newHead          = testOriginRepo.Refs.FirstOrDefault(localRef => string.Equals(localRef.CanonicalName, targetBranchName));
                    testOriginRepo.Refs.UpdateTarget(testOriginRepo.Refs.Head, newHead);

                    // commit a releasenotes file to the branch.
                    var releaseNotesFilePath = Path.Combine(testOriginRepo.Info.WorkingDirectory, releaseNotesFileName);
                    File.WriteAllText(releaseNotesFilePath, @"Some customised release notes contents...");
                    TestGitRepoUtils.CommitFile(testOriginRepo, releaseNotesFilePath, "Added test release notes file to repo");
                }

                // Construct the arguments necessary for cloning the origin repo.
                var remoteArgs = new GitRemoteRepositoryContextFactory.RemoteRepoArgs();
                var creds      = new DefaultCredentials();
                remoteArgs.Credentials = creds;
                var desinationDirForClone = TestGitRepoUtils.GetUniqueTempFolder("testClonedGitRepo"); // Path.Combine(currentDir, "testClonedGitRepo", Guid.NewGuid().ToString("N"));
                remoteArgs.DestinationPath = desinationDirForClone;
                remoteArgs.Url             = testOriginRepo.Info.Path;                                 // This could be the Url of the git repo, but as this is a unit test, we are using a local file path.

                var remoteRepoContextFactory = new GitRemoteRepositoryContextFactory(remoteArgs);
                using (var repoContext = remoteRepoContextFactory.GetRepositoryContext())
                {
                    repoContext.PrepareRemoteRepoForUse(branchName);

                    // Act.
                    repoContext.CheckoutFilesIfExist(releaseNotesFileName);

                    // Assert.
                    var releaseNotesFilePath = Path.Combine(desinationDirForClone, releaseNotesFileName);
                    File.Exists(releaseNotesFilePath).ShouldBe(shouldHaveReleaseNotesFile);
                }
            }
        }
Example #9
0
        /// <summary>
        /// Initialize a credentials object from config for a repository.
        /// </summary>
        private static Credentials GetCredentials(Business.Config.Repository repoConfig)
        {
            Credentials creds = null;

            if (repoConfig.useDefaultCredentials)
            {
                creds = new DefaultCredentials();
            }
            else
            {
                creds = new UsernamePasswordCredentials
                {
                    Username = repoConfig.username,
                    Password = repoConfig.password
                };
            }

            return(creds);
        }
Example #10
0
        /// <summary>
        /// Initializes endpoints in the supplied <paramref name="platibusConfiguration"/> based on the
        /// properties of the specified <paramref name="configuration"/>
        /// </summary>
        /// <param name="platibusConfiguration">The configuration to initialize</param>
        /// <param name="configuration">The configuration section containing the endpoint
        /// properties</param>
        protected virtual void InitializeEndpoints(TConfiguration platibusConfiguration, IConfiguration configuration)
        {
            if (platibusConfiguration == null)
            {
                throw new ArgumentNullException(nameof(platibusConfiguration));
            }
            var endpointsSection = configuration?.GetSection("endpoints");

            if (endpointsSection == null)
            {
                return;
            }

            foreach (var endpointSection in endpointsSection.GetChildren())
            {
                var name = endpointSection.Key ??
                           endpointSection["name"];

                var credentialType = endpointSection.GetValue <ClientCredentialType>("credentialType");
                IEndpointCredentials credentials = null;
                switch (credentialType)
                {
                case ClientCredentialType.Basic:
                    var un = endpointSection["username"];
                    var pw = endpointSection["password"];
                    credentials = new BasicAuthCredentials(un, pw);
                    break;

                case ClientCredentialType.Windows:
                case ClientCredentialType.NTLM:
                    credentials = new DefaultCredentials();
                    break;
                }

                var address  = endpointSection.GetValue <Uri>("address");
                var endpoint = new Endpoint(address, credentials);
                platibusConfiguration.AddEndpoint(name, endpoint);
            }
        }
        private void UpdateDefaultCredentials()
        {
            var path = Path.Combine(s_credentialsStoreRoot, DefaultCredentialsFileName);

            if (CurrentAccount?.AccountName != null)
            {
                var defaultCredentials = new DefaultCredentials
                {
                    ProjectId = CurrentProjectId,
                    AccountName = CurrentAccount?.AccountName,
                };

                try
                {
                    Debug.WriteLine($"Updating default account: {path}");
                    AtomicFileWrite(path, JsonConvert.SerializeObject(defaultCredentials));
                }
                catch (IOException ex)
                {
                    Debug.WriteLine($"Failed to update default credentials: {ex.Message}");
                }
            }
            else
            {
                Debug.WriteLine($"Deleting default account: {path}");
                try
                {
                    File.Delete(path);
                }
                catch (IOException ex)
                {
                    Debug.WriteLine($"Failed to delete the default credentials: {ex.Message}");
                }
            }
        }
        private static bool IsExpectedCredentialsJson(string s, string accountName, string projectId)
        {
            DefaultCredentials credentials = JsonConvert.DeserializeObject <DefaultCredentials>(s);

            return(credentials.AccountName == accountName && credentials.ProjectId == projectId);
        }