terminal

package
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 9, 2026 License: MIT Imports: 38 Imported by: 0

Documentation

Index

Constants

View Source
const (
	LoginToken  = "token"
	LoginOAuth  = "oauth"
	LoginSSHKey = "ssh-key"
)

Login methods that an interactive login offers.

View Source
const BodyTitle = "Body (markdown):"

BodyTitle labels the markdown body of issues, pull requests and comments.

Variables

View Source
var ErrCanceled = clierr.Wrap(clierr.Canceled, errors.New("canceled"))

ErrCanceled reports a declined confirmation or an aborted prompt; it exits with code 3.

ErrInterrupted reports a form left with Ctrl-C, which exits with code 130 as Ctrl-C does elsewhere. It is an ErrCanceled, so callers handle it as any aborted prompt.

View Source
var MergeMethodLabels = map[string]string{
	"merge": "Create a merge commit", "rebase": "Rebase and merge", "rebase-merge": "Rebase and create a merge commit",
	"squash": "Squash and merge", "fast-forward-only": "Fast-forward only",
}

MergeMethodLabels describe Gitea's merge styles in the merge form.

Functions

func Bytes

func Bytes(n int64) string

Bytes formats a size in binary units: "13 B", "2.9 MiB".

func ColorEnabled

func ColorEnabled(preference string, outTTY bool, getenv func(string) string) bool

ColorEnabled resolves the color preference against terminal and environment policy. auto colors a TTY unless NO_COLOR is set, CLICOLOR is 0 or TERM is dumb; CLICOLOR_FORCE, unless empty or 0, overrides CLICOLOR, TERM and a redirected outTTY, but not NO_COLOR. always forces color; never disables it. Callers color stdout only on a terminal, since piped stdout is data, so forced color reaches stderr even when redirected but stdout only on a terminal.

func Colorize

func Colorize(color, text string, enabled bool) string

Colorize colors text by name (red, green, yellow, blue, magenta, cyan or muted) from the terminal's ANSI 16 palette. Other colors, such as label hex colors, leave the text plain.

func ConfirmAction

func ConfirmAction(ctx context.Context, c Confirmation, yes bool, streams Streams, policy Policy, prompt Prompter) error

ConfirmAction asks c unless yes is set. A declined or aborted confirmation returns ErrCanceled.

func DefaultPullTitle

func DefaultPullTitle(head string) string

DefaultPullTitle turns a branch-like head into a readable pull title seed.

func Duration

func Duration(d time.Duration) string

Duration formats an elapsed time by its two largest units: "1h 30m", "1m 12s", "45s".

func Emphasis

func Emphasis(text string, enabled bool) string

Emphasis applies simple bold styling for TTY human tables.

func ExpandHome

func ExpandHome(path string) string

ExpandHome replaces a leading ~/ with the home directory, as a shell would.

func Hyperlink(url, text string, enabled bool) string

Hyperlink wraps text in an OSC 8 terminal hyperlink to url. URLs with control characters are left unlinked so server data cannot inject escape sequences.

func HyperlinksEnabled

func HyperlinksEnabled(preference string, outTTY bool, getenv func(string) string) bool

HyperlinksEnabled resolves the hyperlinks preference like ColorEnabled, but independently of color: NO_COLOR keeps links, and auto links only on TTY stdout whose TERM is not dumb.

func IndentJSON

func IndentJSON(data []byte, color bool) (string, error)

IndentJSON formats JSON text for a terminal like Write with Pretty, but keeps the key order of the text: indented, sanitized, ending with a newline and, with color, highlighted.

func Markdown

func Markdown(text string, d Display) string

Markdown renders sanitized markdown for d: wrapped to its width (80 when unknown), colored or plain, with links only when d allows them. It keeps line breaks like Gitea does, and returns the sanitized text unrendered if rendering fails.

func MarkdownEnabled

func MarkdownEnabled(preference string, outTTY bool) bool

MarkdownEnabled resolves the markdown preference: raw never renders, and auto renders on TTY stdout.

func ParseTime

func ParseTime(raw string) time.Time

ParseTime parses an API timestamp, returning the zero time for an empty or malformed value.

func Plural

func Plural(n int, unit string) string

Plural counts n of a unit, as in "1 fork" or "3 forks".

func RelativeTime

func RelativeTime(now, t time.Time) string

RelativeTime describes t relative to now like gh: "less than a minute ago", "about 3 hours ago", and "in about 2 months" for future times such as due dates.

func RequireInput

func RequireInput(ctx context.Context, value *string, label string, validate func(string) error, missing error, streams Streams, policy Policy, prompt Prompter) (bool, error)

RequireInput fills a missing value from a prompt titled label and marked "(required)" like the form fields, re-prompting inline until the answer is non-empty and validate, when set, accepts it. When prompts are unavailable it returns missing as a usage error. It reports whether it prompted.

func ResetSGR

func ResetSGR(w io.Writer) error

ResetSGR resets the terminal's colors when the SafeWriter w passed SGR sequences, so that text cut off while colored, such as a failed job's log, does not leave the terminal colored.

func SafeColorWriter

func SafeColorWriter(w io.Writer, tty, color bool) io.Writer

SafeColorWriter is SafeWriter for text that is colored throughout, such as job logs: without color it drops SGR sequences whole instead of showing them as "[36m" text.

func SafeLine

func SafeLine(s string) string

SafeLine reduces server text to one line: SafeText, with tabs and line breaks as spaces.

func SafeText

func SafeText(s string) string

SafeText keeps tabs and line breaks in server text, normalizing CRLF to LF, and drops every other control or format character, such as escape sequences, lone carriage returns and bidirectional overrides, so the text cannot drive the terminal.

func SafeWriter

func SafeWriter(w io.Writer, tty, allowSGR bool) io.Writer

