8000 refactor(gh): split the GitHub adapter by what it reads by dominikwozniak · Pull Request #136 · dominikwozniak/dw-mc · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
8000
Diff view
2 changes: 1 addition & 1 deletion docs/adr/0006-source-layout.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ What is a term and what is a rule's input is decided by who has to agree on it.

A module is named, never counted: `#adapters/config.ts`, whether the importer sits in another layer or next door. The name is a node subpath import declared in `package.json`, so it survives the build and reads the same from everywhere, and the layer a module belongs to is stated at each call site rather than inferred from how many `../` precede it. There is no relative import in `src/`, which also means moving a file between layers changes that file and not its importers.

A test lives beside the module it covers, and a module ships the fake its callers need rather than a test-only file next door. The seams are written that way: `src/adapters/spawner.ts` exports the fake spawner and the stubbed one built on it, `src/adapters/store.ts` the in-memory store, `src/adapters/picker.ts` the scripted terminal and the recording console, `src/adapters/config.ts` the in-memory configuration, so a caller's test reaches for one import and gets both the thing and its double. The rule reaches past the seams to the two things a test would otherwise invent. The shape a read answers with belongs to the adapter that makes the read, so `prViewOf` sits beside `prView` in `src/adapters/gh.ts` and a field added to the read has one fixture to grow. The machine those doubles assemble into belongs to `src/cli/cli.ts`, beside the command that runs on it, because the entry point assembles that same stack out of the real layers: a command's test that built its own would be one more answer to the question of what this tool talks to.
A test lives beside the module it covers, and a module ships the fake its callers need rather than a test-only file next door. The seams are written that way: `src/adapters/spawner.ts` exports the fake spawner and the stubbed one built on it, `src/adapters/store.ts` the in-memory store, `src/adapters/picker.ts` the scripted terminal and the recording console, `src/adapters/config.ts` the in-memory configuration, so a caller's test reaches for one import and gets both the thing and its double. The rule reaches past the seams to the two things a test would otherwise invent. The shape a read answers with belongs to the adapter that makes the read, so `prViewOf` sits beside `prView` in `src/adapters/pr.ts` and a field added to the read has one fixture to grow. The machine those doubles assemble into belongs to `src/cli/cli.ts`, beside the command that runs on it, because the entry point assembles that same stack out of the real layers: a command's test that built its own would be one more answer to the question of what this tool talks to.

The layout grows with the code and not ahead of it. A directory appears when there is code to put in it. A fifth layer is a change to this record — rewritten in place, no note of what it replaced — not a directory added quietly next to the others.

Expand Down
21 changes: 20 additions & 1 deletion src/adapters/ci.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { Effect, Schema } from "effect"

import type { CheckEntry } from "#adapters/gh.ts"
import { failedAs, readJson } from "#adapters/gh.ts"
import { capture } from "#adapters/spawner.ts"
import type { ChecksState } from "#terms/pr.ts"
Expand All @@ -11,6 +10,26 @@ import type { ChecksState } from "#terms/pr.ts"
* tool does; what it owns is the checks, not the boundary.
*/

/**
* One entry of a PR's status check rollup.
*
* A rollup mixes two shapes: a `CheckRun` reports a `status` and a `conclusion`,
* a `StatusContext` an overall `state`. Every field is optional because which
* ones arrive depends on which shape it is.
*/
export const CheckEntry = Schema.Struct({
name: Schema.optionalKey(Schema.String),
context: Schema.optionalKey(Schema.String),
status: Schema.optionalKey(Schema.String),
conclusion: Schema.optionalKey(Schema.String),
state: Schema.optionalKey(Schema.String),
/** The workflow the check runs in. A commit status belongs to no workflow. */
workflowName: Schema.optionalKey(Schema.String),
/** Where the check reports, which is the only place its job id appears. */
detailsUrl: Schema.optionalKey(Schema.String)
})
export type CheckEntry = typeof CheckEntry.Type

const failing = new Set(["FAILURE", "TIMED_OUT", "CANCELLED", "STARTUP_FAILURE", "ACTION_REQUIRED", "ERROR"])
const running = new Set(["QUEUED", "IN_PROGRESS", "WAITING", "PENDING", "REQUESTED", "EXPECTED"])

Expand Down
32 changes: 32 additions & 0 deletions src/adapters/conversation.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { assert, describe, it } from "@effect/vitest"
import { Effect } from "effect"

import { prComments } from "#adapters/conversation.ts"
import { layerStubbed, wrote } from "#adapters/spawner.ts"

describe("prComments", () => {
it.effect("says which comments came from an app rather than a person", () => {
const answered = layerStubbed({
stubs: [
(command) =>
wrote(
(command.args[1]?.includes("/issues/") ?? false)
? `[{"created_at":"2026-09-15T08:43:44Z","user":{"login":"coderabbitai[bot]","type":"Bot"}}]`
: `[{"created_at":"2026-09-15T09:00:00Z","user":{"login":"dominikwozniak","type":"User"}}]`
)
]
})

return Effect.gen(function* () {
const comments = yield* prComments("AirHelp/ahplus-rails", 7884)

assert.deepStrictEqual(
comments.map((comment) => [comment.login, comment.bot]),
[
["coderabbitai[bot]", true],
["dominikwozniak", false]
]
)
}).pipe(Effect.provide(answered))
})
})
88 changes: 84 additions & 4 deletions src/adapters/conversation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,92 @@ import { DateTime, Effect, Schema } from "effect"
import { readJson } from "#adapters/gh.ts"

/**
* A pull request's conversation, which is the one read that leaves REST.
* A pull request's conversation, read two ways. A sweep reads who spoke and
* when from REST. A command that prints the conversation reads it in full
* through one GraphQL document, the one read here that leaves REST, because
* only GraphQL says which threads are settled.
*/

const Comments = Schema.fromJsonString(
Schema.Array(
Schema.Struct({
created_at: Schema.DateTimeUtcFromString,
user: Schema.NullOr(Schema.Struct({ login: Schema.String, type: Schema.String }))
})
)
)

/** Who wrote a comment and when. */
export interface Comment {
readonly login: string
readonly bot: boolean
readonly at: DateTime.Utc
}

const comments = (label: string, path: string) =>
readJson(label, "gh", ["api", path], Comments).pipe(
Effect.map((all) =>
all.flatMap((comment): ReadonlyArray<Comment> =>
comment.user === null
? []
: [{ login: comment.user.login, bot: comment.user.type === "Bot", at: comment.created_at }]
)
)
)

/**
* Every comment on a pull request: the ones on the conversation and the ones
* left on the diff.
*
* REST is what says whether an author is a person or an app - `gh pr view`
* reports a bot's login with no sign that it is one - and the bucket rules turn
* on exactly that. Verified by running both: the endpoints ignore `direction`,
* so a page is asked for at its maximum and the newest comment is picked out of
* it rather than asked for first.
*/
export const prComments = Effect.fnUntraced(function* (repo: string, number: number) {
const page = "per_page=100"
const [conversation, onDiff] = yield* Effect.all(
[
comments("api issue comments", `repos/${repo}/issues/${number}/comments?${page}`),
comments("api review comments", `repos/${repo}/pulls/${number}/comments?${page}`)
],
{ concurrency: 2 }
)
return [...conversation, ...onDiff]
})

const Reviews = Schema.fromJsonString(
Schema.Array(
Schema.Struct({
submitted_at: Schema.DateTimeUtcFromString,
body: Schema.String,
user: Schema.NullOr(Schema.Struct({ login: Schema.String, type: Schema.String }))
})
)
)

/**
* The reviews on a pull request that said something, as comments.
*
* It sits beside `gh.ts` rather than in it because it is a boundary of its own:
* one GraphQL document, decoded into the threads a command prints, where every
* other read of GitHub here is a `gh` subcommand or a REST endpoint.
* A review carries a body of its own, which is where a reviewer writes the
* sentence that is not attached to any line. An empty body is a verdict and
* nothing more, and the verdict arrives with the PR as `reviewDecision`.
*/
export const prReviews = Effect.fnUntraced(function* (repo: string, number: number) {
const all = yield* readJson(
"api reviews",
"gh",
["api", `repos/${repo}/pulls/${number}/reviews?per_page=100`],
Reviews
)

return all.flatMap((review): ReadonlyArray<Comment> =>
review.user === null || review.body.trim() === ""
? []
: [{ login: review.user.login, bot: review.user.type === "Bot", at: review.submitted_at }]
)
})

