How to Upload Code to Github Repo

If you need to upload a file to GitHub, you lot can do it easily from github.com. However, that doesn't scale. When it comes to doing it on a repeated footing or facilitating automation, y'all'll desire to have a programmatic approach. While GitHub does have a REST API, C# developers can take reward of the Octokit library. This library saves you lot a lot of time—yous can accept advantage of dynamic typing, get data models automatically, and non have to construct HttpClient calls yourself.

This mail service will bear witness yous how to apply the Octokit library to upload a Markdown file to a GitHub repository.

Before nosotros get started, download the Octokit library from NuGet. You lot can practise this in several different ways, just the simplest is using the dotnet CLI. From the path of your project, execute the following from your favorite last:

              dotnet add bundle Octokit                          

Create the customer

To become started, you'll need to create a client so that Octokit tin connect to GitHub. To do that, you can instantiate a new GitHubClient. The GitHubClient takes a ProductHeaderValue, which can be whatever cord—it'southward and then GitHub can identify your application. GitHub doesn't allow API requests without a User-Agent header, and Octokit uses this value to populate one for you lot.

              //using Octokit;  var gitHubClient = new GitHubClient(new ProductHeaderValue("MyCoolApp"));                          

With this single line of code, yous tin can at present admission public GitHub information. For example, you can use a spider web browser to get a user's details. Here's what you get for api.github.com/users/daveabrock:

              {     "login": "daveabrock",     "id": 275862,     "node_id": "MDQ6VXNlcjI3NTg2Mg==",     "avatar_url": "https://avatars.githubusercontent.com/u/275862?v=4",     "gravatar_id": "",     "url": "https://api.github.com/users/daveabrock",     "html_url": "https://github.com/daveabrock",     "followers_url": "https://api.github.com/users/daveabrock/followers",     "following_url": "https://api.github.com/users/daveabrock/following{/other_user}",     "gists_url": "https://api.github.com/users/daveabrock/gists{/gist_id}",     "starred_url": "https://api.github.com/users/daveabrock/starred{/owner}{/repo}",     "subscriptions_url": "https://api.github.com/users/daveabrock/subscriptions",     "organizations_url": "https://api.github.com/users/daveabrock/orgs",     "repos_url": "https://api.github.com/users/daveabrock/repos",     "events_url": "https://api.github.com/users/daveabrock/events{/privacy}",     "received_events_url": "https://api.github.com/users/daveabrock/received_events",     "type": "User",     "site_admin": faux,     "name": "Dave Brock",     "visitor": null,     "web log": "daveabrock.com",     "location": "Madison, WI",     "email": nix,     "hireable": goose egg,     "bio": "Software engineer, Microsoft MVP, speaker, blogger",     "twitter_username": "daveabrock",     "public_repos": 55,     "public_gists": 2,     "followers": 63,     "following": 12,     "created_at": "2010-05-13T20:05:05Z",     "updated_at": "2021-03-13T19:05:32Z" }                          

(Fun fact: it's fun to expect at the id values to see how long a user has been with GitHub—I was the 275,862nd registered user, a few years subsequently GitHub co-founder Tom Preston-Warner, who has an id of 1.)

To get this information programmatically, y'all can utilize the User object:

              //using Octokit;  var gitHubClient = new GitHubClient(new ProductHeaderValue("MyCoolApp")); var user = expect gitHubClient.User.Become("daveabrock"); Console.WriteLine($"Woah! Dave has {user.PublicRepos} public repositories.");                          

That was quick and easy, only not very much fun. To modify anything in a repository you'll need to authenticate.

Authenticate to the API

You can authenticate to the API using one of ii ways: a basic username/password pair or an OAuth menstruation. Using OAuth (from a generated personal access token) is virtually ever a better approach, as y'all won't have to store a password in the code, and you can revoke it as needed. What happens when a password changes? Bad, bad, bad.

Instead, connect by passing in a personal access token (PAT). From your profile details, navigate to Programmer settings > Personal admission tokens, and create one. You'll desire to include the repo permissions. After you create it, re-create and paste the token somewhere. We'll demand it presently.

Generate GitHub personal access token

With the generated PAT, here'due south how you authenticate to the API. (Notation: Be conscientious with your token. In real-world scenarios, make sure to shop it somewhere safe and admission it from your configuration.)

              //using Octokit;  var gitHubClient = new GitHubClient(new ProductHeaderValue("MyCoolApp")); gitHubClient.Credentials = new Credentials("my-new-personal-admission-token");                          

Add a new file to the repository

With that in place, I'g using a StringBuilder to create a simple Markdown file. Hither's what I have and so far:

              //using Octokit;  var gitHubClient = new GitHubClient(new ProductHeaderValue("MyCoolApp")); gitHubClient.Credentials = new Credentials("my-new-personal-admission-token");  var sb = new StringBuilder("---"); sb.AppendLine(); sb.AppendLine($"date: \"2021-05-01\""); sb.AppendLine($"title: \"My new fancy mail service\""); sb.AppendLine("tags: [csharp, azure, dotnet]"); sb.AppendLine("---"); sb.AppendLine();  sb.AppendLine("# The heading for my showtime post"); sb.AppendLine();                          

Because I need to pass in a cord to create my file, I'll use sb.ToString(), to pass it in. I can call the CreateFile method to upload a file now.

              //using Octokit;  var gitHubClient = new GitHubClient(new ProductHeaderValue("MyCoolApp")); gitHubClient.Credentials = new Credentials("my-new-personal-access-token");  var sb = new StringBuilder("---"); sb.AppendLine(); sb.AppendLine($"appointment: \"2021-05-01\""); sb.AppendLine($"title: \"My new fancy updated post\""); sb.AppendLine("tags: [csharp, azure, dotnet]"); sb.AppendLine("---"); sb.AppendLine();  sb.AppendLine("The heading for my first mail service"); sb.AppendLine();  var (owner, repoName, filePath, branch) = ("daveabrock", "daveabrock.github.io",          "_posts/2021-05-02-my-new-mail.markdown", "principal");  expect gitHubClient.Repository.Content.CreateFile(      possessor, repoName, filePath,      new CreateFileRequest($"Showtime commit for {filePath}", sb.ToString(), branch));                          

You can burn down and forget in many cases, but it'southward good to annotation this method returns a Job<RepositoryChangeSet> which gives you back commit and content details.

Update an existing file

If y'all try to execute CreateFile on an existing file, y'all'll get an error that the SHA for the commit doesn't exist. Y'all'll need to fetch the SHA from the event first.

              var sha = result.Commit.Sha;  await gitHubClient.Repository.Content.UpdateFile(possessor, repoName, filePath,     new UpdateFileRequest("My updated file", sb.ToString(), sha));                          

In many scenarios, you won't be editing the file right after you created it. In these cases, become the file details outset:

              var fileDetails = await gitHubClient.Repository.Content.GetAllContentsByRef(owner, repoName,     filePath, co-operative);  var updateResult = await gitHubClient.Repository.Content.UpdateFile(owner, repoName, filePath,     new UpdateFileRequest("My updated file", sb.ToString(), fileDetails.Commencement().Sha));                          

What about base64?

The CreateFile call likewise has a convertContentToBase64 boolean flag, if you'd adopt. For example, I tin pass in an epitome's base64 string and prepare convertContentToBase64 to true.

              string imagePath = @"C:\pics\headshot.jpg"; string base64String = GetImageBase64String(imagePath);  var consequence = await gitHubClient.Repository.Content.CreateFile(      possessor, repoName, filePath,      new CreateFileRequest($"First commit for {filePath}", base64String, branch, true));  static string GetImageBase64String(cord imgPath) {     byte[] imageBytes = Arrangement.IO.File.ReadAllBytes(imgPath);     return Convert.ToBase64String(imageBytes); }                          

Wrap up

I showed you lot how to utilize the Octokit C# library to upload a new file to GitHub in this post. Nosotros also discussed how to update existing files and pass base64 strings to GitHub too. Thanks for reading, and take fun!

CSharpGitHub

haneyarne1952.blogspot.com

Source: https://www.daveabrock.com/2021/03/14/upload-files-to-github-repository/

0 Response to "How to Upload Code to Github Repo"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel