Documentation
¶
Overview ¶
Package migrate provides hew's migration workflows and the source-neutral, checkpointed engine underneath them in-process. Open resolves the target backend, repository and transport; Migrator.Beads parses a beads snapshot and maps it onto the conventions; Migrator.Local freezes a local tracker, copies every issue and seals the tracker to GitHub only after every step finished. Callers that opened their own target use Wrap with a Config naming their checkpoint and repo identity, and may drive the engine directly with Run.
Every write is checkpointed, so an interrupted run resumes where it stopped. Nothing here prints, exits, or names an internal store in a public signature; a Result carries the counts, the dry-run plan, the backend a workflow changed and typed warnings, and a caller decides what it all means. Its API is experimental until hew 1.0.
Index ¶
- Constants
- type BeadsRequest
- type Checkpoint
- type CheckpointError
- type CloseReason
- type Config
- type CreateRequest
- type DuplicateKeyError
- type IncompleteError
- type Issue
- type Item
- type ItemError
- type Label
- type Labeler
- type LocalRequest
- type Migrator
- func (m *Migrator) Backend() tracker.Backend
- func (m *Migrator) Beads(ctx context.Context, req BeadsRequest) (Result, error)
- func (m *Migrator) Local(ctx context.Context, req LocalRequest) (Result, error)
- func (m *Migrator) Repo() string
- func (m *Migrator) Run(ctx context.Context, req RunRequest) (Result, error)
- type NotLocalError
- type Options
- type PlanStep
- type PlannedItem
- type Result
- type RunRequest
- type SealError
- type Target
- type Warning
- type WarningKind
Constants ¶
const AssigneeViewer = "@me"
AssigneeViewer, in an Item's Assignees, stands for the target's authenticated identity. It is resolved lazily, so a migration with nobody to assign never pays for the lookup. A Target that cannot name its viewer reports the failure when the engine asks for it.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type BeadsRequest ¶
type BeadsRequest struct {
// Snapshot is the issues.jsonl contents.
Snapshot []byte
// Reader streams the snapshot. When non-nil it is read instead of
// Snapshot, so a caller that has a file or an HTTP body need not buffer it.
Reader io.Reader
// Source names the snapshot in messages ("issues.jsonl"). Empty means
// "beads snapshot".
Source string
// IncludeClosed migrates closed beads too: the issue is created, carries
// the close reason as a comment and is closed. Real databases are mostly
// closed, so this is opt-in.
IncludeClosed bool
}
BeadsRequest is one beads (bd) snapshot to import. The source data or the reader that streams it is the caller's input; which file it came from, and where a checkpoint lives, are the adapter's choices.
type Checkpoint ¶
type Checkpoint interface {
tracker.Checkpoint
// Recorded reports whether a named step was already recorded.
Recorded(key string) bool
// RecordStep records a named step and persists the checkpoint.
RecordStep(key string) error
}
Checkpoint is where a run records progress and resumes from: the issue each item became, the dependency edges already wired, and the named steps already taken (a posted comment). tracker.FileCheckpoint persists it to the state file the CLI uses; tracker.MemoryCheckpoint keeps it in memory.
type CheckpointError ¶
CheckpointError reports a resume-state file the workflow could not use without a target to verify it against.
func (*CheckpointError) Error ¶
func (e *CheckpointError) Error() string
type CloseReason ¶
type CloseReason string
CloseReason is why a migration closes a created issue. The zero value means completed.
const ( // CloseCompleted closes the issue as completed. CloseCompleted CloseReason = "completed" // CloseNotPlanned closes the issue as not planned. CloseNotPlanned CloseReason = "not-planned" // CloseDuplicate closes the issue as a duplicate. CloseDuplicate CloseReason = "duplicate" )
type Config ¶
type Config struct {
// Worktree is the directory the caller works from. Open resolves the
// target backend and the GitHub repository from it, and never reads the
// process's working directory or environment.
Worktree string
// Backend optionally pins the backend the migration writes to. Empty means
// use the backend tracker.Detect finds in Worktree. A local tracker is a
// valid target for Beads; Local always writes to GitHub.
Backend tracker.Backend
// Repo is the GitHub repository as owner/name. Empty means detect it from
// the worktree's origin remote. A dry run with no resolveable repository
// plans the source alone (see the workflow's dry-run rule).
Repo string
// Actor is the claimant identity on a local target: the login an
// in-progress item's claim is preserved as. It is required when the target
// is local, because the library never reads the process's environment to
// guess one; GitHub claims are always made as the authenticated login,
// which the backend resolves lazily.
Actor string
// Notice receives lock-wait notices from the local tracker. Nil discards
// them; no library code prints.
Notice io.Writer
// Transport carries every GitHub API request, so a consumer's tests run a
// migration against an isolated test server with neither the network nor a
// `gh` process. Nil uses go-gh's default.
Transport http.RoundTripper
// Checkpoint is an already-open resume state. A caller that wrapped its own
// target uses it directly; Open leaves it nil and opens CheckpointPath per
// workflow, since the digest binds to source bytes that are only read then.
Checkpoint Checkpoint
// CheckpointPath is the resume-state file a workflow opens when Checkpoint
// is nil. It is required for a real run, and for a dry run that has a
// target to verify an existing file against.
CheckpointPath string
// RepoKey is the identity a checkpoint binds to, when it differs from Repo:
// a local target binds to the tracker's stable id (`local/<id>`), because a
// checkout's directory name is neither unique nor stable. Empty means Repo.
RepoKey string
// Throttle is waited between writes to stay under a backend's rate limits.
// The wait is interruptible by the run's context.
Throttle time.Duration
// DryRun validates the checkpoint and the items and reports what a real run
// would do, without writing anywhere.
DryRun bool
// Progress receives one line of running narration per write, for a caller
// that renders it. Nil is silent; the workflow never prints.
Progress func(format string, args ...any)
}
Config configures Open, and carries the workflow options Wrap cannot resolve for itself: where a checkpoint lives, what identity it binds to, and how the run narrates and paces itself.
The target fields are Open's alone; a caller that wraps an already-open Target ignores them and supplies Repo and RepoKey instead. The checkpoint fields are shared: an already-open Checkpoint wins over CheckpointPath.
type CreateRequest ¶
CreateRequest is the issue the engine asks a Target to create. The body already carries the provenance marker.
type DuplicateKeyError ¶
type DuplicateKeyError struct {
Key string
// ItemNoun names the source's records ("bead"); empty means "item".
ItemNoun string
}
DuplicateKeyError reports two items sharing a checkpoint key. Keys identify an item in the checkpoint and in its provenance marker, so the run refuses before writing anything rather than letting the second item overwrite the first's mapping.
func (*DuplicateKeyError) Error ¶
func (e *DuplicateKeyError) Error() string
type IncompleteError ¶
IncompleteError reports a local migration whose steps did not all finish, so the tracker is still local. Err, when set, is the step's cause.
func (*IncompleteError) Error ¶
func (e *IncompleteError) Error() string
func (*IncompleteError) Unwrap ¶
func (e *IncompleteError) Unwrap() error
type Issue ¶
type Issue struct {
Number int
Title string
Body string
// State is the backend's state name: "OPEN" or "CLOSED".
State string
}
Issue is the Target's view of an issue the engine verifies or rewrites: the subset it needs, named in public terms so a consumer can fake it.
type Item ¶
type Item struct {
// Key identifies the item within its source. It is the checkpoint key and
// the key in the provenance marker.
Key string
Title string
// Body is the prose the issue shows; the engine appends the provenance
// marker, so adapters never stamp one themselves.
Body string
Labels []string
// Assignees are logins; AssigneeViewer means the target's authenticated
// identity.
Assignees []string
// Closed items are closed after their edges are wired and comments posted.
Closed bool
// CloseReason is why a closed item is closed; empty means completed.
CloseReason CloseReason
// Comments are posted, in order, after the edges are wired and before the
// issue is closed, if it is. Each one is checkpointed once posted, so a
// resume carries on from the first that is missing; a Closed item whose
// issue is already closed is skipped, which keeps a finished run quiet.
Comments []string
// Parent and BlockedBy are the Keys of other items.
Parent string
BlockedBy []string
// Epic marks a source record that is a container. It changes nothing about
// the writes — an epic's labels and children carry that — but a dry run
// names it "epic" rather than leaving an untyped issue in the plan.
Epic bool
}
Item is one issue a migration creates, in the source-neutral shape the engine works from. Adapters (beads, a local tracker, an external caller) map their own records onto it; everything target-specific — the provenance marker, write ordering, checkpoint keys — is the engine's, so every source gets the same resume and trust guarantees.
type ItemError ¶
ItemError reports a source item the engine cannot migrate because one of its own fields is invalid.
type Label ¶
Label is one label a migration may need to create before it files issues, in the backend-neutral shape a Target that can bootstrap labels understands.
type Labeler ¶
type Labeler interface {
// ListLabels returns the labels the target already has.
ListLabels(ctx context.Context) ([]Label, error)
// CreateLabel creates one missing label. Creating one that already exists
// under another case is the caller's to avoid.
CreateLabel(ctx context.Context, label Label) error
}
Labeler is the optional half of a Target that can ensure labels exist.
The writes the engine needs are the Target interface; a workflow's creates also reference convention and source labels a repository may not have yet, and creating them is a backend concern rather than an item's. A Target that implements Labeler has them bootstrapped once, after the checkpoint and provenance checks pass and before the first create; one that does not leaves label management to its own backend, which is what a consumer's in-memory fake usually wants.
type LocalRequest ¶
type LocalRequest struct {
// Dir is the local tracker directory (.hew at the main checkout).
Dir string
}
LocalRequest is one local-to-GitHub migration. The tracker directory is the adapter's input (it resolves the main checkout); everything else — the snapshot, the checkpoint and the seal — is the workflow's.
type Migrator ¶
type Migrator struct {
// contains filtered or unexported fields
}
Migrator runs one migration workflow over one Target: the engine's passes with the checkpoint, identity and source options the caller or Open resolved. It owns the checkpoint and a run, so callers run one migration at a time per Migrator.
func Open ¶
Open opens the tracker a migration writes to and returns a Migrator for the beads and local-to-GitHub workflows. The backend is resolved once, from cfg.Worktree unless cfg.Backend pins it, and fixed for the life of the Migrator.
A dry run is allowed to open without a target when the backend is GitHub and no repository can be resolved (no cfg.Repo, no github.com origin remote): the plan then comes from the source alone. A workflow asked to verify an existing checkpoint in that state refuses instead of listing work a real run would skip. Every other unresolved target is an InvalidInputError, and an unusable credential is AuthError.
func Wrap ¶
Wrap makes a Migrator from an already-open target and the workflow options its caller resolved: the seam hew's own CLI uses, where it has opened the store and knows the identity its checkpoint binds to. External callers use Open, which resolves the backend, repository and transport too.
A nil target is allowed only for a dry run: the plan then comes from the source alone, and a workflow asked to verify an existing checkpoint refuses rather than reading a state file it cannot vouch for.
func (*Migrator) Backend ¶
Backend reports the backend the migration writes to. It is empty for a wrapped Migrator and for a targetless dry run, which resolves none.
func (*Migrator) Beads ¶
Beads imports a beads snapshot: create in history order, wire parents and blockers, then close what was closed.
The snapshot's exact bytes are the checkpoint's digest, so a state file written for one snapshot is refused by another. Warnings about the source (an unknown status migrated as open, a label renamed) ride on the result beside the engine's own.
func (*Migrator) Local ¶
Local moves every issue in the local tracker — closed ones too — to the GitHub repository this Migrator writes to, then flips the tracker's backend to GitHub and keeps issues.jsonl as an archive.
The tracker is held under its lock for the whole run, so nothing written locally can slip in after the snapshot and be lost; writers wait, and once the tracker is sealed they find it is no longer local and refuse. The flip happens only when every step finished: a half-wired migration stays local so the rerun that completes it is still possible.
A dry run reads the tracker without locking it and never writes. A dry run with no target (see Open) plans from issues.jsonl alone, and refuses an existing checkpoint rather than listing work a real run would skip.
func (*Migrator) Repo ¶
Repo reports the GitHub repository a Local migration will seal to, as owner/name. It is empty on a local target and on a targetless dry run.
func (*Migrator) Run ¶
Run creates every item not already in the checkpoint, wires parents and blockers, rewrites references, then posts comments and closes the items marked closed. A create failure aborts (the checkpoint makes the rerun resume); later failures warn and continue.
The checkpoint's mappings are verified against the target before the first write: every mapped issue must carry the provenance marker this source kind wrote, bound to its key and digest. A refused run therefore leaves nothing behind. Context cancellation interrupts throttling and backend calls and returns the partial Result with the context error.
type NotLocalError ¶
type NotLocalError struct {
Dir string
Backend string
// Repo is where an earlier migration put the issues, when its record is
// readable. Empty otherwise.
Repo string
}
NotLocalError reports a tracker that cannot be migrated because it is not the local tracker in dir: it is missing, belongs to another backend, or was already moved.
func (*NotLocalError) Error ¶
func (e *NotLocalError) Error() string
type Options ¶
type Options struct {
// Kind is the provenance kind stamped into created bodies and checked
// before the finish pass touches an issue. Empty means the migration kind
// hew's own commands write.
Kind string
// ItemNoun and SourceNoun name the source's records and file in messages
// ("bead", "snapshot").
ItemNoun string
SourceNoun string
// KeyNoun names a checkpoint key in a refusal ("bead ID"). Empty derives
// one from ItemNoun.
KeyNoun string
// Throttle is waited between writes to stay under a backend's rate limits.
// The wait is interruptible by the run's context.
Throttle time.Duration
// DryRun validates the checkpoint and the items and reports what a real
// run would create, without writing.
DryRun bool
// Relink, when set, rewrites the references in an item's body, title and
// comments once every item has a target number: it is handed the text and
// the key → number mapping. Bodies are created as the source wrote them,
// since the numbers are not known yet, and edited afterwards.
Relink func(text string, mapping map[string]int) string
// KnownKeys is every key that belongs to the source, including records a
// run's selection filtered out. A checkpoint mapping outside it is
// refused: a removed record's issue number cannot be trusted. Nil means
// the keys of Items.
KnownKeys map[string]bool
// Digest identifies the source in provenance markers and checkpoint
// records. Empty means the checkpoint's own binding, or a digest computed
// from the items when it has none.
Digest string
// BeforeCreate, when set, runs after the checkpoint and provenance checks
// pass and before the first create. It is where a caller prepares what the
// creates need — the CLI bootstraps labels there — so a refused checkpoint
// costs no write at all. It is not called under DryRun.
BeforeCreate func(ctx context.Context) error
// Progress receives one line of running narration per write, for a caller
// that renders it. Nil is silent; the engine never prints.
Progress func(format string, args ...any)
}
Options configure one run.
type PlanStep ¶
type PlanStep struct {
// Key identifies the source record the step is about.
Key string `json:"key"`
// Migrated is the issue number the checkpoint records for Key; zero means
// the step is a planned create.
Migrated int `json:"migrated"`
// Title, Priority, Type, Parent, BlockedBy, InProgress and ThenClose
// describe the issue a planned create would file, derived from the item's
// labels and edges. They are zero for a step the checkpoint already
// accounts for.
Title string `json:"title"`
Priority string `json:"priority"`
Type string `json:"type"`
Parent string `json:"parent"`
BlockedBy []string `json:"blockedBy"`
InProgress bool `json:"inProgress"`
ThenClose bool `json:"thenClose"`
}
PlanStep is one line of a dry run's plan, in source order.
func (PlanStep) MarshalJSON ¶
MarshalJSON renders the planned blockers as an array even when empty.
type PlannedItem ¶
PlannedItem is one issue a dry run would create, in the source's order.
type Result ¶
type Result struct {
// DryRun reports which mode ran.
DryRun bool `json:"dryRun"`
// Created, Wired, Closed and Relinked count the run's writes.
Created int `json:"created"`
Wired int `json:"wired"`
Closed int `json:"closed"`
Relinked int `json:"relinked"`
// Failed is the number of steps a rerun will attempt again.
Failed int `json:"failed"`
// Selected is how many source records the run selected to migrate.
// A run that selects none reports it here, so a caller can render an empty
// plan without confusing it with a fully resumed run, whose Selected is
// non-zero and Created is zero.
Selected int `json:"selected"`
// Skipped counts source records the run's selection left out: the closed
// beads a run without IncludeClosed does not migrate.
Skipped int `json:"skipped"`
// Backend is the tracker's backend after the run, when a workflow changed
// it: the local-to-GitHub migration seals and flips to BackendGitHub.
// Empty means the workflow did not change it.
Backend tracker.Backend `json:"backend"`
// Warnings names the edges that did not land, the steps that failed, the
// bodies a person edited first, the source labels a migration renamed, and
// anything else a rerun cannot change.
Warnings []Warning `json:"warnings"`
// Mapping is every key → issue number after the run.
Mapping map[string]int `json:"mapping"`
// Plan is a dry run's steps in source order: the items the checkpoint
// already accounts for and the ones a real run would create, interleaved as
// the source lists them. It is empty otherwise.
Plan []PlanStep `json:"plan"`
// WouldCreate and AlreadyCreated are Plan split by kind: the items a real
// run would create, in source order, and the mapping its checkpoint already
// accounts for. They are empty otherwise.
WouldCreate []PlannedItem `json:"wouldCreate"`
AlreadyCreated map[string]int `json:"alreadyCreated"`
}
Result is what the passes did, or — under DryRun — what they would do.
Failed counts the steps that failed and would be tried again by a rerun, so a caller can tell a migration that is whole from one that needs another run. Warnings about things a rerun cannot change (an edge dropped for a cycle, a body a person edited) are listed there but are not failures.
func (Result) MarshalJSON ¶
MarshalJSON renders the run's collections as empty arrays and objects rather than null, so a consumer never has to distinguish an absent collection from an empty one.
type RunRequest ¶
RunRequest is one engine run: the source's items and the options that name it.
type SealError ¶
type SealError struct{ Err error }
SealError reports a local migration that finished its writes but could not switch the tracker over. Everything is on GitHub; the tracker is still local so the rerun that completes the move is possible.
type Target ¶
type Target interface {
// Create files one issue and returns its number.
Create(ctx context.Context, req CreateRequest) (int, error)
// Get reads one issue for verification and relinking.
Get(ctx context.Context, number int) (Issue, error)
EditTitle(ctx context.Context, number int, title string) error
EditBody(ctx context.Context, number int, body string) error
Comment(ctx context.Context, number int, body string) error
Close(ctx context.Context, number int, reason CloseReason) error
// AddSubIssue attaches child under parent.
AddSubIssue(ctx context.Context, parent, child int) error
// AddBlockedBy marks issue as blocked by blocker.
AddBlockedBy(ctx context.Context, issue, blocker int) error
AddAssignee(ctx context.Context, number int, login string) error
// Viewer returns the authenticated identity AssigneeViewer resolves to.
Viewer(ctx context.Context) (string, error)
}
Target is the narrow surface the engine reads and writes through: create, read, edit, comment, close and dependency edges, plus the acting identity for AssigneeViewer. A consumer implements it over its own backend, and a test fakes it without a network or a gh process.
type Warning ¶
type Warning struct {
Kind WarningKind `json:"kind"`
// Key is the source item the warning is about.
Key string `json:"key"`
// Issue is the target issue number, when one was created or read.
Issue int `json:"issue"`
// Message is the complete sentence a caller renders. It is what the CLI
// prints and what --json reports.
Message string `json:"message"`
}
Warning is one advisory notice. The fields a kind uses are documented on that kind; the rest stay zero.
type WarningKind ¶
type WarningKind string
WarningKind identifies one advisory notice about a migration, so a caller can filter by cause and render its own sentence. A warning never aborts the run: a failed edge, comment or close is retried by a rerun; a cycle-dropped edge or a body a person edited first never is.
const ( // WarnEdgeDropped reports a parent or blocked-by edge that was not wired: a // referenced item was never migrated, or the edge would have closed a // dependency cycle. WarnEdgeDropped WarningKind = "edge-dropped" // WarnWriteFailed reports a write that failed. The step is counted in // Result.Failed: a rerun retries it. WarnWriteFailed WarningKind = "write-failed" // WarnBodyEdited reports a body or title that changed after the migration // created it, so its references were left as written rather than // overwriting a person's edit. WarnBodyEdited WarningKind = "body-edited" // WarnAlreadyClosed reports work an item asked for on an issue that is // already closed. WarnAlreadyClosed WarningKind = "already-closed" // WarnLabelRenamed reports a source label whose name had to change to be // usable: a comma would read as two areas, so it becomes a hyphen. WarnLabelRenamed WarningKind = "label-renamed" // WarnUnknownStatus reports a source record whose status the mapping does // not know, which the run migrates as open. WarnUnknownStatus WarningKind = "unknown-status" )