/** One thing somebody said on a pull request, in full. */
export interface Remark {
Expand Down
92 changes: 2 additions & 90 deletions src/adapters/gh.test.ts
C5A5
Original file line number Diff line number Diff line change
@@ -1,16 +1,8 @@
import { assert, describe, it } from "@effect/vitest"
import { Effect, PlatformError } from "effect"

import {
comparedFiles,
currentRepo,
mergeabilityOf,
prComments,
requireAuth,
reviewDecisionOf,
viewer
} from "#adapters/gh.ts"
import { fakeHandle, layerFake, layerStubbed, wrote } from "#adapters/spawner.ts"
import { currentRepo, requireAuth, viewer } from "#adapters/gh.ts"
import { fakeHandle, layerFake, layerStubbed } from "#adapters/spawner.ts"

/** A spawner that answers every program the same way, and records the argv. */
const answering = (spawned: Array<ReadonlyArray<string>>, handle: Parameters<typeof fakeHandle>[0]) =>
Expand Down Expand Up @@ -107,21 +99,6 @@ describe("currentRepo", () => {
})
})

describe("gh's words in ours", () => {
it("reads what gh says about merging", () => {
assert.strictEqual(mergeabilityOf("MERGEABLE"), "mergeable")
assert.strictEqual(mergeabilityOf("CONFLICTING"), "conflicting")
assert.strictEqual(mergeabilityOf("UNKNOWN"), "unknown")
})

it("reads an empty review decision as nobody having been asked", () => {
assert.strictEqual(reviewDecisionOf(""), "none")
assert.strictEqual(reviewDecisionOf("APPROVED"), "approved")
assert.strictEqual(reviewDecisionOf("CHANGES_REQUESTED"), "changes-requested")
assert.strictEqual(reviewDecisionOf("REVIEW_REQUIRED"), "review-required")
})
})

describe("viewer", () => {
it.effect("asks gh who it is logged in as", () => {
const spawned: Array<ReadonlyArray<string>> = []
Expand All @@ -133,68 +110,3 @@ describe("viewer", () => {
}).pipe(Effect.provide(loggedIn))
})
})

describe("prComments", () => {
it.effect("says which comments came from an app rather than a person", () => {
const answered = layerStubbed({
stubs: [
(command) =>
wrote(
(command.args[1]?.includes("/issues/") ?? false)
? `[{"created_at":"2026-09-15T08:43:44Z","user":{"login":"coderabbitai[bot]","type":"Bot"}}]`
: `[{"created_at":"2026-09-15T09:00:00Z","user":{"login":"dominikwozniak","type":"User"}}]`
)
]
})

return Effect.gen(function* () {
const comments = yield* prComments("AirHelp/ahplus-rails", 7884)

assert.deepStrictEqual(
comments.map((comment) => [comment.login, comment.bot]),
[
["coderabbitai[bot]", true],
["dominikwozniak", false]
]
)
}).pipe(Effect.provide(answered))
})
})

describe("comparedFiles", () => {
const base = "284d599022a55d4dcae74b31b9a49a0f50061014"
const head = "9c1f0b7a1d1e4a2c8b3f5d6e7a8b9c0d1e2f3a4b"

it.effect("asks GitHub what changed between two commits", () => {
const spawned: Array<ReadonlyArray<string>> = []
const compared = answering(spawned, {
stdout: JSON.stringify({ files: [{ filename: "README.md" }, { filename: "src/cli/review.ts" }] })
})

return Effect.gen(function* () {
const files = yield* comparedFiles("dominikwozniak/dw-mc", base, head)

assert.deepStrictEqual(files, ["README.md", "src/cli/review.ts"])
assert.deepStrictEqual(spawned, [["gh", "api", `repos/dominikwozniak/dw-mc/compare/${base}...${head}`]])
}).pipe(Effect.provide(compared))
})

it.effect("reads a comparison with nothing between its two commits", () => {
const empty = answering([], { stdout: JSON.stringify({ status: "identical" }) })

return Effect.gen(function* () {
assert.deepStrictEqual(yield* comparedFiles("dominikwozniak/dw-mc", base, base), [])
}).pipe(Effect.provide(empty))
})

it.effect("says what it could not read rather than reporting no change", () => {
const gone = answering([], { exitCode: 1, stderr: "gh: No commit found for SHA\n" })

return Effect.gen(function* () {
const error = yield* Effect.flip(comparedFiles("dominikwozniak/dw-mc", base, head))

assert.strictEqual(error._tag, "GhReadFailed")
assert.include(error.message, "No commit found")
}).pipe(Effect.provide(gone))
})
})
Loading
Loading
0