Documentation
¶
Overview ¶
Package project opens project directories through the OS file picker. Project metadata (list, active, sessions) lives in internal/store; this service only turns a picked directory into a stable identity the window can group its terminal sessions under.
Index ¶
- Constants
- Variables
- func CheckoutRoots(dir string) (top, origin string)
- func GHToken(account string) string
- func GitCommonDir(dir string) string
- type BaseFreshness
- type BaseStatus
- type Blob
- type BranchRules
- type Branches
- type CheckItem
- type ChecksRollup
- type CommitIdentity
- type CommitPattern
- type DiffStats
- type FileListing
- type Issue
- type PRChanged
- type PRComment
- type PRCommit
- type PRConversation
- type PRDetail
- type PRReview
- type PRReviewThread
- type PRReviewer
- type PRSummary
- type PRThreadComment
- type Picker
- type Project
- type PullRequest
- type RevertLine
- type RevertResult
- type ReviewComment
- type SearchMatch
- type SearchResult
- type Service
- func (s *Service) BaseFreshness(path, branch string) (BaseFreshness, error)
- func (s *Service) BaseStatus(path string) *BaseStatus
- func (s *Service) Blob(dir, rel, ref string) (Blob, error)
- func (s *Service) Branch(path string) string
- func (s *Service) BranchRules(path, branch string) (*BranchRules, error)
- func (s *Service) BranchesOf(paths []string) map[string]string
- func (s *Service) CarryUncommitted(src, dst string) error
- func (s *Service) CommentOnPullRequest(path string, number int, body string) error
- func (s *Service) CommitIdentity(path string) CommitIdentity
- func (s *Service) CreatePullRequest(path string) error
- func (s *Service) CreateWorktree(projectPath, projectID, name, base string, baseIsRemote bool) (*Worktree, error)
- func (s *Service) CreateWorktreeFromPR(projectPath, projectID string, number int) (*Worktree, error)
- func (s *Service) Diff(path string) DiffStats
- func (s *Service) DiffText(path string) (string, error)
- func (s *Service) DiscardFile(path, rel string) error
- func (s *Service) EditPullRequestBody(path string, number int, body string) error
- func (s *Service) EditPullRequestTitle(path string, number int, title string) error
- func (s *Service) Exists(path string) bool
- func (s *Service) FileLines(path, rel, ref string, from, to int) ([]string, error)
- func (s *Service) GitHubAccounts() ([]string, error)
- func (s *Service) Home() (*Project, error)
- func (s *Service) Issue(path string, number int) (Issue, error)
- func (s *Service) ListBranches(path string) (Branches, error)
- func (s *Service) ListCheckouts(path string) ([]Worktree, error)
- func (s *Service) ListPullRequests(path, state string) ([]PRSummary, error)
- func (s *Service) MergePullRequest(path string, number int, method, subject, body string, admin bool) error
- func (s *Service) Missing(paths []string) []string
- func (s *Service) Open() (*Project, error)
- func (s *Service) PickFile(title string) (string, error)
- func (s *Service) PickSaveFile(title, defaultName string) (string, error)
- func (s *Service) PullRequest(path string) *PullRequest
- func (s *Service) PullRequestConflicts(path string, number int, base, prURL string) ([]string, error)
- func (s *Service) PullRequestConversation(path string, number int) (*PRConversation, error)
- func (s *Service) PullRequestDetail(path string, number int) (*PRDetail, error)
- func (s *Service) PullRequestDiff(path string, number int) (string, error)
- func (s *Service) PullRequestMergeBase(path string, number int) (string, error)
- func (s *Service) ReadFile(path, rel string) (string, error)
- func (s *Service) ReadFileAt(path, rel, ref string) (string, error)
- func (s *Service) Relocate(id string) (*Project, error)
- func (s *Service) RemoveWorktree(projectPath, wtPath string, force, adoptedAck bool) error
- func (s *Service) ReplyToReviewThread(path string, number int, commentID int64, body string) error
- func (s *Service) ResolveReviewThread(path, threadID string, resolved bool) error
- func (s *Service) RestoreLines(path, rel string, undo RevertResult) error
- func (s *Service) RevertLines(path, rel string, lines []RevertLine) (RevertResult, error)
- func (s *Service) Search(path, query string) (SearchResult, error)
- func (s *Service) ServeBlob(w http.ResponseWriter, r *http.Request)
- func (s *Service) SetAccounts(lookup accountLookup)
- func (s *Service) SetEmit(emit func(name string, data any))
- func (s *Service) SetProjects(lookup projectLookup)
- func (s *Service) SubmitReview(path string, number int, event, body, head string, comments []ReviewComment) error
- func (s *Service) Tree(path string) (FileListing, error)
- func (s *Service) WorktreeAdopted(wtPath string) bool
- func (s *Service) WorktreeDirty(wtPath string) (bool, error)
- type Worktree
- type ZenityPicker
Constants ¶
const PRChangedEvent = "pull-request-changed"
PRChangedEvent is what a pull request write through lich reports once GitHub took it, so every window's pull request store reads it again instead of the screen that made the change telling the others.
Variables ¶
var ErrLinesMoved = errors.New("the file changed since this diff was drawn. Refresh and try again")
ErrLinesMoved is what a revert answers when the lines it was asked about are no longer the lines on disk: the diff on screen is older than the file.
var ErrStagedDiverged = errors.New("these lines have staged changes that differ from the file. Discard the file instead")
ErrStagedDiverged is a revert refused because the index holds a third version of these lines, neither HEAD's nor the working tree's.
Functions ¶
func CheckoutRoots ¶
CheckoutRoots returns the top of the checkout dir is in and the top of the main checkout of its repository: the same directory for a checkout that is not a linked worktree, and origin "" for a worktree of a bare repository, which has no main checkout. Both are "" when dir is not in a work tree.
func GHToken ¶
GHToken returns the API token gh holds for one account ("<host>/<login>"), or for gh's active account when account is empty. It is what a confined session is handed in GH_TOKEN, and it is the whole reason gh can work inside one: gh keeps its tokens in the system keyring, which a private home has no path to, so a sandboxed gh without this is a login prompt.
Every failure answers "" — gh not installed, gh not authenticated, an account gh does not know — because the caller does the same thing with all three: spawn the session without a token and let gh say so itself, rather than fail a whole session over a credential it may never use.
func GitCommonDir ¶
GitCommonDir returns the repository metadata directory shared by a checkout and every worktree linked to it, or "" when dir is not in a repository. It is the same question basestatus.go asks, in the same spelling, and absolute because the caller needs a path rather than something to resolve against dir.
A linked worktree's `.git` is a file naming that directory, so a process that can see the worktree and not the common directory has a checkout git refuses to read at all. It is asked of git rather than parsed out of the `.git` file because git is the one thing that cannot be wrong about its own layout.
Types ¶
type BaseFreshness ¶
type BaseFreshness struct {
Upstream string `json:"upstream"` // "origin/main" form
Ahead int `json:"ahead"`
Behind int `json:"behind"`
// FetchError is why the fetch failed, "" when it did not. The counts are
// then against whatever an earlier fetch left.
FetchError string `json:"fetchError,omitempty"`
}
BaseFreshness is where a local branch stands against its upstream, read right after fetching it: what the new-worktree dialog needs to start a worktree from the newer of the two. Upstream is "" for a branch that tracks nothing on a remote, and every other field is then zero.
type BaseStatus ¶
type BaseStatus struct {
Base string `json:"base"` // the branch merged into, "origin/main" form
Behind int `json:"behind"` // commits the base has that this checkout does not
Conflicts []string `json:"conflicts"`
}
BaseStatus is where a checkout stands against the branch it will merge into: how far that branch has moved underneath it, and which files a merge would collide on right now. It is what turns "the merge button refused" into something a parallel worktree knows before anyone clicks it.
type BranchRules ¶
type BranchRules struct {
// AllowedMergeMethods is squash|merge|rebase, in GitHub's own spelling.
// Empty means the branch has no rule about it and all three stand — which
// is also what a repository with no rulesets at all reports.
AllowedMergeMethods []string `json:"allowedMergeMethods"`
// CommitPatterns are the rules that read a commit's own text. Empty is the
// common case and means only "no rule of this kind", never "nothing blocks".
CommitPatterns []CommitPattern `json:"commitPatterns"`
// ViewerCanBypass is whether this account administers the repository, and so
// may merge past the rules above. It is the one answer here that must fail
// *closed*: an unreadable one hides an action rather than offering one that
// cannot work, because a bypass offered to an account that has none reads as
// a broken button, not as a permission it never had.
ViewerCanBypass bool `json:"viewerCanBypass"`
}
BranchRules is what a repository's rulesets say about merging into one branch. GitHub's pull request fields do not carry it: `mergeStateStatus` answers whether this merge can happen, never which methods the branch would accept, so a Merge menu built without this offers buttons the ruleset refuses — and gh's refusal arrives after the click, as one flat sentence (gherror.go).
The endpoint answers for a branch, not a pull request, which is why this is its own read: every pull request onto the same base shares one answer.
type Branches ¶
type Branches struct {
Local []string `json:"local"`
Remote []string `json:"remote"` // "origin/main" form
Worktrees []Worktree `json:"worktrees"`
}
Branches groups everything the base-branch picker offers: local and remote branch names plus already-existing worktrees, so a closed-but-kept worktree can be resumed instead of recreated.
type CheckItem ¶
type CheckItem struct {
Name string `json:"name"`
State string `json:"state"`
Description string `json:"description"` // workflow name, or the status context's own line
URL string `json:"url"` // where to read the run; "" when gh reports none
StartedAt string `json:"startedAt"`
CompletedAt string `json:"completedAt"`
// Required is GitHub's own answer to "does this check gate the merge", the
// same verdict its checks list labels Required.
Required bool `json:"required"`
}
CheckItem is one check, flattened from gh's two rollup shapes into what the Checks tab lists. State is this package's own passed|failed|pending, the same verdict ChecksRollup counts. The timestamps are gh's ISO strings, left for the window to turn into a duration.
type ChecksRollup ¶
type ChecksRollup struct {
Passed int `json:"passed"`
Failed int `json:"failed"`
Pending int `json:"pending"`
Total int `json:"total"`
}
ChecksRollup collapses gh's statusCheckRollup array into the counts the panel shows. Total is every check, so "all green" is Passed == Total && Total > 0.
type CommitIdentity ¶
type CommitIdentity struct {
Name string `json:"name"`
Email string `json:"email"`
Local bool `json:"local"`
}
CommitIdentity is the name and email the next commit in a checkout would be authored with — the fact the project's gh account (ghaccount.go) does not carry, since that one only governs what lich asks gh. Local says the value comes from the checkout's own config rather than the global one.
The zero value is a legitimate answer, not a failure: a checkout with no identity configured is one of the states worth showing.
type CommitPattern ¶
type CommitPattern struct {
// Target is the part the rule reads, already in the words the screen uses:
// "message", "author email", "committer email".
Target string `json:"target"`
// Operator is GitHub's own: regex | starts_with | ends_with | contains.
Operator string `json:"operator"`
Pattern string `json:"pattern"`
// Negate flips the test — the pattern is then what the text must *not* be.
Negate bool `json:"negate"`
}
CommitPattern is one ruleset rule that tests the text of a commit rather than the state of a pull request. It earns its own field because it is the one class of rule nothing on a pull request hints at: the checks pass, the review lands, no conflict exists, and GitHub still answers BLOCKED — because the message the merge *would* write breaks a pattern nobody can see from here.
type DiffStats ¶
type DiffStats struct {
Files int `json:"files"`
Added int `json:"added"`
Deleted int `json:"deleted"`
Head string `json:"head"`
Branch string `json:"branch"`
}
DiffStats is what one status read says about a work tree: its uncommitted changes, and the two things they sit on. Head is the commit — the window watches it to notice a commit the way it watches Files/Added/Deleted to notice an edit — and Branch is the branch, carried here because git answers both in the same call the counts come out of.
type FileListing ¶
type FileListing struct {
Files []string `json:"files"`
// Cut reports a listing that stopped at walkLimit. Only a plain-folder walk
// can set it; git's own listing is never capped.
Cut bool `json:"cut"`
// Hidden names the walkIgnore directories this folder actually had, sorted
// and deduped: the panel names them, so somebody keeping source under a
// build/ or vendor/ reads why it is missing instead of guessing.
Hidden []string `json:"hidden"`
}
FileListing is one listing of a directory's files: the paths, plus the two things the Files panel has to say out loud about how they were gathered. A tree that silently stops short, or silently leaves a directory out, reads as a folder with fewer files in it than it has.
type Issue ¶
type Issue struct {
Number int `json:"number"`
Title string `json:"title"`
Body string `json:"body"`
URL string `json:"url"`
}
Issue is the little of a GitHub issue the New worktree dialog needs: what to name the branch after, and what to tell the session it opens.
type PRChanged ¶
PRChanged names the checkout the write ran in and the pull request it addressed; Number is 0 where the write addresses a thread or a review rather than a number (the checkout's repository is then all that is known).
type PRComment ¶
type PRComment struct {
Author string `json:"author"`
Body string `json:"body"`
Date string `json:"date"`
}
PRComment is one comment on the pull request itself.
type PRCommit ¶
type PRCommit struct {
OID string `json:"oid"`
Headline string `json:"headline"`
Body string `json:"body"`
Login string `json:"login"`
Name string `json:"name"`
Email string `json:"email"`
Date string `json:"date"` // gh's ISO committedDate
}
PRCommit is one commit the pull request would land, split the way git itself splits a message: the subject line, then the body (empty for a one-liner).
Login and Name are kept apart because only one of them is evidence: Name is free text, Login is the account GitHub resolved the author's email to against every account's verified addresses — an answer lich cannot compute, and one whose "" means the email belongs to nobody rather than "unknown".
type PRConversation ¶
type PRConversation struct {
// HeadRefOID is the commit a new review comment is filed against. GitHub
// defaults to the latest commit, but naming it means a review submitted
// seconds after a push cannot silently land on lines nobody read.
HeadRefOID string `json:"headRefOid"`
Reviews []PRReview `json:"reviews"`
// Comments are the pull request's own comments — the ones with no file and
// no line, which GitHub files as issue comments.
Comments []PRComment `json:"comments"`
Threads []PRReviewThread `json:"threads"`
}
PRConversation is everything said about a pull request: the reviews and their verdicts, the comments left on the pull request itself, and the threads anchored to a file and line. The Pulls screen renders the anchored ones inside the diff and the rest in its Conversation tab.
type PRDetail ¶
type PRDetail struct {
Number int `json:"number"`
URL string `json:"url"`
Title string `json:"title"`
Body string `json:"body"`
// Author is the login of whoever opened it, or their display name when gh
// reports no login. GitHub refuses a review request addressed to them, which
// is what keeps them out of the picker.
Author string `json:"author"`
// AuthorLogin is the same account as Author, minus the fallback to a display
// name — the value a commit's login is compared against. Author cannot serve:
// a name matches no login, so a PR whose author gh reports without one would
// read as every commit landing under the wrong account.
AuthorLogin string `json:"authorLogin"`
// State is gh's OPEN | CLOSED | MERGED. Only a number-addressed lookup can
// return a non-OPEN one; the branch lookup still gates them out.
State string `json:"state"`
IsDraft bool `json:"isDraft"`
Mergeable string `json:"mergeable"` // gh: MERGEABLE | CONFLICTING | UNKNOWN
// MergeStateStatus is GitHub's own answer to "can this merge right now" —
// CLEAN | UNSTABLE | BLOCKED | BEHIND | DIRTY | DRAFT | HAS_HOOKS | UNKNOWN.
// Mergeable alone cannot gate the button: it says nothing about a required
// review or a required check, and it reads UNKNOWN while GitHub recomputes
// after a push.
MergeStateStatus string `json:"mergeStateStatus"`
// ReviewDecision is gh's aggregate verdict — APPROVED | CHANGES_REQUESTED |
// REVIEW_REQUIRED — and "" where the repository requires no review. Who
// reviewed is a different field (latestReviews) this does not carry.
ReviewDecision string `json:"reviewDecision"`
// Reviewers is who was asked and who answered, in one list (prreviewers.go).
Reviewers []PRReviewer `json:"reviewers"`
BaseRefName string `json:"baseRefName"`
HeadRefName string `json:"headRefName"`
ChangedFiles int `json:"changedFiles"`
Checks ChecksRollup `json:"checks"`
CheckRuns []CheckItem `json:"checkRuns"`
Commits []PRCommit `json:"commits"`
// IsCrossRepository marks a head branch that lives on a fork.
IsCrossRepository bool `json:"isCrossRepository"`
// MaintainerCanModify is GitHub's "allow edits by maintainers" on a fork PR,
// and the whole of what decides whether a session can be opened on one: with
// it a push back to the fork's branch is authorised, without it there is
// nowhere for an agent's commits to go (CreateWorktreeFromPR). It is false on
// a same-repository PR, where nothing needs the permission.
MaintainerCanModify bool `json:"maintainerCanModify"`
}
PRDetail is the full view of a branch's open pull request — richer than the footer badge's PullRequest — driving the dock's Pulls panel: the title, body, CI rollup and mergeability gate the merge affordance. gh's state does not travel with it: a detail exists only when the PR is open (parsePRDetail).
type PRReview ¶
type PRReview struct {
// ID is the GraphQL node id, which is what dismissing the review takes.
ID string `json:"id"`
Author string `json:"author"`
// State is gh's APPROVED | CHANGES_REQUESTED | COMMENTED | DISMISSED.
State string `json:"state"`
Body string `json:"body"`
Date string `json:"date"`
}
PRReview is one submitted review: its verdict, and whatever was written in the summary box above the line comments.
type PRReviewThread ¶
type PRReviewThread struct {
// ID is the GraphQL node id, which is what resolving a thread takes. It is
// not the number a reply is addressed to — that is a comment's own ID.
ID string `json:"id"`
Path string `json:"path"`
// Line is the anchor in the file the thread's side names, and StartLine the
// first line of a multi-line thread (0 when it covers one line). A thread
// GitHub could not re-anchor keeps its original line and is marked outdated,
// which is what sends it to the Conversation tab instead of the diff.
Line int `json:"line"`
StartLine int `json:"startLine"`
// Side is RIGHT for a thread on the new file, LEFT for one on a deleted
// line — the two sides the diff renders in one document.
Side string `json:"side"`
IsResolved bool `json:"isResolved"`
IsOutdated bool `json:"isOutdated"`
Comments []PRThreadComment `json:"comments"`
}
PRReviewThread is one conversation anchored to a line of the diff.
type PRReviewer ¶
type PRReviewer struct {
// Login is the account's login, or a team's slug — which is not what gh takes
// to add or remove one (that is org/slug), so a team is shown and not edited.
Login string `json:"login"`
IsTeam bool `json:"isTeam"`
// State is "" while the review is still owed, else gh's APPROVED |
// CHANGES_REQUESTED | COMMENTED | DISMISSED.
State string `json:"state"`
}
PRReviewer is one entry of a pull request's review roster: somebody who was asked and has not answered yet, or somebody who has.
type PRSummary ¶
type PRSummary struct {
Number int `json:"number"`
Title string `json:"title"`
Author string `json:"author"` // login, or the display name when gh reports no login
State string `json:"state"` // gh: OPEN | CLOSED | MERGED
IsDraft bool `json:"isDraft"`
// ReviewDecision is gh's APPROVED | CHANGES_REQUESTED | REVIEW_REQUIRED,
// and "" for a repository that requires no review.
ReviewDecision string `json:"reviewDecision"`
HeadRefName string `json:"headRefName"`
// IsCrossRepository marks a PR whose head branch lives on a fork. lich can
// check such a branch out, but the commits would have nowhere to push, so
// the session flow refuses it (CreateWorktreeFromPR) and the button reads
// as blocked rather than failing on click.
IsCrossRepository bool `json:"isCrossRepository"`
UpdatedAt string `json:"updatedAt"` // gh's ISO timestamp
Checks ChecksRollup `json:"checks"`
}
PRSummary is one row of the repository's open pull requests — what the list column needs to render and rank a PR before anything is selected. The full view behind a row is PRDetail, fetched per PR.
type PRThreadComment ¶
type PRThreadComment struct {
// ID is the REST database id — the address a reply is posted to. GraphQL
// node ids do not work there, which is why both identifiers travel.
ID int64 `json:"id"`
Author string `json:"author"`
Body string `json:"body"`
Date string `json:"date"`
// DiffHunk is GitHub's own snippet of the lines the thread is about. The
// diff already has them where the thread is anchored; this is what an
// outdated thread has left.
DiffHunk string `json:"diffHunk"`
}
PRThreadComment is one message inside a thread.
type Picker ¶
type Picker interface {
PickDirectory(title string) (string, error)
PickFile(title string) (string, error)
PickSaveFile(title, defaultName string) (string, error)
}
Picker shows native file/directory choosers — zenity in production (picker.go), fakes in tests. Returns "" on user cancel.
type Project ¶
Project identifies an opened project directory.
func Identify ¶
Identify turns a directory path into the same identity the picker would give it: the id its sessions and its worktree directory hang off, and the name its tab wears. It is the path a caller outside the window hands in — the `lich` command line and its MCP tools — so it normalizes what a person or an agent types, and validates it here rather than letting a typo become a project.
A leading ~ is expanded because an MCP tool call reaches lich through no shell at all: the tilde arrives literally, and a project named "~" is nobody's intent. ~user is not expanded — the home directory of another user is not a path this ever means.
A relative path is refused rather than resolved. There is no shell at this end either: Abs would resolve it against the directory the lich window was launched from, which is not the caller's, and the project that opened would be a different one than the one asked for with nothing on screen saying so.
type PullRequest ¶
type PullRequest struct {
Number int `json:"number"`
URL string `json:"url"`
State string `json:"state"`
}
PullRequest identifies the open GitHub pull request for a work tree's current branch, as reported by the gh CLI. State is one of gh's OPEN, CLOSED, MERGED; only OPEN reaches the window (see parsePullRequest).
type RevertLine ¶
type RevertLine struct {
Side string `json:"side"`
Line int `json:"line"`
Text string `json:"text"`
}
RevertLine names one changed line of the diff the panel drew. Side "old" is a deletion, numbered in HEAD; "new" is an addition, numbered in the working tree. Text is the line without its +/- prefix, and is what proves the number still points at the same line.
type RevertResult ¶
RevertResult is what undoing a revert needs: the patch reversed onto the working tree, and the one reversed onto the index ("" when the index did not hold the change and was left alone).
func (RevertResult) MarshalJSON ¶
func (r RevertResult) MarshalJSON() ([]byte, error)
func (*RevertResult) UnmarshalJSON ¶
func (r *RevertResult) UnmarshalJSON(data []byte) error
type ReviewComment ¶
type ReviewComment struct {
Path string `json:"path"`
Line int `json:"line"`
StartLine int `json:"startLine"`
// Side is RIGHT (the new file) or LEFT (a deleted line). Empty means RIGHT,
// which is where all but a deletion comment goes.
Side string `json:"side"`
Body string `json:"body"`
}
ReviewComment is one line comment of a review being submitted. Line is the last line it covers and StartLine the first (0 for a single-line comment) — GitHub's own convention, kept here so a selection crosses unchanged.
type SearchMatch ¶
type SearchMatch struct {
Path string `json:"path"`
// Line is 1-based, the same numbering the preview's gutter shows.
Line int `json:"line"`
// Text is the line with its indentation dropped, cut to an excerpt around
// the first occurrence when the line is long.
Text string `json:"text"`
}
SearchMatch is one line of one file that contains the query.
type SearchResult ¶
type SearchResult struct {
Matches []SearchMatch `json:"matches"`
// Cut reports a search that stopped at maxSearchMatches.
Cut bool `json:"cut"`
// TooLarge counts the listed files skipped for being above maxReadFileSize.
// The tree shows them, so an answer that left them out says so; a binary
// is skipped without a count, since nobody searches one for text.
TooLarge int `json:"tooLarge"`
}
SearchResult is one search over a checkout's files.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service opens project directories via the native file picker.
func (*Service) BaseFreshness ¶
func (s *Service) BaseFreshness(path, branch string) (BaseFreshness, error)
BaseFreshness fetches branch's upstream and counts the commits each side has that the other lacks. A fetch that fails is part of the answer, never an error: the caller still has a local branch to start from. It is an error only for a branch the repository does not hold.
func (*Service) BaseStatus ¶
func (s *Service) BaseStatus(path string) *BaseStatus
BaseStatus reports the path's standing against its base branch, or nil when there is nothing to answer from: not a repository, no origin, no origin/HEAD. Nil is the "hide the segment" contract Branch and PullRequest share — this is polled, and a checkout without a remote is an ordinary state.
The answer is memoised on the two commits it was computed from, because the poll runs every few seconds and merge-tree writes tree objects into the object database on every call. Only a moved HEAD or a moved base recomputes.
func (*Service) Blob ¶
Blob reads rel at ref for an image preview. ref is "" for the working tree, "HEAD" for the commit a checkout's uncommitted diff stands on, or an object id. An object this clone does not hold, a pull request's head or merge base, is read from GitHub, the way FileLines reads it.
A path absent at ref is fs.ErrNotExist: the side of an added or deleted file that has nothing to show.
func (*Service) Branch ¶
Branch returns the current git branch of the project directory, or "" when the path is not a git work tree or HEAD is detached (no branch to name). It reads the current state on call, so a checkout made after opening is not reflected until the branch is resolved again.
func (*Service) BranchRules ¶
func (s *Service) BranchRules(path, branch string) (*BranchRules, error)
BranchRules reads the rules a repository's rulesets apply to one branch, and whether this account may merge past them.
A branch nothing governs answers with an empty list, and so does a token that may not read the rules — both reach the screen as "no rule known", which is the same shape as a repository that has none. That is deliberate: this read exists to *narrow* what the merge menu offers, so failing to answer must leave the menu as wide as it was, never empty. The bypass is the exception and runs the other way; see ViewerCanBypass and viewerAdministers.
func (*Service) BranchesOf ¶
BranchesOf answers Branch for several checkouts at once, keyed by path; a path that names no branch — gone, not a repository, a detached HEAD — is left out rather than mapped to "", so a caller reads "no branch" from the absence.
The batch exists because the list that asks is a list of parked sessions: it wants each row's branch once, when it is drawn, not the per-path poll a live card rides (native/cmd/lich-native/model.go, pollGit). Two RPCs per row every few seconds is what that poll costs, and a history list is long.
func (*Service) CarryUncommitted ¶
CarryUncommitted copies the work src has not committed onto dst, so a new worktree starts from a checkout as it stands rather than from its last commit. src is a forked session's checkout, or the project's own checkout when the + dialog's working-tree row was picked. Either way src is only read: the work stays where it was.
Both checkouts must sit on the same commit, which is what the caller picking src's own branch as the base guarantees: the patch is read against src's HEAD and applied to dst's, and git refuses it outright if they differ.
Everything lands unstaged in dst. Which of src's changes were staged is not carried: it is a fact about the commit src is preparing, and dst is a different piece of work from here on.
What git ignores is not carried either (--exclude-standard), and it is the one part of the checkout a fork does not get from the session it forked: seedWorktree copies the ignored files the project names (`.env*` by default) out of the *main* checkout into every new worktree, and nothing builds the rest. So an ignored file the forked session edited arrives as the main checkout's copy of it. When src is the main checkout the two agree, because both copies are read from the same place.
func (*Service) CommentOnPullRequest ¶
CommentOnPullRequest leaves a comment on the pull request itself — the conversation with no file and no line behind it.
func (*Service) CommitIdentity ¶
func (s *Service) CommitIdentity(path string) CommitIdentity
CommitIdentity reads the identity git itself resolves in the checkout at path, so a repository-local override wins over the global config exactly as it would for a commit. A non-repository, an unreadable config or no identity at all answer the zero value — hence the quiet probes (see runGit for why).
func (*Service) CreatePullRequest ¶
CreatePullRequest opens GitHub's "new pull request" page in the browser for the path's branch (gh pushes the branch first when it has no upstream). Deliberately the web flow, not an in-app form — GitHub's page already owns the title, body, reviewers and template. Returns once the browser is launched.
func (*Service) CreateWorktree ¶
func (s *Service) CreateWorktree(projectPath, projectID, name, base string, baseIsRemote bool) (*Worktree, error)
CreateWorktree creates a git worktree named name (random when empty) under the app data dir, branching off base. A remote base is fetched first, and the new branch is left with no upstream. A branch that already exists is checked out as it stands, and base is ignored. The worktree is verified usable before returning, so a success here means a session can be opened at Path right away.
func (*Service) CreateWorktreeFromPR ¶
func (s *Service) CreateWorktreeFromPR(projectPath, projectID string, number int) (*Worktree, error)
CreateWorktreeFromPR checks a pull request out into its own worktree under the app data dir, so a session can be opened on the PR's own branch. The checkout is created detached and handed to `gh pr checkout`, which owns resolving the head ref and its tracking — the part raw git cannot do for a pull request.
It refuses a PR from a fork that has "allow edits by maintainers" off: the branch would check out, but the commits an agent makes there have nowhere to push, so the failure belongs before the worktree exists rather than at the first push. With the permission on, the fork's branch takes a push like any other and the pull request opens. A failed checkout takes the worktree with it — a detached husk would sit in the picker offering a resume of nothing, and would hold the path against a second attempt.
func (*Service) Diff ¶
Diff returns the dirty-file count (modified + untracked), the added/deleted line totals against HEAD, the HEAD commit itself and the branch it is on. A non-repository path yields the zero value, matching Branch's contract.
One git child on a clean checkout, two on a dirty one: the status read answers the branch, the head and everything dirty (status.go), and the line totals are asked for only when there is something to total.
func (*Service) DiffText ¶
DiffText returns the full unified diff of uncommitted changes (staged + unstaged + untracked) against HEAD. A repository without commits diffs against git's empty tree. Untracked files are rendered as new-file hunks so the review panel shows them alongside tracked changes.
func (*Service) DiscardFile ¶
DiscardFile reverts one file's uncommitted changes. A file known to HEAD is checked out from it (restoring index and worktree in one step); a new file (staged or untracked) is unstaged and deleted from disk. rel must be a repo-relative path — the review panel passes paths parsed from git's own diff output.
func (*Service) EditPullRequestBody ¶
EditPullRequestBody rewrites the pull request's description on GitHub, and an empty body clears it. The title is left alone on purpose: sending the one the screen read would undo a rename made on GitHub since.
func (*Service) EditPullRequestTitle ¶ added in v0.75.0
EditPullRequestTitle renames the pull request on GitHub. GitHub refuses a pull request without a title, so an empty one never reaches gh.
func (*Service) Exists ¶
Exists reports whether path is still a directory on disk. A stored project outlives the folder it points at — the picker guarantees the directory exists when a project is first opened, nothing does when one is reopened from a row.
func (*Service) FileLines ¶
FileLines returns lines from..to of one repo-relative file — 1-based and inclusive, the numbering a diff's gutter shows — for the review panel's context expander: the unchanged text around a hunk, which git never printed.
ref names the revision the diff's new side stands at, and the panels differ in which one they have: "" is the working tree, an oid is a git object this checkout holds (a turn's snapshot tree), and a pull request's head is an oid this clone need not hold at all — measured, the head oids `gh pr list` reports are absent from a clone that never checked those branches out, so a local read alone would leave the Pulls screen's expander dead. The object is tried first because it costs nothing; GitHub answers for the rest.
rel is validated against traversal like every other file-by-path surface, and binaries and oversize files are refused the way ReadFile refuses them: this is a source viewer, and a blob has no lines to show.
func (*Service) GitHubAccounts ¶
GitHubAccounts lists the accounts gh is authenticated as, "<host>/<login>", in gh's own order (each host's active account first). It backs the account picker in the project's Version Control settings; an unauthenticated gh yields an error, which the picker shows instead of an empty list.
func (*Service) Home ¶
Home returns a project rooted at the user's home directory, without a picker. The update flow opens an install terminal there when no project is in view, so clicking Install never dead-ends on the Home screen.
func (*Service) Issue ¶
Issue resolves one GitHub issue through gh, as the account the project selected. The title names the branch the dialog is about to create, and the body is what that worktree's session finds at its prompt.
A pull request is refused rather than answered. GitHub numbers issues and pull requests in one sequence and its API calls them all issues, so `gh issue view <n>` answers for either — and taking the pull request would branch off the base under its title instead of checking its head branch out, which is a different flow entirely (CreateWorktreeFromPR). The URL is the only field in the answer that tells the two apart.
func (*Service) ListBranches ¶
ListBranches returns the repository's local and remote branches and its existing worktrees. A path that is not a git repository yields an error.
func (*Service) ListCheckouts ¶
ListCheckouts returns every checkout of the repository holding a branch — the project's own directory included, which ListBranches deliberately leaves out because a main checkout is not something the worktree picker can resume. It answers a different question: which branches are spoken for. git refuses to check one branch out twice, so a caller about to check a branch out has to know about the main checkout as much as about the linked ones.
func (*Service) ListPullRequests ¶
ListPullRequests returns the repository's pull requests in the given state (open|closed|merged|all, defaulting to open), newest update first — gh's own order, which the window re-sorts. It returns nil for a repository with none; a real failure (gh missing, unauthenticated, not a GitHub repo) yields an error so the column can say why it is empty.
func (*Service) MergePullRequest ¶
func (s *Service) MergePullRequest(path string, number int, method, subject, body string, admin bool) error
MergePullRequest merges a pull request on GitHub with the given method (squash|merge|rebase) — the given number, or the PR of the branch checked out at path when number is zero. A non-empty subject overrides the commit message (the dock's "edit message" flow); an empty subject leaves gh's default, the quick merge. admin merges with administrator privileges, GitHub's own bypass of the rules on the base branch. It does not pass --delete-branch: lich's worktree removal owns that cleanup, and deleting a checked-out worktree's branch is trouble. gh's stderr is surfaced on failure (not mergeable, branch protection, gh missing).
func (*Service) Missing ¶
Missing returns the subset of paths whose directory is no longer there. The lists that offer closed projects ask about all their rows at once, so a row that cannot be opened as it stands says so before it is clicked.
func (*Service) Open ¶
Open shows the native directory picker and returns the chosen project, or nil if the user cancels the dialog.
func (*Service) PickFile ¶
PickFile shows the native file picker and returns the chosen file path, or "" if the user cancels the dialog.
func (*Service) PickSaveFile ¶
PickSaveFile shows the native save dialog seeded with defaultName and returns the chosen destination, or "" if the user cancels.
func (*Service) PullRequest ¶
func (s *Service) PullRequest(path string) *PullRequest
PullRequest returns the open pull request for the path's current branch, or nil when there is none, gh is missing/unauthenticated, or the path is not a GitHub repo. It shells out to `gh pr view`, which resolves the PR from the checked-out branch. Any failure yields nil, matching Branch's "hide the segment" contract.
func (*Service) PullRequestConflicts ¶
func (s *Service) PullRequestConflicts(path string, number int, base, prURL string) ([]string, error)
PullRequestConflicts lists the files a merge of pull request number into base would collide on. GitHub publishes that a pull request conflicts and never where: its answer is one word (mergeable: CONFLICTING), which left the reader opening github.com or a session to find out which files it meant. This computes it instead — both commits are fetched into refs lich owns and merged in the object database alone (mergeConflicts), never in a worktree, an index or HEAD. The refs live no longer than the answer (dropPRRefs).
nil means the merge is clean, so this is asked only once GitHub has said it is not: the fetch is a network round trip, not something to poll.
prURL is the pull request's own URL, which names the repository it lives on — see prRemote. refs/pull/<n>/head is GitHub's own ref, a fork's pull request included, since GitHub keeps that ref on the base repository.
func (*Service) PullRequestConversation ¶
func (s *Service) PullRequestConversation(path string, number int) (*PRConversation, error)
PullRequestConversation reads one pull request's reviews, comments and review threads. The number is required: the query addresses a pull request by number, and the screen always knows it by the time there is a conversation to show — resolving "the branch's PR" here would cost a second gh round-trip on every read.
func (*Service) PullRequestDetail ¶
PullRequestDetail returns one open pull request in full: the given number, or the PR of the branch checked out at path when number is zero. It yields nil when there is no open PR — gh reports none, or the PR is merged/closed, which the OPEN-only gate treats the same as the badge does. A real failure (gh missing, not a GitHub repo) yields an error so the panel can tell "no PR" apart from "could not look up".
func (*Service) PullRequestDiff ¶
PullRequestDiff returns the unified diff of the path's branch pull request — every change the PR would merge into its base, as GitHub computes it — for the Pulls screen's "Files changed" tab. --color never keeps the output plain so the window's parsePatchFiles reads it. An empty string with no error means the branch has no open PR (nothing to show).
Ceiling: the whole diff is buffered here and shipped as one JSON string, so a monster PR costs its own size in memory on both sides. Reviewing a diff that large in a panel is not the workflow; stream it (or cap and mark it truncated) if that ever stops being true.
func (*Service) PullRequestMergeBase ¶ added in v0.77.0
PullRequestMergeBase is the commit pull request number's diff is taken from, the old side of every file GitHub shows. The base branch's tip is not it once the base moved past where the branch left it. The tips come from GitHub; their merge base is computed here when the clone holds both, and asked of GitHub otherwise.
func (*Service) ReadFile ¶
ReadFile returns the text content of one repo-relative file for the read-only preview. rel goes through relpath.Resolve rather than the lexical Validate its neighbours use, because this is the surface that reads bytes: a checkout can ship a symlink out of the tree, and a preview that followed one would print a file the diff beside it describes as the link's target text. Binaries, irregular files, and files above maxReadFileSize are refused — the preview is for source, not blobs.
func (*Service) ReadFileAt ¶ added in v0.77.0
ReadFileAt is ReadFile at ref, for a preview of a file's new version that the working tree does not hold: a pull request's head. See FileLines for what a ref can be and where it is read from.
func (*Service) Relocate ¶
Relocate points a stored project at a directory chosen from the picker, keeping id rather than deriving a new one from the path. The id is the project's identity in the store — what its sessions hang off and what names its worktree directory — so a checkout that was moved or renamed keeps both. The name follows the new directory. nil when the user cancels.
A directory another project already sits on is refused: the two rows would hold the same path under different ids, and every path-addressed lookup the app makes — which project a checkout belongs to, which account its gh calls run as — answers with whichever row the query reached first.
func (*Service) RemoveWorktree ¶
RemoveWorktree removes a worktree checkout. Without force git refuses to delete a dirty worktree, which is the safety net the close-session flow relies on; force discards uncommitted changes after the user has confirmed. The branch is never deleted either way.
An adopted checkout is the user's own directory, made outside lich and only listed by it, so deleting one needs adoptedAck on top of the usual answers: the caller has put the absolute path in front of the user and been told to go ahead. Without it the removal is refused, force or not — which is the answer for a caller that has nobody to ask (the MCP close_session tool) and the one that holds when a caller forgets.
func (*Service) ReplyToReviewThread ¶
ReplyToReviewThread answers an existing thread. commentID is the database id of any comment in it — GitHub files the reply against the thread that comment belongs to. A reply posts immediately and is never part of the pending review: it is an answer to something already said, which is the same split GitHub draws between "add single comment" and "start a review".
func (*Service) ResolveReviewThread ¶
ResolveReviewThread marks a thread resolved, or reopens it. threadID is the GraphQL node id the conversation read carries — the database id a reply uses does not address a thread here.
func (*Service) RestoreLines ¶
func (s *Service) RestoreLines(path, rel string, undo RevertResult) error
RestoreLines undoes RevertLines: the same patches applied forwards, to the same targets. They come back from the caller, so each is held to the one file it was built for before git sees it.
func (*Service) RevertLines ¶
func (s *Service) RevertLines(path, rel string, lines []RevertLine) (RevertResult, error)
RevertLines puts the chosen changed lines of rel back to HEAD, leaving every other change in the file alone. The patch is rebuilt here from git's own diff rather than taken from the caller, so a stale screen fails instead of reverting whatever those line numbers point at now.
The index is reverted with the working tree whenever it holds the change: the panel draws staged and unstaged as one diff, so reverting only the file would leave the line in the next commit with nothing on screen showing it.
func (*Service) Search ¶
func (s *Service) Search(path, query string) (SearchResult, error)
Search finds the lines that contain query, case-insensitively and as a literal, across the files Tree lists for path. It reads Tree's listing rather than running git grep so that every hit is a file the tree beside it shows, in a repository and in a plain folder alike. A file the preview would refuse (binary, irregular, above maxReadFileSize) is skipped, so every hit opens. Matches come in Tree's order, file by file, line by line.
func (*Service) ServeBlob ¶
func (s *Service) ServeBlob(w http.ResponseWriter, r *http.Request)
ServeBlob is Blob over HTTP, so the bytes travel raw rather than as base64 inside an RPC answer. The query carries path, rel and ref.
The window tells the sides apart by status: 404 is a side with no file, 413 a file over the limit, 415 a type with no preview. The body says which, in the words the window shows.
func (*Service) SetAccounts ¶
func (s *Service) SetAccounts(lookup accountLookup)
SetAccounts wires the per-project account resolution. Left unset, every gh call runs as gh's active account — lich's behaviour before this existed.
func (*Service) SetProjects ¶
func (s *Service) SetProjects(lookup projectLookup)
SetProjects wires the workspace lookup Relocate validates against. Left unset, any picked directory is taken as free.
func (*Service) SubmitReview ¶
func (s *Service) SubmitReview(path string, number int, event, body, head string, comments []ReviewComment) error
SubmitReview files one review on GitHub: the verdict, the summary body, and every line comment the window has been holding, in a single call. head is the commit the comments were written against — empty lets GitHub assume its own latest, which is wrong the moment a push landed while the review was open.
This is also the plain Approve: no comments, no body, event "approve". GitHub refuses an approval of one's own pull request, which the message table turns into a sentence (gherror.go).
func (*Service) Tree ¶
func (s *Service) Tree(path string) (FileListing, error)
Tree lists a directory's files as root-relative, slash-separated paths, sorted. Inside a repository it merges tracked files with untracked-but-not-ignored ones (`ls-files --cached --others --exclude-standard`) and drops any tracked file deleted from disk (`--deleted`), so a file created or removed since the session began shows without a commit; .gitignore is honored for free, so no node_modules and no build output leak in. Anywhere else — a plain folder, a machine without git — it falls back to walking the directory: browsing a project's files is not a git feature, and only the diff panel beside it is.
func (*Service) WorktreeAdopted ¶
WorktreeAdopted reports whether the checkout at wtPath is one lich adopted rather than created: `git worktree list` hands back every worktree of a repository, so one the user made by hand appears in the picker and hosts a session like any other, and nothing but its path tells the two apart. Everything lich creates lives under the worktrees root reserveWorktreePath builds its paths in; anything outside it is the user's own directory, which lich deletes only once the user has been shown that path and said yes.
Both sides go through canonicalPath, and an unresolvable root reads as adopted: the answer gates a deletion, so the unknown case has to be the one that asks first.
type Worktree ¶
type Worktree struct {
Name string `json:"name"`
Path string `json:"path"`
// Whether CreateWorktree checked out a branch that already existed instead
// of starting one at the base it was given — the one case where the base
// the caller picked decided nothing. Always false on a listed worktree.
Reused bool `json:"reused,omitempty"`
}
Worktree is a git worktree checkout: the branch it holds and its path.
type ZenityPicker ¶
type ZenityPicker struct{}
ZenityPicker opens the OS file chooser through github.com/ncruces/zenity. Only Linux shells out to zenity/qarma; Windows and macOS run the dialog in-process, so there it is a window of lich's own and wears the executable's icon. Cancel maps to ("", nil).
func (ZenityPicker) PickDirectory ¶
func (ZenityPicker) PickDirectory(title string) (string, error)
func (ZenityPicker) PickSaveFile ¶
func (ZenityPicker) PickSaveFile(title, defaultName string) (string, error)
PickSaveFile opens the save dialog. ConfirmOverwrite is the dialog's own guard: the caller writes whatever path comes back, so replacing an existing file is agreed to here or nowhere.
Source Files
¶
- basestatus.go
- blob.go
- branchrules.go
- carry.go
- commitidentity.go
- difftext.go
- discard.go
- filelines.go
- freshness.go
- ghaccount.go
- gherror.go
- git.go
- giterror.go
- issue.go
- names.go
- picker.go
- pr.go
- prchanged.go
- prchecks.go
- prconflicts.go
- project.go
- prreview.go
- prreviewers.go
- prthreads.go
- revertlines.go
- revertpatch.go
- search.go
- seed.go
- status.go
- toolerror.go
- tree.go
- worktree.go