public static async Task<TreeResponse> CreateTree(this IGitHubClient client, Repository repository, IEnumerable<KeyValuePair<string, string>> treeContents) { var collection = new List<NewTreeItem>(); foreach (var c in treeContents) { var baselineBlob = new NewBlob { Content = c.Value, Encoding = EncodingType.Utf8 }; var baselineBlobResult = await client.GitDatabase.Blob.Create(repository.Owner.Login, repository.Name, baselineBlob); collection.Add(new NewTreeItem { Type = TreeType.Blob, Mode = FileMode.File, Path = c.Key, Sha = baselineBlobResult.Sha }); } var newTree = new NewTree(); foreach (var item in collection) { newTree.Tree.Add(item); } return await client.GitDatabase.Tree.Create(repository.Owner.Login, repository.Name, newTree); }
/// <summary> /// Creates a new Blob /// </summary> /// <remarks> /// http://developer.github.com/v3/git/blobs/#create-a-blob /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="newBlob">The new Blob</param> /// <returns>The <see cref="Blob"/> that was just created.</returns> public IObservable<BlobReference> Create(string owner, string name, NewBlob newBlob) { Ensure.ArgumentNotNullOrEmptyString(owner, "owner"); Ensure.ArgumentNotNullOrEmptyString(name, "name"); Ensure.ArgumentNotNull(newBlob, "newBlob"); return _client.Create(owner, name, newBlob).ToObservable(); }
public void PostsToCorrectUrl() { var newBlob = new NewBlob(); var connection = Substitute.For<IApiConnection>(); var client = new BlobsClient(connection); client.Create("fake", "repo", newBlob); connection.Received().Post<BlobReference>(Arg.Is<Uri>(u => u.ToString() == "repos/fake/repo/git/blobs"), newBlob); }
public void PostsToCorrectUrlWithRepositoryId() { var gitHubClient = Substitute.For<IGitHubClient>(); var client = new ObservableBlobClient(gitHubClient); var newBlob = new NewBlob(); client.Create(1, newBlob); gitHubClient.Git.Blob.Received().Create(1, newBlob); }
public void PostsToCorrectUrl() { var newBlob = new NewBlob(); var gitHubClient = Substitute.For<IGitHubClient>(); var client = new ObservableBlobClient(gitHubClient); client.Create("fake", "repo", newBlob); gitHubClient.GitDatabase.Blob.Received().Create("fake", "repo", newBlob); }
public async Task CanUpdateAReference() { var firstBlob = new NewBlob { Content = "Hello World!", Encoding = EncodingType.Utf8 }; var firstBlobResult = await _github.GitDatabase.Blob.Create(_context.RepositoryOwner, _context.RepositoryName, firstBlob); var secondBlob = new NewBlob { Content = "This is a test!", Encoding = EncodingType.Utf8 }; var secondBlobResult = await _github.GitDatabase.Blob.Create(_context.RepositoryOwner, _context.RepositoryName, secondBlob); var firstTree = new NewTree(); firstTree.Tree.Add(new NewTreeItem { Mode = FileMode.File, Type = TreeType.Blob, Path = "README.md", Sha = firstBlobResult.Sha }); var firstTreeResult = await _github.GitDatabase.Tree.Create(_context.RepositoryOwner, _context.RepositoryName, firstTree); var firstCommit = new NewCommit("This is a new commit", firstTreeResult.Sha); var firstCommitResult = await _github.GitDatabase.Commit.Create(_context.RepositoryOwner, _context.RepositoryName, firstCommit); var newReference = new NewReference("heads/develop", firstCommitResult.Sha); await _fixture.Create(_context.RepositoryOwner, _context.RepositoryName, newReference); var secondTree = new NewTree(); secondTree.Tree.Add(new NewTreeItem { Mode = FileMode.File, Type = TreeType.Blob, Path = "README.md", Sha = secondBlobResult.Sha }); var secondTreeResult = await _github.GitDatabase.Tree.Create(_context.RepositoryOwner, _context.RepositoryName, secondTree); var secondCommit = new NewCommit("This is a new commit", secondTreeResult.Sha, firstCommitResult.Sha); var secondCommitResult = await _github.GitDatabase.Commit.Create(_context.RepositoryOwner, _context.RepositoryName, secondCommit); var referenceUpdate = new ReferenceUpdate(secondCommitResult.Sha); var result = await _fixture.Update(_context.RepositoryOwner, _context.RepositoryName, "heads/develop", referenceUpdate); Assert.Equal(secondCommitResult.Sha, result.Object.Sha); }
private void ConstructTreeInternal(Folder folderInfo, NewTree tree, string parentPath) { var path = string.Empty; if (string.IsNullOrEmpty(folderInfo.Name)) { if (!string.IsNullOrEmpty(parentPath)) { throw new ArgumentException("Invalid arguments"); } } else { if (!string.IsNullOrEmpty(parentPath)) { path = parentPath; } path = path + folderInfo.Name + "/"; } if (folderInfo.Files != null) { foreach (var file in folderInfo.Files) { var filePath = path + file.Name; var newBlob = new NewBlob() { Content = file.Content, Encoding = EncodingType.Utf8 }; var createdBlob = client.Git.Blob.Create(repo.Id, newBlob); createdBlob.Wait(); var item = new NewTreeItem() { Path = filePath, Mode = Octokit.FileMode.File, Sha = createdBlob.Result.Sha, Type = TreeType.Blob }; tree.Tree.Add(item); } } if (folderInfo.SubFolders != null) { foreach (var folder in folderInfo.SubFolders) { this.ConstructTreeInternal(folder, tree, path); } } }
public void PostsToCorrectUrlWithRepositoryId() { var gitHubClient = Substitute.For <IGitHubClient>(); var client = new ObservableBlobClient(gitHubClient); var newBlob = new NewBlob(); client.Create(1, newBlob); gitHubClient.Git.Blob.Received().Create(1, newBlob); }
public void PostsToCorrectUrl() { var gitHubClient = Substitute.For <IGitHubClient>(); var client = new ObservableBlobClient(gitHubClient); var newBlob = new NewBlob(); client.Create("fake", "repo", newBlob); gitHubClient.Git.Blob.Received().Create("fake", "repo", newBlob); }
public void PostsToCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new BlobsClient(connection); var newBlob = new NewBlob(); client.Create(1, newBlob); connection.Received().Post<BlobReference>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/git/blobs"), newBlob); }
public void PostsToCorrectUrlWithRepositoryId() { var connection = Substitute.For <IApiConnection>(); var client = new BlobsClient(connection); var newBlob = new NewBlob(); client.Create(1, newBlob); connection.Received().Post <BlobReference>(Arg.Is <Uri>(u => u.ToString() == "repositories/1/git/blobs"), newBlob); }
public void PostsToCorrectUrl() { var connection = Substitute.For <IApiConnection>(); var client = new BlobsClient(connection); var newBlob = new NewBlob(); client.Create("fake", "repo", newBlob); connection.Received().Post <BlobReference>(Arg.Is <Uri>(u => u.ToString() == "repos/fake/repo/git/blobs"), newBlob); }
public async Task CanCreateABlob() { var blob = new NewBlob { Content = "Hello World!", Encoding = EncodingType.Utf8 }; var result = await _fixture.Create(_owner, _repository.Name, blob); Assert.False(String.IsNullOrWhiteSpace(result.Sha)); }
public async Task CanCreateABlobWithRepositoryId() { var blob = new NewBlob { Content = "Hello World!", Encoding = EncodingType.Utf8 }; var result = await _fixture.Create(_context.Repository.Id, blob); Assert.False(string.IsNullOrWhiteSpace(result.Sha)); }
public async Task CanCreateABlobWithBase64ContentsAndWithRepositoryId() { var utf8Bytes = Encoding.UTF8.GetBytes("Hello World!"); var base64String = Convert.ToBase64String(utf8Bytes); var blob = new NewBlob { Content = base64String, Encoding = EncodingType.Base64 }; var result = await _fixture.Create(_context.Repository.Id, blob); Assert.False(string.IsNullOrWhiteSpace(result.Sha)); }
public TheGetMethod() { var github = Helper.GetAuthenticatedClient(); fixture = github.Git.Tag; context = github.CreateRepositoryContext("public-repo").Result; var blob = new NewBlob { Content = "Hello World!", Encoding = EncodingType.Utf8 }; var blobResult = github.Git.Blob.Create(context.RepositoryOwner, context.RepositoryName, blob).Result; sha = blobResult.Sha; }
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; }
/// <inheritdoc/> protected override async Task <object> CallGitHubApi(DialogContext dc, Octokit.GitHubClient gitHubClient, CancellationToken cancellationToken = default(CancellationToken)) { if (Owner != null && Name != null && NewBlob != null) { var ownerValue = Owner.GetValue(dc.State); var nameValue = Name.GetValue(dc.State); var newBlobValue = NewBlob.GetValue(dc.State); return(await gitHubClient.Git.Blob.Create(ownerValue, nameValue, newBlobValue).ConfigureAwait(false)); } if (RepositoryId != null && NewBlob != null) { var repositoryIdValue = RepositoryId.GetValue(dc.State); var newBlobValue = NewBlob.GetValue(dc.State); return(await gitHubClient.Git.Blob.Create((Int64)repositoryIdValue, newBlobValue).ConfigureAwait(false)); } throw new ArgumentNullException("Required [newBlob] arguments missing for GitHubClient.Git.Blob.Create"); }
private async Task <List <NewTreeItem> > CreateNewTreeItemList(StringBuilder sb, IEnumerable <string> pathArray, VersionData versionData) { var newTreeItemList = new List <NewTreeItem>(); sb.Append("[Update Data] "); foreach (var path in pathArray) { var fileName = Path.GetFileNameWithoutExtension(path); var fileExtension = Path.GetExtension(path); if (versionData.GetVersionValue(fileName) == null) { versionData.AddNewVerionData(fileName); } var fileVersionName = versionData.GetNextVersion(fileName); var fileFullName = string.Format("{0}{1}", fileVersionName, fileExtension); fileExtension = fileExtension.Replace(".", ""); var fileToBase64 = Convert.ToBase64String(File.ReadAllBytes(path)); var newBlob = new NewBlob { Encoding = EncodingType.Base64, Content = fileToBase64 }; var newBlobRef = await Client.Git.Blob.Create(OwnerSpaceName, RepositoryName, newBlob); var newTreeItem = new NewTreeItem { Path = string.Format("{0}/{1}/{2}/{3}", BaseDataPath, fileExtension, fileName, fileFullName), Mode = "100644", Type = TreeType.Blob, Sha = newBlobRef.Sha }; newTreeItemList.Add(newTreeItem); sb.AppendFormat(" {0} /", fileFullName); } return(newTreeItemList); }
public async Task CanGetABlob() { var newBlob = new NewBlob { Content = "Hello World!", Encoding = EncodingType.Utf8 }; var result = await _fixture.Create(_context.RepositoryOwner, _context.RepositoryName, newBlob); var blob = await _fixture.Get(_context.RepositoryOwner, _context.RepositoryName, result.Sha); Assert.Equal(result.Sha, blob.Sha); Assert.Equal(EncodingType.Base64, blob.Encoding); var contents = Encoding.UTF8.GetString(Convert.FromBase64String(blob.Content)); Assert.Equal("Hello World!", contents); }
protected async Task <BlobReference> CreateBlob(IGitHubClient client, Repository repository, string content) { if (client == null) { throw new ArgumentNullException(nameof(client)); } if (repository == null) { throw new ArgumentNullException(nameof(repository)); } var blob = new NewBlob() { Content = content, Encoding = EncodingType.Utf8 }; var blobReference = await client.Git.Blob.Create(repository.Owner.Login, repository.Name, blob).ConfigureAwait(false); _logger.LogTrace("Created blob SHA {sha}", blobReference.Sha); return(blobReference); }
private async Task <NewTreeItem> CreateNewVersionTreeItem(StringBuilder sb, VersionData versionData) { sb.Append(" Update version"); var newBlob = new NewBlob { Encoding = EncodingType.Utf8, Content = versionData.ToString() }; var newBlobRef = await Client.Git.Blob.Create(OwnerSpaceName, RepositoryName, newBlob); var newTreeItem = new NewTreeItem { Path = VersionDataPath, Mode = "100644", Type = TreeType.Blob, Sha = newBlobRef.Sha }; return(newTreeItem); }
public async Task CreateBlob(string owner, string repository, string sha) { var blobPath = Path.Combine(blobStoragePath, sha); var buf = File.ReadAllBytes(blobPath); var base64String = Convert.ToBase64String(buf); var newBlob = new NewBlob { Encoding = EncodingType.Base64, Content = base64String }; log($"API Query - Create blob '{sha.Substring(0, 7)}' in '{owner}/{repository}'."); // ReSharper disable once RedundantAssignment var createdBlob = await client.Git.Blob.Create(owner, repository, newBlob); Debug.Assert(sha == createdBlob.Sha); AddToKnown <Blob>(sha, owner, repository); }
public static async Task <IDictionary <string, NewBlob> > GetEditsToCommit( GitHubClient client, Repository upstreamRepo, string baseSha, IEnumerable <PropertyUpdate> propertyUpdates) { // Find the file to update var existingTree = await client.Git.Tree.GetRecursive(upstreamRepo.Id, baseSha); // Update the files' contents var result = new Dictionary <string, NewBlob>(); var filesToUpdate = propertyUpdates.GroupBy(p => p.Filename); foreach (var fileToUpdate in filesToUpdate) { var fileContents = await GetFileContentsAsString( client, upstreamRepo, existingTree.Tree, fileToUpdate.Key); foreach (var propToUpdate in fileToUpdate) { var propName = propToUpdate.PropertyName; var patternToReplace = new Regex($"<{propName}>[^<]+</{propName}>"); if (!patternToReplace.IsMatch(fileContents)) { throw new Exception($"The file {fileToUpdate.Key} does not contain a match for regex " + patternToReplace.ToString()); } fileContents = patternToReplace.Replace( fileContents, $"<{propName}>{propToUpdate.NewValue}</{propName}>"); } var newBlob = new NewBlob { Content = fileContents, Encoding = EncodingType.Utf8 }; result.Add(fileToUpdate.Key, newBlob); } return(result); }
public async Task CanCreateAndRetrieveCommit() { var github = Helper.GetAuthenticatedClient(); var fixture = github.Git.Commit; using (var context = await github.CreateRepositoryContext("public-repo")) { var owner = context.Repository.Owner.Login; var blob = new NewBlob { Content = "Hello World!", Encoding = EncodingType.Utf8 }; var blobResult = await github.Git.Blob.Create(owner, context.Repository.Name, blob); var newTree = new NewTree(); newTree.Tree.Add(new NewTreeItem { Type = TreeType.Blob, Mode = FileMode.File, Path = "README.md", Sha = blobResult.Sha }); var treeResult = await github.Git.Tree.Create(owner, context.Repository.Name, newTree); var newCommit = new NewCommit("test-commit", treeResult.Sha); var commit = await fixture.Create(owner, context.Repository.Name, newCommit); Assert.NotNull(commit); var retrieved = await fixture.Get(owner, context.Repository.Name, commit.Sha); Assert.NotNull(retrieved); } }
public DeploymentStatusClientTests() { var github = Helper.GetAuthenticatedClient(); _deploymentsClient = github.Repository.Deployment; _context = github.CreateRepositoryContext("public-repo").Result; var blob = new NewBlob { Content = "Hello World!", Encoding = EncodingType.Utf8 }; var blobResult = github.Git.Blob.Create(_context.RepositoryOwner, _context.RepositoryName, 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 = github.Git.Tree.Create(_context.RepositoryOwner, _context.RepositoryName, newTree).Result; var newCommit = new NewCommit("test-commit", treeResult.Sha); var commit = github.Git.Commit.Create(_context.RepositoryOwner, _context.RepositoryName, newCommit).Result; var newDeployment = new NewDeployment(commit.Sha) { Environment = "production", AutoMerge = false }; _deployment = _deploymentsClient.Create(_context.RepositoryOwner, _context.RepositoryName, newDeployment).Result; }
public async Task AddLastCommitAsync(string repositoryName) { var owner = "mehmetozkaya"; var headMasterRef = $"heads/master"; var masterReference = await _client.Git.Reference.Get(owner, repositoryName, headMasterRef); var latestCommit = await _client.Git.Commit.Get(owner, repositoryName, masterReference.Object.Sha); var imgBase64 = Convert.ToBase64String(File.ReadAllBytes("MyImage.jpg")); var imgBlob = new NewBlob { Encoding = EncodingType.Base64, Content = (imgBase64) }; var imgBlobRef = await _client.Git.Blob.Create(owner, repositoryName, imgBlob); var textBlob = new NewBlob { Encoding = EncodingType.Utf8, Content = "Hellow World!" }; var textBlobRef = await _client.Git.Blob.Create(owner, repositoryName, textBlob); var nt = new NewTree { BaseTree = latestCommit.Tree.Sha }; nt.Tree.Add(new NewTreeItem { Path = "MyImage.jpg", Mode = "100644", Type = TreeType.Blob, Sha = imgBlobRef.Sha }); nt.Tree.Add(new NewTreeItem { Path = "HelloW.txt", Mode = "100644", Type = TreeType.Blob, Sha = textBlobRef.Sha }); var newTree = await _client.Git.Tree.Create(owner, repositoryName, nt); // Create Commit var newCommit = new NewCommit("Commit test with several files", newTree.Sha, masterReference.Object.Sha); var commit = await _client.Git.Commit.Create(owner, repositoryName, newCommit); await _client.Git.Reference.Update(owner, repositoryName, headMasterRef, new ReferenceUpdate(commit.Sha)); }
public DeploymentsClientTests() { _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; }
async Task <Commit> CreateCommit(string repoName, string blobContent, string treePath, string reference, string commitMessage) { // Creating a blob var blob = new NewBlob { Content = blobContent, Encoding = EncodingType.Utf8 }; var createdBlob = await _github.Git.Blob.Create(Helper.UserName, repoName, blob); // Creating a tree var newTree = new NewTree(); newTree.Tree.Add(new NewTreeItem { Type = TreeType.Blob, Mode = FileMode.File, Path = treePath, Sha = createdBlob.Sha }); var createdTree = await _github.Git.Tree.Create(Helper.UserName, repoName, newTree); var treeSha = createdTree.Sha; // Creating a commit var parent = await _github.Git.Reference.Get(Helper.UserName, repoName, reference); var commit = new NewCommit(commitMessage, treeSha, parent.Object.Sha); var createdCommit = await _github.Git.Commit.Create(Helper.UserName, repoName, commit); await _github.Git.Reference.Update(Helper.UserName, repoName, reference, new ReferenceUpdate(createdCommit.Sha)); return(createdCommit); }
public async static Task <Reference> CreateFeatureBranch(string owner, string repo, string parentSha, string branchName) { var github = Helper.GetAuthenticatedClient(); // Create content blob var baselineBlob = new NewBlob { Content = "I am overwriting this blob with something new", Encoding = EncodingType.Utf8 }; var baselineBlobResult = await github.Git.Blob.Create(owner, repo, baselineBlob); // Create tree item var treeItem = new NewTreeItem { Type = TreeType.Blob, Mode = FileMode.File, Path = "README.md", Sha = baselineBlobResult.Sha }; // Create tree var newTree = new NewTree(); newTree.Tree.Add(treeItem); var tree = await github.Git.Tree.Create(owner, repo, newTree); // Create commit var newCommit = new NewCommit("this is the new commit", tree.Sha, parentSha); var commit = await github.Git.Commit.Create(owner, repo, newCommit); // Create branch var branch = await github.Git.Reference.Create(owner, repo, new NewReference($"refs/heads/{branchName}", commit.Sha)); // Return commit return(branch); }
public async Task CanCreateATreeWithRepositoryId() { var blob = new NewBlob { Content = "Hello World!", Encoding = EncodingType.Utf8 }; var createdBlob = await _github.Git.Blob.Create(_context.RepositoryOwner, _context.RepositoryName, blob); var newTree = new NewTree(); newTree.Tree.Add(new NewTreeItem { Type = TreeType.Blob, Path = "README.md", Sha = createdBlob.Sha, Mode = FileMode.File }); var result = await _fixture.Create(_context.Repository.Id, newTree); Assert.NotNull(result); }
public async Task CanCreateATree() { var blob = new NewBlob { Content = "Hello World!", Encoding = EncodingType.Utf8 }; var createdBlob = await _client.GitDatabase.Blob.Create(_owner, _repository.Name, blob); var newTree = new NewTree(); newTree.Tree.Add(new NewTreeItem { Type = TreeType.Blob, Path = "README.md", Sha = createdBlob.Sha, Mode = FileMode.File }); var result = await _fixture.Create(_owner, _repository.Name, newTree); Assert.NotNull(result); }
public async Task CanGetABlobWithBase64TextWithRepositoryId() { var utf8Bytes = Encoding.UTF8.GetBytes("Hello World!"); var base64String = Convert.ToBase64String(utf8Bytes); var newBlob = new NewBlob { Content = base64String, Encoding = EncodingType.Base64 }; var result = await _fixture.Create(_context.Repository.Id, newBlob); var blob = await _fixture.Get(_context.Repository.Id, result.Sha); Assert.Equal(result.Sha, blob.Sha); Assert.Equal(EncodingType.Base64, blob.Encoding); // NOTE: it looks like the blobs you get back from the GitHub API // will have an additional \n on the end. :cool:! var expectedOutput = base64String + "\n"; Assert.Equal(expectedOutput, blob.Content); }
/// <summary> /// Creates a new Blob /// </summary> /// <remarks> /// http://developer.github.com/v3/git/blobs/#create-a-blob /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="newBlob">The new Blob</param> public IObservable <BlobReference> Create(long repositoryId, NewBlob newBlob) { Ensure.ArgumentNotNull(newBlob, "newBlob"); return(_client.Create(repositoryId, newBlob).ToObservable()); }
/// <summary> /// Writes contents to a specified blob in the specified GitHub repository. /// </summary> /// <param name="appConfig">The application configuration object which contains values /// for connecting to the specified GitHub repository.</param> /// <param name="privateKey">The RSA private key of a registered GitHub app installed in the specified repository.</param> /// <returns>A task.</returns> public static async Task WriteToRepositoryAsync(ApplicationConfig appConfig, string privateKey) { if (appConfig == null) { throw new ArgumentNullException(nameof(appConfig), "Parameter cannot be null"); } if (string.IsNullOrEmpty(privateKey)) { throw new ArgumentNullException(nameof(privateKey), "Parameter cannot be null or empty"); } var gitHubClient = GitHubClientFactory.GetGitHubClient(appConfig, privateKey); // Get repo references var references = await gitHubClient.Git.Reference.GetAll(appConfig.GitHubOrganization, appConfig.GitHubRepoName); // Check if the working branch is in the refs var workingBranch = references.Where(reference => reference.Ref == $"refs/heads/{appConfig.WorkingBranch}").FirstOrDefault(); // Check if branch already exists if (workingBranch == null) { // Working branch does not exist, so branch off from the reference branch var refBranch = references.Where(reference => reference.Ref == $"refs/heads/{appConfig.ReferenceBranch}").FirstOrDefault(); // Create new branch; exception will throw if branch already exists workingBranch = await gitHubClient.Git.Reference.Create(appConfig.GitHubOrganization, appConfig.GitHubRepoName, new NewReference($"refs/heads/{appConfig.WorkingBranch}", refBranch.Object.Sha)); } // Get reference of the working branch var workingReference = await gitHubClient.Git.Reference.Get(appConfig.GitHubOrganization, appConfig.GitHubRepoName, workingBranch.Ref); // Get the latest commit of this branch var latestCommit = await gitHubClient.Git.Commit.Get(appConfig.GitHubOrganization, appConfig.GitHubRepoName, workingReference.Object.Sha); // Create blob NewBlob blob = new NewBlob { Encoding = EncodingType.Utf8, Content = appConfig.FileContent }; BlobReference blobRef = await gitHubClient.Git.Blob.Create(appConfig.GitHubOrganization, appConfig.GitHubRepoName, blob); // Create new Tree var tree = new NewTree { BaseTree = latestCommit.Tree.Sha }; var treeMode = (int)appConfig.TreeItemMode; // Add items based on blobs tree.Tree.Add(new NewTreeItem { Path = appConfig.FileContentPath, Mode = treeMode.ToString(), Type = TreeType.Blob, Sha = blobRef.Sha }); var newTree = await gitHubClient.Git.Tree.Create(appConfig.GitHubOrganization, appConfig.GitHubRepoName, tree); // Create a commit var newCommit = new NewCommit(appConfig.CommitMessage, newTree.Sha, workingReference.Object.Sha); var commit = await gitHubClient.Git.Commit.Create(appConfig.GitHubOrganization, appConfig.GitHubRepoName, newCommit); // Push the commit await gitHubClient.Git.Reference.Update(appConfig.GitHubOrganization, appConfig.GitHubRepoName, workingBranch.Ref, new ReferenceUpdate(commit.Sha)); }
public async Task WriteToRepositoryAsync(ApplicationConfig appConfig, string privateKey) { if (appConfig == null) { throw new ArgumentNullException(nameof(appConfig), "Parameter cannot be null"); } try { string token = await GitHubAuthService.GetGithubAppTokenAsync(appConfig, privateKey); // Pass the JWT as a Bearer token to Octokit.net var finalClient = new GitHubClient(new ProductHeaderValue(appConfig.GitHubAppName)) { Credentials = new Credentials(token, AuthenticationType.Bearer) }; // Get repo references var references = await finalClient.Git.Reference.GetAll(appConfig.GitHubOrganization, appConfig.GitHubRepoName); // Check if the working branch is in the refs var workingBranch = references.Where(reference => reference.Ref == $"refs/heads/{appConfig.WorkingBranch}").FirstOrDefault(); // Check if branch already exists. if (workingBranch == null) { // Working branch does not exist so branch off reference branch var refBranch = references.Where(reference => reference.Ref == $"refs/heads/{appConfig.ReferenceBranch}").FirstOrDefault(); // Exception will throw if branch already exists var newBranch = await finalClient.Git.Reference.Create(appConfig.GitHubOrganization, appConfig.GitHubRepoName, new NewReference($"refs/heads/{appConfig.WorkingBranch}", refBranch.Object.Sha)); // create file var createChangeSet = await finalClient.Repository.Content.CreateFile( appConfig.GitHubOrganization, appConfig.GitHubRepoName, appConfig.FileContentPath, new CreateFileRequest(appConfig.CommitMessage, appConfig.FileContent, appConfig.WorkingBranch)); } else { // Get reference of the working branch var masterReference = await finalClient.Git.Reference.Get(appConfig.GitHubOrganization, appConfig.GitHubRepoName, workingBranch.Ref); // Get the latest commit of this branch var latestCommit = await finalClient.Git.Commit.Get(appConfig.GitHubOrganization, appConfig.GitHubRepoName, masterReference.Object.Sha); // Create blob NewBlob blob = new NewBlob { Encoding = EncodingType.Utf8, Content = appConfig.FileContent }; BlobReference blobRef = await finalClient.Git.Blob.Create(appConfig.GitHubOrganization, appConfig.GitHubRepoName, blob); // Create new Tree var tree = new NewTree { BaseTree = latestCommit.Tree.Sha }; // Add items based on blobs tree.Tree.Add(new NewTreeItem { Path = appConfig.FileContentPath, Mode = appConfig.TreeItemMode.ToString(), Type = TreeType.Blob, Sha = blobRef.Sha }); var newTree = await finalClient.Git.Tree.Create(appConfig.GitHubOrganization, appConfig.GitHubRepoName, tree); // Create commit var newCommit = new NewCommit(appConfig.CommitMessage, newTree.Sha, masterReference.Object.Sha); var commit = await finalClient.Git.Commit.Create(appConfig.GitHubOrganization, appConfig.GitHubRepoName, newCommit); // Push the commit await finalClient.Git.Reference.Update(appConfig.GitHubOrganization, appConfig.GitHubRepoName, workingBranch.Ref, new ReferenceUpdate(commit.Sha)); } // Create PR var pullRequest = await finalClient.Repository.PullRequest.Create(appConfig.GitHubOrganization, appConfig.GitHubAppName, new NewPullRequest(appConfig.PullRequestTitle, appConfig.WorkingBranch, appConfig.ReferenceBranch) { Body = appConfig.PullRequestBody }); // Add reviewers var teamMembers = appConfig.Reviewers; var reviewersResult = await finalClient.Repository.PullRequest.ReviewRequest.Create(appConfig.GitHubOrganization, appConfig.GitHubRepoName, pullRequest.Number, new PullRequestReviewRequest(teamMembers.AsReadOnly(), null)); // Add label var issueUpdate = new IssueUpdate(); issueUpdate.AddAssignee(appConfig.PullRequestAssignee); issueUpdate.AddLabel(appConfig.PullRequestLabel); // Update the PR with the relevant info await finalClient.Issue.Update(appConfig.GitHubOrganization, appConfig.GitHubRepoName, pullRequest.Number, issueUpdate); } catch (Exception ex) { throw ex; } }
/// <summary> /// Creates a new Blob /// </summary> /// <remarks> /// http://developer.github.com/v3/git/blobs/#create-a-blob /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="newBlob">The new Blob</param> public IObservable<BlobReference> Create(long repositoryId, NewBlob newBlob) { Ensure.ArgumentNotNull(newBlob, "newBlob"); return _client.Create(repositoryId, newBlob).ToObservable(); }
private async Task<Commit> CommitToRepository(RepositorySummary repositorySummary) { var owner = repositorySummary.Owner; var repository = repositorySummary.Name; var blob = new NewBlob { Content = "Hello World!", Encoding = EncodingType.Utf8 }; var blobResult = await _client.Git.Blob.Create(owner, repository, blob); var newTree = new NewTree(); newTree.Tree.Add(new NewTreeItem { Type = TreeType.Blob, Mode = FileMode.File, Path = "README.md", Sha = blobResult.Sha }); var treeResult = await _client.Git.Tree.Create(owner, repository, newTree); var newCommit = new NewCommit("test-commit", treeResult.Sha); var commit = await _fixture.Create(owner, repository, newCommit); return commit; }