SafeWriter returns w unchanged when tty is false, so piped output stays byte-exact. On a terminal it filters streamed server text like SafeText, and with allowSGR it keeps SGR color sequences (ESC [ ... m) while dropping every other escape sequence's ESC; ResetSGR then ends the colors it passed.

func SaveDraft

func SaveDraft(dir, pattern, body string) (string, error)

SaveDraft writes body to a new private file named after pattern in dir, or in the temporary directory when dir is empty, and returns its path. A file that cannot be written is removed.

func Table

func Table(columns []Column, rows [][]Cell, d Display) string

Table renders rows under columns; rows may have more cells than there are columns. On a TTY it aligns columns under an uppercase header and shrinks Flex columns to the display width; otherwise it writes tab-separated lines. Cell text passes through SafeLine either way.

func Timestamp

func Timestamp(t time.Time) string

Timestamp formats t for scripts: RFC3339 in UTC at second precision.

func ValidateOutput

func ValidateOutput(fields, query string, allowed []string) error

ValidateOutput catches invalid projection/filter syntax before a service mutates data. An unknown field error lists the allowed fields.

func ValidateTemplate added in v1.1.0

func ValidateTemplate(text string) error

ValidateTemplate checks the syntax of a --template, so that a mistake fails before any request.

func WriteHuman

func WriteHuman(ctx context.Context, streams Streams, command string, pager Pager, text string) error

WriteHuman writes human text directly, or through a pager when stdout is a TTY, a pager command is configured, and the content spans multiple lines. Prompting policy such as --no-input does not affect paging.

Types

type BodyEditor

type BodyEditor func(context.Context, string) (Draft, error)

BodyEditor collects a markdown body through the shared draft editor instead of an inline text field. Callers must finish the returned Draft.

type Browser

type Browser interface {
	Open(context.Context, string, string) error
}

Browser opens an explicitly requested resource using a configured command.

type Cell

type Cell struct {
	Text, Link, Color string
	Bold, Muted       bool
	// Time, when set, replaces Text: relative on a TTY, RFC3339 UTC otherwise.
	Time time.Time
}

Cell is one value in a Table. Color (a name such as green), Bold and Muted style the text after alignment, so escape sequences never count toward the column width. Link applies to the first column only.

func StatusIcon

func StatusIcon(status, conclusion string) Cell

StatusIcon summarizes a check or run in one cell: ✓ succeeded, X failed, - skipped or canceled, and * still pending. A conclusion, when present, takes precedence over the status.

func (Cell) Render

func (c Cell) Render(d Display) string

Render styles the cell's text outside a table: its color, muted or bold, without a link.

type Choice

type Choice struct {
	Label, Value string
}

Choice is one option of a selection prompt: Label is shown and Value returned.

type Chooser

type Chooser interface {
	// Choose asks for one of choices, starting at the one whose value is initial, else the first.
	Choose(ctx context.Context, title string, choices []Choice, initial string) (string, error)
}

Chooser asks for one of several options. FormPrompter implements it; a Prompter without it cannot offer a selection.

type Column

type Column struct {
	// Header names the column; a TTY shows it uppercased above the rows.
	Header string
	// Flex columns shrink to fit the terminal width, widest first, cutting text with "…", down to
	// Min, the header width or eight cells, whichever is wider. Other columns are never cut.
	Flex bool
	Min  int
	// TTYOnly and PipedOnly restrict the column to one kind of output.
	TTYOnly, PipedOnly bool
	// Prefix precedes non-empty cells on a TTY, such as "#" before issue numbers.
	Prefix string
}

Column describes one table column.

type Confirmation

type Confirmation struct {
	// Prompt asks about the action in sentence case: `Delete label "bug" from alice/x?`.
	Prompt string
	// DefaultYes lets Enter accept, for constructive actions the user just asked for, such as
	// submitting a form they filled in. Destructive actions keep the default no.
	DefaultYes bool
	// Typed, when set, must be typed to confirm, for irreversible actions such as deleting a repository.
	Typed string
	// NonTTY names the action in the error returned when no prompt is possible and --yes is
	// missing: `delete label "bug" from alice/x`. Without it, a confirmation that defaults to no
	// names the Prompt up to its question mark.
	NonTTY string
}

Confirmation describes the question asked before an action.

type Display

type Display struct {
	TTY bool
	// Color enables SGR colors and emphasis on a TTY.
	Color bool
	// Links enables OSC 8 links on the first table column on a TTY.
	Links bool
	// Markdown renders view bodies on a TTY.
	Markdown bool
	// Width is the terminal width that table rows fit in; 0 disables truncation.
	Width int
	// Now is the reference for relative times; zero means the current time.
	Now time.Time
}

Display describes the output that tables and views render for: a terminal (TTY), or plain text for scripts.

type Draft

type Draft struct {
	Path string
	Body string
}

Draft holds edited text and the private file retained until successful submission.

type Editor

type Editor interface {
	Edit(context.Context, string, string) (Draft, error)
	EditPath(context.Context, string, string) error
}

Editor edits drafts or existing files using an explicitly selected command.

type Field

type Field struct {
	Label string
	// Value is plain text. Cells, when set, replace it with styled values joined by commas, such
	// as colored labels.
	Value string
	Cells []Cell
	// TTYOnly and PipedOnly restrict the field to one kind of output, like table columns.
	TTYOnly, PipedOnly bool
}

Field is one labeled fact in a View.

type FormPrompter

type FormPrompter struct {
	Streams Streams
	// Color reports whether forms are colored, following gt's color settings for ErrOut; nil colors
	// them as the terminal allows.
	Color func() bool
	// contains filtered or unexported fields
}

FormPrompter uses cancellable terminal forms with explicitly injected streams.

func (*FormPrompter) Ask

func (p *FormPrompter) Ask(ctx context.Context, title string, validate func(string) error) (string, error)

Ask collects one line, re-prompting inline until validate accepts the trimmed answer.

func (*FormPrompter) AskText

func (p *FormPrompter) AskText(ctx context.Context, title, initial string) (string, error)

AskText collects multi-line markdown in an inline field, starting from initial.

func (*FormPrompter) Choose

func (p *FormPrompter) Choose(ctx context.Context, title string, choices []Choice, initial string) (string, error)

Choose asks on stderr for one of choices and returns its value.

func (*FormPrompter) ConfirmDefault

func (p *FormPrompter) ConfirmDefault(ctx context.Context, title string, defaultYes bool) (bool, error)

ConfirmDefault asks a yes/no question that Enter answers with defaultYes.

func (*FormPrompter) CreateIssue

func (p *FormPrompter) CreateIssue(ctx context.Context, choices IssueFormChoices) (IssueFormValues, error)

CreateIssue runs the interactive issue create form on stderr.

func (*FormPrompter) CreatePull

func (p *FormPrompter) CreatePull(ctx context.Context, choices PullFormChoices) (PullFormValues, error)

CreatePull runs the interactive pull create form on stderr, like gh pr create: the title and body of a pull request from the current branch, then "What's next?" to submit it, submit it as a draft, add metadata, change the branches or cancel. Branches are asked first when unknown.

func (*FormPrompter) CreateRepo added in v0.2.0

func (p *FormPrompter) CreateRepo(ctx context.Context, choices RepoFormChoices) (RepoFormValues, error)

CreateRepo runs the interactive repository create form on stderr, like gh repo create: the owner, name, description and visibility, then whether to add initial content, which license and .gitignore templates it uses, and whether to clone the new repository.

func (*FormPrompter) CreateReview

func (p *FormPrompter) CreateReview(ctx context.Context, choices ReviewFormChoices) (ReviewFormValues, error)

CreateReview asks for the review type, then the body, then whether to annotate the diff, on stderr.

func (*FormPrompter) EditIssue

EditIssue runs the interactive issue edit form on stderr, seeded with the current values.

func (*FormPrompter) EditLabel added in v0.2.0

func (p *FormPrompter) EditLabel(ctx context.Context, heading string, current LabelFormValues, validColor func(string) error) (LabelFormValues, error)

EditLabel runs the interactive label form on stderr.

func (*FormPrompter) EditMilestone

func (p *FormPrompter) EditMilestone(ctx context.Context, heading string, current MilestoneFormValues) (MilestoneFormValues, error)

EditMilestone runs the interactive milestone form on stderr.

func (*FormPrompter) EditRelease added in v0.2.0

func (p *FormPrompter) EditRelease(ctx context.Context, heading string, current ReleaseFormValues) (ReleaseFormValues, error)

EditRelease runs the interactive release form on stderr.

func (*FormPrompter) Login

Login asks the selected questions on stderr, one at a time, so that later questions can depend on earlier answers.

func (*FormPrompter) MergeOptions

func (p *FormPrompter) MergeOptions(ctx context.Context, choices MergeFormChoices) (MergeFormValues, error)

MergeOptions asks for the merge style and whether to delete the head branch, on stderr.

func (*FormPrompter) SecretInput

func (p *FormPrompter) SecretInput(ctx context.Context, title string) (string, error)

SecretInput collects a value without displaying it on the terminal.

func (*FormPrompter) SelectPull

func (p *FormPrompter) SelectPull(ctx context.Context, choices []MergePullChoice) (int64, error)

SelectPull prompts for a pull request on stderr.

type IssueEditForm

type IssueEditForm interface {
	EditIssue(context.Context, IssueEditFormChoices) (IssueEditFormValues, error)
}

IssueEditForm collects interactive issue edit input.

type IssueEditFormChoices

type IssueEditFormChoices struct {
	// Heading names the edited issue above the form, such as "Editing alice/x#2 (Fix login)".
	Heading     string
	Title, Body string
	// Base, set for a pull request, is its base branch, which the form asks for after the title.
	Base               string
	Assignees          []string
	Milestone          *IssueMilestoneChoice
	Labels             []IssueLabelChoice
	Deadline           *time.Time
	AvailableAssignees []string
	Milestones         []IssueMilestoneChoice
	AvailableLabels    []IssueLabelChoice
	EditBody           BodyEditor
}

IssueEditFormChoices supplies current issue or pull request values and selectable options for edit. Current values missing from the options stay selectable.

type IssueEditFormValues

type IssueEditFormValues struct {
	Title, Body    string
	Base           string
	Assignees      []string
	Milestone      int64
	ClearMilestone bool
	Labels         []int64
	Deadline       *time.Time
	ClearDeadline  bool
	Draft          Draft
}

IssueEditFormValues holds interactively edited issue fields. Deadline is set only when the due date changed.

type IssueForm

type IssueForm interface {
	CreateIssue(context.Context, IssueFormChoices) (IssueFormValues, error)
}

IssueForm collects interactive issue create input.

type IssueFormChoices

type IssueFormChoices struct {
	Templates []IssueTemplateChoice
	// Template, when set, is used instead of asking: the form starts with its title and body.
	Template   *IssueTemplateChoice
	Assignees  []string
	Milestones []IssueMilestoneChoice
	Labels     []IssueLabelChoice
	EditBody   BodyEditor
	// AskNext asks "What's next?" after the title and body, offering metadata only on request.
	AskNext bool
}

IssueFormChoices supplies options for an interactive issue create form.

type IssueFormValues

type IssueFormValues struct {
	Title, Body string
	Assignees   []string
	Milestone   int64
	Labels      []int64
	Deadline    *time.Time
	Draft       Draft
	// TemplateLabels are the label names of the chosen template, which the caller adds to Labels.
	TemplateLabels []string
	// TemplateRef is the branch or tag the chosen template sets on the issue.
	TemplateRef string
}

IssueFormValues holds interactively collected issue create fields.

type IssueLabelChoice

type IssueLabelChoice struct {
	Name string
	ID   int64
}

IssueLabelChoice identifies a repository label for interactive selection.

type IssueMilestoneChoice

type IssueMilestoneChoice struct {
	Title string
	ID    int64
}

IssueMilestoneChoice identifies an open milestone for interactive selection.

type IssueTemplateChoice

type IssueTemplateChoice struct {
	Name, About, Title, Body, Ref string
	Labels                        []string
}

IssueTemplateChoice seeds title/body when selected in an interactive create form. Its labels and ref are returned as IssueFormValues.TemplateLabels and TemplateRef for the caller to apply.

type JSONOutput

type JSONOutput struct {
	// Fields holds the comma-separated fields to keep; "" and "*" keep every field.
	Fields string
	// Allowed lists the fields the command documents. A listed field that an item omits (an empty
	// omitempty value) is selected as null instead of being reported unknown; nil allows none.
	Allowed []string
	// Query is a jq expression applied after field selection.
	Query string
	// Pretty indents the JSON for a terminal and strips control characters from raw jq strings.
	Pretty bool
	// Safe strips control characters from raw jq strings and encoded text like Pretty, for terminal
	// output that must stay one line per value.
	Safe bool
	// Color highlights pretty JSON keys and values.
	Color bool
	// Links lets a template's hyperlink function emit links.
	Links bool
	// CSV writes the selected objects as CSV instead of JSON; Query must be empty.
	CSV bool
	// NoHeader leaves out the CSV header row, for rows that continue earlier output.
	NoHeader bool
	// Template renders the selected objects through this Go template instead of writing JSON; Query
	// and CSV must be empty.
	Template string
	// Now is the time that the template function timeago measures from; it is the clock by default.
	Now func() time.Time
}

JSONOutput selects, filters, and formats command results as JSON.

func (JSONOutput) Write

func (o JSONOutput) Write(w io.Writer, value any) error

Write projects explicit result fields of value, applies the jq filter, and writes the results.

type LabelForm added in v0.2.0

type LabelForm interface {
	// EditLabel asks for the name, color and description of a label, starting from current, under
	// heading, such as `Editing label "bug" in alice/x`. validColor checks a color answer.
	EditLabel(ctx context.Context, heading string, current LabelFormValues, validColor func(string) error) (LabelFormValues, error)
}

LabelForm collects interactive label input.

type LabelFormValues added in v0.2.0

type LabelFormValues struct {
	Name, Color, Description string
}

LabelFormValues holds interactively edited label fields.

type LoginAnswers

type LoginAnswers struct {
	// Host is the instance URL; Method one of LoginToken, LoginOAuth and LoginSSHKey.
	Host, Method string
	// Token is the pasted access token, and SSHKey the private key path, for their methods.
	Token, SSHKey string
	// Store is the credential store of a token: keyring or file.
	Store string
	// SetupGit configures Git to use gt for the instance.
	SetupGit bool
}

LoginAnswers holds the choices of an interactive login. Callers prefill the defaults.

type LoginForm

type LoginForm interface {
	Login(context.Context, LoginQuestions, *LoginAnswers) error
}

LoginForm collects how to log in to a Gitea instance.

type LoginQuestions

type LoginQuestions struct {
	Host, Method, Store, SetupGit bool
	// ResolveHost normalizes an entered instance, or explains why it is not one.
	ResolveHost func(string) (string, error)
	// TokenHint tells where to create an access token on an instance.
	TokenHint func(host string) string
}

LoginQuestions selects what an interactive login asks. The token of the token method and the key of the SSH key method are always asked; Store and SetupGit only for tokens.

type MergeForm

type MergeForm interface {
	SelectPull(context.Context, []MergePullChoice) (int64, error)
	MergeOptions(context.Context, MergeFormChoices) (MergeFormValues, error)
}

MergeForm collects which pull request to merge, and how.

type MergeFormChoices

type MergeFormChoices struct {
	// Header introduces the form, such as `Merge #3 "Merge me" (feat/merge-me → main) in alice/x`.
	Header string
	// Methods are the merge styles the repository allows; Method preselects one. Without Methods,
	// the form does not ask for one.
	Methods []string
	Method  string
	// DeleteBranch preselects whether to delete the head branch; Branch, when set, asks it.
	DeleteBranch bool
	Branch       string
}

MergeFormChoices describes the pull request to merge and what the form asks about it.

type MergeFormValues

type MergeFormValues struct {
	Method       string
	DeleteBranch bool
}

MergeFormValues are the chosen merge style and whether to delete the head branch.

type MergePullChoice

type MergePullChoice struct {
	Number      int64
	Title, Head string
}

MergePullChoice is one selectable open pull request for interactive merge.

type MilestoneForm

type MilestoneForm interface {
	// EditMilestone asks for the fields of a milestone, starting from current, under heading, such
	// as "Editing milestone v1.0". Empty values create a milestone.
	EditMilestone(ctx context.Context, heading string, current MilestoneFormValues) (MilestoneFormValues, error)
}

MilestoneForm collects interactive milestone input.

type MilestoneFormValues

type MilestoneFormValues struct {
	Title, Description string
	Deadline           *time.Time
	// Editor is the configured editor command, input only: with one, ctrl+e opens it in the description, except in accessible mode.
	Editor string
}

MilestoneFormValues holds interactively collected milestone fields.

type Pager

type Pager interface {
	Page(context.Context, string, io.Reader, Streams) error
}

Pager renders multi-line human output through an external command.

type PagerError

type PagerError struct{ Err error }

PagerError reports a pager command that could not run or failed; callers name where it was configured.

func (*PagerError) Error

func (e *PagerError) Error() string

func (*PagerError) Unwrap

func (e *PagerError) Unwrap() error

type Policy

type Policy struct{ Enabled, NoInput, Machine, Interactive bool }

Policy controls input interaction independently of supplied flag count.

func (Policy) CanPrompt

func (p Policy) CanPrompt(s Streams) bool

CanPrompt requires terminal input and diagnostics, without requiring terminal stdout.

func (Policy) Validate

func (p Policy) Validate(s Streams) error

Validate rejects an explicit interactive request incompatible with terminal policy.

type Prompter

type Prompter interface {
	// Ask collects one line, re-prompting inline until validate, when set, accepts it.
	Ask(ctx context.Context, title string, validate func(string) error) (string, error)
	// AskText collects multi-line markdown, starting from initial.
	AskText(ctx context.Context, title, initial string) (string, error)
	// SecretInput collects a value without displaying it.
	SecretInput(ctx context.Context, title string) (string, error)
	// ConfirmDefault asks a yes/no question that Enter answers with defaultYes.
	ConfirmDefault(ctx context.Context, title string, defaultYes bool) (bool, error)
}

Prompter abstracts cancellable input collection and confirmation.

type PullForm

type PullForm interface {
	CreatePull(context.Context, PullFormChoices) (PullFormValues, error)
}

PullForm collects interactive pull create input.

type PullFormChoices

type PullFormChoices struct {
	// Repo is the base repository, named in the form's header.
	Repo                                   string
	BaseOwner, Base, HeadOwner, HeadBranch string
	// Title and Body seed the form; Title applies only while HeadBranch is kept.
	Title, Body          string
	AllowMaintainerEdits bool
	Assignees            []string
	Milestones           []IssueMilestoneChoice
	Labels               []IssueLabelChoice
	// CanPush offers metadata, which needs push access; without it, changing branches offers AGit.
	CanPush  bool
	EditBody BodyEditor
	// SeedBody seeds the body in place of Body when the branches asked first change.
	SeedBody func(ctx context.Context, base, headBranch string) (string, error)
}

PullFormChoices supplies defaults and selectable options for interactive PR create.

type PullFormValues

type PullFormValues struct {
	IssueFormValues
	Agit                 bool
	Base, Head, Topic    string
	AllowMaintainerEdits bool
	// AsDraft submits the pull request as a draft.
	AsDraft bool
}

PullFormValues holds interactively collected pull request create fields.

type ReleaseForm added in v0.2.0

type ReleaseForm interface {
	// EditRelease asks for the fields of a release, starting from current, under heading, such as
	// "Editing release v1.0 in alice/x". Empty values create a release.
	EditRelease(ctx context.Context, heading string, current ReleaseFormValues) (ReleaseFormValues, error)
}

ReleaseForm collects interactive release input.

type ReleaseFormValues added in v0.2.0

type ReleaseFormValues struct {
	Tag, Title, Notes, Target string
	Draft, Prerelease         bool
	// Editor is the configured editor command, input only: with one, ctrl+e opens it in the notes, except in accessible mode.
	Editor string
}

ReleaseFormValues holds interactively collected release fields.

type RepoForm added in v0.2.0

type RepoForm interface {
	CreateRepo(context.Context, RepoFormChoices) (RepoFormValues, error)
}

RepoForm collects interactive repository create input.

type RepoFormChoices added in v0.2.0

type RepoFormChoices struct {
	// Owners are the accounts the repository can belong to, yourself first.
	Owners               []string
	Licenses, Gitignores []string
	// ValidateName and ValidateDescription check the answers as repository creation does.
	ValidateName, ValidateDescription func(string) error
}

RepoFormChoices supplies the selectable options of interactive repository create.

type RepoFormValues added in v0.2.0

type RepoFormValues struct {
	Owner, Name, Description string
	Private, AutoInit        bool
	License                  string
	Gitignores               []string
	Clone                    bool
}

RepoFormValues holds interactively collected repository create fields.

type ReviewCommentDraft

type ReviewCommentDraft struct {
	Path, Body       string
	OldLine, NewLine int64
}

ReviewCommentDraft is an inline comment collected during interactive review.

type ReviewForm

type ReviewForm interface {
	CreateReview(context.Context, ReviewFormChoices) (ReviewFormValues, error)
}

ReviewForm collects interactive pull review input.

type ReviewFormChoices

type ReviewFormChoices struct {
	// Header introduces the form, such as `Reviewing #1 "Add one.txt" (feat/one → main) in alice/x`.
	Header string
	// Author leaves out approving and requesting changes, which Gitea refuses on one's own pull request.
	Author bool
	// Body seeds the review body.
	Body string
	// Editor is the configured editor command that ctrl+e opens on the body, except in accessible mode; empty disables it.
	Editor string
	// ReviewDiff, when non-nil, offers to annotate the diff in the editor after the body.
	ReviewDiff func(context.Context) ([]ReviewCommentDraft, error)
	// Pending tells that the pending review a comment would publish has a body or inline
	// comments, so that the comment needs neither.
	Pending bool
}

ReviewFormChoices describes the pull request under review and how its review is collected.

type ReviewFormValues

type ReviewFormValues struct {
	Event    string
	Body     string
	Comments []ReviewCommentDraft
}

ReviewFormValues holds an interactively collected review: its API state, body and inline comments.

type Streams

type Streams struct {
	In     io.Reader
	Out    io.Writer
	ErrOut io.Writer
	InTTY  bool
	OutTTY bool
	ErrTTY bool
	// OutPlain and ErrPlain mark a terminal that shows escape sequences as text, such as a Windows
	// console without virtual terminal processing: output on it stays uncolored.
	OutPlain, ErrPlain bool
	// Width is the number of columns human output on Out fits in; 0 means unlimited.
	Width int
	// contains filtered or unexported fields
}

Streams records injected IO and independently detected terminal capabilities.

func System

func System() Streams

System binds streams to the current process and detects each terminal, enabling escape sequences on the terminals that need it. Restore undoes that.

func (Streams) ErrColor

func (s Streams) ErrColor(preference string, getenv func(string) string) bool

ErrColor is OutColor for ErrOut.

func (Streams) ErrEscapes

func (s Streams) ErrEscapes() bool

ErrEscapes reports whether ErrOut is a terminal that interprets escape sequences.

func (Streams) OutColor

func (s Streams) OutColor(preference string, getenv func(string) string) bool

OutColor resolves the color preference for Out with ColorEnabled. A terminal that shows escape sequences as text stays uncolored even when color is forced, as color would only garble it.

func (Streams) OutEscapes

func (s Streams) OutEscapes() bool

OutEscapes reports whether Out is a terminal that interprets escape sequences.

func (Streams) Restore

func (s Streams) Restore()

Restore undoes what System changed on the terminals, such as the mode of a Windows console, which would otherwise keep the change after gt exits.

type SystemBrowser

type SystemBrowser struct{ ErrOut io.Writer }

SystemBrowser runs the browser without a shell and routes diagnostics to stderr.

func (SystemBrowser) Open

func (b SystemBrowser) Open(ctx context.Context, resource, command string) error

Open validates the resource and invokes the selected browser directly.

type SystemEditor

type SystemEditor struct {
	Directory string
	Streams   Streams
}

SystemEditor uses private temporary files and the application's terminal streams.

func (SystemEditor) Edit

func (e SystemEditor) Edit(ctx context.Context, command, body string) (Draft, error)

Edit preserves the draft on failure; the caller removes it after submission.

func (SystemEditor) EditPath

func (e SystemEditor) EditPath(ctx context.Context, command, path string) error

EditPath opens an existing file in the configured editor and blocks until it exits. Like Git, it waits for the editor instead of killing it on cancellation, so the editor can restore the terminal.

type SystemPager

type SystemPager struct{}

SystemPager runs the pager without a shell and routes diagnostics to stderr.

func (SystemPager) Page

func (SystemPager) Page(ctx context.Context, command string, input io.Reader, streams Streams) error

Page validates the command and feeds content to the pager stdin. The pager handles interrupts itself; killing it on cancellation would leave the terminal raw.

type View

type View struct {
	Title, ID string
	// Badges, such as the state, start the line under the title; Meta completes it, for example
	// "alice opened about 2 hours ago • 2 comments".
	Badges []Cell
	Meta   string
	Fields []Field
	Body   string
	// Plain marks the body as plain text, such as a commit message, which is never rendered as markdown.
	Plain bool
	// Bodyless resources, such as webhooks, have no body: the view ends with the fields and URL.
	Bodyless bool
	// Kind names the resource in the footer, such as "issue".
	Kind, URL string
}

View is one resource for human readers, such as an issue. On a TTY it shows the title, badges, fields, body and a "View this <kind> on Gitea" footer; piped, "key:\tvalue" lines, "--" and the raw body.

func (View) Render

func (v View) Render(d Display) string

Render formats the view for d. All server text is sanitized.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL