1 import { Octokit } from "octokit"
2 import promiseExec from "../../utils/promise-exec.js"
3 import getMonorepoRoot from "../../utils/get-monorepo-root.js"
4 import filterFiles from "../../utils/filter-files.js"
5
6 type Options = {
7 owner?: string
8 repo?: string
9 authToken?: string
10 }
11
12 export class GitManager {
13 private owner: string
14 private repo: string
15 private authToken: string
16 private octokit: Octokit
17 private gitApiVersion = "2022-11-28"
18
19 constructor(options?: Options) {
20 this.owner = options?.owner || process.env.GIT_OWNER || ""
21 this.repo = options?.repo || process.env.GIT_REPO || ""
22 this.authToken = options?.authToken || process.env.GITHUB_TOKEN || ""
23
24 this.octokit = new Octokit({
25 auth: this.authToken,
26 })
27 }
28
29 async getCommitFilesSinceRelease(tagName: string) {
30 const { data: release } = await this.octokit.request(
31 "GET /repos/{owner}/{repo}/releases/tags/{tag}",
32 {
33 owner: this.owner,
34 repo: this.repo,
35 tag: tagName,
36 headers: {
37 "X-GitHub-Api-Version": this.gitApiVersion,
38 },
39 }
40 )
41
42 return this.getCommitsFiles(release.published_at)
43 }
44
45 async getCommitFilesSinceLastRelease() {
46 // list releases to get the latest two releases
47 const { data: release } = await this.octokit.request(
48 "GET /repos/{owner}/{repo}/releases/latest",
49 {
50 owner: this.owner,
51 repo: this.repo,
52 headers: {
53 "X-GitHub-Api-Version": this.gitApiVersion,
54 },
55 }
56 )
57
58 return this.getCommitsFiles(release.published_at)
59 }
60
61 async getCommitsFiles(date?: string | null) {
62 // get commits between the last two releases
63 const commits = await this.octokit.paginate(
64 "GET /repos/{owner}/{repo}/commits",
65 {
66 owner: this.owner,
67 repo: this.repo,
68 since: date || undefined,
69 per_page: 100,
70 }
71 )
72
73 // get files of each of the commits
74 const files = new Set<string>()
75
76 await Promise.all(
77 commits.map(async (commit) => {
78 const commitFiles = await this.getCommitFiles(commit.sha)
79
80 commitFiles?.forEach((commitFile) => files.add(commitFile.filename))
81 })
82 )
83
84 return [...files]
85 }
86
87 async getDiffFiles(): Promise<string[]> {
88 const childProcess = await promiseExec(
89 `git diff --name-only -- "packages/**/**.ts" "packages/**/*.js" "packages/**/*.tsx" "packages/**/*.jsx"`,
90 {
91 cwd: getMonorepoRoot(),
92 }
93 )
94
95 return filterFiles(
96 childProcess.stdout.toString().split("\n").filter(Boolean)
97 )
98 }
99
100 async getCommitFiles(commitSha: string) {
101 const {
102 data: { files },
103 } = await this.octokit.request("GET /repos/{owner}/{repo}/commits/{ref}", {
104 owner: "medusajs",
105 repo: "medusa",
106 ref: commitSha,
107 headers: {
108 "X-GitHub-Api-Version": "2022-11-28",
109 },
110 per_page: 3000,
111 })
112
113 return files
114 }
115 }