-
Notifications
You must be signed in to change notification settings - Fork 26
/
getFileHistory.ts
79 lines (74 loc) · 1.79 KB
/
getFileHistory.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import * as Diff from "diff"
import * as git from "isomorphic-git"
import { CommitDescription, GitBlobDescription } from "../../types"
export async function getFileHistory(
dir: string,
ref: string,
filepath: string
): Promise<
Array<{
commit: CommitDescription
blob: GitBlobDescription
}>
> {
const commits: CommitDescription[] = await git.log({ dir, ref })
const rawChanges = await Promise.all(
commits.map(async commit => {
try {
const blob = await git.readObject({
dir,
oid: commit.oid,
filepath
})
return {
commit,
blob
}
} catch (e) {
return
}
})
)
const history: any = rawChanges.filter(r => r != null).reverse()
const fileChanges = history.reduce(
(acc: any, current: any, index: number) => {
const prev = history[index - 1]
if (prev && prev.blob.oid !== current.blob.oid) {
return [...acc, current]
} else {
return acc
}
},
[history[0]]
)
return fileChanges.filter((f: any) => f != null)
}
export async function getFileHistoryWithDiff(
dir: string,
ref: string,
filepath: string
): Promise<
Array<{
commit: CommitDescription
blob: GitBlobDescription
diff: Array<{
value: string
count: number
removed?: boolean
added?: boolean
}>
}>
> {
const history = await getFileHistory(dir, ref, filepath)
return history.map((current, index) => {
const prev = history[index - 1]
const currentRaw = current.blob.object.toString()
const prevRaw = prev == null ? "" : prev.blob.object.toString()
const diff = Diff.diffLines(prevRaw, currentRaw)
// const diff = diff3Merge(currentRaw, currentRaw, prevRaw)
return {
...current,
diff
}
})
}