add tests for building file changes

This commit is contained in:
Peter Evans 2024-07-31 21:28:37 +00:00
parent 3d409de49f
commit 7575ead361
3 changed files with 123 additions and 72 deletions

View file

@ -48,6 +48,38 @@ export async function tryFetch(
}
}
export async function buildFileChanges(
git: GitCommandManager,
base: string,
branch: string
): Promise<FileChanges> {
const fileChanges: FileChanges = {
additions: [],
deletions: []
}
const changedFiles = await git.getChangedFiles([
'--diff-filter=AM',
`${base}..${branch}`
])
const deletedFiles = await git.getChangedFiles([
'--diff-filter=D',
`${base}..${branch}`
])
const repoPath = git.getWorkingDirectory()
for (const file of changedFiles) {
fileChanges.additions!.push({
path: file,
contents: utils.readFileBase64([repoPath, file])
})
}
for (const file of deletedFiles) {
fileChanges.deletions!.push({
path: file
})
}
return fileChanges
}
// Return the number of commits that branch2 is ahead of branch1
async function commitsAhead(
git: GitCommandManager,
@ -111,20 +143,22 @@ function splitLines(multilineString: string): string[] {
.filter(x => x !== '')
}
interface FileChanges {
additions: {
path: string
contents: string
}[]
deletions: {
path: string
}[]
}
interface CreateOrUpdateBranchResult {
action: string
base: string
hasDiffWithBase: boolean
headSha: string
fileChanges?: {
additions: {
path: string
contents: string
}[]
deletions: {
path: string
}[]
}
fileChanges?: FileChanges
}
export async function createOrUpdateBranch(
@ -300,39 +334,7 @@ export async function createOrUpdateBranch(
}
if (result.hasDiffWithBase) {
// Build file changes
result.fileChanges = {
additions: [],
deletions: []
}
const changedFiles = await git.getChangedFiles([
'--diff-filter=M',
`${base}..${branch}`
])
const deletedFiles = await git.getChangedFiles([
'--diff-filter=D',
`${base}..${branch}`
])
core.debug(`Changed files: '${JSON.stringify(changedFiles)}'`)
core.debug(`Deleted files: '${JSON.stringify(deletedFiles)}'`)
const repoPath = git.getWorkingDirectory()
for (const file of changedFiles) {
core.debug(`Reading contents of file: '${file}'`)
result.fileChanges.additions!.push({
path: file,
contents: utils.readFileBase64([repoPath, file])
})
}
for (const file of deletedFiles) {
core.debug(`Marking file as deleted: '${file}'`)
result.fileChanges.deletions!.push({
path: file
})
}
result.fileChanges = await buildFileChanges(git, base, branch)
}
// Get the pull request branch SHA