Created
March 21, 2023 21:48
-
-
Save ericksoa/ffa543e0241140a851836c5738ab2528 to your computer and use it in GitHub Desktop.
Client to do all the git things
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // gitClient.ts | |
| import { Octokit } from '@octokit/rest'; | |
| export class GitClient { | |
| private octokit: Octokit; | |
| private owner: string; | |
| private repo: string; | |
| constructor(baseURL: string, apiToken: string, owner: string, repo: string) { | |
| this.octokit = new Octokit({ | |
| baseUrl: baseURL, | |
| auth: apiToken, | |
| }); | |
| this.owner = owner; | |
| this.repo = repo; | |
| } | |
| async createBranch(branchName: string): Promise<void> { | |
| const { data: mainBranch } = await this.octokit.git.getRef({ | |
| owner: this.owner, | |
| repo: this.repo, | |
| ref: 'heads/main', | |
| }); | |
| await this.octokit.git.createRef({ | |
| owner: this.owner, | |
| repo: this.repo, | |
| ref: `refs/heads/${branchName}`, | |
| sha: mainBranch.object.sha, | |
| }); | |
| } | |
| async commitCode(branchName: string, code: string): Promise<void> { | |
| const { data: baseTree } = await this.octokit.git.getTree({ | |
| owner: this.owner, | |
| repo: this.repo, | |
| tree_sha: 'main', | |
| }); | |
| const { data: newBlob } = await this.octokit.git.createBlob({ | |
| owner: this.owner, | |
| repo: this.repo, | |
| content: code, | |
| encoding: 'utf-8', | |
| }); | |
| const { data: newTree } = await this.octokit.git.createTree({ | |
| owner: this.owner, | |
| repo: this.repo, | |
| base_tree: baseTree.sha, | |
| tree: [ | |
| { | |
| path: 'generated_code.ts', | |
| mode: '100644', | |
| type: 'blob', | |
| sha: newBlob.sha, | |
| }, | |
| ], | |
| const { data: newCommit } = await this.octokit.git.createCommit({ | |
| owner: this.owner, | |
| repo: this.repo, | |
| message: `Implement ${branchName}`, | |
| tree: newTree.sha, | |
| parents: [baseTree.sha], | |
| }); | |
| await this.octokit.git.updateRef({ | |
| owner: this.owner, | |
| repo: this.repo, | |
| ref: `heads/${branchName}`, | |
| sha: newCommit.sha, | |
| }); | |
| } | |
| async createPullRequest(sourceBranch: string, targetBranch: string, title: string): Promise<void> { | |
| await this.octokit.pulls.create({ | |
| owner: this.owner, | |
| repo: this.repo, | |
| head: sourceBranch, | |
| base: targetBranch, | |
| title: title, | |
| }); | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment