Exemplo n.º 1
0
        async Task <Repository> Create(Uri url, string organizationLogin, NewRepository newRepository)
        {
            try
            {
                return(await ApiConnection.Post <Repository>(url, newRepository));
            }
            catch (ApiValidationException e)
            {
                string errorMessage = e.ApiError.FirstErrorMessageSafe();

                if (String.Equals(
                        "name already exists on this account",
                        errorMessage,
                        StringComparison.OrdinalIgnoreCase))
                {
                    var baseAddress = Connection.BaseAddress.Host != GitHubClient.GitHubApiUrl.Host
                        ? Connection.BaseAddress
                        : new Uri("https://github.com/");
                    throw new RepositoryExistsException(
                              organizationLogin,
                              newRepository.Name,
                              baseAddress, e);
                }
                if (String.Equals(
                        "name can't be private. You are over your quota.",
                        errorMessage,
                        StringComparison.OrdinalIgnoreCase))
                {
                    throw new PrivateRepositoryQuotaExceededException(e);
                }
                throw;
            }
        }
    public DeploymentsClientTests()
    {
        var gitHubClient = Helper.GetAuthenticatedClient();

        _deploymentsClient = gitHubClient.Repository.Deployment;

        var newRepository = new NewRepository(Helper.MakeNameWithTimestamp("public-repo"))
        {
            AutoInit = true
        };

        _repository = gitHubClient.Repository.Create(newRepository).Result;
        _repositoryOwner = _repository.Owner.Login;

        var blob = new NewBlob
        {
            Content = "Hello World!",
            Encoding = EncodingType.Utf8
        };

        var blobResult = gitHubClient.GitDatabase.Blob.Create(_repositoryOwner, _repository.Name, blob).Result;

        var newTree = new NewTree();
        newTree.Tree.Add(new NewTreeItem
        {
            Type = TreeType.Blob,
            Mode = FileMode.File,
            Path = "README.md",
            Sha = blobResult.Sha
        });

        var treeResult = gitHubClient.GitDatabase.Tree.Create(_repositoryOwner, _repository.Name, newTree).Result;
        var newCommit = new NewCommit("test-commit", treeResult.Sha);
        _commit = gitHubClient.GitDatabase.Commit.Create(_repositoryOwner, _repository.Name, newCommit).Result;
    }
        public async Task<string> CreateAsync(string name)
        {
            var newRepo = new NewRepository(name) { AutoInit = true };

            var repository = await Client.Repository.Create(newRepo).ConfigureAwait(false);
            var newLabels =
                Configuration.repository.labels.Select(label => new NewLabel(label.name, label.color)).ToList();
            foreach (var newLabel in newLabels)
            {
                await Client.Issue.Labels.Create(repository.Owner.Login, repository.Name, newLabel).ConfigureAwait(false);
            }
            foreach (var branch in Configuration.repository.branches)
            {
                var master =
                    await
                        Client.GitDatabase.Reference.Get(repository.Owner.Login, repository.Name, "heads/master")
                            .ConfigureAwait(false);

                var reference = new NewReference($"refs/heads/{branch.Name}", master.Object.Sha);
                var createdReference = await
                    Client.GitDatabase.Reference.Create(repository.Owner.Login, repository.Name, reference)
                        .ConfigureAwait(false);
                if (branch.IsDefault)
                {
                    var repositoryUpdate = new RepositoryUpdate();
                    repositoryUpdate.Name = repository.Name;
                    repositoryUpdate.DefaultBranch = branch.Name;
                    await Client.Repository.Edit(repository.Owner.Login, repository.Name, repositoryUpdate).ConfigureAwait(false);
                }
            }

            return repository.HtmlUrl;
        }
Exemplo n.º 4
0
 async Task<Repository> Create(Uri url, string organizationLogin, NewRepository newRepository)
 {
     try
     {
         return await ApiConnection.Post<Repository>(url, newRepository);
     }
     catch (ApiValidationException e)
     {
         string errorMessage = e.ApiError.FirstErrorMessageSafe();
         
         if (String.Equals(
             "name already exists on this account",
             errorMessage,
             StringComparison.OrdinalIgnoreCase))
         {
             var baseAddress = Connection.BaseAddress.Host != GitHubClient.GitHubApiUrl.Host
                 ? Connection.BaseAddress
                 : new Uri("https://github.com/");
             throw new RepositoryExistsException(
                 organizationLogin,
                 newRepository.Name,
                 baseAddress, e);
         }
         if (String.Equals(
             "name can't be private. You are over your quota.",
             errorMessage,
             StringComparison.OrdinalIgnoreCase))
         {
             throw new PrivateRepositoryQuotaExceededException(e);
         }
         throw;
     }
 }
        /// <summary>
        /// Creates a new repository for the current user.
        /// </summary>
        /// <remarks>
        /// See the <a href="http://developer.github.com/v3/repos/#create">API documentation</a> for more information.
        /// </remarks>
        /// <param name="newRepository">A <see cref="NewRepository"/> instance describing the new repository to create</param>
        /// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
        /// <returns>A <see cref="Repository"/> instance for the created repository.</returns>
        public Task<Repository> Create(NewRepository newRepository)
        {
            Ensure.ArgumentNotNull(newRepository, "newRepository");
            if (string.IsNullOrEmpty(newRepository.Name))
                throw new ArgumentException("The new repository's name must not be null.");

            return ApiConnection.Post<Repository>(ApiUrls.Repositories(), newRepository);
        }
Exemplo n.º 6
0
        public IObservable<Repository> CreateRepository(NewRepository repository, string login, bool isUser)
        {
            Guard.ArgumentNotEmptyString(login, "login");

            var client = gitHubClient.Repository;

            return (isUser ? client.Create(repository) : client.Create(login, repository));
        }
Exemplo n.º 7
0
        /// <summary>
        /// Creates a new repository in the specified organization.
        /// </summary>
        /// <remarks>
        /// See the <a href="http://developer.github.com/v3/repos/#create">API documentation</a> for more information.
        /// </remarks>
        /// <param name="organizationLogin">Login of the organization in which to create the repository</param>
        /// <param name="newRepository">A <see cref="NewRepository"/> instance describing the new repository to create</param>
        /// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
        /// <returns>A <see cref="Repository"/> instance for the created repository</returns>
        public Task<Repository> Create(string organizationLogin, NewRepository newRepository)
        {
            Ensure.ArgumentNotNull(organizationLogin, "organizationLogin");
            Ensure.ArgumentNotNull(newRepository, "newRepository");
            if (string.IsNullOrEmpty(newRepository.Name))
                throw new ArgumentException("The new repository's name must not be null.");

            return Create(ApiUrls.OrganizationRepositories(organizationLogin), organizationLogin, newRepository);
        }
            public void TheNewRepositoryDescription()
            {
                var connection = Substitute.For<IApiConnection>();
                var client = new RepositoriesClient(connection);
                var newRepository = new NewRepository { Name = "aName" };

                client.Create(newRepository);

                connection.Received().Post<Repository>(Args.Uri, newRepository);
            }
Exemplo n.º 9
0
        /// <summary>
        /// Creates a new repository for the current user.
        /// </summary>
        /// <remarks>
        /// See the <a href="http://developer.github.com/v3/repos/#create">API documentation</a> for more information.
        /// </remarks>
        /// <param name="newRepository">A <see cref="NewRepository"/> instance describing the new repository to create</param>
        /// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
        /// <returns>A <see cref="Repository"/> instance for the created repository.</returns>
        public Task <Repository> Create(NewRepository newRepository)
        {
            Ensure.ArgumentNotNull(newRepository, "newRepository");
            if (string.IsNullOrEmpty(newRepository.Name))
            {
                throw new ArgumentException("The new repository's name must not be null.");
            }

            return(Create(ApiUrls.Repositories(), null, newRepository));
        }
Exemplo n.º 10
0
        /// <summary>
        /// Creates a new repository in the specified organization.
        /// </summary>
        /// <remarks>
        /// See the <a href="http://developer.github.com/v3/repos/#create">API documentation</a> for more information.
        /// </remarks>
        /// <param name="organizationLogin">Login of the organization in which to create the repostiory</param>
        /// <param name="newRepository">A <see cref="NewRepository"/> instance describing the new repository to create</param>
        /// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
        /// <returns>A <see cref="Repository"/> instance for the created repository</returns>
        public Task <Repository> Create(string organizationLogin, NewRepository newRepository)
        {
            Ensure.ArgumentNotNull(organizationLogin, "organizationLogin");
            Ensure.ArgumentNotNull(newRepository, "newRepository");
            if (string.IsNullOrEmpty(newRepository.Name))
            {
                throw new ArgumentException("The new repository's name must not be null.");
            }

            return(Create(ApiUrls.OrganizationRepositories(organizationLogin), organizationLogin, newRepository));
        }
        public IObservable<Unit> CreateRepository(
            NewRepository newRepository,
            IAccount account,
            string directory,
            IApiClient apiClient)
        {
            Guard.ArgumentNotEmptyString(directory, nameof(directory));

            return apiClient.CreateRepository(newRepository, account.Login, account.IsUser)
                .Select(repository => cloneService.CloneRepository(repository.CloneUrl, repository.Name, directory))
                .SelectUnit();
        }
Exemplo n.º 12
0
        async Task <Repository> Create(Uri url, string organizationLogin, NewRepository newRepository)
        {
            try
            {
                return(await ApiConnection.Post <Repository>(url, newRepository));
            }
            catch (ApiValidationException e)
            {
                string errorMessage = e.ApiError.FirstErrorMessageSafe();

                if (string.Equals(
                        "name already exists on this account",
                        errorMessage,
                        StringComparison.OrdinalIgnoreCase))
                {
                    if (string.IsNullOrEmpty(organizationLogin))
                    {
                        throw new RepositoryExistsException(newRepository.Name, e);
                    }

                    var baseAddress = Connection.BaseAddress.Host != GitHubClient.GitHubApiUrl.Host
                        ? Connection.BaseAddress
                        : new Uri("https://github.com/");
                    throw new RepositoryExistsException(
                              organizationLogin,
                              newRepository.Name,
                              baseAddress, e);
                }

                if (string.Equals(
                        "please upgrade your plan to create a new private repository.",
                        errorMessage,
                        StringComparison.OrdinalIgnoreCase))
                {
                    throw new PrivateRepositoryQuotaExceededException(e);
                }

                if (string.Equals(
                        "name can't be private. You are over your quota.",
                        errorMessage,
                        StringComparison.OrdinalIgnoreCase))
                {
                    throw new PrivateRepositoryQuotaExceededException(e);
                }

                if (errorMessage != null && errorMessage.EndsWith("is an unknown gitignore template.", StringComparison.OrdinalIgnoreCase))
                {
                    throw new InvalidGitIgnoreTemplateException(e);
                }

                throw;
            }
        }
Exemplo n.º 13
0
        async Task<Repository> Create(Uri url, string organizationLogin, NewRepository newRepository)
        {
            try
            {
                return await ApiConnection.Post<Repository>(url, newRepository).ConfigureAwait(false);
            }
            catch (ApiValidationException e)
            {
                string errorMessage = e.ApiError.FirstErrorMessageSafe();

                if (string.Equals(
                    "name already exists on this account",
                    errorMessage,
                    StringComparison.OrdinalIgnoreCase))
                {
                    if (string.IsNullOrEmpty(organizationLogin))
                    {
                        throw new RepositoryExistsException(newRepository.Name, e);
                    }

                    var baseAddress = Connection.BaseAddress.Host != GitHubClient.GitHubApiUrl.Host
                        ? Connection.BaseAddress
                        : new Uri("https://github.com/");
                    throw new RepositoryExistsException(
                        organizationLogin,
                        newRepository.Name,
                        baseAddress, e);
                }

                if (string.Equals(
                    "please upgrade your plan to create a new private repository.",
                    errorMessage,
                    StringComparison.OrdinalIgnoreCase))
                {
                    throw new PrivateRepositoryQuotaExceededException(e);
                }

                if (string.Equals(
                    "name can't be private. You are over your quota.",
                    errorMessage,
                    StringComparison.OrdinalIgnoreCase))
                {
                    throw new PrivateRepositoryQuotaExceededException(e);
                }

                if (errorMessage != null && errorMessage.EndsWith("is an unknown gitignore template.", StringComparison.OrdinalIgnoreCase))
                {
                    throw new InvalidGitIgnoreTemplateException(e);
                }

                throw;
            }
        }
    public async Task CanQueueAllCodeRepository()
    {
        var newRepository = new NewRepository(Helper.MakeNameWithTimestamp("public-repo"));
        using (var context = await _github.CreateRepositoryContext(newRepository))
        {
            var response = await
                _github.Enterprise.SearchIndexing.QueueAllCode(EnterpriseHelper.UserName, context.RepositoryName);

            Assert.NotNull(response);
            Assert.NotNull(response.Message);
            Assert.True(response.Message.All(m => m.Contains("was added to the indexing queue")));
        }
    }
Exemplo n.º 15
0
        void CreateRepository(string name)
        {
            var nrep = new NewRepository("test");
            //nrep.AutoInit = true;
            try
            {
                //client.Repository.Create(nrep).Wait();
                //var rep = await client.Repository.Create(nrep);

            }
            catch (Exception e)
            {
                ;
            }
        }
        public async Task CreatesRepositoryAndPushesLocalToIt()
        {
            var solution = Substitute.For<IVsSolution>();
            var gitClient = Substitute.For<IGitClient>();
            var service = new RepositoryPublishService(gitClient, Substitutes.IVSGitServices);
            var newRepository = new Octokit.NewRepository("test");
            var account = Substitute.For<IAccount>();
            account.Login.Returns("monalisa");
            account.IsUser.Returns(true);
            var gitHubRepository = CreateRepository(account.Login, newRepository.Name);
            var apiClient = Substitute.For<IApiClient>();
            apiClient.CreateRepository(newRepository, "monalisa", true).Returns(Observable.Return(gitHubRepository));

            var repository = await service.PublishRepository(newRepository, account, apiClient);

            Assert.Equal("https://github.com/monalisa/test", repository.CloneUrl);
        }
        public async Task CreatesARepositoryWithoutDownloads()
        {
            var github = Helper.GetAuthenticatedClient();

            var repoName = Helper.MakeNameWithTimestamp("repo-without-downloads");

            var newRepository = new NewRepository(repoName) { HasDownloads = false };

            using (var context = await github.CreateRepositoryContext(newRepository))
            {
                var createdRepository = context.Repository;

                Assert.False(createdRepository.HasDownloads);
                var repository = await github.Repository.Get(Helper.UserName, repoName);
                Assert.False(repository.HasDownloads);
            }
        }
