@eliya-oss/agent-diff 0.1.0-alpha.0 → 0.1.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/LICENSE +21 -0
  3. package/README.md +72 -189
  4. package/bin/adiff.js +1 -1
  5. package/dist/main.js +14467 -0
  6. package/package.json +8 -6
  7. package/src/cli/catalog.ts +0 -178
  8. package/src/cli/commands.ts +0 -335
  9. package/src/cli/error.ts +0 -44
  10. package/src/cli/index.ts +0 -24
  11. package/src/cli/parse.ts +0 -31
  12. package/src/cli/report.ts +0 -96
  13. package/src/cli/story.ts +0 -223
  14. package/src/domain/narrative/coverage.ts +0 -54
  15. package/src/domain/narrative/index.ts +0 -4
  16. package/src/domain/narrative/model.ts +0 -46
  17. package/src/domain/narrative/version.ts +0 -63
  18. package/src/domain/patch/anchor.ts +0 -40
  19. package/src/domain/patch/index.ts +0 -7
  20. package/src/domain/patch/model.ts +0 -54
  21. package/src/domain/patch/parse.ts +0 -106
  22. package/src/domain/patch/render.ts +0 -48
  23. package/src/domain/patch/sticky.ts +0 -39
  24. package/src/domain/review/index.ts +0 -4
  25. package/src/domain/review/lifecycle.ts +0 -45
  26. package/src/domain/review/model.ts +0 -23
  27. package/src/domain/review/vouch.ts +0 -15
  28. package/src/main.ts +0 -186
  29. package/src/service/git/error.ts +0 -16
  30. package/src/service/git/index.ts +0 -3
  31. package/src/service/git/model.ts +0 -13
  32. package/src/service/git/run.ts +0 -27
  33. package/src/service/git/service.ts +0 -133
  34. package/src/service/store/error.ts +0 -11
  35. package/src/service/store/index.ts +0 -5
  36. package/src/service/store/model.ts +0 -33
  37. package/src/service/store/paths.ts +0 -25
  38. package/src/service/store/service.ts +0 -154
  39. package/src/testing/agent-surface.test.ts +0 -92
  40. package/src/testing/batch.test.ts +0 -93
  41. package/src/testing/branch-state.test.ts +0 -99
  42. package/src/testing/chrome-tone.test.ts +0 -57
  43. package/src/testing/comment-block.test.ts +0 -84
  44. package/src/testing/comment-walk.test.ts +0 -96
  45. package/src/testing/compose-box.test.ts +0 -97
  46. package/src/testing/compose.test.ts +0 -67
  47. package/src/testing/context.test.ts +0 -77
  48. package/src/testing/cursor.test.ts +0 -49
  49. package/src/testing/delivery.test.ts +0 -94
  50. package/src/testing/domains/agent/driver.ts +0 -50
  51. package/src/testing/domains/agent/index.ts +0 -2
  52. package/src/testing/domains/app/driver.ts +0 -168
  53. package/src/testing/domains/app/index.ts +0 -2
  54. package/src/testing/domains/branch/driver.ts +0 -51
  55. package/src/testing/domains/branch/index.ts +0 -3
  56. package/src/testing/domains/branch/model.ts +0 -39
  57. package/src/testing/domains/screen/driver.ts +0 -241
  58. package/src/testing/domains/screen/index.ts +0 -2
  59. package/src/testing/driver.ts +0 -31
  60. package/src/testing/escape.test.ts +0 -56
  61. package/src/testing/focus.test.ts +0 -104
  62. package/src/testing/footer-chips.test.ts +0 -65
  63. package/src/testing/footer.test.ts +0 -64
  64. package/src/testing/gaps.test.ts +0 -47
  65. package/src/testing/highlight.test.ts +0 -49
  66. package/src/testing/home-screen.test.ts +0 -51
  67. package/src/testing/index.ts +0 -4
  68. package/src/testing/inline-comments.test.ts +0 -131
  69. package/src/testing/marks.test.ts +0 -49
  70. package/src/testing/mouse.test.ts +0 -87
  71. package/src/testing/navigate.test.ts +0 -73
  72. package/src/testing/palette.test.ts +0 -68
  73. package/src/testing/pending.test.ts +0 -70
  74. package/src/testing/pin-align.test.ts +0 -37
  75. package/src/testing/progress.test.ts +0 -88
  76. package/src/testing/report.test.ts +0 -83
  77. package/src/testing/resume.test.ts +0 -39
  78. package/src/testing/review.test.ts +0 -181
  79. package/src/testing/roundtrip.test.ts +0 -70
  80. package/src/testing/scale.test.ts +0 -55
  81. package/src/testing/scroll-feel.test.ts +0 -81
  82. package/src/testing/sent-comments.test.ts +0 -106
  83. package/src/testing/state.ts +0 -55
  84. package/src/testing/sticky-removed.test.ts +0 -67
  85. package/src/testing/sticky.test.ts +0 -90
  86. package/src/testing/story-rail.test.ts +0 -122
  87. package/src/testing/story.test.ts +0 -183
  88. package/src/testing/stress.test.ts +0 -74
  89. package/src/testing/tree-collapse.test.ts +0 -108
  90. package/src/testing/tree-rows.test.ts +0 -66
  91. package/src/testing/tree.test.ts +0 -91
  92. package/src/testing/tui.test.ts +0 -73
  93. package/src/testing/typing.test.ts +0 -65
  94. package/src/testing/vouch-next.test.ts +0 -65
  95. package/src/testing/vouch-tui.test.ts +0 -77
  96. package/src/testing/wash.test.ts +0 -32
  97. package/src/testing/width.test.ts +0 -62
  98. package/src/tui/app.ts +0 -467
  99. package/src/tui/command.ts +0 -390
  100. package/src/tui/diffview.ts +0 -333
  101. package/src/tui/index.ts +0 -9
  102. package/src/tui/marks.ts +0 -102
  103. package/src/tui/match.ts +0 -34
  104. package/src/tui/model.ts +0 -310
  105. package/src/tui/reduce.ts +0 -305
  106. package/src/tui/render.ts +0 -897
  107. package/src/tui/report.ts +0 -74
  108. package/src/tui/session.ts +0 -32
  109. package/src/tui/theme.ts +0 -61
  110. package/src/tui/tree.ts +0 -149
@@ -1,106 +0,0 @@
1
- import { Option } from "effect"
2
- import type { Hunk, Patch, Row, RowKind } from "./model.ts"
3
-
4
- const FILE_MARKER = "diff --git "
5
- const HUNK_MARKER = "@@"
6
- const BLOB_MARKER = "index "
7
- const OLD_PATH_MARKER = "--- "
8
- const NEW_PATH_MARKER = "+++ "
9
-
10
- const HUNK_HEADER = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@ ?(.*)$/
11
- const FILE_HEADER = / a\/(.+) b\/(.+)$/
12
-
13
- const SIGNS: Record<string, RowKind> = { " ": "context", "+": "added", "-": "removed" }
14
-
15
- type Draft = {
16
- path: string
17
- previousPath: string
18
- blob: string
19
- headerLines: Array<string>
20
- hunks: Array<Hunk & { rows: Array<Row> }>
21
- rows: Array<Row>
22
- added: number
23
- removed: number
24
- oldLine: number
25
- newLine: number
26
- }
27
-
28
- const draftFrom = (line: string): Draft => {
29
- const named = FILE_HEADER.exec(line)
30
- return {
31
- path: named?.[2] ?? "",
32
- previousPath: named?.[1] ?? "",
33
- blob: "",
34
- headerLines: [line],
35
- hunks: [],
36
- rows: [],
37
- added: 0,
38
- removed: 0,
39
- oldLine: 1,
40
- newLine: 1,
41
- }
42
- }
43
-
44
- const openHunk = (draft: Draft, line: string): void => {
45
- const header = HUNK_HEADER.exec(line)
46
- const previousNew = draft.newLine
47
- draft.oldLine = Number(header?.[1] ?? 1)
48
- draft.newLine = Number(header?.[2] ?? 1)
49
- draft.hunks.push({
50
- marker: line,
51
- scope: (header?.[3] ?? "").trim(),
52
- startRow: draft.rows.length,
53
- rows: [],
54
- skipped: draft.hunks.length === 0 ? 0 : Math.max(0, draft.newLine - previousNew),
55
- })
56
- }
57
-
58
- const appendRow = (draft: Draft, kind: RowKind, text: string): void => {
59
- const row: Row = {
60
- index: draft.rows.length,
61
- kind,
62
- oldLine: kind === "added" ? Option.none() : Option.some(draft.oldLine),
63
- newLine: kind === "removed" ? Option.none() : Option.some(draft.newLine),
64
- text,
65
- }
66
- if (kind !== "added") draft.oldLine += 1
67
- if (kind !== "removed") draft.newLine += 1
68
- if (kind === "added") draft.added += 1
69
- if (kind === "removed") draft.removed += 1
70
- draft.rows.push(row)
71
- draft.hunks.at(-1)?.rows.push(row)
72
- }
73
-
74
- const readBody = (draft: Draft, line: string): void => {
75
- const kind = SIGNS[line.slice(0, 1)]
76
- if (kind !== undefined) appendRow(draft, kind, line.slice(1))
77
- }
78
-
79
- const readHeader = (draft: Draft, line: string): boolean => {
80
- if (line.startsWith(BLOB_MARKER)) {
81
- draft.blob = line.slice(BLOB_MARKER.length).split("..")[1]?.split(" ")[0] ?? ""
82
- draft.headerLines.push(line)
83
- return true
84
- }
85
- if (line.startsWith(OLD_PATH_MARKER) || line.startsWith(NEW_PATH_MARKER)) {
86
- draft.headerLines.push(line)
87
- return true
88
- }
89
- return false
90
- }
91
-
92
- export const parsePatches = (diff: string): ReadonlyArray<Patch> => {
93
- const drafts: Array<Draft> = []
94
- for (const line of diff.split("\n")) {
95
- if (line.startsWith(FILE_MARKER)) {
96
- drafts.push(draftFrom(line))
97
- continue
98
- }
99
- const draft = drafts.at(-1)
100
- if (draft === undefined) continue
101
- if (readHeader(draft, line)) continue
102
- if (line.startsWith(HUNK_MARKER)) openHunk(draft, line)
103
- else readBody(draft, line)
104
- }
105
- return drafts
106
- }
@@ -1,48 +0,0 @@
1
- import { Option } from "effect"
2
- import { lineOn, type Patch, type Row, type RowKind } from "./model.ts"
3
-
4
- const SIGNS: Record<RowKind, string> = { context: " ", added: "+", removed: "-" }
5
-
6
- export type RenderedHunk = {
7
- readonly startRow: number
8
- readonly scope: string
9
- }
10
-
11
- export type Rendered = {
12
- readonly text: string
13
- readonly hunks: ReadonlyArray<RenderedHunk>
14
- }
15
-
16
- export const renderPatch = (patch: Patch): Rendered => {
17
- const lines: Array<string> = [...patch.headerLines]
18
- for (const hunk of patch.hunks) {
19
- lines.push(hunk.marker)
20
- for (const row of hunk.rows) lines.push(`${SIGNS[row.kind]}${row.text}`)
21
- }
22
- return {
23
- text: lines.join("\n"),
24
- hunks: patch.hunks.map((hunk) => ({ startRow: hunk.startRow, scope: hunk.scope })),
25
- }
26
- }
27
-
28
- export const scopeAbove = (rendered: Rendered, topRow: number): string => {
29
- const hunk = rendered.hunks.findLast((candidate) => candidate.startRow < topRow)
30
- return hunk === undefined ? "" : hunk.scope
31
- }
32
-
33
- const countOn = (rows: ReadonlyArray<Row>, side: "old" | "new"): number =>
34
- rows.filter((row) => Option.isSome(lineOn(row, side))).length
35
-
36
- const firstOn = (rows: ReadonlyArray<Row>, side: "old" | "new"): number => {
37
- const found = rows.find((row) => Option.isSome(lineOn(row, side)))
38
- return found === undefined ? 1 : Option.getOrElse(lineOn(found, side), () => 1)
39
- }
40
-
41
- export const renderWindow = (patch: Patch, from: number, count: number): string => {
42
- const rows = patch.rows.slice(from, from + count)
43
- if (rows.length === 0) return patch.headerLines.join("\n")
44
- const marker = `@@ -${firstOn(rows, "old")},${countOn(rows, "old")} +${firstOn(rows, "new")},${countOn(rows, "new")} @@`
45
- return [...patch.headerLines, marker, ...rows.map((row) => `${SIGNS[row.kind]}${row.text}`)].join(
46
- "\n",
47
- )
48
- }
@@ -1,39 +0,0 @@
1
- const CLOSER = /^[)\]}>;,]/
2
- const COMMENT = /^(\/\/|\/\*|\*|#|<!--)/
3
- const LOOKAHEAD = 5
4
-
5
- const indentOf = (text: string): number => text.length - text.trimStart().length
6
-
7
- const pinnable = (text: string): boolean => {
8
- const trimmed = text.trim()
9
- if (trimmed.length === 0) return false
10
- return !CLOSER.test(trimmed) && !COMMENT.test(trimmed)
11
- }
12
-
13
- const limitFrom = (source: ReadonlyArray<string>, index: number): number => {
14
- const here = source[index] ?? ""
15
- if (here.trim().length > 0) return indentOf(here)
16
- const ahead = source.slice(index, index + LOOKAHEAD).find((line) => line.trim().length > 0)
17
- return ahead === undefined ? 0 : indentOf(ahead)
18
- }
19
-
20
- export const stickyChain = (
21
- source: ReadonlyArray<string>,
22
- line: number,
23
- max: number,
24
- ): ReadonlyArray<string> => {
25
- const index = line - 1
26
- if (index <= 0 || index >= source.length) return []
27
- let limit = limitFrom(source, index)
28
- const chain: Array<string> = []
29
- for (let above = index - 1; above >= 0; above -= 1) {
30
- const text = source[above] ?? ""
31
- if (!pinnable(text)) continue
32
- const indent = indentOf(text)
33
- if (indent >= limit) continue
34
- chain.push(text)
35
- limit = indent
36
- if (indent === 0) break
37
- }
38
- return chain.toReversed().slice(0, max)
39
- }
@@ -1,4 +0,0 @@
1
- export { advance, commentOn, needsAttention, stage, submitAll } from "./lifecycle.ts"
2
- export { isVouched, vouch, vouchedCount } from "./vouch.ts"
3
- export { CommentId } from "./model.ts"
4
- export type { Comment, CommentState, VouchedFile, Vouches } from "./model.ts"
@@ -1,45 +0,0 @@
1
- import { Option } from "effect"
2
- import type { Comment, CommentState } from "./model.ts"
3
-
4
- const RANK: Readonly<Record<CommentState, number>> = {
5
- draft: 0,
6
- submitted: 1,
7
- seen: 2,
8
- working: 3,
9
- question: 4,
10
- done: 5,
11
- wontfix: 5,
12
- }
13
-
14
- const RESUMABLE: ReadonlySet<CommentState> = new Set<CommentState>(["question"])
15
-
16
- const permits = (from: CommentState, to: CommentState): boolean =>
17
- RANK[to] > RANK[from] || RESUMABLE.has(from)
18
-
19
- export const commentOn = (id: string, anchor: Comment["anchor"], body: string): Comment => ({
20
- id,
21
- anchor,
22
- body,
23
- state: "draft",
24
- reply: Option.none(),
25
- })
26
-
27
- export const advance = (
28
- comment: Comment,
29
- to: CommentState,
30
- reply: Option.Option<string>,
31
- ): Option.Option<Comment> =>
32
- permits(comment.state, to)
33
- ? Option.some({ ...comment, state: to, reply: Option.orElse(reply, () => comment.reply) })
34
- : Option.none()
35
-
36
- export const needsAttention = (comments: ReadonlyArray<Comment>): ReadonlyArray<Comment> =>
37
- comments.filter((comment) => comment.state === "question")
38
-
39
- export const stage = (staged: ReadonlyArray<Comment>, comment: Comment): ReadonlyArray<Comment> => [
40
- ...staged,
41
- comment,
42
- ]
43
-
44
- export const submitAll = (staged: ReadonlyArray<Comment>): ReadonlyArray<Comment> =>
45
- staged.map((comment) => ({ ...comment, state: "submitted" as const }))
@@ -1,23 +0,0 @@
1
- import { Schema } from "effect"
2
- import type { Option } from "effect"
3
- import type { Anchor } from "../patch/index.ts"
4
-
5
- export const CommentId = Schema.String.pipe(Schema.brand("@adiff/CommentId"))
6
- export type CommentId = typeof CommentId.Type
7
-
8
- export type CommentState = "draft" | "submitted" | "seen" | "working" | "question" | "done" | "wontfix"
9
-
10
- export type Comment = {
11
- readonly id: string
12
- readonly anchor: Anchor
13
- readonly body: string
14
- readonly state: CommentState
15
- readonly reply: Option.Option<string>
16
- }
17
-
18
- export type Vouches = Readonly<Record<string, string>>
19
-
20
- export type VouchedFile = {
21
- readonly path: string
22
- readonly blob: string
23
- }
@@ -1,15 +0,0 @@
1
- import type { VouchedFile, Vouches } from "./model.ts"
2
-
3
- export const isVouched = (vouches: Vouches, path: string, blob: string): boolean =>
4
- vouches[path] === blob
5
-
6
- export const vouch = (vouches: Vouches, path: string, blob: string): Vouches => {
7
- if (isVouched(vouches, path, blob)) {
8
- const { [path]: _cleared, ...rest } = vouches
9
- return rest
10
- }
11
- return { ...vouches, [path]: blob }
12
- }
13
-
14
- export const vouchedCount = (vouches: Vouches, files: ReadonlyArray<VouchedFile>): number =>
15
- files.filter((file) => isVouched(vouches, file.path, file.blob)).length
package/src/main.ts DELETED
@@ -1,186 +0,0 @@
1
- import { randomUUID } from "node:crypto"
2
- import { readFile } from "node:fs/promises"
3
- import { text as readStream } from "node:stream/consumers"
4
- import { Cause, Effect, Exit, Layer } from "effect"
5
- import {
6
- awaitComments,
7
- catalog,
8
- commandNames,
9
- failure,
10
- fieldsOf,
11
- findCommand,
12
- listBranches,
13
- MalformedStory,
14
- narrow,
15
- numeric,
16
- optionsFrom,
17
- required,
18
- reviewProgress,
19
- setStory,
20
- showStory,
21
- stageComment,
22
- submitComment,
23
- submitReview,
24
- takeComments,
25
- toggleVouch,
26
- UnknownCommand,
27
- type Options,
28
- } from "./cli/index.ts"
29
- import { GitLive } from "./service/git/index.ts"
30
- import { runTui } from "./tui/index.ts"
31
- import { storeAt, defaultRoot } from "./service/store/index.ts"
32
-
33
- const WAIT_UNIT = 1000
34
-
35
- const answer = (options: Options, body: Record<string, unknown>): Effect.Effect<void> =>
36
- Effect.sync(() => {
37
- const fields = fieldsOf(options)
38
- const narrowed = Object.fromEntries(
39
- Object.entries(body).map(([key, value]) => [key, narrow(value, fields)]),
40
- )
41
- process.stdout.write(`${JSON.stringify({ ok: true, ...narrowed })}\n`)
42
- })
43
-
44
- const branchList = Effect.fn("Main.branchList")(function* (options: Options) {
45
- const branches = yield* listBranches(yield* required(options, "repo"))
46
- yield* answer(options, { branches })
47
- })
48
-
49
- const commentAdd = Effect.fn("Main.commentAdd")(function* (options: Options) {
50
- const batch = yield* submitComment({
51
- repo: yield* required(options, "repo"),
52
- branch: yield* required(options, "branch"),
53
- file: yield* required(options, "file"),
54
- start: yield* numeric(options, "start"),
55
- end: yield* numeric(options, "end"),
56
- body: yield* required(options, "body"),
57
- side: options["side"] === "old" ? "old" : "new",
58
- id: options["id"] ?? randomUUID(),
59
- at: options["at"] ?? new Date().toISOString(),
60
- })
61
- yield* answer(options, { batch })
62
- })
63
-
64
- const commentTake = Effect.fn("Main.commentTake")(function* (options: Options) {
65
- const worktree = yield* required(options, "worktree")
66
- const wait = Number(options["wait"] ?? 0)
67
- const comments =
68
- wait > 0
69
- ? yield* awaitComments(worktree, Date.now() + wait * WAIT_UNIT)
70
- : yield* takeComments(worktree)
71
- yield* answer(options, { comments })
72
- })
73
-
74
- const commentStage = Effect.fn("Main.commentStage")(function* (options: Options) {
75
- const report = yield* stageComment({
76
- repo: yield* required(options, "repo"),
77
- branch: yield* required(options, "branch"),
78
- file: yield* required(options, "file"),
79
- start: yield* numeric(options, "start"),
80
- end: yield* numeric(options, "end"),
81
- body: yield* required(options, "body"),
82
- side: options["side"] === "old" ? "old" : "new",
83
- id: options["id"] ?? randomUUID(),
84
- at: options["at"] ?? new Date().toISOString(),
85
- })
86
- yield* answer(options, { pending: report.pending })
87
- })
88
-
89
- const reviewSubmit = Effect.fn("Main.reviewSubmit")(function* (options: Options) {
90
- const report = yield* submitReview(
91
- yield* required(options, "repo"),
92
- yield* required(options, "branch"),
93
- options["id"] ?? randomUUID(),
94
- options["at"] ?? new Date().toISOString(),
95
- )
96
- yield* answer(options, { submitted: report.submitted })
97
- })
98
-
99
- const fileVouch = Effect.fn("Main.fileVouch")(function* (options: Options) {
100
- const report = yield* toggleVouch({
101
- repo: yield* required(options, "repo"),
102
- branch: yield* required(options, "branch"),
103
- file: yield* required(options, "file"),
104
- })
105
- yield* answer(options, { vouched: report.vouched, total: report.total })
106
- })
107
-
108
- const reviewStatus = Effect.fn("Main.reviewStatus")(function* (options: Options) {
109
- const report = yield* reviewProgress(
110
- yield* required(options, "repo"),
111
- yield* required(options, "branch"),
112
- )
113
- yield* answer(options, { vouched: report.vouched, total: report.total, pending: report.pending })
114
- })
115
-
116
- const documentAt = Effect.fn("Main.documentAt")(function* (source: string) {
117
- return yield* Effect.tryPromise({
118
- try: () => (source === "-" ? readStream(process.stdin) : readFile(source, "utf8")),
119
- catch: (cause) => new MalformedStory({ reason: String(cause) }),
120
- })
121
- })
122
-
123
- const storySet = Effect.fn("Main.storySet")(function* (options: Options) {
124
- const document = yield* documentAt(yield* required(options, "json"))
125
- const story = yield* setStory(
126
- yield* required(options, "worktree"),
127
- document,
128
- options["at"] ?? new Date().toISOString(),
129
- )
130
- yield* answer(options, { story })
131
- })
132
-
133
- const storyShow = Effect.fn("Main.storyShow")(function* (options: Options) {
134
- const story = yield* showStory(yield* required(options, "worktree"))
135
- yield* answer(options, { story })
136
- })
137
-
138
- const describe = Effect.fn("Main.describe")(function* (options: Options) {
139
- const wanted = options["command"]
140
- const asked = wanted === undefined || wanted === "true" ? undefined : wanted
141
- const found = asked === undefined ? undefined : findCommand(asked)
142
- if (asked !== undefined && found === undefined) {
143
- return yield* new UnknownCommand({ name: asked, known: commandNames })
144
- }
145
- yield* answer(options, { commands: found === undefined ? catalog : [found] })
146
- })
147
-
148
- const routes = {
149
- "branch list": branchList,
150
- "comment add": commentAdd,
151
- "comment stage": commentStage,
152
- "comment take": commentTake,
153
- "review submit": reviewSubmit,
154
- "review progress": reviewStatus,
155
- "story set": storySet,
156
- "story show": storyShow,
157
- describe,
158
- } as const
159
-
160
- const run = Effect.fn("Main.run")(function* (name: string, options: Options) {
161
- const route = Object.hasOwn(routes, name) ? routes[name as keyof typeof routes] : undefined
162
- if (route !== undefined) return yield* route(options)
163
- if (name === "file vouch") return yield* fileVouch(options)
164
- if (name === "review open") {
165
- return yield* runTui(yield* required(options, "repo"), process.env["ADIFF_SESSION"])
166
- }
167
- return yield* new UnknownCommand({ name, known: commandNames })
168
- })
169
-
170
- const nameOf = (argv: ReadonlyArray<string>): string => {
171
- const words = argv.filter((token) => !token.startsWith("--"))
172
- const pair = words.slice(0, 2).join(" ")
173
- return findCommand(pair) === undefined ? (words[0] ?? "") : pair
174
- }
175
-
176
- const argv = process.argv.slice(2)
177
- const layer = Layer.mergeAll(GitLive, storeAt(process.env["ADIFF_ROOT"] ?? defaultRoot()))
178
- const exit = await Effect.runPromiseExit(
179
- run(nameOf(argv), optionsFrom(argv)).pipe(Effect.provide(layer)),
180
- )
181
-
182
- if (Exit.isFailure(exit)) {
183
- const reported = failure(Cause.squash(exit.cause))
184
- process.stderr.write(`${reported.line}\n`)
185
- process.exitCode = reported.exit
186
- }
@@ -1,16 +0,0 @@
1
- import { Data } from "effect"
2
-
3
- export class GitCommandFailed extends Data.TaggedError("GitCommandFailed")<{
4
- readonly command: ReadonlyArray<string>
5
- readonly cwd: string
6
- readonly stderr: string
7
- }> {}
8
-
9
- export class NotARepository extends Data.TaggedError("NotARepository")<{
10
- readonly path: string
11
- }> {}
12
-
13
- export class FileUnreadable extends Data.TaggedError("FileUnreadable")<{
14
- readonly path: string
15
- readonly reason: string
16
- }> {}
@@ -1,3 +0,0 @@
1
- export { Git, GitLive } from "./service.ts"
2
- export { FileUnreadable, GitCommandFailed, NotARepository } from "./error.ts"
3
- export type { DiffStat, Worktree } from "./model.ts"
@@ -1,13 +0,0 @@
1
- export type Worktree = {
2
- readonly path: string
3
- readonly branch: string
4
- readonly head: string
5
- readonly base: string
6
- readonly detached: boolean
7
- }
8
-
9
- export type DiffStat = {
10
- readonly files: number
11
- readonly added: number
12
- readonly removed: number
13
- }
@@ -1,27 +0,0 @@
1
- import { execFile } from "node:child_process"
2
- import { promisify } from "node:util"
3
- import { Effect } from "effect"
4
- import { GitCommandFailed } from "./error.ts"
5
-
6
- const exec = promisify(execFile)
7
-
8
- const MAX_OUTPUT = 64 * 1024 * 1024
9
-
10
- export const git = Effect.fn("Git.run")(function* (cwd: string, args: ReadonlyArray<string>) {
11
- return yield* Effect.tryPromise({
12
- try: () => exec("git", [...args], { cwd, maxBuffer: MAX_OUTPUT, encoding: "utf8" }),
13
- catch: (cause) =>
14
- new GitCommandFailed({
15
- command: args,
16
- cwd,
17
- stderr: cause instanceof Error ? cause.message : String(cause),
18
- }),
19
- }).pipe(Effect.map((result) => result.stdout))
20
- })
21
-
22
- export const gitOrEmpty = Effect.fn("Git.runOrEmpty")(function* (
23
- cwd: string,
24
- args: ReadonlyArray<string>,
25
- ) {
26
- return yield* git(cwd, args).pipe(Effect.catchTag("GitCommandFailed", () => Effect.succeed("")))
27
- })
@@ -1,133 +0,0 @@
1
- import { readFile } from "node:fs/promises"
2
- import { join } from "node:path"
3
- import { Context, Effect, Layer, Option } from "effect"
4
- import { FileUnreadable } from "./error.ts"
5
- import type { DiffStat, Worktree } from "./model.ts"
6
- import { gitOrEmpty } from "./run.ts"
7
-
8
- const DEFAULT_BRANCH_CANDIDATES = ["origin/master", "origin/main", "master", "main"]
9
-
10
- const STAT = /(\d+) files? changed(?:, (\d+) insertions?\(\+\))?(?:, (\d+) deletions?\(-\))?/
11
-
12
- type Shape = {
13
- readonly worktrees: (repo: string) => Effect.Effect<ReadonlyArray<Worktree>>
14
- readonly diff: (worktree: Worktree, context: number) => Effect.Effect<string>
15
- readonly stat: (worktree: Worktree) => Effect.Effect<DiffStat>
16
- readonly source: (
17
- worktree: Worktree,
18
- path: string,
19
- ) => Effect.Effect<Option.Option<ReadonlyArray<string>>>
20
- }
21
-
22
- export class Git extends Context.Service<Git, Shape>()("adiff/Git") {}
23
-
24
- const parseStat = (raw: string): DiffStat => {
25
- const matched = STAT.exec(raw)
26
- return {
27
- files: Number(matched?.[1] ?? 0),
28
- added: Number(matched?.[2] ?? 0),
29
- removed: Number(matched?.[3] ?? 0),
30
- }
31
- }
32
-
33
- type Entry = { path: string; branch: string; head: string; detached: boolean }
34
-
35
- const readEntries = (porcelain: string): ReadonlyArray<Entry> => {
36
- const entries: Array<Entry> = []
37
- for (const line of porcelain.split("\n")) {
38
- if (line.startsWith("worktree ")) {
39
- entries.push({ path: line.slice("worktree ".length), branch: "", head: "", detached: false })
40
- }
41
- const current = entries.at(-1)
42
- if (current === undefined) continue
43
- if (line.startsWith("branch ")) current.branch = line.slice("branch ".length).replace("refs/heads/", "")
44
- if (line.startsWith("HEAD ")) current.head = line.slice("HEAD ".length)
45
- if (line === "detached") current.detached = true
46
- }
47
- return entries
48
- }
49
-
50
- const baseNames = new Map<string, string>()
51
- const mergeBases = new Map<string, string>()
52
-
53
- const findDefaultBranch = Effect.fn("Git.findDefaultBranch")(function* (repo: string) {
54
- const symbolic = yield* gitOrEmpty(repo, ["symbolic-ref", "refs/remotes/origin/HEAD"])
55
- if (symbolic.trim().length > 0) return symbolic.trim().replace("refs/remotes/", "")
56
- for (const candidate of DEFAULT_BRANCH_CANDIDATES) {
57
- const verified = yield* gitOrEmpty(repo, ["rev-parse", "--verify", candidate])
58
- if (verified.trim().length > 0) return candidate
59
- }
60
- return "HEAD"
61
- })
62
-
63
- const defaultBranch = Effect.fn("Git.defaultBranch")(function* (repo: string) {
64
- const known = baseNames.get(repo)
65
- if (known !== undefined) return known
66
- const found = yield* findDefaultBranch(repo)
67
- baseNames.set(repo, found)
68
- return found
69
- })
70
-
71
- const mergeBaseOf = Effect.fn("Git.mergeBase")(function* (entry: Entry, base: string) {
72
- const key = `${entry.path} ${entry.head} ${base}`
73
- const known = mergeBases.get(key)
74
- if (known !== undefined) return known
75
- const found = (yield* gitOrEmpty(entry.path, ["merge-base", base, "HEAD"])).trim()
76
- mergeBases.set(key, found)
77
- return found
78
- })
79
-
80
- const toWorktree = Effect.fn("Git.toWorktree")(function* (entry: Entry, base: string) {
81
- const mergeBase = yield* mergeBaseOf(entry, base)
82
- return {
83
- path: entry.path,
84
- branch: entry.detached ? `(detached ${entry.head.slice(0, 8)})` : entry.branch,
85
- head: entry.head.slice(0, 8),
86
- base: mergeBase.slice(0, 8),
87
- detached: entry.detached,
88
- } satisfies Worktree
89
- })
90
-
91
- const splitLines = (text: string): ReadonlyArray<string> => text.split("\n")
92
-
93
- const absent = Effect.succeed(Option.none<string>())
94
-
95
- const readText = Effect.fn("Git.readText")(function* (absolute: string, path: string) {
96
- return yield* Effect.tryPromise({
97
- try: () => readFile(absolute, "utf8"),
98
- catch: (cause) => new FileUnreadable({ path, reason: String(cause) }),
99
- }).pipe(Effect.map(Option.some), Effect.catchTag("FileUnreadable", () => absent))
100
- })
101
-
102
- const listWorktrees = Effect.fn("Git.worktrees")(function* (repo: string) {
103
- const porcelain = yield* gitOrEmpty(repo, ["worktree", "list", "--porcelain"])
104
- const base = yield* defaultBranch(repo)
105
- const entries = readEntries(porcelain)
106
- const found: Array<Worktree> = []
107
- for (const entry of entries) found.push(yield* toWorktree(entry, base))
108
- return found as ReadonlyArray<Worktree>
109
- })
110
-
111
- const readDiff = Effect.fn("Git.diff")(function* (worktree: Worktree, context: number) {
112
- const target = worktree.base.length > 0 ? worktree.base : "HEAD"
113
- return yield* gitOrEmpty(worktree.path, ["diff", `-U${context}`, target])
114
- })
115
-
116
- const readStat = Effect.fn("Git.stat")(function* (worktree: Worktree) {
117
- const raw = yield* gitOrEmpty(worktree.path, ["diff", "--shortstat", worktree.base])
118
- return parseStat(raw)
119
- })
120
-
121
- const readSource = Effect.fn("Git.source")(function* (worktree: Worktree, path: string) {
122
- const text = yield* readText(join(worktree.path, path), path)
123
- return Option.map(text, splitLines)
124
- })
125
-
126
- const shape: Shape = {
127
- worktrees: listWorktrees,
128
- diff: readDiff,
129
- stat: readStat,
130
- source: readSource,
131
- }
132
-
133
- export const GitLive = Layer.succeed(Git)(shape)
@@ -1,11 +0,0 @@
1
- import { Data } from "effect"
2
-
3
- export class StoreUnwritable extends Data.TaggedError("StoreUnwritable")<{
4
- readonly path: string
5
- readonly reason: string
6
- }> {}
7
-
8
- export class StoreUnreadable extends Data.TaggedError("StoreUnreadable")<{
9
- readonly path: string
10
- readonly reason: string
11
- }> {}