Exemplo n.º 18
0
        public async Task CreatesRepositoryAndPushesLocalToIt()
        {
            var solution      = Substitute.For <IVsSolution>();
            var gitClient     = Substitute.For <IGitClient>();
            var service       = new RepositoryPublishService(gitClient, Substitutes.IVSGitServices);
            var newRepository = new Octokit.NewRepository("test");
            var account       = Substitute.For <IAccount>();

            account.Login.Returns("monalisa");
            account.IsUser.Returns(true);
            var gitHubRepository = CreateRepository(account.Login, newRepository.Name);
            var apiClient        = Substitute.For <IApiClient>();

            apiClient.CreateRepository(newRepository, "monalisa", true).Returns(Observable.Return(gitHubRepository));

            var repository = await service.PublishRepository(newRepository, account, apiClient);

            Assert.Equal("https://github.com/monalisa/test", repository.CloneUrl);
        }
    public DeploymentStatusClientTests()
    {
        _gitHubClient = new GitHubClient(new ProductHeaderValue("OctokitTests"))
        {
            Credentials = Helper.Credentials
        };

        _deploymentsClient = _gitHubClient.Repository.Deployment;

        var newRepository = new NewRepository
        {
            Name = Helper.MakeNameWithTimestamp("public-repo"),
            AutoInit = true
        };

        _repository = _gitHubClient.Repository.Create(newRepository).Result;
        _repositoryOwner = _repository.Owner.Login;

        var blob = new NewBlob
        {
            Content = "Hello World!",
            Encoding = EncodingType.Utf8
        };

        var blobResult = _gitHubClient.GitDatabase.Blob.Create(_repositoryOwner, _repository.Name, blob).Result;

        var newTree = new NewTree();
        newTree.Tree.Add(new NewTreeItem
        {
            Type = TreeType.Blob,
            Mode = FileMode.File,
            Path = "README.md",
            Sha = blobResult.Sha
        });

        var treeResult = _gitHubClient.GitDatabase.Tree.Create(_repositoryOwner, _repository.Name, newTree).Result;
        var newCommit = new NewCommit("test-commit", treeResult.Sha);
        _commit = _gitHubClient.GitDatabase.Commit.Create(_repositoryOwner, _repository.Name, newCommit).Result;

        var newDeployment = new NewDeployment { Ref = _commit.Sha };
        _deployment = _deploymentsClient.Create(_repositoryOwner, _repository.Name, newDeployment).Result;
    }
        public void CreatesRepositoryOnlineViaApiAndThenClonesIt()
        {
            var provider = Substitutes.ServiceProvider;
            var newRepository = new NewRepository("octokit.net");
            var repository = new TestRepository("octokit.net", "https://github.com/octokit/octokit.net");
            var account = Substitute.For<IAccount>();
            account.Login.Returns("octokit");
            account.IsUser.Returns(false);
            var apiClient = Substitute.For<IApiClient>();
            apiClient.CreateRepository(newRepository, "octokit", false)
                .Returns(Observable.Return(repository));
            var cloneService = provider.GetRepositoryCloneService();
            cloneService.CloneRepository("https://github.com/octokit/octokit.net", "octokit.net", @"c:\dev")
                .Returns(Observable.Return(Unit.Default));
            var creator = provider.GetRepositoryCreationService();

            creator.CreateRepository(newRepository, account, @"c:\dev", apiClient).Subscribe();

            apiClient.Received().CreateRepository(newRepository, "octokit", false);
        }
            public async Task ThrowsRepositoryExistsExceptionWhenRepositoryExistsForCurrentUser()
            {
                var newRepository = new NewRepository { Name = "aName" };
                var response = Substitute.For<IResponse>();
                response.StatusCode.Returns((HttpStatusCode)422);
                response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":"
                    + @"""http://developer.github.com/v3/repos/#create"",""errors"":[{""resource"":""Repository"","
                    + @"""code"":""custom"",""field"":""name"",""message"":""name already exists on this account""}]}");
                var credentials = new Credentials("haacked", "pwd");
                var connection = Substitute.For<IApiConnection>();
                connection.Connection.BaseAddress.Returns(GitHubClient.GitHubApiUrl);
                connection.Connection.Credentials.Returns(credentials);
                connection.Post<Repository>(Args.Uri, newRepository)
                    .Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); });
                var client = new RepositoriesClient(connection);

                var exception = await AssertEx.Throws<RepositoryExistsException>(
                    async () => await client.Create(newRepository));

                Assert.False(exception.OwnerIsOrganization);
                Assert.Null(exception.Owner);
                Assert.Equal("aName", exception.RepositoryName);
                Assert.Null(exception.ExistingRepositoryWebUrl);
            }
Exemplo n.º 22
0
        public async Task ThrowsRepositoryExistsExceptionForExistingRepository()
        {
            var github = new GitHubClient(new ProductHeaderValue("OctokitTests"))
            {
                Credentials = Helper.Credentials
            };
            var repoName = Helper.MakeNameWithTimestamp("existing-repo");
            var repository = new NewRepository { Name = repoName };
            var createdRepository = await github.Repository.Create(repository);

            try
            {
                var thrown = await AssertEx.Throws<RepositoryExistsException>(
                    async () => await github.Repository.Create(repository));
                Assert.NotNull(thrown);
                Assert.Equal(repoName, thrown.RepositoryName);
                Assert.Equal(Helper.Credentials.Login, thrown.Owner);
                Assert.False(thrown.OwnerIsOrganization);
            }
            finally
            {
                Helper.DeleteRepo(createdRepository);
            }
        }
Exemplo n.º 23
0
        /// <summary>
        /// Creates a new repository for the current user.
        /// </summary>
        /// <remarks>
        /// See the <a href="http://developer.github.com/v3/repos/#create">API documentation</a> for more information.
        /// </remarks>
        /// <param name="newRepository">A <see cref="NewRepository"/> instance describing the new repository to create</param>
        /// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
        /// <returns>A <see cref="Repository"/> instance for the created repository.</returns>
        public Task <Repository> Create(NewRepository newRepository)
        {
            Ensure.ArgumentNotNull(newRepository, "newRepository");

            return(Create(ApiUrls.Repositories(), null, newRepository));
        }
        public async Task ThrowsRepositoryExistsExceptionForExistingRepository()
        {
            var github = Helper.GetAuthenticatedClient();

            var repoName = Helper.MakeNameWithTimestamp("existing-org-repo");

            var repository = new NewRepository(repoName);

            using (var context = await github.CreateRepositoryContext(Helper.Organization, repository))
            {
                var createdRepository = context.Repository;

                var repositoryUrl = string.Format(CultureInfo.InvariantCulture, "https://github.com/{0}/{1}", Helper.Organization, repository.Name);
                var message = string.Format(CultureInfo.InvariantCulture, "There is already a repository named '{0}' in the organization '{1}'.", repository.Name, Helper.Organization);

                var thrown = await Assert.ThrowsAsync<RepositoryExistsException>(
                    () => github.Repository.Create(Helper.Organization, repository));

                Assert.NotNull(thrown);
                Assert.Equal(repoName, thrown.RepositoryName);
                Assert.Equal(message, thrown.Message);
                Assert.True(thrown.OwnerIsOrganization);
                Assert.Equal(Helper.Organization, thrown.Organization);
                Assert.Equal(repositoryUrl, thrown.ExistingRepositoryWebUrl.ToString());
            }
        }
        public async Task ThrowsPrivateRepositoryQuotaExceededExceptionWhenOverQuota()
        {
            var github = Helper.GetAuthenticatedClient();

            var userDetails = await github.User.Current();
            var freePrivateSlots = userDetails.Plan.PrivateRepos - userDetails.OwnedPrivateRepos;

            if (userDetails.Plan.PrivateRepos == 0)
            {
                throw new Exception("Test cannot complete, account is on free plan");
            }

            var createRepoTasks =
                Enumerable.Range(0, (int)freePrivateSlots)
                .Select(x =>
                {
                    var repoName = Helper.MakeNameWithTimestamp("private-repo-" + x);
                    var repository = new NewRepository(repoName) { Private = true };
                    return github.Repository.Create(repository);
                });

            var createdRepositories = await Task.WhenAll(createRepoTasks);

            try
            {
                await Assert.ThrowsAsync<PrivateRepositoryQuotaExceededException>(
                    () => github.Repository.Create(new NewRepository("x-private") { Private = true }));
            }
            finally
            {
                var deleteRepos = createdRepositories
                    .Select(repo => github.Repository.Delete(repo.Owner.Login, repo.Name));

                Task.WhenAll(deleteRepos).Wait();
            }
        }
        public async Task CreatesARepositoryWithAGitignoreTemplate()
        {
            var github = Helper.GetAuthenticatedClient();
            var repoName = Helper.MakeNameWithTimestamp("repo-with-gitignore");

            var newRepository = new NewRepository(repoName)
            {
                AutoInit = true,
                GitignoreTemplate = "VisualStudio"
            };

            using (var context = await github.CreateRepositoryContext(newRepository))
            {
                var createdRepository = context.Repository;

                // TODO: Once the contents API has been added, check the actual files in the created repo
                Assert.Equal(repoName, createdRepository.Name);
                var repository = await github.Repository.Get(Helper.UserName, repoName);
                Assert.Equal(repoName, repository.Name);
            }
        }
            public async Task ThrowsExceptionWhenPrivateRepositoryQuotaExceeded()
            {
                var newRepository = new NewRepository { Name = "aName", Private = true };
                var response = Substitute.For<IResponse>();
                response.StatusCode.Returns((HttpStatusCode)422);
                response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":"
                    + @"""http://developer.github.com/v3/repos/#create"",""errors"":[{""resource"":""Repository"","
                    + @"""code"":""custom"",""field"":""name"",""message"":"
                    + @"""name can't be private. You are over your quota.""}]}");
                var credentials = new Credentials("haacked", "pwd");
                var connection = Substitute.For<IApiConnection>();
                connection.Connection.BaseAddress.Returns(GitHubClient.GitHubApiUrl);
                connection.Connection.Credentials.Returns(credentials);
                connection.Post<Repository>(Args.Uri, newRepository)
                    .Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); });
                var client = new RepositoriesClient(connection);

                var exception = await AssertEx.Throws<PrivateRepositoryQuotaExceededException>(
                    async () => await client.Create(newRepository));

                Assert.NotNull(exception);
            }
Exemplo n.º 28
0
        public async Task ThrowsPrivateRepositoryQuotaExceededExceptionWhenOverQuota()
        {
            var github = new GitHubClient(new ProductHeaderValue("OctokitTests"))
            {
                Credentials = Helper.Credentials
            };

            for (int i = 0; i < 5; i++)
            {
                var repoName = Helper.MakeNameWithTimestamp("private-repo" + i);
                var repository = new NewRepository { Name = repoName, Private = true };
                await github.Repository.Create(repository);
            }

            var thrown = await AssertEx.Throws<PrivateRepositoryQuotaExceededException>(
                async () => await github.Repository.Create(new NewRepository { Name = "x-private", Private = true }));
            Assert.NotNull(thrown);
        }
            public async Task ThrowsRepositoryExistsExceptionForEnterpriseInstance()
            {
                var newRepository = new NewRepository { Name = "aName" };
                var response = Substitute.For<IResponse>();
                response.StatusCode.Returns((HttpStatusCode)422);
                response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":"
                    + @"""http://developer.github.com/v3/repos/#create"",""errors"":[{""resource"":""Repository"","
                    + @"""code"":""custom"",""field"":""name"",""message"":""name already exists on this account""}]}");
                var connection = Substitute.For<IApiConnection>();
                connection.Connection.BaseAddress.Returns(new Uri("https://example.com"));
                connection.Post<Repository>(Args.Uri, newRepository)
                    .Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); });
                var client = new RepositoriesClient(connection);

                var exception = await AssertEx.Throws<RepositoryExistsException>(
                    async () => await client.Create("illuminati", newRepository));

                Assert.Equal("aName", exception.RepositoryName);
                Assert.Equal(new Uri("https://example.com/illuminati/aName"), exception.ExistingRepositoryWebUrl);
            }
Exemplo n.º 30
0
        private static async Task<object> directoryDelegate(string path, object input)
        {
            var folder = PathInfo.UncheckedFolderFromPath(path);
            if (folder == null)
            {
                var repoInfo = PathInfo.UncheckedRepoFromPath(path);
                if (repoInfo == null)
                {
                    throw new NotSupportedException("The Github Provider does not support making directories in this location.");
                }
                if (await repoInfo.Exists())
                {
                    throw new Exception("The given repository already exists."); //TODO: Custom exceptions
                }
                var parentInfo = await PathInfo.FromFSPath(GithubProvider.StaticGetParentPath(path, null));
                if (parentInfo != null)
                {
                    var repo = new NewRepository(repoInfo.Name) { AutoInit = true };
                    switch (parentInfo.Type)
                    {
                        case (PathType.User):
                            {
                                await Static.Client.Repository.Create(repo);
                                PathInfo.PathInfoCache.Remove(parentInfo.VirtualPath);
                                return repoInfo;
                            }
                        case (PathType.Org):
                            {
                                await Static.Client.Repository.Create(repoInfo.Org, repo);
                                PathInfo.PathInfoCache.Remove(parentInfo.VirtualPath);
                                return repoInfo;
                            }
                        default:
                            throw new Exception("Given path is neither a repository nor a folder and cannot be created."); //TODO
                    }
                }

            }

            if (await folder.Exists())
            {
                throw new Exception("The folder being created already exists"); //TODO: Stop being lazy and write my own exceptions
            }

            try
            {
                await Static.Client.Repository.Content.CreateFile(
                    folder.Org,
                    folder.Repo,
                    Path.Combine(folder.FilePath, ".gitkeep"),
                    new CreateFileRequest("Add .gitkeep", "")
                );
            }
            catch (Octokit.NotFoundException e)
            {
                throw new Exception("Couldn't create directory - couldn't find the repo.", e);
            }
            return folder;
        }
Exemplo n.º 31
0
        /// <summary>
        /// Creates a new repository for the current user.
        /// </summary>
        /// <remarks>
        /// See the <a href="http://developer.github.com/v3/repos/#create">API documentation</a> for more information.
        /// </remarks>
        /// <param name="newRepository">A <see cref="NewRepository"/> instance describing the new repository to create</param>
        /// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
        /// <returns>A <see cref="Repository"/> instance for the created repository.</returns>
        public Task<Repository> Create(NewRepository newRepository)
        {
            Ensure.ArgumentNotNull(newRepository, "newRepository");

            return Create(ApiUrls.Repositories(), null, newRepository);
        }
        public async Task ThrowsInvalidGitIgnoreExceptionForInvalidTemplateNames()
        {
            var github = Helper.GetAuthenticatedClient();
            var repoName = Helper.MakeNameWithTimestamp("repo-with-gitignore");

            var newRepository = new NewRepository(repoName)
            {
                AutoInit = true,
                GitignoreTemplate = "visualstudio"
            };

            var thrown = await Assert.ThrowsAsync<InvalidGitIgnoreTemplateException>(
                    () => github.CreateRepositoryContext(newRepository));

            Assert.NotNull(thrown);
        }
            public async Task ThrowsValidationException()
            {
                var newRepository = new NewRepository { Name = "aName" };
                var response = Substitute.For<IResponse>();
                response.StatusCode.Returns((HttpStatusCode)422);
                response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":"
                    + @"""http://developer.github.com/v3/repos/#create"",""errors"":[]}");
                var connection = Substitute.For<IApiConnection>();
                connection.Connection.BaseAddress.Returns(GitHubClient.GitHubApiUrl);
                connection.Post<Repository>(Args.Uri, newRepository)
                    .Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); });
                var client = new RepositoriesClient(connection);

                var exception = await AssertEx.Throws<ApiValidationException>(
                    async () => await client.Create("illuminati", newRepository));

                Assert.Null(exception as RepositoryExistsException);
            }
        public async Task ThrowsRepositoryExistsExceptionForExistingRepository()
        {
            var github = Helper.GetAuthenticatedClient();
            var repoName = Helper.MakeNameWithTimestamp("existing-repo");
            var repository = new NewRepository(repoName);

            using (var context = await github.CreateRepositoryContext(repository))
            {
                var createdRepository = context.Repository;

                var message = string.Format(CultureInfo.InvariantCulture, "There is already a repository named '{0}' for the current account.", repoName);

                var thrown = await Assert.ThrowsAsync<RepositoryExistsException>(
                    () => github.Repository.Create(repository));

                Assert.NotNull(thrown);
                Assert.Equal(repoName, thrown.RepositoryName);
                Assert.Equal(message, thrown.Message);
                Assert.False(thrown.OwnerIsOrganization);
            }
        }