From 3cac6bdb302f3311a4cfb842fdae9a539417bdc1 Mon Sep 17 00:00:00 2001 From: Darren Schroeder <343840+fdncred@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:15:54 -0600 Subject: [PATCH] git and gh completions: one extern per tool, alias-aware, full coverage --- custom-completions/gh/gh-completions.nu | 2630 ++++++++++++++--- custom-completions/gh/tests/gh-completions.nu | 179 ++ custom-completions/git/git-completions.nu | 2624 ++++++++++------ .../git/tests/git-completions.nu | 256 ++ 4 files changed, 4350 insertions(+), 1339 deletions(-) create mode 100644 custom-completions/gh/tests/gh-completions.nu diff --git a/custom-completions/gh/gh-completions.nu b/custom-completions/gh/gh-completions.nu index 0d08970b..137ad71a 100644 --- a/custom-completions/gh/gh-completions.nu +++ b/custom-completions/gh/gh-completions.nu @@ -1,558 +1,2257 @@ +# nu-version: 0.116.1 + +# Completions for gh (generated from `gh help reference`, gh 2.104.0) and +# your gh aliases. One `gh` extern with no declared flags hands the whole command line to +# `nu-complete gh`, so every argument reaches gh exactly as typed (`--draft=false`, +# `-f body='Hi there'`, `-L5`). Command and flag data are tab-separated rows, decoded only +# for the command being completed. + +# command path, positional kinds, description +const GH_COMMANDS = r#' + gh-command Work seamlessly with GitHub from the command line +agent-task Work with agent tasks (preview) +agent-task create Create an agent task (preview) +agent-task list List agent tasks (preview) +agent-task view pr View an agent task session (preview) +alias Create command shortcuts +alias delete alias Delete set aliases +alias import file Import aliases from a YAML file +alias list List your aliases +alias set Create a shortcut for a gh command +api api-endpoint Make an authenticated GitHub API request +attestation Work with artifact attestations +attestation download file Download an artifact's attestations for offline use +attestation trusted-root Output trusted_root.jsonl contents, likely for offline verification +attestation verify file Verify an artifact's integrity using attestations +auth Authenticate gh and git with GitHub +auth login Log in to a GitHub account +auth logout Log out of a GitHub account +auth refresh Refresh stored authentication credentials +auth setup-git Setup git with GitHub CLI +auth status Display active account and authentication state on each known GitHub host +auth switch Switch active GitHub account +auth token Print the authentication token gh uses for a hostname and account +browse file Open repositories, issues, pull requests, and more in the browser +cache Manage GitHub Actions caches +cache delete cache Delete GitHub Actions caches +cache list List GitHub Actions caches +codespace Connect to and manage codespaces +codespace code Open a codespace in Visual Studio Code +codespace cp file... Copy files between local and remote file systems +codespace create Create a codespace +codespace delete Delete codespaces +codespace edit Edit a codespace +codespace jupyter Open a codespace in JupyterLab +codespace list List codespaces +codespace logs Access codespace logs +codespace ports List ports in a codespace +codespace ports forward Forward ports +codespace ports visibility Change the visibility of the forwarded port +codespace rebuild Rebuild a codespace +codespace ssh SSH into a codespace +codespace stop Stop a running codespace +codespace view View details about a codespace +completion Generate shell completion scripts +config Manage configuration for gh +config clear-cache Clear the cli cache +config get config-key Print the value of a given configuration key +config list Print a list of configuration keys and values +config set config-key config-value Update configuration with a value for the given key +copilot Run the GitHub Copilot CLI (preview) +discussion Work with GitHub Discussions (preview) +discussion comment discussion Add, edit, or delete a comment or a reply on a discussion (preview) +discussion create Create a new discussion (preview) +discussion edit discussion Edit a discussion (preview) +discussion list List discussions in a repository (preview) +discussion view discussion View a discussion (preview) +extension Manage gh extensions +extension browse Enter a UI for browsing, adding, and removing extensions +extension create Create a new extension +extension exec extension none... Execute an installed extension +extension install Install a gh extension from a repository +extension list List installed extension commands +extension remove extension Remove an installed extension +extension search Search extensions to the GitHub CLI +extension upgrade extension Upgrade installed extensions +gist Manage gists +gist clone gist file Clone a gist locally +gist create file... Create a new gist +gist delete gist Delete a gist +gist edit gist gist-file Edit one of your gists +gist list List your gists +gist rename gist gist-file Rename a file in a gist +gist view gist View a gist +gpg-key Manage GPG keys +gpg-key add file Add a GPG key to your GitHub account +gpg-key delete gpg-key Delete a GPG key from your GitHub account +gpg-key list Lists GPG keys in your GitHub account +issue Manage issues +issue artifact Work with issue artifacts (preview) +issue artifact create issue file... Create issue artifacts (preview) +issue artifact delete issue Delete issue artifacts (preview) +issue artifact download issue Download issue artifacts (preview) +issue artifact edit issue Edit an issue artifact (preview) +issue artifact list issue List artifacts on an issue (preview) +issue artifact view issue View an issue artifact (preview) +issue close issue Close issue +issue comment issue Add a comment to an issue +issue create Create a new issue +issue delete issue Delete issue +issue develop issue Manage linked branches for an issue +issue edit issue... Edit issues +issue list List issues in a repository +issue lock issue Lock issue conversation +issue pin issue Pin an issue +issue reopen issue-closed Reopen issue +issue status Show status of relevant issues +issue transfer issue repo Transfer issue to another repository +issue unlock issue Unlock issue conversation +issue unpin issue Unpin an issue +issue view issue View an issue +label Manage labels +label clone repo Clones labels from one repository to another +label create Create a new label +label delete label Delete a label from a repository +label edit label Edit a label +label list List labels in a repository +licenses View third-party license information +org Manage organizations +org list List organizations for the authenticated user. +pr Manage pull requests +pr checkout pr Check out a pull request in git +pr checks pr Show CI status for a single pull request +pr close pr Close a pull request +pr comment pr Add a comment to a pull request +pr create Create a pull request +pr diff pr View changes in a pull request +pr edit pr Edit a pull request +pr list List pull requests in a repository +pr lock pr Lock pull request conversation +pr merge pr Merge a pull request +pr ready pr Mark a pull request as ready for review +pr reopen pr-closed Reopen a pull request +pr revert pr-merged Revert a pull request +pr review pr Add a review to a pull request +pr status Show status of relevant pull requests +pr unlock pr Unlock pull request conversation +pr update-branch pr Update a pull request branch +pr view pr View a pull request +preview Execute previews for gh features +preview prompter prompt-type Execute a test program to preview the prompter +project Work with GitHub Projects. +project close project Close a project +project copy project Copy a project +project create Create a project +project delete project Delete a project +project edit project Edit a project +project field-create project Create a field in a project +project field-delete Delete a field in a project +project field-list project List the fields in a project +project item-add project Add a pull request or an issue to a project +project item-archive project Archive an item in a project +project item-create project Create a draft issue item in a project +project item-delete project Delete an item from a project by ID +project item-edit project Edit an item in a project +project item-list project List the items in a project +project link project Link a project to a repository or a team +project list List the projects for an owner +project mark-template project Mark a project as a template +project unlink project Unlink a project from a repository or a team +project view project View a project +release Manage releases +release create none file... Create a new release +release delete release Delete a release +release delete-asset release release-asset Delete an asset from a release +release download release Download release assets +release edit release Edit a release +release list List releases in a repository +release upload release file... Upload assets to a release +release verify release Verify the attestation for a release +release verify-asset release file Verify that a given asset originated from a release +release view release View information about a release +repo Manage repositories +repo archive repo Archive a repository +repo autolink Manage autolink references +repo autolink create Create a new autolink reference +repo autolink delete autolink Delete an autolink reference +repo autolink list List autolink references for a GitHub repository +repo autolink view autolink View an autolink reference +repo clone repo file Clone a repository locally +repo create Create a new repository +repo delete repo Delete a repository +repo deploy-key Manage deploy keys in a repository +repo deploy-key add file Add a deploy key to a GitHub repository +repo deploy-key delete deploy-key Delete a deploy key from a GitHub repository +repo deploy-key list List deploy keys in a GitHub repository +repo edit repo Edit repository settings +repo fork repo Create a fork of a repository +repo gitignore List and view available repository gitignore templates +repo gitignore list List available repository gitignore templates +repo gitignore view gitignore View an available repository gitignore template +repo license Explore repository licenses +repo license list List common repository licenses +repo license view license View a specific repository license +repo list owner List repositories owned by user or organization +repo read-dir List a directory in a repository (preview) +repo read-file Read a file from a repository (preview) +repo rename Rename a repository +repo set-default repo Configure default repository for this directory +repo sync repo Sync a repository +repo unarchive repo Unarchive a repository +repo view repo View a repository +ruleset View info about repo rulesets +ruleset check branch View rules that would apply to a given branch +ruleset list List rulesets for a repository or organization +ruleset view ruleset View information about a ruleset +run View details about workflow runs +run cancel run Cancel a workflow run +run delete run Delete a workflow run +run download run Download artifacts generated by a workflow run +run list List recent workflow runs +run rerun run Rerun a run +run view run View a summary of a workflow run +run watch run Watch a run until it completes, showing its progress +search Search for repositories, issues, and pull requests +search code Search within code +search commits Search for commits +search issues Search for issues +search prs Search for pull requests +search repos Search for repositories +secret Manage GitHub secrets +secret delete secret Delete secrets +secret list List secrets +secret set secret Create or update secrets +skill Install and manage agent skills (preview) +skill install Install agent skills from a GitHub repository (preview) +skill list List installed skills (preview) +skill preview Preview a skill from a GitHub repository (preview) +skill publish file Validate and publish skills to a GitHub repository (preview) +skill search Search for skills across GitHub (preview) +skill update skill... Update installed skills to their latest versions (preview) +ssh-key Manage SSH keys +ssh-key add file Add an SSH key to your GitHub account +ssh-key delete ssh-key Delete an SSH key from your GitHub account +ssh-key list Lists SSH keys in your GitHub account +status Print information about relevant issues, pull requests, and notifications across repositories +variable Manage GitHub Actions variables +variable delete variable Delete variables +variable get variable Get variables +variable list List variables +variable set variable Create or update variables +workflow View details about GitHub Actions workflows +workflow disable workflow Disable a workflow +workflow enable workflow Enable a workflow +workflow list List workflows +workflow run workflow Run a workflow by creating a workflow_dispatch event +workflow view workflow View the summary of a workflow +help help-topic help-subcommand Help about any command or topic +'# + +# command path, long flag, short flag, b(ool)|v(alue)|i(nt)|f(ile), completer or =values, description +const GH_FLAGS = r#' + version b Show gh version +agent-task create base b v branches Base branch for the pull request (use default branch if not provided) +agent-task create custom-agent a v Use a custom agent for the task. e.g., use 'my-agent' for the 'my-agent.md' agent +agent-task create follow b Follow agent session logs +agent-task create from-file F f Read task description from file (use "-" to read from standard input) +agent-task create repo R v repos Select another repository using the [HOST/]OWNER/REPO format +agent-task list jq q v Filter JSON output using a jq expression +agent-task list json v json-fields Output JSON with the specified fields +agent-task list limit L i Maximum number of agent tasks to fetch (default 30) +agent-task list template t v Format JSON output using a Go template; see "gh help formatting" +agent-task list web w b Open agent tasks in the browser +agent-task view follow b Follow agent session logs +agent-task view jq q v Filter JSON output using a jq expression +agent-task view json v json-fields Output JSON with the specified fields +agent-task view log b Show agent session logs +agent-task view repo R v repos Select another repository using the [HOST/]OWNER/REPO format +agent-task view template t v Format JSON output using a Go template; see "gh help formatting" +agent-task view web w b Open agent task in the browser +alias delete all b Delete all aliases +alias import clobber b Overwrite existing aliases of the same name +alias set clobber b Overwrite existing aliases of the same name +alias set shell s b Declare an alias to be passed through a shell interpreter +api allow-escape-sequences b Allow printing terminal escape sequences +api cache v Cache the response, e.g. "3600s", "60m", "1h" +api field F v Add a typed parameter in key=value format (use "@" or "@-" to read value from file or stdin) +api header H v api-headers Add a HTTP request header in key:value format +api hostname v hosts The GitHub hostname for the request (default "github.com") +api include i b Include HTTP response status line and headers in the output +api input f The file to use as body for the HTTP request (use "-" to read from standard input) +api jq q v Query to select values from the response using jq syntax +api method X v http-methods The HTTP method for the request (default "GET") +api paginate b Make additional HTTP requests to fetch all pages of results +api preview p v Opt into GitHub API previews (names should omit '-preview') +api raw-field f v Add a string parameter in key=value format +api silent b Do not print the response body +api slurp b Use with "--paginate" to return an array of all pages of either JSON arrays or objects +api template t v Format JSON output using a Go template; see "gh help formatting" +api verbose b Include full HTTP request and response in the output +attestation download digest-alg d v =sha256|sha512 The algorithm used to compute a digest of the artifact: {sha256|sha512} (default "sha256") +attestation download hostname v hosts Configure host to use +attestation download limit L i Maximum number of attestations to fetch (default 30) +attestation download owner o v owners GitHub organization to scope attestation lookup by +attestation download predicate-type v Filter attestations by provided predicate type +attestation download repo R v repos Repository name in the format / +attestation trusted-root hostname v hosts Configure host to use +attestation trusted-root tuf-root v Path to the TUF root.json file on disk +attestation trusted-root tuf-url v URL to the TUF repository mirror +attestation trusted-root verify-only b Don't output trusted_root.jsonl contents +attestation verify bundle b v Path to bundle on disk, either a single bundle in a JSON file or a JSON lines file with multiple bundles +attestation verify bundle-from-oci b When verifying an OCI image, fetch the attestation bundle from the OCI registry instead of from GitHub +attestation verify cert-identity v Enforce that the certificate's SubjectAlternativeName matches the provided value exactly +attestation verify cert-identity-regex i v Enforce that the certificate's SubjectAlternativeName matches the provided regex +attestation verify cert-oidc-issuer v Enforce that the issuer of the OIDC token matches the provided value (default "https://token.actions.githubusercontent.com") +attestation verify custom-trusted-root v Path to a trusted_root.jsonl file; likely for offline verification +attestation verify deny-self-hosted-runners b Fail verification for attestations generated on self-hosted runners +attestation verify digest-alg d v =sha256|sha512 The algorithm used to compute a digest of the artifact: {sha256|sha512} (default "sha256") +attestation verify format v =json Output format: {json} +attestation verify hostname v hosts Configure host to use +attestation verify jq q v Filter JSON output using a jq expression +attestation verify limit L i Maximum number of attestations to fetch (default 30) +attestation verify no-public-good b Do not verify attestations signed with Sigstore public good instance +attestation verify owner o v owners GitHub organization to scope attestation lookup by +attestation verify predicate-type v Enforce that verified attestations' predicate type matches the provided value (default "https://slsa.dev/provenance/v1") +attestation verify repo R v repos Repository name in the format / +attestation verify signer-digest v Enforce that the digest associated with the signer workflow matches the provided value +attestation verify signer-repo v repos Enforce that the workflow that signed the attestation's repository matches the provided value (/) +attestation verify signer-workflow v Enforce that the workflow that signed the attestation matches the provided value ([host/]////) +attestation verify source-digest v Enforce that the digest associated with the source repository matches the provided value +attestation verify source-ref v Enforce that the git ref associated with the source repository matches the provided value +attestation verify template t v Format JSON output using a Go template; see "gh help formatting" +auth login clipboard c b Copy one-time OAuth device code to clipboard +auth login expiring b Prefer expiring credentials that gh refreshes automatically, if the host supports them +auth login git-protocol p v =ssh|https The protocol to use for git operations on this host: {ssh|https} +auth login hostname h v hosts The hostname of the GitHub instance to authenticate with +auth login insecure-storage b Save authentication credentials in plain text instead of credential store +auth login scopes s v scopes Additional authentication scopes to request +auth login skip-ssh-key b Skip generate/upload SSH key prompt +auth login web w b Open a browser to authenticate +auth login with-token b Read token from standard input +auth logout hostname h v hosts The hostname of the GitHub instance to log out of +auth logout user u v accounts The account to log out of +auth refresh clipboard c b Copy one-time OAuth device code to clipboard +auth refresh expiring b Prefer expiring credentials that gh refreshes automatically, if the host supports them +auth refresh hostname h v hosts The GitHub host to use for authentication +auth refresh insecure-storage b Save authentication credentials in plain text instead of credential store +auth refresh remove-scopes r v scopes Authentication scopes to remove from gh +auth refresh reset-scopes b Reset authentication scopes to the default minimum set of scopes +auth refresh scopes s v scopes Additional authentication scopes for gh to have +auth setup-git force f b Force setup even if the host is not known. Must be used in conjunction with --hostname +auth setup-git hostname h v hosts The hostname to configure git for +auth status active a b Display the active account only +auth status hostname h v hosts Check only a specific hostname's auth status +auth status jq v Filter JSON output using a jq expression +auth status json v json-fields Output JSON with the specified fields +auth status no-refresh b Do not automatically refresh expired tokens +auth status show-token t b Display the auth token +auth status template v Format JSON output using a Go template; see "gh help formatting" +auth switch hostname h v hosts The hostname of the GitHub instance to switch account for +auth switch user u v accounts The account to switch to +auth token hostname h v hosts The hostname of the GitHub instance authenticated with +auth token no-refresh b Do not automatically refresh an expired token +auth token user u v accounts The account to output the token for +browse actions a b Open repository actions +browse blame b Open blame view for a file +browse branch b v branches Select another branch by passing in the branch name +browse commit c b Select another commit by passing in the commit SHA, default is the last commit +browse no-browser n b Print destination URL instead of opening the browser +browse projects p b Open repository projects +browse releases r b Open repository releases +browse repo R v repos Select another repository using the [HOST/]OWNER/REPO format +browse settings s b Open repository settings +browse wiki w b Open repository wiki +cache repo R v repos Select another repository using the [HOST/]OWNER/REPO format +cache delete all a b Delete all caches, can be used with --ref to delete all caches for a specific ref +cache delete ref r v cache-refs Delete by cache key and ref, formatted as refs/heads/ or refs/pull//merge +cache delete repo R v repos Select another repository using the [HOST/]OWNER/REPO format +cache delete succeed-on-no-caches b Return exit code 0 if no caches found. Must be used in conjunction with --all +cache list jq q v Filter JSON output using a jq expression +cache list json v json-fields Output JSON with the specified fields +cache list key k v Filter by cache key prefix +cache list limit L i Maximum number of caches to fetch (default 30) +cache list order O v =asc|desc Order of caches returned: {asc|desc} (default "desc") +cache list ref r v cache-refs Filter by ref, formatted as refs/heads/ or refs/pull//merge +cache list repo R v repos Select another repository using the [HOST/]OWNER/REPO format +cache list sort S v =created_at|last_accessed_at|size_in_bytes Sort fetched caches: {created_at|last_accessed_at|size_in_bytes} (default "last_accessed_at") +cache list template t v Format JSON output using a Go template; see "gh help formatting" +codespace code codespace c v codespaces Name of the codespace +codespace code insiders b Use the insiders version of Visual Studio Code +codespace code repo R v repos Filter codespace selection by repository name (user/repo) +codespace code repo-owner v owners Filter codespace selection by repository owner (username or org) +codespace code web w b Use the web version of Visual Studio Code +codespace cp codespace c v codespaces Name of the codespace +codespace cp expand e b Expand remote file names on remote shell +codespace cp profile p v Name of the SSH profile to use +codespace cp recursive r b Recursively copy directories +codespace cp repo R v repos Filter codespace selection by repository name (user/repo) +codespace cp repo-owner v owners Filter codespace selection by repository owner (username or org) +codespace create branch b v branches Repository branch +codespace create default-permissions b Do not prompt to accept additional permissions requested by the codespace +codespace create devcontainer-path v Path to the devcontainer.json file to use when creating codespace +codespace create display-name d v Display name for the codespace (48 characters or less) +codespace create idle-timeout v Allowed inactivity before codespace is stopped, e.g. "10m", "1h" +codespace create location l v =EastUs|SouthEastAsia|WestEurope|WestUs2 Location: {EastUs|SouthEastAsia|WestEurope|WestUs2} (determined automatically if not provided) +codespace create machine m v Hardware specifications for the VM +codespace create repo R v repos Repository name with owner: user/repo +codespace create retention-period v Allowed time after shutting down before the codespace is automatically deleted (maximum 30 days), e.g. "1h", "72h" +codespace create status s b Show status of post-create command and dotfiles +codespace create web w b Create codespace from browser, cannot be used with --display-name, --idle-timeout, or --retention-period +codespace delete all b Delete all codespaces +codespace delete codespace c v codespaces Name of the codespace +codespace delete days i Delete codespaces older than N days +codespace delete force f b Skip confirmation for codespaces that contain unsaved changes +codespace delete org o v orgs The login handle of the organization (admin-only) +codespace delete repo R v repos Filter codespace selection by repository name (user/repo) +codespace delete repo-owner v owners Filter codespace selection by repository owner (username or org) +codespace delete user u v The username to delete codespaces for (used with --org) +codespace edit codespace c v codespaces Name of the codespace +codespace edit display-name d v Set the display name +codespace edit machine m v Set hardware specifications for the VM +codespace edit repo R v repos Filter codespace selection by repository name (user/repo) +codespace edit repo-owner v owners Filter codespace selection by repository owner (username or org) +codespace jupyter codespace c v codespaces Name of the codespace +codespace jupyter repo R v repos Filter codespace selection by repository name (user/repo) +codespace jupyter repo-owner v owners Filter codespace selection by repository owner (username or org) +codespace list jq q v Filter JSON output using a jq expression +codespace list json v json-fields Output JSON with the specified fields +codespace list limit L i Maximum number of codespaces to list (default 30) +codespace list org o v orgs The login handle of the organization to list codespaces for (admin-only) +codespace list repo R v repos Repository name with owner: user/repo +codespace list template t v Format JSON output using a Go template; see "gh help formatting" +codespace list user u v The username to list codespaces for (used with --org) +codespace list web w b List codespaces in the web browser, cannot be used with --user or --org +codespace logs codespace c v codespaces Name of the codespace +codespace logs follow f b Tail and follow the logs +codespace logs repo R v repos Filter codespace selection by repository name (user/repo) +codespace logs repo-owner v owners Filter codespace selection by repository owner (username or org) +codespace ports codespace c v codespaces Name of the codespace +codespace ports jq q v Filter JSON output using a jq expression +codespace ports json v json-fields Output JSON with the specified fields +codespace ports repo R v repos Filter codespace selection by repository name (user/repo) +codespace ports repo-owner v owners Filter codespace selection by repository owner (username or org) +codespace ports template t v Format JSON output using a Go template; see "gh help formatting" +codespace ports forward all-interfaces b Listen on all network interfaces +codespace ports forward codespace c v codespaces Name of the codespace +codespace ports forward repo R v repos Filter codespace selection by repository name (user/repo) +codespace ports forward repo-owner v owners Filter codespace selection by repository owner (username or org) +codespace ports visibility codespace c v codespaces Name of the codespace +codespace ports visibility repo R v repos Filter codespace selection by repository name (user/repo) +codespace ports visibility repo-owner v owners Filter codespace selection by repository owner (username or org) +codespace rebuild codespace c v codespaces Name of the codespace +codespace rebuild full b Perform a full rebuild +codespace rebuild repo R v repos Filter codespace selection by repository name (user/repo) +codespace rebuild repo-owner v owners Filter codespace selection by repository owner (username or org) +codespace ssh codespace c v codespaces Name of the codespace +codespace ssh config b Write OpenSSH configuration to stdout +codespace ssh debug d b Log debug data to a file +codespace ssh debug-file v Path of the file log to +codespace ssh profile v Name of the SSH profile to use +codespace ssh repo R v repos Filter codespace selection by repository name (user/repo) +codespace ssh repo-owner v owners Filter codespace selection by repository owner (username or org) +codespace ssh server-port i SSH server port number (0 => pick unused) +codespace stop codespace c v codespaces Name of the codespace +codespace stop org o v orgs The login handle of the organization (admin-only) +codespace stop repo R v repos Filter codespace selection by repository name (user/repo) +codespace stop repo-owner v owners Filter codespace selection by repository owner (username or org) +codespace stop user u v The username to stop codespace for (used with --org) +codespace view codespace c v codespaces Name of the codespace +codespace view jq q v Filter JSON output using a jq expression +codespace view json v json-fields Output JSON with the specified fields +codespace view repo R v repos Filter codespace selection by repository name (user/repo) +codespace view repo-owner v owners Filter codespace selection by repository owner (username or org) +codespace view template t v Format JSON output using a Go template; see "gh help formatting" +completion shell s v =bash|zsh|fish|powershell Shell type: {bash|zsh|fish|powershell} +config get host h v hosts Get per-host setting +config list host h v hosts Get per-host configuration +config set host h v hosts Set per-host setting +copilot remove b Remove the downloaded Copilot CLI +discussion repo R v repos Select another repository using the [HOST/]OWNER/REPO format +discussion comment body b v Comment body text +discussion comment body-file F v Read body text from file (use "-" to read from standard input) +discussion comment delete b Delete the specified comment +discussion comment edit b Edit the specified comment +discussion comment repo R v repos Select another repository using the [HOST/]OWNER/REPO format +discussion comment yes b Skip the delete confirmation prompt +discussion create body b v Body for the discussion +discussion create body-file F v Read body text from file (use "-" to read from stdin) +discussion create category c v Category name or slug for the discussion +discussion create label l v labels Labels to apply to the discussion +discussion create repo R v repos Select another repository using the [HOST/]OWNER/REPO format +discussion create title t v Title for the discussion +discussion edit add-label v labels Add labels by name +discussion edit body b v New body for the discussion +discussion edit body-file F v Read body text from file (use "-" to read from standard input) +discussion edit category c v New category name or slug for the discussion +discussion edit remove-label v labels Remove labels by name +discussion edit repo R v repos Select another repository using the [HOST/]OWNER/REPO format +discussion edit title t v New title for the discussion +discussion list after v Cursor for the next page of results +discussion list answered b Filter by answered state +discussion list author A v users Filter by author +discussion list category c v Filter by category name or slug +discussion list jq q v Filter JSON output using a jq expression +discussion list json v json-fields Output JSON with the specified fields +discussion list label l v labels Filter by label +discussion list limit L i Maximum number of discussions to fetch (default 30) +discussion list order v =asc|desc Order of results: {asc|desc} (default "desc") +discussion list repo R v repos Select another repository using the [HOST/]OWNER/REPO format +discussion list search S v Search discussions with query +discussion list sort v =created|updated Sort by field: {created|updated} (default "updated") +discussion list state s v =open|closed|all Filter by state: {open|closed|all} (default "open") +discussion list template t v Format JSON output using a Go template; see "gh help formatting" +discussion list web w b List discussions in the web browser +discussion view after v Cursor for the next page +discussion view comments c b View discussion comments +discussion view jq q v Filter JSON output using a jq expression +discussion view json v json-fields Output JSON with the specified fields +discussion view limit L i Maximum number of comments or replies to fetch (default 30) +discussion view order v =oldest|newest Order of comments or replies: {oldest|newest} (default "newest") +discussion view repo R v repos Select another repository using the [HOST/]OWNER/REPO format +discussion view template t v Format JSON output using a Go template; see "gh help formatting" +discussion view web w b Open a discussion in the browser +extension browse debug b Log to /tmp/extBrowse-* +extension browse single-column s b Render TUI with only one column of text +extension create precompiled v =go|other Create a precompiled extension. Possible values: go, other +extension install force b Force upgrade extension, or ignore if latest already installed +extension install pin v Pin extension to a release tag or commit ref +extension search jq q v Filter JSON output using a jq expression +extension search json v json-fields Output JSON with the specified fields +extension search license v licenses Filter based on license type +extension search limit L i Maximum number of extensions to fetch (default 30) +extension search order v =asc|desc Order of repositories returned, ignored unless '--sort' flag is specified: {asc|desc} (default "desc") +extension search owner v owners Filter on owner +extension search sort v =forks|help-wanted-issues|stars|updated Sort fetched repositories: {forks|help-wanted-issues|stars|updated} (default "best-match") +extension search template t v Format JSON output using a Go template; see "gh help formatting" +extension search web w b Open the search query in the web browser +extension upgrade all b Upgrade all extensions +extension upgrade dry-run b Only display upgrades +extension upgrade force b Force upgrade extension +gist create desc d v A description for this gist +gist create filename f v Provide a filename to be used when reading from standard input +gist create public p b List the gist publicly (default "secret") +gist create web w b Open the web browser with created gist +gist delete yes b Confirm deletion without prompting +gist edit add a v Add a new file to the gist +gist edit desc d v New description for the gist +gist edit filename f v gist-files Select a file to edit +gist edit remove r v gist-files Remove a file from the gist +gist list filter v Filter gists using a regular expression +gist list include-content b Include gists' file content when filtering +gist list limit L i Maximum number of gists to fetch (default 10) +gist list public b Show only public gists +gist list secret b Show only secret gists +gist view allow-escape-sequences b Allow printing terminal escape sequences +gist view filename f v gist-files Display a single file from the gist +gist view files b List file names from the gist +gist view raw r b Print raw instead of rendered gist contents +gist view web w b Open gist in the browser +gpg-key add title t v Title for the new key +gpg-key delete yes y b Skip the confirmation prompt +issue repo R v repos Select another repository using the [HOST/]OWNER/REPO format +issue artifact repo R v repos Select another repository using the [HOST/]OWNER/REPO format +issue artifact create attach f Attach an image or video file, in '#' format +issue artifact create body b v Content for a single document +issue artifact create body-file F f Read content for a single artifact from file (use "-" to read from standard input) +issue artifact create name v Name for a single artifact +issue artifact create repo R v repos Select another repository using the [HOST/]OWNER/REPO format +issue artifact create type v =generic|plan|embedded_html Type for documents: {generic|plan|embedded_html} +issue artifact delete repo R v repos Select another repository using the [HOST/]OWNER/REPO format +issue artifact delete yes b Confirm deletion without prompting +issue artifact download clobber b Overwrite existing files of the same name +issue artifact download dir D f The directory to download files into (default ".") +issue artifact download output O f The file to write a single artifact to (use "-" to write to standard output) +issue artifact download repo R v repos Select another repository using the [HOST/]OWNER/REPO format +issue artifact download skip-existing b Skip downloading when files of the same name exist +issue artifact download version v Download the version with this number from the edit history +issue artifact edit attach f Attach an image or video file, in '#' format +issue artifact edit body b v New content; for a link, a URL +issue artifact edit body-file F f Read new content from file (use "-" to read from standard input) +issue artifact edit name v New name +issue artifact edit repo R v repos Select another repository using the [HOST/]OWNER/REPO format +issue artifact edit restore-version v Restore the version with this number from the edit history +issue artifact list jq q v Filter JSON output using a jq expression +issue artifact list json v json-fields Output JSON with the specified fields +issue artifact list limit L i Maximum number of artifacts to fetch +issue artifact list repo R v repos Select another repository using the [HOST/]OWNER/REPO format +issue artifact list template t v Format JSON output using a Go template; see "gh help formatting" +issue artifact list type v =generic|plan|link|embedded_html Filter by type: {generic|plan|link|embedded_html} +issue artifact view jq q v Filter JSON output using a jq expression +issue artifact view json v json-fields Output JSON with the specified fields +issue artifact view repo R v repos Select another repository using the [HOST/]OWNER/REPO format +issue artifact view template t v Format JSON output using a Go template; see "gh help formatting" +issue artifact view version v Show the version with this number from the edit history +issue artifact view web w b Open a document's page on GitHub, or a link's URL +issue close comment c v Leave a closing comment +issue close duplicate-of v issues Mark as duplicate of another issue by number or URL +issue close reason r v close-reasons Reason for closing: {completed|not planned|duplicate} +issue close repo R v repos Select another repository using the [HOST/]OWNER/REPO format +issue comment attach f Attach an image or video file, in '#' format +issue comment body b v The comment body text +issue comment body-file F f Read body text from file (use "-" to read from standard input) +issue comment create-if-none b Create a new comment if no comments are found. Can be used only with --edit-last +issue comment delete-last b Delete the last comment of the current user +issue comment edit-last b Edit the last comment of the current user +issue comment editor e b Skip prompts and open the text editor to write the body in +issue comment repo R v repos Select another repository using the [HOST/]OWNER/REPO format +issue comment web w b Open the web browser to write the comment +issue comment yes b Skip the delete confirmation prompt when --delete-last is provided +issue create assignee a v users Assign people by their login. Use "@me" to self-assign. +issue create attach f Attach an image or video file, in '#' format +issue create blocked-by v issues Mark the new issue as blocked by these issue numbers or URLs +issue create blocking v issues Mark the new issue as blocking these issue numbers or URLs +issue create body b v Supply a body. Will prompt for one otherwise. +issue create body-file F f Read body text from file (use "-" to read from standard input) +issue create editor e b Skip prompts and open the text editor to write the title and body in. The first line is the title and the remaining text is the body. +issue create label l v labels Add labels by name +issue create milestone m v milestones Add the issue to a milestone by name +issue create parent v issues Add the new issue as a sub-issue of the specified parent number or URL +issue create project p v projects Add the issue to projects by title +issue create recover v Recover input from a failed run of create +issue create repo R v repos Select another repository using the [HOST/]OWNER/REPO format +issue create template T v issue-templates Template name to use as starting body text +issue create title t v Supply a title. Will prompt for one otherwise. +issue create type v Set the issue type by name +issue create web w b Open the browser to create an issue +issue delete repo R v repos Select another repository using the [HOST/]OWNER/REPO format +issue delete yes b Confirm deletion without prompting +issue develop base b v branches Name of the remote branch you want to make your new branch from +issue develop branch-repo v repos Name or URL of the repository where you want to create your new branch +issue develop checkout c b Checkout the branch after creating it +issue develop list l b List linked branches for the issue +issue develop name n v Name of the branch to create +issue develop repo R v repos Select another repository using the [HOST/]OWNER/REPO format +issue develop worktree f Check out the branch into a worktree at the given path +issue edit add-assignee v users Add assigned users by their login. Use "@me" to assign yourself, or "@copilot" to assign Copilot. +issue edit add-blocked-by v issues Add 'blocked by' relationships by issue number or URL +issue edit add-blocking v issues Add 'blocking' relationships by issue number or URL +issue edit add-label v labels Add labels by name +issue edit add-project v projects Add the issue to projects by title +issue edit add-sub-issue v issues Add sub-issues by number or URL +issue edit attach f Attach an image or video file, in '#' format +issue edit body b v Set the new body. +issue edit body-file F f Read body text from file (use "-" to read from standard input) +issue edit milestone m v milestones Edit the milestone the issue belongs to by name +issue edit parent v issues Set the parent issue by number or URL +issue edit remove-assignee v users Remove assigned users by their login. Use "@me" to unassign yourself, or "@copilot" to unassign Copilot. +issue edit remove-blocked-by v issues Remove 'blocked by' relationships by issue number or URL +issue edit remove-blocking v issues Remove 'blocking' relationships by issue number or URL +issue edit remove-label v labels Remove labels by name +issue edit remove-milestone b Remove the milestone association from the issue +issue edit remove-parent b Remove the parent issue +issue edit remove-project v projects Remove the issue from projects by title +issue edit remove-sub-issue v issues Remove sub-issues by number or URL +issue edit remove-type b Remove the issue type from the issue +issue edit repo R v repos Select another repository using the [HOST/]OWNER/REPO format +issue edit title t v Set the new title. +issue edit type v Set the issue type by name +issue list app v Filter by GitHub App author +issue list assignee a v users Filter by assignee +issue list author A v users Filter by author (use --app to filter by a GitHub App) +issue list jq q v Filter JSON output using a jq expression +issue list json v json-fields Output JSON with the specified fields +issue list label l v labels Filter by label +issue list limit L i Maximum number of issues to fetch (default 30) +issue list mention v users Filter by mention +issue list milestone m v milestones Filter by milestone number or title +issue list repo R v repos Select another repository using the [HOST/]OWNER/REPO format +issue list search S v Search issues with query +issue list state s v =open|closed|all Filter by state: {open|closed|all} (default "open") +issue list template t v Format JSON output using a Go template; see "gh help formatting" +issue list type v Filter by issue type name +issue list web w b List issues in the web browser +issue lock reason r v lock-reasons Optional reason for locking conversation (off_topic, resolved, spam, too_heated). +issue lock repo R v repos Select another repository using the [HOST/]OWNER/REPO format +issue pin repo R v repos Select another repository using the [HOST/]OWNER/REPO format +issue reopen comment c v Add a reopening comment +issue reopen repo R v repos Select another repository using the [HOST/]OWNER/REPO format +issue status jq q v Filter JSON output using a jq expression +issue status json v json-fields Output JSON with the specified fields +issue status repo R v repos Select another repository using the [HOST/]OWNER/REPO format +issue status template t v Format JSON output using a Go template; see "gh help formatting" +issue transfer repo R v repos Select another repository using the [HOST/]OWNER/REPO format +issue unlock repo R v repos Select another repository using the [HOST/]OWNER/REPO format +issue unpin repo R v repos Select another repository using the [HOST/]OWNER/REPO format +issue view comments c b View issue comments +issue view jq q v Filter JSON output using a jq expression +issue view json v json-fields Output JSON with the specified fields +issue view repo R v repos Select another repository using the [HOST/]OWNER/REPO format +issue view template t v Format JSON output using a Go template; see "gh help formatting" +issue view web w b Open an issue in the browser +label repo R v repos Select another repository using the [HOST/]OWNER/REPO format +label clone force f b Overwrite labels in the destination repository +label clone repo R v repos Select another repository using the [HOST/]OWNER/REPO format +label create color c v Color of the label +label create description d v Description of the label +label create force f b Update the label color and description if label already exists +label create repo R v repos Select another repository using the [HOST/]OWNER/REPO format +label delete repo R v repos Select another repository using the [HOST/]OWNER/REPO format +label delete yes b Confirm deletion without prompting +label edit color c v Color of the label +label edit description d v Description of the label +label edit name n v New name of the label +label edit repo R v repos Select another repository using the [HOST/]OWNER/REPO format +label list jq q v Filter JSON output using a jq expression +label list json v json-fields Output JSON with the specified fields +label list limit L i Maximum number of labels to fetch (default 30) +label list order v =asc|desc Order of labels returned: {asc|desc} (default "asc") +label list repo R v repos Select another repository using the [HOST/]OWNER/REPO format +label list search S v Search label names and descriptions +label list sort v =created|name Sort fetched labels: {created|name} (default "created") +label list template t v Format JSON output using a Go template; see "gh help formatting" +label list web w b List labels in the web browser +org list limit L i Maximum number of organizations to list (default 30) +pr repo R v repos Select another repository using the [HOST/]OWNER/REPO format +pr checkout branch b v Local branch name to use (default [the name of the head branch]) +pr checkout detach b Checkout PR with a detached HEAD +pr checkout force f b Reset the existing local branch to the latest state of the pull request +pr checkout recurse-submodules b Update all submodules after checkout +pr checkout repo R v repos Select another repository using the [HOST/]OWNER/REPO format +pr checkout worktree f Check out the pull request into a worktree at the given path +pr checks fail-fast b Exit watch mode on first check failure +pr checks interval i i Refresh interval in seconds in watch mode (default 10) +pr checks jq q v Filter JSON output using a jq expression +pr checks json v json-fields Output JSON with the specified fields +pr checks repo R v repos Select another repository using the [HOST/]OWNER/REPO format +pr checks required b Only show checks that are required +pr checks template t v Format JSON output using a Go template; see "gh help formatting" +pr checks watch b Watch checks until they finish +pr checks web w b Open the web browser to show details about checks +pr close comment c v Leave a closing comment +pr close delete-branch d b Delete the local and remote branch after close +pr close repo R v repos Select another repository using the [HOST/]OWNER/REPO format +pr comment attach f Attach an image or video file, in '#' format +pr comment body b v The comment body text +pr comment body-file F f Read body text from file (use "-" to read from standard input) +pr comment create-if-none b Create a new comment if no comments are found. Can be used only with --edit-last +pr comment delete-last b Delete the last comment of the current user +pr comment edit-last b Edit the last comment of the current user +pr comment editor e b Skip prompts and open the text editor to write the body in +pr comment repo R v repos Select another repository using the [HOST/]OWNER/REPO format +pr comment web w b Open the web browser to write the comment +pr comment yes b Skip the delete confirmation prompt when --delete-last is provided +pr create assignee a v users Assign people by their login. Use "@me" to self-assign. +pr create attach f Attach an image or video file, in '#' format +pr create base B v branches The branch into which you want your code merged +pr create body b v Body for the pull request +pr create body-file F f Read body text from file (use "-" to read from standard input) +pr create draft d b Mark pull request as a draft +pr create dry-run b Print details instead of creating the PR. May still push git changes. +pr create editor e b Skip prompts and open the text editor to write the title and body in. The first line is the title and the remaining text is the body. +pr create fill f b Use commit info for title and body +pr create fill-first b Use first commit info for title and body +pr create fill-verbose b Use commits msg+body for description +pr create head H v branches The branch that contains commits for your pull request (default [current branch]) +pr create label l v labels Add labels by name +pr create milestone m v milestones Add the pull request to a milestone by name +pr create no-maintainer-edit b Disable maintainer's ability to modify pull request +pr create project p v projects Add the pull request to projects by title +pr create recover v Recover input from a failed run of create +pr create repo R v repos Select another repository using the [HOST/]OWNER/REPO format +pr create reviewer r v users Request reviews from people or teams by their handle +pr create template T f Template file to use as starting body text +pr create title t v Title for the pull request +pr create web w b Open the web browser to create a pull request +pr diff allow-escape-sequences b Allow printing terminal escape sequences +pr diff color v =always|never|auto Use color in diff output: {always|never|auto} (default "auto") +pr diff exclude e v Exclude files matching glob patterns from the diff +pr diff name-only b Display only names of changed files +pr diff patch b Display diff in patch format +pr diff repo R v repos Select another repository using the [HOST/]OWNER/REPO format +pr diff web w b Open the pull request diff in the browser +pr edit add-assignee v users Add assigned users by their login. Use "@me" to assign yourself, or "@copilot" to assign Copilot. +pr edit add-label v labels Add labels by name +pr edit add-project v projects Add the pull request to projects by title +pr edit add-reviewer v users Add or re-request reviewers by their login. Use "@copilot" to request review from Copilot. +pr edit attach f Attach an image or video file, in '#' format +pr edit base B v branches Change the base branch for this pull request +pr edit body b v Set the new body. +pr edit body-file F f Read body text from file (use "-" to read from standard input) +pr edit milestone m v milestones Edit the milestone the pull request belongs to by name +pr edit remove-assignee v users Remove assigned users by their login. Use "@me" to unassign yourself, or "@copilot" to unassign Copilot. +pr edit remove-label v labels Remove labels by name +pr edit remove-milestone b Remove the milestone association from the pull request +pr edit remove-project v projects Remove the pull request from projects by title +pr edit remove-reviewer v users Remove reviewers by their login. Use "@copilot" to remove review request from Copilot. +pr edit repo R v repos Select another repository using the [HOST/]OWNER/REPO format +pr edit title t v Set the new title. +pr list app v Filter by GitHub App author +pr list assignee a v users Filter by assignee +pr list author A v users Filter by author (use --app to filter by a GitHub App) +pr list base B v branches Filter by base branch +pr list draft d b Filter by draft state +pr list head H v branches Filter by head branch (":" syntax not supported) +pr list jq q v Filter JSON output using a jq expression +pr list json v json-fields Output JSON with the specified fields +pr list label l v labels Filter by label +pr list limit L i Maximum number of items to fetch (default 30) +pr list repo R v repos Select another repository using the [HOST/]OWNER/REPO format +pr list search S v Search pull requests with query +pr list state s v =open|closed|merged|all Filter by state: {open|closed|merged|all} (default "open") +pr list template t v Format JSON output using a Go template; see "gh help formatting" +pr list web w b List pull requests in the web browser +pr lock reason r v lock-reasons Optional reason for locking conversation (off_topic, resolved, spam, too_heated). +pr lock repo R v repos Select another repository using the [HOST/]OWNER/REPO format +pr merge admin b Use administrator privileges to merge a pull request that does not meet requirements +pr merge author-email A v Email text for merge commit author +pr merge auto b Automatically merge only after necessary requirements are met +pr merge body b v Body text for the merge commit +pr merge body-file F f Read body text from file (use "-" to read from standard input) +pr merge delete-branch d b Delete the local and remote branch after merge +pr merge disable-auto b Disable auto-merge for this pull request +pr merge match-head-commit v commits Commit SHA that the pull request head must match to allow merge +pr merge merge m b Merge the commits with the base branch +pr merge rebase r b Rebase the commits onto the base branch +pr merge repo R v repos Select another repository using the [HOST/]OWNER/REPO format +pr merge squash s b Squash the commits into one commit and merge it into the base branch +pr merge subject t v Subject text for the merge commit +pr ready repo R v repos Select another repository using the [HOST/]OWNER/REPO format +pr ready undo b Convert a pull request to "draft" +pr reopen comment c v Add a reopening comment +pr reopen repo R v repos Select another repository using the [HOST/]OWNER/REPO format +pr revert body b v Body for the revert pull request +pr revert body-file F f Read body text from file (use "-" to read from standard input) +pr revert draft d b Mark revert pull request as a draft +pr revert repo R v repos Select another repository using the [HOST/]OWNER/REPO format +pr revert title t v Title for the revert pull request +pr review approve a b Approve pull request +pr review body b v Specify the body of a review +pr review body-file F f Read body text from file (use "-" to read from standard input) +pr review comment c b Comment on a pull request +pr review repo R v repos Select another repository using the [HOST/]OWNER/REPO format +pr review request-changes r b Request changes on a pull request +pr status conflict-status c b Display the merge conflict status of each pull request +pr status jq q v Filter JSON output using a jq expression +pr status json v json-fields Output JSON with the specified fields +pr status repo R v repos Select another repository using the [HOST/]OWNER/REPO format +pr status template t v Format JSON output using a Go template; see "gh help formatting" +pr unlock repo R v repos Select another repository using the [HOST/]OWNER/REPO format +pr update-branch rebase b Update PR branch by rebasing on top of latest base branch +pr update-branch repo R v repos Select another repository using the [HOST/]OWNER/REPO format +pr view comments c b View pull request comments +pr view jq q v Filter JSON output using a jq expression +pr view json v json-fields Output JSON with the specified fields +pr view repo R v repos Select another repository using the [HOST/]OWNER/REPO format +pr view template t v Format JSON output using a Go template; see "gh help formatting" +pr view web w b Open a pull request in the browser +project close format v =json Output format: {json} +project close jq q v Filter JSON output using a jq expression +project close owner v owners Login of the owner. Use "@me" for the current user. +project close template t v Format JSON output using a Go template; see "gh help formatting" +project close undo b Reopen a closed project +project copy drafts b Include draft issues when copying +project copy format v =json Output format: {json} +project copy jq q v Filter JSON output using a jq expression +project copy source-owner v owners Login of the source owner. Use "@me" for the current user. +project copy target-owner v owners Login of the target owner. Use "@me" for the current user. +project copy template t v Format JSON output using a Go template; see "gh help formatting" +project copy title v Title for the new project +project create format v =json Output format: {json} +project create jq q v Filter JSON output using a jq expression +project create owner v owners Login of the owner. Use "@me" for the current user. +project create template t v Format JSON output using a Go template; see "gh help formatting" +project create title v Title for the project +project delete format v =json Output format: {json} +project delete jq q v Filter JSON output using a jq expression +project delete owner v owners Login of the owner. Use "@me" for the current user. +project delete template t v Format JSON output using a Go template; see "gh help formatting" +project edit description d v New description of the project +project edit format v =json Output format: {json} +project edit jq q v Filter JSON output using a jq expression +project edit owner v owners Login of the owner. Use "@me" for the current user. +project edit readme v New readme for the project +project edit template t v Format JSON output using a Go template; see "gh help formatting" +project edit title v New title for the project +project edit visibility v =PUBLIC|PRIVATE Change project visibility: {PUBLIC|PRIVATE} +project field-create data-type v =TEXT|SINGLE_SELECT|DATE|NUMBER DataType of the new field.: {TEXT|SINGLE_SELECT|DATE|NUMBER} +project field-create format v =json Output format: {json} +project field-create jq q v Filter JSON output using a jq expression +project field-create name v Name of the new field +project field-create owner v owners Login of the owner. Use "@me" for the current user. +project field-create single-select-options v Options for SINGLE_SELECT data type +project field-create template t v Format JSON output using a Go template; see "gh help formatting" +project field-delete format v =json Output format: {json} +project field-delete id v ID of the field to delete +project field-delete jq q v Filter JSON output using a jq expression +project field-delete template t v Format JSON output using a Go template; see "gh help formatting" +project field-list format v =json Output format: {json} +project field-list jq q v Filter JSON output using a jq expression +project field-list limit L i Maximum number of fields to fetch (default 30) +project field-list owner v owners Login of the owner. Use "@me" for the current user. +project field-list template t v Format JSON output using a Go template; see "gh help formatting" +project item-add format v =json Output format: {json} +project item-add jq q v Filter JSON output using a jq expression +project item-add owner v owners Login of the owner. Use "@me" for the current user. +project item-add template t v Format JSON output using a Go template; see "gh help formatting" +project item-add url v URL of the issue or pull request to add to the project +project item-archive format v =json Output format: {json} +project item-archive id v ID of the item to archive +project item-archive jq q v Filter JSON output using a jq expression +project item-archive owner v owners Login of the owner. Use "@me" for the current user. +project item-archive template t v Format JSON output using a Go template; see "gh help formatting" +project item-archive undo b Unarchive an item +project item-create body v Body for the draft issue +project item-create format v =json Output format: {json} +project item-create jq q v Filter JSON output using a jq expression +project item-create owner v owners Login of the owner. Use "@me" for the current user. +project item-create template t v Format JSON output using a Go template; see "gh help formatting" +project item-create title v Title for the draft issue +project item-delete format v =json Output format: {json} +project item-delete id v ID of the item to delete +project item-delete jq q v Filter JSON output using a jq expression +project item-delete owner v owners Login of the owner. Use "@me" for the current user. +project item-delete template t v Format JSON output using a Go template; see "gh help formatting" +project item-edit body v Body of the draft issue item +project item-edit clear b Remove field value +project item-edit date v Date value for the field (YYYY-MM-DD) +project item-edit field v Name of the field to update +project item-edit field-id v ID of the field to update +project item-edit format v =json Output format: {json} +project item-edit id v ID of the item to edit +project item-edit iteration-id v ID of the iteration value to set on the field +project item-edit jq q v Filter JSON output using a jq expression +project item-edit number v Number value for the field +project item-edit owner v owners Login of the owner. Use "@me" for the current user. +project item-edit project-id v ID of the project to which the field belongs to +project item-edit single-select-option-id v ID of the single select option value to set on the field +project item-edit template t v Format JSON output using a Go template; see "gh help formatting" +project item-edit text v Text value for the field +project item-edit title v Title of the draft issue item +project item-edit url v URL of the issue or pull request whose project item to edit +project item-edit value v Value to set on the field named by --field +project item-list field v Name of a field to show as an extra column +project item-list field-id v ID of a field to show as an extra column +project item-list format v =json Output format: {json} +project item-list jq q v Filter JSON output using a jq expression +project item-list limit L i Maximum number of items to fetch (default 30) +project item-list owner v owners Login of the owner. Use "@me" for the current user +project item-list query v Filter items using the Projects filter syntax, e.g. "assignee:octocat -status:Done" +project item-list template t v Format JSON output using a Go template; see "gh help formatting" +project link owner v owners Login of the owner. Use "@me" for the current user. +project link repo R v repos The repository to be linked to this project +project link team T v The team to be linked to this project +project list closed b Include closed projects +project list format v =json Output format: {json} +project list jq q v Filter JSON output using a jq expression +project list limit L i Maximum number of projects to fetch (default 30) +project list owner v owners Login of the owner +project list template t v Format JSON output using a Go template; see "gh help formatting" +project list web w b Open projects list in the browser +project mark-template format v =json Output format: {json} +project mark-template jq q v Filter JSON output using a jq expression +project mark-template owner v owners Login of the org owner. +project mark-template template t v Format JSON output using a Go template; see "gh help formatting" +project mark-template undo b Unmark the project as a template. +project unlink owner v owners Login of the owner. Use "@me" for the current user. +project unlink repo R v repos The repository to be unlinked from this project +project unlink team T v The team to be unlinked from this project +project view format v =json Output format: {json} +project view jq q v Filter JSON output using a jq expression +project view owner v owners Login of the owner. Use "@me" for the current user. +project view template t v Format JSON output using a Go template; see "gh help formatting" +project view web w b Open a project in the browser +release repo R v repos Select another repository using the [HOST/]OWNER/REPO format +release create discussion-category v Start a discussion in the specified category +release create draft d b Save the release as a draft instead of publishing it +release create fail-on-no-commits b Fail if there are no commits since the last release (no impact on the first release) +release create generate-notes b Automatically generate title and notes for the release via GitHub Release Notes API +release create latest b Mark this release as "Latest" (default [automatic based on date and version]). --latest=false to explicitly NOT set as latest +release create notes n v Release notes +release create notes-file F f Read release notes from file (use "-" to read from standard input) +release create notes-from-tag b Fetch notes from the tag annotation or message of commit associated with tag +release create notes-start-tag v releases Tag to use as the starting point for generating release notes +release create prerelease p b Mark the release as a prerelease +release create repo R v repos Select another repository using the [HOST/]OWNER/REPO format +release create target v branches Target branch or full commit SHA (default [main branch]) +release create title t v Release title +release create verify-tag b Abort in case the git tag doesn't already exist in the remote repository +release delete cleanup-tag b Delete the specified tag in addition to its release +release delete repo R v repos Select another repository using the [HOST/]OWNER/REPO format +release delete yes y b Skip the confirmation prompt +release delete-asset repo R v repos Select another repository using the [HOST/]OWNER/REPO format +release delete-asset yes y b Skip the confirmation prompt +release download allow-escape-sequences b Allow printing terminal escape sequences when writing an asset to standard output +release download archive A v archive-formats Download the source code archive in the specified format (zip or tar.gz) +release download clobber b Overwrite existing files of the same name +release download dir D f The directory to download files into (default ".") +release download output O f The file to write a single asset to (use "-" to write to standard output) +release download pattern p v Download only assets that match a glob pattern +release download repo R v repos Select another repository using the [HOST/]OWNER/REPO format +release download skip-existing b Skip downloading when files of the same name exist +release edit discussion-category v Start a discussion in the specified category when publishing a draft +release edit draft b Save the release as a draft instead of publishing it +release edit latest b Explicitly mark the release as "Latest" +release edit notes n v Release notes +release edit notes-file F f Read release notes from file (use "-" to read from standard input) +release edit prerelease b Mark the release as a prerelease +release edit repo R v repos Select another repository using the [HOST/]OWNER/REPO format +release edit tag v The name of the tag +release edit target v branches Target branch or full commit SHA (default [main branch]) +release edit title t v Release title +release edit verify-tag b Abort in case the git tag doesn't already exist in the remote repository +release list exclude-drafts b Exclude draft releases +release list exclude-pre-releases b Exclude pre-releases +release list jq q v Filter JSON output using a jq expression +release list json v json-fields Output JSON with the specified fields +release list limit L i Maximum number of items to fetch (default 30) +release list order O v =asc|desc Order of releases returned: {asc|desc} (default "desc") +release list repo R v repos Select another repository using the [HOST/]OWNER/REPO format +release list template t v Format JSON output using a Go template; see "gh help formatting" +release upload clobber b Delete and re-upload existing assets of the same name +release upload repo R v repos Select another repository using the [HOST/]OWNER/REPO format +release verify format v =json Output format: {json} +release verify jq q v Filter JSON output using a jq expression +release verify repo R v repos Select another repository using the [HOST/]OWNER/REPO format +release verify template t v Format JSON output using a Go template; see "gh help formatting" +release verify-asset format v =json Output format: {json} +release verify-asset jq q v Filter JSON output using a jq expression +release verify-asset repo R v repos Select another repository using the [HOST/]OWNER/REPO format +release verify-asset template t v Format JSON output using a Go template; see "gh help formatting" +release view jq q v Filter JSON output using a jq expression +release view json v json-fields Output JSON with the specified fields +release view repo R v repos Select another repository using the [HOST/]OWNER/REPO format +release view template t v Format JSON output using a Go template; see "gh help formatting" +release view web w b Open the release in the browser +repo archive yes y b Skip the confirmation prompt +repo autolink repo R v repos Select another repository using the [HOST/]OWNER/REPO format +repo autolink create numeric n b Mark autolink as numeric +repo autolink create repo R v repos Select another repository using the [HOST/]OWNER/REPO format +repo autolink delete repo R v repos Select another repository using the [HOST/]OWNER/REPO format +repo autolink delete yes b Confirm deletion without prompting +repo autolink list jq q v Filter JSON output using a jq expression +repo autolink list json v json-fields Output JSON with the specified fields +repo autolink list repo R v repos Select another repository using the [HOST/]OWNER/REPO format +repo autolink list template t v Format JSON output using a Go template; see "gh help formatting" +repo autolink list web w b List autolink references in the web browser +repo autolink view jq q v Filter JSON output using a jq expression +repo autolink view json v json-fields Output JSON with the specified fields +repo autolink view repo R v repos Select another repository using the [HOST/]OWNER/REPO format +repo autolink view template t v Format JSON output using a Go template; see "gh help formatting" +repo clone no-upstream b Do not add an upstream remote when cloning a fork +repo clone upstream-remote-name u v Upstream remote name when cloning a fork (default "upstream") +repo create add-readme b Add a README file to the new repository +repo create clone c b Clone the new repository to the current directory +repo create description d v Description of the repository +repo create disable-issues b Disable issues in the new repository +repo create disable-wiki b Disable wiki in the new repository +repo create gitignore g v gitignores Specify a gitignore template for the repository +repo create homepage h v Repository home page URL +repo create include-all-branches b Include all branches from template repository +repo create internal b Make the new repository internal +repo create license l v licenses Specify an Open Source License for the repository +repo create private b Make the new repository private +repo create public b Make the new repository public +repo create push b Push local commits to the new repository +repo create remote r v Specify remote name for the new repository +repo create source s v Specify path to local repository to use as source +repo create team t v The name of the organization team to be granted access +repo create template p v repos Make the new repository based on a template repository +repo delete accept-cascading-deletion-of-private-forks b Accept that deleting a private repository also deletes its forks +repo delete yes b Confirm deletion without prompting for confirmation +repo deploy-key repo R v repos Select another repository using the [HOST/]OWNER/REPO format +repo deploy-key add allow-write w b Allow write access for the key +repo deploy-key add repo R v repos Select another repository using the [HOST/]OWNER/REPO format +repo deploy-key add title t v Title of the new key +repo deploy-key delete repo R v repos Select another repository using the [HOST/]OWNER/REPO format +repo deploy-key list jq q v Filter JSON output using a jq expression +repo deploy-key list json v json-fields Output JSON with the specified fields +repo deploy-key list repo R v repos Select another repository using the [HOST/]OWNER/REPO format +repo deploy-key list template t v Format JSON output using a Go template; see "gh help formatting" +repo edit accept-visibility-change-consequences b Accept the consequences of changing the repository visibility +repo edit add-topic v Add repository topic +repo edit allow-forking b Allow forking of an organization repository +repo edit allow-update-branch b Allow a pull request head branch that is behind its base branch to be updated +repo edit default-branch v branches Set the default branch name for the repository +repo edit delete-branch-on-merge b Delete head branch when pull requests are merged +repo edit description d v Description of the repository +repo edit enable-advanced-security b Enable advanced security in the repository +repo edit enable-auto-merge b Enable auto-merge functionality +repo edit enable-discussions b Enable discussions in the repository +repo edit enable-issues b Enable issues in the repository +repo edit enable-merge-commit b Enable merging pull requests via merge commit +repo edit enable-projects b Enable projects in the repository +repo edit enable-rebase-merge b Enable merging pull requests via rebase +repo edit enable-secret-scanning b Enable secret scanning in the repository +repo edit enable-secret-scanning-push-protection b Enable secret scanning push protection in the repository. Secret scanning must be enabled first +repo edit enable-squash-merge b Enable merging pull requests via squashed commit +repo edit enable-wiki b Enable wiki in the repository +repo edit homepage h v Repository home page URL +repo edit remove-topic v repo-topics Remove repository topic +repo edit squash-merge-commit-message v =default|pr-title|pr-title-commits|pr-title-description The default value for a squash merge commit message: {default|pr-title|pr-title-commits|pr-title-description} +repo edit template b Make the repository available as a template repository +repo edit visibility v =public|private|internal Change the visibility of the repository to {public,private,internal} +repo fork clone b Clone the fork +repo fork default-branch-only b Only include the default branch in the fork +repo fork fork-name v Rename the forked repository +repo fork org v orgs Create the fork in an organization +repo fork remote b Add a git remote for the fork +repo fork remote-name v Specify the name for the new remote (default "origin") +repo license view web w b Open https://choosealicense.com/ in the browser +repo list archived b Show only archived repositories +repo list fork b Show only forks +repo list jq q v Filter JSON output using a jq expression +repo list json v json-fields Output JSON with the specified fields +repo list language l v Filter by primary coding language +repo list limit L i Maximum number of repositories to list (default 30) +repo list no-archived b Omit archived repositories +repo list source b Show only non-forks +repo list template t v Format JSON output using a Go template; see "gh help formatting" +repo list topic v Filter by topic +repo list visibility v =public|private|internal Filter by repository visibility: {public|private|internal} +repo read-dir jq q v Filter JSON output using a jq expression +repo read-dir json v json-fields Output JSON with the specified fields +repo read-dir ref v branches The branch, tag, or commit to list from +repo read-dir repo R v repos Select another repository using the [HOST/]OWNER/REPO format +repo read-dir template t v Format JSON output using a Go template; see "gh help formatting" +repo read-file allow-escape-sequences b Allow printing terminal escape sequences +repo read-file clobber b Overwrite the output path if it already exists +repo read-file jq q v Filter JSON output using a jq expression +repo read-file json v json-fields Output JSON with the specified fields +repo read-file output o f Write the file to a path instead of stdout +repo read-file ref v branches The branch, tag, or commit to read from +repo read-file repo R v repos Select another repository using the [HOST/]OWNER/REPO format +repo read-file template t v Format JSON output using a Go template; see "gh help formatting" +repo rename repo R v repos Select another repository using the [HOST/]OWNER/REPO format +repo rename yes y b Skip the confirmation prompt +repo set-default unset u b Unset the current default repository +repo set-default view v b View the current default repository +repo sync branch b v branches Branch to sync (default [default branch]) +repo sync force b Hard reset the branch of the destination repository to match the source repository +repo sync source s v repos Source repository +repo unarchive yes y b Skip the confirmation prompt +repo view branch b v View a specific branch of the repository +repo view jq q v Filter JSON output using a jq expression +repo view json v json-fields Output JSON with the specified fields +repo view template t v Format JSON output using a Go template; see "gh help formatting" +repo view web w b Open a repository in the browser +ruleset repo R v repos Select another repository using the [HOST/]OWNER/REPO format +ruleset check default b Check rules on default branch +ruleset check repo R v repos Select another repository using the [HOST/]OWNER/REPO format +ruleset check web w b Open the branch rules page in a web browser +ruleset list limit L i Maximum number of rulesets to list (default 30) +ruleset list org o v orgs List organization-wide rulesets for the provided organization +ruleset list parents p b Whether to include rulesets configured at higher levels that also apply (default true) +ruleset list repo R v repos Select another repository using the [HOST/]OWNER/REPO format +ruleset list web w b Open the list of rulesets in the web browser +ruleset view org o v orgs Organization name if the provided ID is an organization-level ruleset +ruleset view parents p b Whether to include rulesets configured at higher levels that also apply (default true) +ruleset view repo R v repos Select another repository using the [HOST/]OWNER/REPO format +ruleset view web w b Open the ruleset in the browser +run repo R v repos Select another repository using the [HOST/]OWNER/REPO format +run cancel force b Force cancel a workflow run +run cancel repo R v repos Select another repository using the [HOST/]OWNER/REPO format +run delete repo R v repos Select another repository using the [HOST/]OWNER/REPO format +run download dir D v The directory to download artifacts into (default ".") +run download name n v artifacts Download artifacts that match any of the given names +run download pattern p v Download artifacts that match a glob pattern +run download repo R v repos Select another repository using the [HOST/]OWNER/REPO format +run list all a b Include disabled workflows +run list branch b v branches Filter runs by branch +run list commit c v commits Filter runs by the SHA of the commit +run list created v Filter runs by the date it was created +run list event e v events Filter runs by which event triggered the run +run list jq q v Filter JSON output using a jq expression +run list json v json-fields Output JSON with the specified fields +run list limit L i Maximum number of runs to fetch (default 20) +run list repo R v repos Select another repository using the [HOST/]OWNER/REPO format +run list status s v =queued|completed|in_progress|requested|waiting|pending|action_required|cancelled|failure|neutral|skipped|stale|startup_failure|success|timed_out Filter runs by status: {queued|completed|in_progress|requested|waiting|pending|action_required|cancelled|failure|neutral|skipped|stale|startup_failure|success|timed_out} +run list template t v Format JSON output using a Go template; see "gh help formatting" +run list user u v Filter runs by user who triggered the run +run list workflow w v workflows Filter runs by workflow +run rerun debug d b Rerun with debug logging +run rerun failed b Rerun only failed jobs, including dependencies +run rerun job j v run-jobs Rerun a specific job ID from a run, including dependencies +run rerun repo R v repos Select another repository using the [HOST/]OWNER/REPO format +run view attempt a i The attempt number of the workflow run +run view exit-status b Exit with non-zero status if run failed +run view job j v run-jobs View a specific job ID from a run +run view jq q v Filter JSON output using a jq expression +run view json v json-fields Output JSON with the specified fields +run view log b View full log for either a run or specific job +run view log-failed b View the log for any failed steps in a run or specific job +run view repo R v repos Select another repository using the [HOST/]OWNER/REPO format +run view template t v Format JSON output using a Go template; see "gh help formatting" +run view verbose v b Show job steps +run view web w b Open run in the browser +run watch compact b Show only relevant/failed steps +run watch exit-status b Exit with non-zero status if run fails +run watch interval i i Refresh interval in seconds (default 3) +run watch repo R v repos Select another repository using the [HOST/]OWNER/REPO format +search code extension v Filter on file extension +search code filename v Filter on filename +search code jq q v Filter JSON output using a jq expression +search code json v json-fields Output JSON with the specified fields +search code language v Filter results by language +search code limit L i Maximum number of code results to fetch (default 30) +search code match v =file|path Restrict search to file contents or file path: {file|path} +search code owner v owners Filter on owner +search code repo R v repos Filter on repository, in OWNER/REPO format +search code size v Filter on size range, in kilobytes +search code template t v Format JSON output using a Go template; see "gh help formatting" +search code web w b Open the search query in the web browser +search commits author v users Filter by author +search commits author-date v Filter based on authored date +search commits author-email v Filter on author email +search commits author-name v Filter on author name +search commits committer v Filter by committer +search commits committer-date v Filter based on committed date +search commits committer-email v Filter on committer email +search commits committer-name v Filter on committer name +search commits hash v Filter by commit hash +search commits jq q v Filter JSON output using a jq expression +search commits json v json-fields Output JSON with the specified fields +search commits limit L i Maximum number of commits to fetch (default 30) +search commits merge b Filter on merge commits +search commits order v =asc|desc Order of commits returned, ignored unless '--sort' flag is specified: {asc|desc} (default "desc") +search commits owner v owners Filter on repository owner +search commits parent v issues Filter by parent hash +search commits repo R v repos Filter on repository, in OWNER/REPO format +search commits sort v =author-date|committer-date Sort fetched commits: {author-date|committer-date} (default "best-match") +search commits template t v Format JSON output using a Go template; see "gh help formatting" +search commits tree v Filter by tree hash +search commits visibility v =public|private|internal Filter based on repository visibility: {public|private|internal} +search commits web w b Open the search query in the web browser +search issues app v Filter by GitHub App author +search issues archived b Filter based on the repository archived state {true|false} +search issues assignee v users Filter by assignee +search issues author v users Filter by author (use --app to filter by a GitHub App) +search issues closed v Filter on closed at date +search issues commenter v me Filter based on comments by user +search issues comments v Filter on number of comments +search issues created v Filter based on created at date +search issues include-prs b Include pull requests in results +search issues interactions v Filter on number of reactions and comments +search issues involves v me Filter based on involvement of user +search issues jq q v Filter JSON output using a jq expression +search issues json v json-fields Output JSON with the specified fields +search issues label v labels Filter on label +search issues language v Filter based on the coding language +search issues limit L i Maximum number of results to fetch (default 30) +search issues locked b Filter on locked conversation status +search issues match v =title|body|comments Restrict search to specific field of issue: {title|body|comments} +search issues mentions v me Filter based on user mentions +search issues milestone v milestones Filter by milestone title +search issues no-assignee b Filter on missing assignee +search issues no-label b Filter on missing label +search issues no-milestone b Filter on missing milestone +search issues no-project b Filter on missing project +search issues order v =asc|desc Order of results returned, ignored unless '--sort' flag is specified: {asc|desc} (default "desc") +search issues owner v owners Filter on repository owner +search issues project v Filter on project board owner/number +search issues reactions v Filter on number of reactions +search issues repo R v repos Filter on repository, in OWNER/REPO format +search issues search-type v =lexical|semantic|hybrid Type of issue search to perform: {lexical|semantic|hybrid} (default "lexical") +search issues sort v =comments|created|interactions|reactions|reactions-+1|reactions--1|reactions-heart|reactions-smile|reactions-tada|reactions-thinking_face|updated Sort fetched results: {comments|created|interactions|reactions|reactions-+1|reactions--1|reactions-heart|reactions-smile|reactions-tada|reactions-thinking_face|updated} (default "best-match") +search issues state v =open|closed Filter based on state: {open|closed} +search issues team-mentions v Filter based on team mentions +search issues template t v Format JSON output using a Go template; see "gh help formatting" +search issues updated v Filter on last updated at date +search issues visibility v =public|private|internal Filter based on repository visibility: {public|private|internal} +search issues web w b Open the search query in the web browser +search prs app v Filter by GitHub App author +search prs archived b Filter based on the repository archived state {true|false} +search prs assignee v users Filter by assignee +search prs author v users Filter by author (use --app to filter by a GitHub App) +search prs base B v Filter on base branch name +search prs checks v =pending|success|failure Filter based on status of the checks: {pending|success|failure} +search prs closed v Filter on closed at date +search prs commenter v me Filter based on comments by user +search prs comments v Filter on number of comments +search prs created v Filter based on created at date +search prs draft b Filter based on draft state +search prs head H v Filter on head branch name +search prs interactions v Filter on number of reactions and comments +search prs involves v me Filter based on involvement of user +search prs jq q v Filter JSON output using a jq expression +search prs json v json-fields Output JSON with the specified fields +search prs label v labels Filter on label +search prs language v Filter based on the coding language +search prs limit L i Maximum number of results to fetch (default 30) +search prs locked b Filter on locked conversation status +search prs match v =title|body|comments Restrict search to specific field of issue: {title|body|comments} +search prs mentions v me Filter based on user mentions +search prs merged b Filter based on merged state +search prs merged-at v Filter on merged at date +search prs milestone v milestones Filter by milestone title +search prs no-assignee b Filter on missing assignee +search prs no-label b Filter on missing label +search prs no-milestone b Filter on missing milestone +search prs no-project b Filter on missing project +search prs order v =asc|desc Order of results returned, ignored unless '--sort' flag is specified: {asc|desc} (default "desc") +search prs owner v owners Filter on repository owner +search prs project v Filter on project board owner/number +search prs reactions v Filter on number of reactions +search prs repo R v repos Filter on repository, in OWNER/REPO format +search prs review v =none|required|approved|changes_requested Filter based on review status: {none|required|approved|changes_requested} +search prs review-requested v me Filter on user or team requested to review +search prs reviewed-by v me Filter on user who reviewed +search prs sort v =comments|reactions|reactions-+1|reactions--1|reactions-smile|reactions-thinking_face|reactions-heart|reactions-tada|interactions|created|updated Sort fetched results: {comments|reactions|reactions-+1|reactions--1|reactions-smile|reactions-thinking_face|reactions-heart|reactions-tada|interactions|created|updated} (default "best-match") +search prs state v =open|closed Filter based on state: {open|closed} +search prs team-mentions v Filter based on team mentions +search prs template t v Format JSON output using a Go template; see "gh help formatting" +search prs updated v Filter on last updated at date +search prs visibility v =public|private|internal Filter based on repository visibility: {public|private|internal} +search prs web w b Open the search query in the web browser +search repos archived b Filter based on the repository archived state {true|false} +search repos created v Filter based on created at date +search repos followers v Filter based on number of followers +search repos forks v Filter on number of forks +search repos good-first-issues v Filter on number of issues with the 'good first issue' label +search repos help-wanted-issues v Filter on number of issues with the 'help wanted' label +search repos include-forks v =false|true|only Include forks in fetched repositories: {false|true|only} +search repos jq q v Filter JSON output using a jq expression +search repos json v json-fields Output JSON with the specified fields +search repos language v Filter based on the coding language +search repos license v licenses Filter based on license type +search repos limit L i Maximum number of repositories to fetch (default 30) +search repos match v =name|description|readme Restrict search to specific field of repository: {name|description|readme} +search repos number-topics v Filter on number of topics +search repos order v =asc|desc Order of repositories returned, ignored unless '--sort' flag is specified: {asc|desc} (default "desc") +search repos owner v owners Filter on owner +search repos size v Filter on a size range, in kilobytes +search repos sort v =forks|help-wanted-issues|stars|updated Sort fetched repositories: {forks|help-wanted-issues|stars|updated} (default "best-match") +search repos stars v Filter on number of stars +search repos template t v Format JSON output using a Go template; see "gh help formatting" +search repos topic v Filter on topic +search repos updated v Filter on last updated at date +search repos visibility v =public|private|internal Filter based on visibility: {public|private|internal} +search repos web w b Open the search query in the web browser +secret repo R v repos Select another repository using the [HOST/]OWNER/REPO format +secret delete app a v =actions|agents|codespaces|dependabot Delete a secret for a specific application: {actions|agents|codespaces|dependabot} +secret delete env e v environments Delete a secret for an environment +secret delete org o v orgs Delete a secret for an organization +secret delete repo R v repos Select another repository using the [HOST/]OWNER/REPO format +secret delete user u b Delete a secret for your user +secret list app a v =actions|agents|codespaces|dependabot List secrets for a specific application: {actions|agents|codespaces|dependabot} +secret list env e v environments List secrets for an environment +secret list jq q v Filter JSON output using a jq expression +secret list json v json-fields Output JSON with the specified fields +secret list org o v orgs List secrets for an organization +secret list repo R v repos Select another repository using the [HOST/]OWNER/REPO format +secret list template t v Format JSON output using a Go template; see "gh help formatting" +secret list user u b List a secret for your user +secret set app a v =actions|agents|codespaces|dependabot Set the application for a secret: {actions|agents|codespaces|dependabot} +secret set body b v The value for the secret (reads from standard input if not specified) +secret set env e v environments Set deployment environment secret +secret set env-file f f Load secret names and values from a dotenv-formatted file +secret set no-repos-selected b No repositories can access the organization secret +secret set no-store b Print the encrypted, base64-encoded value instead of storing it on GitHub +secret set org o v orgs Set organization secret +secret set repo R v repos Select another repository using the [HOST/]OWNER/REPO format +secret set repos r v repos List of repositories that can access an organization or user secret +secret set user u b Set a secret for your user +secret set visibility v v =all|private|selected Set visibility for an organization secret: {all|private|selected} (default "private") +skill install agent v Target agent (see supported values above) +skill install all b Install all skills without prompting for skill selection +skill install allow-hidden-dirs b Include skills in hidden directories (e.g. .claude/skills/, .agents/skills/) +skill install dir v Install to a custom directory (overrides --agent and --scope) +skill install force f b Overwrite existing skills without prompting +skill install from-local b Treat the argument as a local directory path instead of a repository +skill install pin v Pin to a specific git tag or commit SHA +skill install scope v =project|user Installation scope: {project|user} (default "project") +skill install upstream b Install from the upstream source when a re-published skill is detected +skill list agent v =github-copilot|claude-code|cursor|codex|gemini-cli|antigravity|antigravity-cli|antigravity2.0|adal|amp|augment|bob|cline|codebuddy|command-code|continue|cortex|crush|deepagents|devin|droid|firebender|goose|grok|iflow-cli|junie|kilo|kimi-cli|kiro-cli|kode|mcpjam|mistral-vibe|mux|neovate|openclaw|opencode|openhands|pi|pochi|qoder|qwen-code|replit|roo|trae|trae-cn|universal|warp|zencoder Filter by target agent: {github-copilot|claude-code|cursor|codex|gemini-cli|antigravity|antigravity-cli|antigravity2.0|adal|amp|augment|bob|cline|codebuddy|command-code|continue|cortex|crush|deepagents|devin|droid|firebender|goose|grok|iflow-cli|junie|kilo|kimi-cli|kiro-cli|kode|mcpjam|mistral-vibe|mux|neovate|openclaw|opencode|openhands|pi|pochi|qoder|qwen-code|replit|roo|trae|trae-cn|universal|warp|zencoder} +skill list dir v Scan a custom directory for installed skills +skill list jq q v Filter JSON output using a jq expression +skill list json v json-fields Output JSON with the specified fields +skill list scope v =project|user Filter by installation scope: {project|user} +skill list template t v Format JSON output using a Go template; see "gh help formatting" +skill preview allow-hidden-dirs b Include skills in hidden directories (e.g. .claude/skills/, .agents/skills/) +skill publish dry-run b Validate without publishing +skill publish fix b Auto-fix issues where possible without publishing (e.g. strip install metadata) +skill publish tag v Version tag for the release (e.g. v1.0.0) +skill search jq q v Filter JSON output using a jq expression +skill search json v json-fields Output JSON with the specified fields +skill search limit L i Maximum number of results per page (default 15) +skill search owner v owners Filter results to a specific GitHub user or organization +skill search page i Page number of results to fetch (default 1) +skill search template t v Format JSON output using a Go template; see "gh help formatting" +skill update all b Update all skills without prompting +skill update dir v Scan a custom directory for installed skills +skill update dry-run b Report available updates without modifying files +skill update force b Re-download even if already up to date +skill update unpin b Clear pinned version and include pinned skills in update +ssh-key add title t v Title for the new key +ssh-key add type v =authentication|signing Type of the ssh key: {authentication|signing} (default "authentication") +ssh-key delete yes y b Skip the confirmation prompt +status exclude e v repos Comma separated list of repos to exclude in owner/name format +status org o v orgs Report status within an organization +variable repo R v repos Select another repository using the [HOST/]OWNER/REPO format +variable delete env e v environments Delete a variable for an environment +variable delete org o v orgs Delete a variable for an organization +variable delete repo R v repos Select another repository using the [HOST/]OWNER/REPO format +variable get env e v environments Get a variable for an environment +variable get jq q v Filter JSON output using a jq expression +variable get json v json-fields Output JSON with the specified fields +variable get org o v orgs Get a variable for an organization +variable get repo R v repos Select another repository using the [HOST/]OWNER/REPO format +variable get template t v Format JSON output using a Go template; see "gh help formatting" +variable list env e v environments List variables for an environment +variable list jq q v Filter JSON output using a jq expression +variable list json v json-fields Output JSON with the specified fields +variable list org o v orgs List variables for an organization +variable list repo R v repos Select another repository using the [HOST/]OWNER/REPO format +variable list template t v Format JSON output using a Go template; see "gh help formatting" +variable set body b v The value for the variable (reads from standard input if not specified) +variable set env e v environments Set deployment environment variable +variable set env-file f f Load variable names and values from a dotenv-formatted file +variable set org o v orgs Set organization variable +variable set repo R v repos Select another repository using the [HOST/]OWNER/REPO format +variable set repos r v repos List of repositories that can access an organization variable +variable set visibility v v =all|private|selected Set visibility for an organization variable: {all|private|selected} (default "private") +workflow repo R v repos Select another repository using the [HOST/]OWNER/REPO format +workflow disable repo R v repos Select another repository using the [HOST/]OWNER/REPO format +workflow enable repo R v repos Select another repository using the [HOST/]OWNER/REPO format +workflow list all a b Include disabled workflows +workflow list jq q v Filter JSON output using a jq expression +workflow list json v json-fields Output JSON with the specified fields +workflow list limit L i Maximum number of workflows to fetch (default 50) +workflow list repo R v repos Select another repository using the [HOST/]OWNER/REPO format +workflow list template t v Format JSON output using a Go template; see "gh help formatting" +workflow run field F v Add a string parameter in key=value format, respecting @ syntax (see "gh help api"). +workflow run json b Read workflow inputs as JSON via STDIN +workflow run raw-field f v Add a string parameter in key=value format +workflow run ref r v branches Branch or tag name which contains the version of the workflow file you'd like to run +workflow run repo R v repos Select another repository using the [HOST/]OWNER/REPO format +workflow view ref r v The branch or tag name which contains the version of the workflow file you'd like to view +workflow view repo R v repos Select another repository using the [HOST/]OWNER/REPO format +workflow view web w b Open workflow in the browser +workflow view yaml y b View the workflow yaml file +'# + +# Command aliases gh accepts (`pr co`), and the command each stands for. +const GH_ALIASES = r#' +agent-tasks agent-task +agent agent-task +agents agent-task +alias ls alias list +at attestation +cache ls cache list +cs codespace +codespace ls codespace list +cs ls codespace list +config ls config list +discussion ls discussion list +extensions extension +ext extension +ext ls extension list +extension ls extension list +extensions ls extension list +ext uninstall extension remove +extension uninstall extension remove +extensions uninstall extension remove +gist new gist create +gist ls gist list +gpg-key ls gpg-key list +issue artifact new issue artifact create +issue artifact ls issue artifact list +issue new issue create +issue ls issue list +label ls label list +org ls org list +pr co pr checkout +pr new pr create +pr ls pr list +project ls project list +release new release create +release ls release list +repo autolink new repo autolink create +repo autolink ls repo autolink list +repo new repo create +repo deploy-key ls repo deploy-key list +repo gitignore ls repo gitignore list +repo license ls repo license list +repo ls repo list +rs ruleset +rs ls ruleset list +ruleset ls ruleset list +run ls run list +secret remove secret delete +secret ls secret list +skills skill +skill add skill install +skills add skill install +skill ls skill list +skills ls skill list +skill show skill preview +skills show skill preview +ssh-key ls ssh-key list +variable remove variable delete +variable ls variable list +workflow ls workflow list +'# + +const GH_HELP_TOPICS = [ + [value description]; + [accessibility "Learn about GitHub CLI's accessibility experiences"] + [actions "Learn about working with GitHub Actions"] + [environment "Environment variables that can be used with gh"] + [exit-codes "Exit codes used by gh"] + [formatting "Formatting options for JSON data exported from gh"] + [mintty "Information about using gh with MinTTY"] + [reference "A comprehensive reference of all gh commands"] + [telemetry "Information about telemetry in gh"] +] -def "nu-complete gh" [] { - ^gh --help - | lines - | where { str starts-with " " } - | skip 1 - | parse "{value}: {description}" - | str trim -} - -export extern "gh" [ - command?: string@"nu-complete gh" - --help # Show help for command +const GH_API_ENDPOINTS = [ + [value description]; + [graphql "GraphQL API"] + [user "The authenticated user"] + [user/repos "Repositories of the authenticated user"] + [user/orgs "Organizations of the authenticated user"] + [notifications "Notifications of the authenticated user"] + [rate_limit "Rate limit status"] + ["repos/{owner}/{repo}" "The current repository"] + ["repos/{owner}/{repo}/branches" "Branches"] + ["repos/{owner}/{repo}/commits" "Commits"] + ["repos/{owner}/{repo}/contents" "Contents"] + ["repos/{owner}/{repo}/contributors" "Contributors"] + ["repos/{owner}/{repo}/issues" "Issues"] + ["repos/{owner}/{repo}/issues/comments" "Issue comments"] + ["repos/{owner}/{repo}/labels" "Labels"] + ["repos/{owner}/{repo}/milestones" "Milestones"] + ["repos/{owner}/{repo}/pulls" "Pull requests"] + ["repos/{owner}/{repo}/pulls/comments" "Pull request review comments"] + ["repos/{owner}/{repo}/releases" "Releases"] + ["repos/{owner}/{repo}/releases/latest" "Latest release"] + ["repos/{owner}/{repo}/tags" "Tags"] + ["repos/{owner}/{repo}/actions/runs" "Workflow runs"] + ["repos/{owner}/{repo}/actions/workflows" "Workflows"] + ["repos/{owner}/{repo}/actions/artifacts" "Artifacts"] + ["repos/{owner}/{repo}/actions/caches" "Actions caches"] + ["repos/{owner}/{repo}/actions/secrets" "Actions secrets"] + ["repos/{owner}/{repo}/actions/variables" "Actions variables"] + ["repos/{owner}/{repo}/collaborators" "Collaborators"] + ["repos/{owner}/{repo}/deployments" "Deployments"] + ["repos/{owner}/{repo}/environments" "Environments"] + ["repos/{owner}/{repo}/forks" "Forks"] + ["repos/{owner}/{repo}/hooks" "Webhooks"] + ["repos/{owner}/{repo}/rulesets" "Rulesets"] + ["repos/{owner}/{repo}/stargazers" "Stargazers"] + ["repos/{owner}/{repo}/topics" "Topics"] + ["search/code" "Search code"] + ["search/commits" "Search commits"] + ["search/issues" "Search issues and pull requests"] + ["search/repositories" "Search repositories"] + ["search/users" "Search users"] ] -def "nu-complete gh auth" [] { - ^gh auth --help - | lines - | where { str starts-with " " } - | skip 1 - | parse "{value}: {description}" - | str trim -} +const GH_SCOPES = [ + repo repo:status repo_deployment public_repo repo:invite security_events + admin:repo_hook write:repo_hook read:repo_hook admin:org write:org read:org + admin:public_key write:public_key read:public_key admin:org_hook gist notifications + user read:user user:email user:follow project read:project delete_repo + write:packages read:packages delete:packages admin:gpg_key write:gpg_key read:gpg_key + codespace workflow admin:ssh_signing_key write:ssh_signing_key read:ssh_signing_key + copilot audit_log read:audit_log admin:enterprise manage_runners:enterprise + manage_billing:enterprise read:enterprise +] -export extern "gh auth" [ - command?: string@"nu-complete gh auth" - --help # Show help for command +const GH_EVENTS = [ + branch_protection_rule check_run check_suite create delete deployment + deployment_status discussion discussion_comment fork gollum issue_comment issues + label merge_group milestone page_build public pull_request pull_request_review + pull_request_review_comment pull_request_target push registry_package release + repository_dispatch schedule status watch workflow_call workflow_dispatch workflow_run ] -export extern "gh browse" [ - command?: string # TODO: completion with [ | | ] - --branch(-b) # Select another branch by passing in the branch name - --commit(-c) # Select another commit by passing in the commit SHA, default is the last commit - --no-browser(-n) # Print destination URL instead of opening the browser - --projects(-p) # Open repository projects - --releases(-r) # Open repository releases - --repo(-R) # Select another repository using the [HOST/]OWNER/REPO format - --settings(-s) # Open repository settings - --wiki(-w) # Open repository wiki - --help # Show help for command +const GH_PROMPT_TYPES = [ + select multi-select multi-select-with-search input password confirm auth-token + confirm-deletion input-hostname markdown-editor ] -def "nu-complete gh codespace" [] { - ^gh codespace --help - | lines - | where { str starts-with " " } - | skip 1 - | parse "{value}: {description}" - | str trim +# A completion value that Nushell parses back to the same string, so it is quoted +# only when it is not a plain word (spaces, globs, leading dash, octal-looking ints). +def gh-bare [text: string]: nothing -> bool { + ($text =~ '^[\w@./:+=,%][\w@./:+=,%-]*$') and ($text !~ '^0[0-9xob]') and $text != 'null' } -export extern "gh codespace" [ - command?: string@"nu-complete gh codespace" - --help # Show help for command -] +# Completion records for rows of {value, description}. With `--multi`, the text up to +# the last comma of the current word is kept, for flags that take comma-separated lists. +def gh-items [token: record, --multi]: list -> record { + let text = $token.text? | default '' | str trim -c '"' | str trim -c "'" + let prefix = if $multi { $text | str replace -r '[^,]*$' '' } else { '' } + let completions = $in | each {|row| + let full = $"($prefix)($row.value)" + let description = $row.description? | default '' + if (gh-bare $full) { + {value: $full, description: $description} + } else { + {value: ($full | to nuon), display_override: $full, description: $description} + } + } + {options: {sort: false, case_sensitive: false}, completions: $completions} +} -def "nu-complete gh gist" [] { - ^gh gist --help - | lines - | where { str starts-with " " } - | skip 1 - | parse "{value}: {description}" - | str trim +def gh-rows [description: string = '']: list -> list { + each {|value| {value: $value, description: $description} } } -export extern "gh gist" [ - command?: string@"nu-complete gh gist" - --help # Show help for command -] +# Words of the command line up to (but excluding) the word under the cursor. The first +# entry of `place.command` is the resolved command name, e.g. `gh pr view`. +def gh-words [place: record]: nothing -> list { + let command = $place.command? | default [] + if ($command | is-empty) { return [] } + $command.0 | split row ' ' | append ($command | skip 1 | drop 1) + | each {|word| $word | str trim -c '"' | str trim -c "'" } +} -export extern "gh gist clone" [ - gist: string # gist to clone - directory?:path # directory to clone - --help # Show help for command -] +# Value of the last occurrence of one of `names` (`--repo x`, `--repo=x`, `-R x`, `-Rx`). +def gh-flag-value [words: list, names: list]: nothing -> any { + $words | enumerate | each {|it| + $names | each {|name| + if $it.item == $name { + $words | get -o ($it.index + 1) + } else if ($name | str starts-with '--') and ($it.item | str starts-with $"($name)=") { + $it.item | str substring (($name | str length) + 1).. + } else if ($name =~ '^-\w$') and ($it.item | str starts-with $name) and ($it.item | str length) > 2 { + $it.item | str substring 2.. + } + } + } | flatten | compact | last +} -export extern "gh gist create" [ - filename_or_stdin: string # gist to create - --desc(-d): string # A description for this gist - --filename(-f): string # Provide a filename to be used when reading from standard input - --public(-p) # List the gist publicly (default: secret) - --web(-w) # Open the web browser with created gist - --public # Make the new gist public - --help # Show help for command -] +# Run gh for a completer. Returns null instead of failing when gh is missing, the +# directory is not a repository, the user is signed out, or the network is down. +const GH_QUIET_ENV = {GH_PROMPT_DISABLED: '1', GH_NO_UPDATE_NOTIFIER: '1', NO_COLOR: '1'} -export extern "gh gist delete" [ - gist: string@"nu-complete gist list" # gist to delete - --help # Show help for command -] +def gh-run [words: list, args: list]: nothing -> any { + let repo = gh-flag-value $words [--repo -R] + let env_vars = $GH_QUIET_ENV | merge (if $repo == null { {} } else { {GH_REPO: $repo} }) + let result = try { with-env $env_vars { '' | ^gh ...$args | complete } } catch { return null } + if $result.exit_code != 0 { return null } + $result.stdout +} -export extern "gh gist edit" [ - gist?: string@"nu-complete gist list" # gist to edit - --add(-a): string # Add a new file to the gist - --desc(-d): string # New description for the gist - --filename(-f): string # Select a file to edit - --remove(-r): string # Remove a file from the gist - --help # Show help for command -] +def gh-json [words: list, args: list]: nothing -> any { + let out = gh-run $words $args + if $out == null { return null } + try { $out | from json } catch { null } +} -def "nu-complete gist list" [] { - # TODO add the name of the gist to autocompletion - ^gh gist list --limit 100 | lines | str replace --regex --multiline '\S+\K.*' '' +# A cached `gh api` call; `{owner}`/`{repo}` follow `-R` on the line or the current repo. +def gh-api [words: list, ttl: string, endpoint: string, jq: string]: nothing -> list { + gh-json $words [api --cache $ttl $endpoint --jq $jq] | default [] } -export extern "gh gist list" [ - --limit(-L): number # Maximum number of repositories to list (default 30) - --public # Show only the public gists - --secret # Show only the secret gists - --help # Show help for command -] +def --wrapped gh-git-lines [...args: string]: nothing -> list { + let result = try { ^git ...$args | complete } catch { return [] } + if $result.exit_code != 0 { return [] } + $result.stdout | lines +} -export extern "gh gist rename" [ - gist: string # gist to rename - oldFilename: string # gist to rename - newFilename: string # gist to rename - --help # Show help for command -] +# Directory that holds gh's config.yml and hosts.yml. +def gh-config-dir []: nothing -> path { + if ($env.GH_CONFIG_DIR? | is-not-empty) { return $env.GH_CONFIG_DIR } + if ($env.XDG_CONFIG_HOME? | is-not-empty) { return ($env.XDG_CONFIG_HOME | path join gh) } + if $nu.os-info.name == 'windows' and ($env.AppData? | is-not-empty) { + return ($env.AppData | path join 'GitHub CLI') + } + $nu.home-dir | path join .config gh +} -export extern "gh gist view" [ - gist?: string # gist to view - --filename(-f): string # Display a single file from the gist - --files # List file names from the gist - --raw(-r) # Print raw instead of rendered gist contents - --web(-w) # Open gist in the browser - --help # Show help for command -] +def gh-hosts-file []: nothing -> record { + let file = gh-config-dir | path join hosts.yml + if not ($file | path exists) { return {} } + try { open --raw $file | from yaml | default {} } catch { {} } +} -def "nu-complete gh issue" [] { - ^gh issue --help - | lines - | where { str starts-with " " } - | skip 1 - | parse "{value}: {description}" - | str trim +# Command rows of GH_COMMANDS: {path, kinds, desc}. +def gh-commands []: nothing -> table { + $GH_COMMANDS | lines | where $it != '' | split column "\t" path kinds desc } -export extern "gh issue" [ - command?: string@"nu-complete gh issue" - --repo(-R) # Select another repository using the [HOST/]OWNER/REPO format - --help # Show help for command -] +# Flag rows of GH_FLAGS for one command: {long, short, kind, completer, desc}. +def gh-flags [path: string]: nothing -> table { + $GH_FLAGS | lines | where {|line| $line starts-with $"($path)\t" } + | split column "\t" path long short kind completer desc +} -def "nu-complete gh org" [] { - ^gh org --help - | lines - | where { str starts-with " " } - | skip 1 - | parse "{value}: {description}" - | str trim +# The command path (with aliases resolved) and its spec, from the words on the line. +def gh-spec [words: list, commands?: table]: nothing -> record { + let commands = if $commands == null { gh-commands } else { $commands } + let aliases = $GH_ALIASES | lines | where $it != '' | split column "\t" alias path + mut path = '' + mut used = 0 + for word in ($words | skip 1) { + if $word !~ '^[a-z][a-z0-9-]*$' { break } + let candidate = [$path $word] | where $it != '' | str join ' ' + let canonical = if $candidate in $commands.path { $candidate } else { $aliases | where alias == $candidate | get -o 0.path } + if $canonical == null { break } + $path = $canonical + $used += 1 + } + let path = $path + let row = $commands | where path == $path | get -o 0 + let flags = gh-flags $path + let valued = $flags | where kind != b | each {|f| [$"--($f.long)"] | append (if $f.short != '' { [$"-($f.short)"] } else { [] }) } | flatten + { + path: $path, rest: ($words | skip ($used + 1)), flags: $flags, valued: $valued + pos: ($row.kinds? | default '' | split row ' ' | where $it != ''), desc: ($row.desc? | default '') + } } -export extern "gh org" [ - command?: string@"nu-complete gh org" - --help # Show help for command -] +# Positional words after the command path, and whether `--` was seen. +def gh-positionals [spec: record]: nothing -> record { + mut positionals = [] + mut skip_value = false + mut after_dashes = false + for word in $spec.rest { + if $skip_value { $skip_value = false; continue } + if not $after_dashes and $word == '--' { $after_dashes = true; continue } + if not $after_dashes and ($word | str starts-with '-') and $word != '-' { + if $word in $spec.valued { $skip_value = true } + continue + } + $positionals = $positionals | append $word + } + {words: $positionals, after_dashes: $after_dashes} +} -def "nu-complete gh pr" [] { - ^gh pr --help | lines | where { str starts-with " " } | skip 1 | parse "{value}: {description}" | str trim +def gh-kind [spec: record, index: int]: nothing -> string { + let pos = $spec.pos + if $index < ($pos | length) { return ($pos | get $index | str replace '...' '') } + let last = $pos | last + if $last != null and ($last | str ends-with '...') { $last | str replace '...' '' } else { 'none' } } -export extern "gh pr" [ - command?: string@"nu-complete gh pr" - --repo(-R) # Select another repository using the [HOST/]OWNER/REPO format - --help # Show help for command -] +# Flag names of a command, for a word that starts with `-`. +def gh-flag-rows [spec: record]: nothing -> list { + $spec.flags | each {|flag| + [{value: $"--($flag.long)", description: $flag.desc}] + | append (if $flag.short != '' { [{value: $"-($flag.short)", description: $flag.desc}] } else { [] }) + } | flatten | append {value: '--help', description: 'Show help for command'} +} -def "nu-complete gh list prs" [] { - gh pr list --json title,number,author,updatedAt | from json | update author {|row| $row.author.login } | rename --column { number: value } | insert description { |row| ( $row.updatedAt | date humanize) + " - " + $row.title + " by " + $row.author } | select value description +def gh-prs [words: list, state: string]: nothing -> list { + let query = if $state == 'open' { 'open' } else { 'closed' } + let jq = '[.[] | {number, title, branch: .head.ref, author: .user.login, merged: (.merged_at != null)}]' + gh-api $words 1m $"repos/{owner}/{repo}/pulls?state=($query)&sort=updated&direction=desc&per_page=50" $jq + | where {|pr| $state == 'open' or ($pr.merged == ($state == 'merged')) } + | each {|pr| {value: $"($pr.number)", description: $"($pr.title) [($pr.branch)] by ($pr.author)"} } } -export extern "gh pr checkout" [ - branch_url_or_PRnumber: string@"nu-complete gh list prs" # { | | } - --branch(-b): string # Local branch name to use (default: the name of the head branch) - --detach # Checkout PR with a detached HEAD - --force(-f) # Reset the existing local branch to the latest state of the pull request - --recurse-submodules # Update all submodules after checkout - --repo(-R) # Select another repository using the [HOST/]OWNER/REPO format - --help # Show help for command -] +def gh-issues [words: list, state: string]: nothing -> list { + let jq = '[.[] | select(.pull_request == null) | {number, title, author: .user.login}]' + gh-api $words 1m $"repos/{owner}/{repo}/issues?state=($state)&sort=updated&direction=desc&per_page=50" $jq + | each {|issue| {value: $"($issue.number)", description: $"($issue.title) by ($issue.author)"} } +} -def "nu-complete gh project" [] { - ^gh project --help - | lines - | where { str starts-with " " } - | skip 1 - | parse "{value}: {description}" - | str trim +def gh-repos []: nothing -> list { + let remotes = gh-git-lines remote --verbose + | parse -r '^(?\S+)\s+\S*github\.com[:/](?[^/\s]+/[^/\s]+?)(?:\.git)?/?\s' + | uniq-by repo + | each {|it| {value: $it.repo, description: $"git remote ($it.remote)"} } + let mine = gh-api [] 1h 'user/repos?per_page=100&sort=pushed' '[.[] | {name: .full_name, description}]' + | each {|repo| {value: $repo.name, description: ($repo.description | default '')} } + $remotes | append $mine | uniq-by value } -export extern "gh project" [ - command?: string@"nu-complete gh project" - --help # Show help for command -] +def gh-branches [words: list]: nothing -> list { + if (gh-flag-value $words [--repo -R]) == null { + let local = gh-git-lines for-each-ref '--format=%(refname:lstrip=2)' refs/heads + let remote = gh-git-lines for-each-ref '--format=%(refname:lstrip=3)' refs/remotes | where $it != 'HEAD' + let branches = $local | append $remote | uniq + if ($branches | is-not-empty) { return $branches } + } + gh-api $words 10m 'repos/{owner}/{repo}/branches?per_page=100' '[.[].name]' +} -def "nu-complete gh release" [] { - ^gh release --help - | lines - | where { str starts-with " " } - | skip 1 - | parse "{value}: {description}" - | str trim +def gh-orgs []: nothing -> list { + gh-api [] 1h 'user/orgs?per_page=100' '[.[] | {login, description}]' + | each {|org| {value: $org.login, description: ($org.description | default 'Organization')} } } -export extern "gh release" [ - command?: string@"nu-complete gh release" - --repo(-R) # Select another repository using the [HOST/]OWNER/REPO format - --help # Show help for command -] +def gh-positional [words: list, index: int]: nothing -> any { + gh-positionals (gh-spec $words) | get words | get -o $index +} -def "nu-complete gh repo" [] { - ^gh repo --help - | lines - | where { str starts-with " " } - | skip 1 - | parse "{value}: {description}" - | str trim +def gh-labels [words: list]: nothing -> list { + gh-api $words 10m 'repos/{owner}/{repo}/labels?per_page=100' '[.[] | {name, description}]' + | each {|label| {value: $label.name, description: ($label.description | default '')} } } -export extern "gh repo" [ - command?: string@"nu-complete gh repo" - --help # Show help for command -] +def gh-releases [words: list]: nothing -> list { + let jq = '[.[] | {tag: .tag_name, name, draft, prerelease}]' + gh-api $words 10m 'repos/{owner}/{repo}/releases?per_page=50' $jq + | each {|release| + let kind = if $release.draft { ' (draft)' } else if $release.prerelease { ' (pre-release)' } else { '' } + {value: $release.tag, description: $"($release.name | default '')($kind)"} + } +} -def "nu-complete gh repo clone" [] { - # regex that actually works - # ^(?P\S+) +(?P\S+( \S+)*)? {2,}(?Ppublic|private),?.*(?Pabout.*) - ^gh repo list --limit 100 | lines | str replace --regex --multiline '\S+\K.*' '' +def gh-gist-files [words: list]: nothing -> list { + let gist = gh-positional $words 0 + if $gist == null { return [] } + let id = $gist | split row / | last + gh-api [] 10m $"gists/($id)" '[.files[] | {filename, language}]' + | each {|file| {value: $file.filename, description: ($file.language | default 'File')} } } -export extern "gh repo clone" [ - command: string@"nu-complete gh repo clone" - --help # Show help for command -] +# REST endpoint listing secrets or variables for the scope selected on the line +# (`--org`, `--env`, `--user`, `--app`), like `gh secret list` would. +def gh-secrets-endpoint [words: list, what: string]: nothing -> string { + let org = gh-flag-value $words [--org -o] + let env_name = gh-flag-value $words [--env -e] + let app = gh-flag-value $words [--app -a] | default actions + if $org != null { return $"orgs/($org)/($app)/($what)?per_page=100" } + if $env_name != null { return $"repos/{owner}/{repo}/environments/($env_name | url encode)/($what)?per_page=100" } + if $what == 'secrets' and ([--user -u] | any {|flag| $flag in $words }) { + return 'user/codespaces/secrets?per_page=100' + } + $"repos/{owner}/{repo}/($app)/($what)?per_page=100" +} -def "nu-complete visibility" [] { - ['public', 'private', 'internal'] -} - -export extern "gh repo list" [ - owner?: string # List repos of this owner - --archived # Show only archived repositories - --fork # Show only forks - --jq(-q):string # Filter JSON output using a jq expression - --json: string # Output JSON with the specified fields - --language(-l): string # Filter by primary coding language - --limit(-L): number # Maximum number of repositories to list (default 30) - --no-archived # Omit archived repositories - --source # Show only non-forks - --template(-t): string # Format JSON output using a Go template; see "gh help formatting" - --topic: string # Filter by topic - --visibility: string@"nu-complete visibility" # Filter by repository visibility: {public|private|internal} - --help # Show help for command -] +def gh-run-id [words: list]: nothing -> any { + gh-positional $words 0 | default (gh-flag-value $words [--run-id]) +} -export extern "gh repo view" [ - org_repo: string # to view - --branch(-b):string # View a specific branch of the repository - --jq(-q):string # Filter JSON output using a jq expression - --json: string # Output JSON with the specified fields - --template(-t):string # Format JSON output using a Go template; see "gh help formatting" - --web # Open a repository in the browser - --help # Show help for command -] +def gh-skill-names []: nothing -> list { + gh-json [] [skill list --json 'skillName,scope'] | default [] + | each {|skill| {value: $skill.skillName, description: $"Skill \(($skill.scope)\)"} } + | uniq-by value +} -def "nu-complete gitignore list" [] { - ^gh api -H "Accept: application/vnd.github+json" /gitignore/templates - | from json +def gh-config-keys []: nothing -> list { + gh-run [] [config --help] | default '' + | lines + | parse -r '^- `(?[^`]+)`: (?.*)$' } -def "nu-complete licenses list" [] { - let value = ^gh api -H "Accept: application/vnd.github+json" /licenses | from json | get key | enumerate | reject index | rename value - let description = ^gh api -H "Accept: application/vnd.github+json" /licenses | from json | get name | enumerate | reject index | rename description - $value | merge $description -} - -export extern "gh repo create" [ - repo_name?: string - --help # Show help for command - --add-readme # Add a README file to the new repository - --clone(-c) # Clone the new repository to the current directory - --description(-d): string # Description of the repository - --disable-issues # Disable issues in the new repository - --disable-wiki # Disable wiki in the new repository - --gitignore(-g): string@"nu-complete gitignore list" # Specify a gitignore template for the repository - --homepage(-g): string # Repository home page URL - --include-all-branches # Include all branches from template repository - --internal # Make the new repository internal - --license(-l): string@"nu-complete licenses list" # Specify an Open Source License for the repository - --private # Make the new repository private - --public # Make the new repository public - --push # Push local commits to the new repository - --remote(-r): string # Specify remote name for the new repository - --source(-s): string # Specify path to local repository to use as source - --team(-t): string # The name of the organization team to be granted access - --template(-p): string # Make the new repository based on a template repository -] +def gh-help-commands [first?: string]: nothing -> list { + let commands = gh-commands | where path != '' and path != 'help' + if $first == null { + $commands | where path !~ ' ' | each {|c| {value: $c.path, description: $c.desc} } | append $GH_HELP_TOPICS + } else { + $commands | where {|c| $c.path starts-with $"($first) " } | each {|c| $c.path | split row ' ' | get 1 } + | uniq | gh-rows Subcommand + } +} -export extern "gh repo fork" [ - repo?: string - --clone # Clone the fork - --default-branch-only # Only include the default branch in the fork - --fork-name: string # Rename the forked repository - --org: string # Create the fork in an organization - --remote # Add a git remote for the fork - --remote-name: string # Specify the name for the new remote (default "origin") - --help # Show help for command -] +# User aliases from gh's config.yml (`gh alias set`), as {name: expansion}. +def gh-user-aliases []: nothing -> record { + let file = gh-config-dir | path join config.yml + if not ($file | path exists) { return {} } + try { open --raw $file | from yaml | get -o aliases | default {} } catch { {} } +} + +# Installed extensions, from gh's data directory (`gh extension list` would cost a gh start). +def gh-extensions []: nothing -> list { + let base = if ($env.XDG_DATA_HOME? | is-not-empty) { + $env.XDG_DATA_HOME | path join gh + } else if $nu.os-info.name == 'windows' and ($env.LocalAppData? | is-not-empty) { + $env.LocalAppData | path join 'GitHub CLI' + } else { + $nu.home-dir | path join .local share gh + } + let dir = $base | path join extensions + if not ($dir | path exists) { return [] } + ls $dir | where type in [dir symlink] | get name | path basename | where $it starts-with 'gh-' | str replace 'gh-' '' +} -def "nu-complete gh cache" [] { - ^gh cache --help - | lines - | where { str starts-with " " } - | skip 1 - | parse "{value}: {description}" - | str trim +# Replace a leading user alias with what it stands for (`gh co 12` -> `gh pr checkout 12`). +# A `!` alias runs a shell command; only a `gh ` inside it is followed. +def gh-expand-alias [words: list, commands: table]: nothing -> list { + let aliases = gh-user-aliases + mut words = $words + for _ in 1..8 { + let name = $words | get -o 1 + if $name == null or ($name in $commands.path) { break } + let value = $aliases | get -o $name + if $value == null { break } + let expansion = if ($value starts-with '!') { + let parts = $value | str substring 1.. | split row -r '\s+' + let start = $parts | enumerate | where item == gh | get -o 0.index + if $start == null { [] } else { $parts | skip ($start + 1) | take until {|w| $w in [';' '&&' '||' '|'] } } + } else { + $value | split row -r '\s+' | where $it != '' + } + let expansion = $expansion | where $it !~ '^\$' + if ($expansion | is-empty) { break } + $words = [gh] | append $expansion | append ($words | skip 2) + } + $words } -export extern "gh cache" [ - command?: string@"nu-complete gh cache" - --repo(-R) # Select another repository using the [HOST/]OWNER/REPO format - --help # Show help for command -] +# Completions for one positional slot kind. +def gh-complete-kind [kind: string, words: list]: nothing -> any { + match $kind { + none => [] + file => null + gh-command => { + let aliases = gh-user-aliases | transpose value description + | update description {|it| $"Alias for ($it.description)" } + let extensions = gh-extensions | each {|name| {value: $name, description: 'Extension'} } + $aliases | append $extensions + } + pr => (gh-prs $words open) + pr-closed => (gh-prs $words closed) + pr-merged => (gh-prs $words merged) + issue => (gh-issues $words open) + issue-closed => (gh-issues $words closed) + repo => (gh-repos) + branch => (gh-branches $words | gh-rows Branch) + owner => { + let me = gh-api [] 1h user '[.login]' | gh-rows 'You' + $me | append (gh-orgs) + } + release => (gh-releases $words) + release-asset => { + let tag = gh-positional $words 0 + if $tag == null { return [] } + gh-api $words 10m $"repos/{owner}/{repo}/releases/tags/($tag | url encode)" '[.assets[] | {name, size}]' + | each {|asset| {value: $asset.name, description: $"($asset.size | into filesize)"} } + } + workflow => { + gh-api $words 10m 'repos/{owner}/{repo}/actions/workflows?per_page=100' '[.workflows[] | {name, path, state}]' + | each {|wf| {value: ($wf.path | path basename), description: $"($wf.name) \(($wf.state)\)"} } + } + run => { + let jq = '[.workflow_runs[] | {id, name, title: .display_title, status, conclusion, branch: .head_branch}]' + gh-api $words 1m 'repos/{owner}/{repo}/actions/runs?per_page=30' $jq + | each {|run| {value: $"($run.id)", description: $"($run.name): ($run.title) [($run.branch)] ($run.conclusion | default $run.status)"} } + } + cache => { + gh-api $words 1m 'repos/{owner}/{repo}/actions/caches?per_page=100' '[.actions_caches[] | {id, key, ref}]' + | each {|cache| {value: $"($cache.id)", description: $"($cache.key) \(($cache.ref)\)"} } + } + gist => { + gh-api [] 5m 'gists?per_page=100' '[.[] | {id, description, files: (.files | keys)}]' + | each {|gist| {value: $gist.id, description: ($gist.description | default ($gist.files | str join ', '))} } + } + gist-file => (gh-gist-files $words) + secret => { + let endpoint = gh-secrets-endpoint $words secrets + gh-api $words 1m $endpoint '[.secrets[] | {name, updated_at}]' + | each {|secret| {value: $secret.name, description: $"Updated ($secret.updated_at)"} } + } + variable => { + let endpoint = gh-secrets-endpoint $words variables + gh-api $words 1m $endpoint '[.variables[] | {name, value}]' + | each {|var| {value: $var.name, description: $var.value} } + } + label => (gh-labels $words) + alias => (gh-user-aliases | transpose value description) + extension => (gh-extensions | gh-rows Extension) + skill => (gh-skill-names) + ssh-key => { + gh-api [] 10m 'user/keys?per_page=100' '[.[] | {id, title}]' + | each {|key| {value: $"($key.id)", description: $key.title} } + } + gpg-key => { + gh-api [] 10m 'user/gpg_keys?per_page=100' '[.[] | {key_id, emails: [.emails[].email]}]' + | each {|key| {value: $key.key_id, description: ($key.emails | str join ', ')} } + } + ruleset => { + gh-api $words 10m 'repos/{owner}/{repo}/rulesets?per_page=100' '[.[] | {id, name, enforcement}]' + | each {|rule| {value: $"($rule.id)", description: $"($rule.name) \(($rule.enforcement)\)"} } + } + deploy-key => { + gh-api $words 10m 'repos/{owner}/{repo}/keys?per_page=100' '[.[] | {id, title}]' + | each {|key| {value: $"($key.id)", description: $key.title} } + } + autolink => { + gh-api $words 10m 'repos/{owner}/{repo}/autolinks' '[.[] | {id, key_prefix, url_template}]' + | each {|link| {value: $"($link.id)", description: $"($link.key_prefix) -> ($link.url_template)"} } + } + project => { + let owner = gh-flag-value $words [--owner] | default '@me' + gh-json [] [project list --owner $owner --format json --limit 50] | default {projects: []} + | get projects | each {|project| {value: $"($project.number)", description: $project.title} } + } + discussion => { + let query = 'query($owner: String!, $repo: String!) { repository(owner: $owner, name: $repo) { discussions(first: 50, orderBy: {field: UPDATED_AT, direction: DESC}) { nodes { number title } } } }' + gh-json $words [api --cache 5m graphql -F 'owner={owner}' -F 'repo={repo}' -f $"query=($query)" --jq '.data.repository.discussions.nodes'] + | default [] | each {|d| {value: $"($d.number)", description: $d.title} } + } + gitignore => (gh-api [] 24h gitignore/templates '.' | gh-rows Template) + license => { + gh-api [] 24h licenses '[.[] | {key, name}]' | each {|lic| {value: $lic.key, description: $lic.name} } + } + config-key => (gh-config-keys) + config-value => { + let key = gh-positional $words 0 + gh-config-keys | where value == $key | get -o 0.description | default '' + | parse -r '`\{(?[^}]+)\}`' | get -o 0.values | default '' + | split row '|' | str trim | where $it != '' | gh-rows + } + help-topic => (gh-help-commands) + help-subcommand => (gh-help-commands (gh-positional $words 0)) + prompt-type => ($GH_PROMPT_TYPES | gh-rows 'Prompt type') + api-endpoint => $GH_API_ENDPOINTS + _ => [] + } +} -def "nu-complete gh run" [] { - ^gh run --help - | lines - | where { str starts-with " " } - | skip 1 - | parse "{value}: {description}" - | str trim +# The value of a flag (`--label `, `--label=`): its completer or fixed values. +def gh-flag-value-rows [flag: record, token: record, place: record]: nothing -> any { + if $flag.kind == f { return null } + let source = $flag.completer + if ($source | str starts-with '=') { + return ($source | str substring 1.. | split row '|' | gh-rows | gh-items $token) + } + match $source { + '' => [] + repos => (nu-complete gh repos $token) + json-fields => (nu-complete gh json-fields $token $place) + labels => (nu-complete gh labels $token $place) + users => (nu-complete gh users $token $place) + me => (nu-complete gh me $token) + milestones => (nu-complete gh milestones $token $place) + branches => (nu-complete gh branches $token $place) + cache-refs => (nu-complete gh cache-refs $token $place) + workflows => (nu-complete gh workflows $token $place) + orgs => (nu-complete gh orgs $token) + owners => (nu-complete gh owners $token) + hosts => (nu-complete gh hosts $token) + accounts => (nu-complete gh accounts $token) + codespaces => (nu-complete gh codespaces $token) + environments => (nu-complete gh environments $token $place) + projects => (nu-complete gh projects $token $place) + scopes => (nu-complete gh scopes $token) + gitignores => (nu-complete gh gitignores $token) + licenses => (nu-complete gh licenses $token) + issues => (nu-complete gh issues $token $place) + issue-templates => (nu-complete gh issue-templates $token) + run-jobs => (nu-complete gh run-jobs $token $place) + artifacts => (nu-complete gh artifacts $token $place) + gist-files => (nu-complete gh gist-files $token $place) + releases => (nu-complete gh releases $token $place) + commits => (nu-complete gh commits $token) + repo-topics => (nu-complete gh repo-topics $token $place) + events => (nu-complete gh events $token) + http-methods => (nu-complete gh http-methods $token) + api-headers => (nu-complete gh api-headers $token) + close-reasons => (nu-complete gh close-reasons $token) + lock-reasons => (nu-complete gh lock-reasons $token) + archive-formats => (nu-complete gh archive-formats $token) + _ => [] + } } -export extern "gh run" [ - command?: string@"nu-complete gh run" - --help # Show help for command -] +# Prefix completion values with `--flag=` (quoting again where needed). +def gh-prefixed [prefix: string]: any -> any { + let out = $in + if $out == null { return null } + let rows = if ($out | describe | str starts-with 'record') { $out.completions } else { $out } + let rows = $rows | each {|row| + let text = $"($prefix)($row.display_override? | default $row.value)" + if (gh-bare $text) { {value: $text, description: ($row.description? | default '')} } else { + {value: ($text | to nuon), display_override: $text, description: ($row.description? | default '')} + } + } + {options: {sort: false, case_sensitive: false}, completions: $rows} +} -def "nu-complete gh workflow" [] { - ^gh workflow --help - | lines - | where { str starts-with " " } - | skip 1 - | parse "{value}: {description}" - | str trim +# Completions for everything after `gh`. +def "nu-complete gh" [token: record, place: record] { + let commands = gh-commands + let words = gh-expand-alias (gh-words $place) $commands + let spec = gh-spec $words $commands + let text = $token.text + # `place` for the completers: the resolved command followed by its arguments. + let inner = {command: ([$"gh ($spec.path)" | str trim] | append $spec.rest | append $text)} + let positionals = gh-positionals $spec + # The cursor is where a subcommand goes. + let children = $commands | where {|c| $c.path =~ $'^($spec.path | str replace -a '-' '\-') ?[a-z0-9-]+$' and $c.path != $spec.path and ($c.path | split row ' ' | length) == (($spec.path | split row ' ' | where $it != '' | length) + 1) } + if ($children | is-not-empty) and ($spec.rest | is-empty) and not ($text starts-with '-') { + let rows = $children | each {|c| {value: ($c.path | split row ' ' | last), description: $c.desc} } + let extra = if $spec.path == '' { gh-complete-kind gh-command $words } else { [] } + return ($rows | append $extra | gh-items $token) + } + if ($text starts-with '-') { + if $positionals.after_dashes { return null } + let eq = $text | parse --regex '^(?--[^=]+)=(?.*)$' | get -o 0 + if $eq != null { + let flag = $spec.flags | where long == ($eq.flag | str substring 2..) | get -o 0 + if $flag == null or $flag.kind == b { return [] } + return (gh-flag-value-rows $flag ($token | update text $eq.rest) $inner | gh-prefixed $"($eq.flag)=") + } + return (gh-flag-rows $spec) + } + if $positionals.after_dashes { return null } + # The value of the flag just before the cursor. + let prev = $spec.rest | last + if $prev in $spec.valued { + let flag = $spec.flags | where {|f| $"--($f.long)" == $prev or ($f.short != '' and $"-($f.short)" == $prev) } | get 0 + return (gh-flag-value-rows $flag $token $inner) + } + let rows = gh-complete-kind (gh-kind $spec ($positionals.words | length)) $words + if $rows == null { return null } + $rows | gh-items $token } -export extern "gh workflow" [ - command?: string@"nu-complete gh workflow" - --repo(-R) # Select another repository using the [HOST/]OWNER/REPO format - --help # Show help for command -] +def "nu-complete gh json-fields" [token: record, place: record] { + let spec = gh-spec (gh-words $place) + # gh lists the fields on stderr when `--json` has no value; it needs no network for that. + let result = try { with-env $GH_QUIET_ENV { '' | ^gh ...($spec.path | split row ' ') --json | complete } } catch { return [] } + $result.stderr | lines | skip 1 | str trim | where $it != '' | gh-rows Field | gh-items $token --multi +} + +def "nu-complete gh repos" [token: record] { gh-repos | gh-items $token --multi } -def "nu-complete gh alias" [] { - ^gh alias --help - | lines - | where { str starts-with " " } - | skip 1 - | parse "{value}: {description}" - | str trim +def "nu-complete gh labels" [token: record, place: record] { + gh-labels (gh-words $place) | gh-items $token --multi } -export extern "gh alias" [ - command?: string@"nu-complete gh alias" - --help # Show help for command -] +def "nu-complete gh users" [token: record, place: record] { + let users = gh-api (gh-words $place) 10m 'repos/{owner}/{repo}/assignees?per_page=100' '[.[].login]' + ['@me'] | append $users | gh-rows User | gh-items $token --multi +} -def "nu-complete gh api" [] { - # TODO - # endpoints - # ["graphql", "gists"] -} - -export extern "gh api" [ - --cache # Cache the response, e.g. "3600s", "60m", "1h" - --field(-F) # `key=value` Add a typed parameter in key=value format - --header(-H) # `key:value` Add a HTTP request header in key:value format - --hostname # The GitHub hostname for the request (default "github.com") - --include(-i) # Include HTTP response status line and headers in the output - --input file # The file to use as body for the HTTP request (use "-" to read from standard input) - --jq(-q) # Query to select values from the response using jq syntax - --method(-X) # The HTTP method for the request (default "GET") - --paginate # Make additional HTTP requests to fetch all pages of results - --preview(-p) # GitHub API preview names to request (without the "-preview" suffix) - --raw-field(-f) # `key:value` Add a string parameter in key=value format - --silent # Do not print the response body - --template(-t) # Format JSON output using a Go template; see "gh help formatting" - --verbose # Include full HTTP request and response in the output - --help # Show help for command - command?: string@"nu-complete gh api" -] +def "nu-complete gh me" [token: record] { ['@me'] | gh-rows 'The authenticated user' | gh-items $token } -def "nu-complete gh completion" [] { - ['bash', 'fish', 'powershell', 'zsh'] +def "nu-complete gh milestones" [token: record, place: record] { + gh-api (gh-words $place) 10m 'repos/{owner}/{repo}/milestones?state=all&per_page=100' '[.[] | {title, state, due_on}]' + | each {|m| {value: $m.title, description: $"($m.state) ($m.due_on | default '')"} } + | gh-items $token } -export extern "gh completion" [ - command?: string@"nu-complete gh completion" - --shell(-s) # Shell type: {bash|zsh|fish|powershell} - --help # Show help for command -] +def "nu-complete gh branches" [token: record, place: record] { + gh-branches (gh-words $place) | gh-rows Branch | gh-items $token +} -def "nu-complete gh config" [] { - ^gh config --help - | lines - | where { str starts-with " " } - | skip 1 - | parse "{value}: {description}" - | str trim +def "nu-complete gh cache-refs" [token: record, place: record] { + gh-branches (gh-words $place) | each {|b| $"refs/heads/($b)" } | gh-rows Ref | gh-items $token } -export extern "gh config" [ - command?: string@"nu-complete gh config" - --help # Show help for command -] +def "nu-complete gh workflows" [token: record, place: record] { + gh-complete-kind workflow (gh-words $place) | gh-items $token +} -def "nu-complete gh extension" [] { - ^gh extension --help - | lines - | where { str starts-with " " } - | skip 1 - | parse "{value}: {description}" - | str trim +def "nu-complete gh orgs" [token: record] { gh-orgs | gh-items $token } + +def "nu-complete gh owners" [token: record] { + [{value: '@me', description: 'The authenticated user'}] | append (gh-orgs) | gh-items $token --multi } -export extern "gh extension" [ - command?: string@"nu-complete gh extension" - --help # Show help for command -] +def "nu-complete gh hosts" [token: record] { + gh-hosts-file | columns | append github.com | uniq | gh-rows Host | gh-items $token +} -def "nu-complete gh gpg-key" [] { - ^gh gpg-key --help - | lines - | where { str starts-with " " } - | skip 1 - | parse "{value}: {description}" - | str trim +def "nu-complete gh accounts" [token: record] { + gh-hosts-file | items {|host, conf| + $conf.users? | default {} | columns | each {|user| {value: $user, description: $host} } + } | flatten | gh-items $token } -export extern "gh gpg-key" [ - command?: string@"nu-complete gh gpg-key" - --help # Show help for command -] +def "nu-complete gh codespaces" [token: record] { + gh-api [] 1m 'user/codespaces?per_page=100' '[.codespaces[] | {name, display_name, repo: .repository.full_name, state}]' + | each {|cs| {value: $cs.name, description: $"($cs.display_name) ($cs.repo) \(($cs.state)\)"} } + | gh-items $token +} -def "nu-complete gh label" [] { - ^gh label --help - | lines - | where { str starts-with " " } - | skip 1 - | parse "{value}: {description}" - | str trim +def "nu-complete gh environments" [token: record, place: record] { + gh-api (gh-words $place) 10m 'repos/{owner}/{repo}/environments' '[.environments[].name]' + | gh-rows Environment | gh-items $token } -export extern "gh label" [ - command?: string@"nu-complete gh label" - --repo(-R) # Select another repository using the [HOST/]OWNER/REPO format - --help # Show help for command -] +def "nu-complete gh projects" [token: record, place: record] { + let query = 'query($owner: String!, $repo: String!) { repository(owner: $owner, name: $repo) { projectsV2(first: 50) { nodes { title number } } } }' + gh-json (gh-words $place) [api --cache 10m graphql -F 'owner={owner}' -F 'repo={repo}' -f $"query=($query)" --jq '.data.repository.projectsV2.nodes'] + | default [] | each {|p| {value: $p.title, description: $"Project ($p.number)"} } + | gh-items $token --multi +} -def "nu-complete gh ruleset" [] { - ^gh ruleset --help - | lines - | where { str starts-with " " } - | skip 1 - | parse "{value}: {description}" - | str trim +def "nu-complete gh scopes" [token: record] { $GH_SCOPES | gh-rows Scope | gh-items $token --multi } + +def "nu-complete gh gitignores" [token: record] { + gh-complete-kind gitignore [] | gh-items $token } -export extern "gh ruleset" [ - command?: string@"nu-complete gh ruleset" - --repo(-R) # Select another repository using the [HOST/]OWNER/REPO format - --help # Show help for command -] +def "nu-complete gh licenses" [token: record] { + gh-complete-kind license [] | gh-items $token --multi +} -def "nu-complete gh search" [] { - ^gh search --help - | lines - | where { str starts-with " " } - | skip 1 - | parse "{value}: {description}" - | str trim -} - -export extern "gh search" [ - --extension # Filter on file extension - --filename # Filter on filename - --jq(-q) # Filter JSON output using a jq expression - --json # Output JSON with the specified fields - --language # Filter results by language - --limit(-L) # Maximum number of code results to fetch (default 30) - --match # Restrict search to file contents or file path: {file|path} - --owner # Filter on owner - --repo(-R) # Filter on repository - --size # Filter on size range, in kilobytes - --template(-t) # Format JSON output using a Go template; see "gh help formatting" - --web(-w) a # Open the search query in the web browser - --help # Show help for command - command?: string@"nu-complete gh search" -] +def "nu-complete gh issues" [token: record, place: record] { + gh-issues (gh-words $place) open | gh-items $token --multi +} -def "nu-complete gh secret" [] { - ^gh secret --help - | lines - | where { str starts-with " " } - | skip 1 - | parse "{value}: {description}" - | str trim +def "nu-complete gh issue-templates" [token: record] { + let root = gh-git-lines rev-parse --show-toplevel | get -o 0 + if $root == null { return [] } + let dir = $root | path join .github ISSUE_TEMPLATE + if not ($dir | path exists) { return [] } + ls $dir | where type == 'file' | get name + | where {|f| ($f | path parse | get extension) in [md yml yaml] and ($f | path basename) != 'config.yml' } + | each {|f| open --raw $f | lines | where $it =~ '^name:' | get -o 0 } + | compact | str replace -r '^name:\s*' '' | str trim -c '"' | str trim -c "'" + | gh-rows 'Issue template' | gh-items $token } -export extern "gh secret" [ - command?: string@"nu-complete gh secret" - --repo(-R) # Select another repository using the [HOST/]OWNER/REPO format - --help # Show help for command -] +def "nu-complete gh run-jobs" [token: record, place: record] { + let words = gh-words $place + let run = gh-run-id $words + if $run == null { return [] } + gh-api $words 1m $"repos/{owner}/{repo}/actions/runs/($run)/jobs?per_page=100" '[.jobs[] | {id, name, conclusion, status}]' + | each {|job| {value: $"($job.id)", description: $"($job.name) ($job.conclusion | default $job.status)"} } + | gh-items $token +} -def "nu-complete gh ssh-key" [] { - ^gh ssh-key --help - | lines - | where { str starts-with " " } - | skip 1 - | parse "{value}: {description}" - | str trim +def "nu-complete gh artifacts" [token: record, place: record] { + let words = gh-words $place + let run = gh-run-id $words + let endpoint = if $run == null { + 'repos/{owner}/{repo}/actions/artifacts?per_page=100' + } else { + $"repos/{owner}/{repo}/actions/runs/($run)/artifacts?per_page=100" + } + gh-api $words 1m $endpoint '[.artifacts[].name]' | uniq | gh-rows Artifact | gh-items $token } -export extern "gh ssh-key" [ - command?: string@"nu-complete gh ssh-key" - --help # Show help for command -] +def "nu-complete gh gist-files" [token: record, place: record] { + gh-gist-files (gh-words $place) | gh-items $token +} -export extern "gh status" [ - --exclude(-e) # Comma separated list of repos to exclude in owner/name format - --org(-o) # Report status within an organization - --help # Show help for command -] +def "nu-complete gh releases" [token: record, place: record] { + gh-releases (gh-words $place) | gh-items $token +} + +def "nu-complete gh commits" [token: record] { + gh-git-lines log -n 50 '--format=%h%x09%s' | split column "\t" value description | gh-items $token +} + +def "nu-complete gh repo-topics" [token: record, place: record] { + let words = gh-words $place + let repo = gh-positional $words 0 + let endpoint = if $repo == null { 'repos/{owner}/{repo}/topics' } else { $"repos/($repo)/topics" } + gh-api $words 10m $endpoint '.names' | gh-rows Topic | gh-items $token --multi +} + +def "nu-complete gh events" [token: record] { $GH_EVENTS | gh-rows Event | gh-items $token } + +def "nu-complete gh http-methods" [token: record] { + [GET POST PUT PATCH DELETE HEAD] | gh-rows 'HTTP method' | gh-items $token +} -def "nu-complete gh variable" [] { - ^gh variable --help - | lines - | where { str starts-with " " } - | skip 1 - | parse "{value}: {description}" - | str trim +def "nu-complete gh api-headers" [token: record] { + ['Accept: application/vnd.github+json' 'Accept: application/vnd.github.raw+json' + 'Accept: application/vnd.github.diff' 'X-GitHub-Api-Version: 2022-11-28'] + | gh-rows Header | gh-items $token } -export extern "gh variable" [ - command?: string@"nu-complete gh variable" - --repo(-R) # Select another repository using the [HOST/]OWNER/REPO format - --help # Show help for command +def "nu-complete gh close-reasons" [token: record] { + [completed 'not planned' duplicate] | gh-rows Reason | gh-items $token +} + +def "nu-complete gh lock-reasons" [token: record] { + [off_topic resolved spam too_heated] | gh-rows Reason | gh-items $token +} + +def "nu-complete gh archive-formats" [token: record] { + [zip tar.gz] | gh-rows Format | gh-items $token +} + + +export extern "gh" [ + ...args: external_arg@"nu-complete gh" # a gh command or alias, and its arguments ] +# Review comments of a pull request, with the diff hunk each one is attached to export def "gh pr view inlined-comments" [ - pr?: int - repo?: string # e.g. nushell/nu_scripts + pr?: int # pull request number (default: the pull request of the current branch) + repo?: string # e.g. nushell/nu_scripts (default: the current repository) ] { -# nushell/nu_scripts/pull/1105 let pr = if ($pr == null) { ^gh pr view --json number | from json | get number } else { $pr } let repo = if ($repo == null) { ^gh repo view --json name,owner | from json | select owner.login name | rename owner name @@ -560,13 +2259,13 @@ export def "gh pr view inlined-comments" [ $repo | parse '{owner}/{name}' | get 0 } - ( (gh api - -H "Accept: application/vnd.github+json" - -H "X-GitHub-Api-Version: 2022-11-28" - $"/repos/($repo.owner.)/($repo.name)/pulls/($pr)/comments") - | from json - | select user.login body diff_hunk - | rename user comment diff ) + (^gh api + -H "Accept: application/vnd.github+json" + -H "X-GitHub-Api-Version: 2022-11-28" + $"/repos/($repo.owner)/($repo.name)/pulls/($pr)/comments") + | from json + | select user.login body diff_hunk + | rename user comment diff } def "gh get stars" [ @@ -588,11 +2287,12 @@ def "gh get stars" [ | rename stars pageInfo } +# Repositories the authenticated user has starred, oldest star first export def "gh my stars" [] { mut stars = [] mut end_cursor = "" loop { - let $part = gh get stars $end_cursor + let part = gh get stars $end_cursor $stars = $stars | append $part.stars if $part.pageInfo?.hasNextPage? == true { $end_cursor = $part.pageInfo.endCursor diff --git a/custom-completions/gh/tests/gh-completions.nu b/custom-completions/gh/tests/gh-completions.nu new file mode 100644 index 00000000..c99968f1 --- /dev/null +++ b/custom-completions/gh/tests/gh-completions.nu @@ -0,0 +1,179 @@ +# Run with `nu custom-completions/gh/tests/gh-completions.nu`. +# A fake `gh` on PATH answers the calls the completers make, so no test touches the network. +use std/assert +source ../gh-completions.nu + +const FAKE_GH_BODY = r#' +printf "%s|%s\n" "${GH_REPO:-}" "$*" >> "$GH_FAKE_LOG" +case "$*" in + "alias list") echo "co: pr checkout" ;; + "extension list") printf "gh stack\tgithub/gh-stack\tv0.0.8\n" ;; + "config --help") printf '%s\n' 'Settings:' '- `git_protocol`: the protocol `{https | ssh}` (default `https`)' '- `prompt`: toggle prompting `{enabled | disabled}`' '- `editor`: the text editor' ;; + "pr list --json") printf '%s\n' 'Specify one or more comma-separated fields for `--json`:' ' author' ' number' ' title' >&2; exit 1 ;; + *"pulls?state=open"*) echo "[{\"number\":12,\"title\":\"Fix it\",\"branch\":\"fix\",\"author\":\"amy\",\"merged\":false},{\"number\":3,\"title\":\"Old\",\"branch\":\"old\",\"author\":\"bo\",\"merged\":false}]" ;; + *"pulls?state=closed"*) echo "[{\"number\":7,\"title\":\"Shipped\",\"branch\":\"s\",\"author\":\"amy\",\"merged\":true},{\"number\":8,\"title\":\"Dropped\",\"branch\":\"d\",\"author\":\"bo\",\"merged\":false}]" ;; + *"/labels?"*) + if [ "$GH_REPO" = "other/repo" ]; then echo "[{\"name\":\"other-label\",\"description\":null}]" + else echo "[{\"name\":\"bug\",\"description\":\"Broken\"},{\"name\":\"help wanted\",\"description\":null}]"; fi ;; + *"releases/tags/v1"*) echo "[{\"name\":\"app.tar.gz\",\"size\":2048}]" ;; + *"user/repos"*) echo "[{\"name\":\"me/tool\",\"description\":\"A tool\"}]" ;; + *) exit 1 ;; +esac +'# + +def with-fake-gh [test: closure] { + let dir = mktemp -d + let log = $dir | path join calls.log + $"#!/bin/sh($FAKE_GH_BODY)" | save ($dir | path join gh) + ^chmod +x ($dir | path join gh) + # gh's config (aliases) and data (extensions) directories, read directly by the completer. + mkdir ($dir | path join config) ($dir | path join data gh extensions gh-stack) + "aliases:\n co: pr checkout\n bugs: issue list --label=bug\n hi: '!echo hi'\n" | save ($dir | path join config config.yml) + let original = pwd + try { + cd $dir + let env_vars = { + PATH: ($env.PATH | prepend $dir), GH_FAKE_LOG: $log + GH_CONFIG_DIR: ($dir | path join config), XDG_DATA_HOME: ($dir | path join data) + } + with-env $env_vars { do $test $log } + cd $original + rm -r $dir + } catch {|error| + cd $original + rm -r $dir + error make $error + } +} + +# Argument completions for `line`, leaving out subcommand names. +def values-of [line: string]: nothing -> list { + $line | commandline complete --detailed | where kind? != command + | each {|row| $row.display_override? | default $row.value } +} + +def calls [log: string]: nothing -> list { + if ($log | path exists) { open --raw $log | lines } else { [] } +} + +def "top level offers aliases and extensions next to subcommands" [] { + with-fake-gh {|log| + let top = values-of 'gh ' + for name in [pr issue repo api co bugs stack] { assert ($name in $top) $name } + assert equal (values-of 'gh pr li') [list] + assert ('view' in (values-of 'gh pr ')) + assert equal (values-of 'gh extension remove ') [stack] + assert equal (calls $log) [] + } +} + +def "user aliases complete like the command they stand for" [] { + with-fake-gh {|log| + assert equal (values-of 'gh co ') ['12' '3'] + assert ('--state' in (values-of 'gh bugs --st')) + # A shell alias is never run; it just gets no argument completions. + assert equal (values-of 'gh hi ') [] + } +} + +def "pull requests are completed by state" [] { + with-fake-gh {|log| + assert equal (values-of 'gh pr view ') ['12' '3'] + assert equal (values-of 'gh pr reopen ') ['8'] + assert equal (values-of 'gh pr revert ') ['7'] + # A command alias resolves to the command it stands for. + assert equal (values-of 'gh pr co ') ['12' '3'] + let detailed = 'gh pr view ' | commandline complete --detailed + assert equal $detailed.0.description 'Fix it [fix] by amy' + } +} + +def "flag names never reach the network" [] { + with-fake-gh {|log| + let values = values-of 'gh pr view --' + for flag in [--repo --json --web --comments --help] { assert ($flag in $values) $flag } + assert ('-w' in (values-of 'gh pr view -')) + assert equal (calls $log) [] + } +} + +def "the second slot follows the first" [] { + with-fake-gh {|log| + assert equal (values-of 'gh release delete-asset v1 ') ['app.tar.gz'] + assert equal (values-of 'gh config set prompt ') ['enabled' 'disabled'] + assert equal (values-of 'gh config get ') ['git_protocol' 'prompt' 'editor'] + } +} + +def "labels follow --repo and quote names with spaces" [] { + with-fake-gh {|log| + let rows = 'gh issue list --label ' | commandline complete --detailed + assert equal ($rows | where value == bug | length) 1 + let spaced = $rows | where display_override? == 'help wanted' + assert equal ($spaced.0.value | from nuon) 'help wanted' + let multi = 'gh issue list --label bug,he' | commandline complete --detailed + assert equal ($multi.0.value | from nuon) 'bug,help wanted' + assert equal (values-of 'gh issue list -R other/repo --label ') ['other-label'] + assert equal (values-of 'gh issue list --repo=other/repo --label ') ['other-label'] + assert ((calls $log) | any {|call| $call starts-with 'other/repo|' }) + } +} + +def "json fields come from gh and accept comma lists" [] { + with-fake-gh {|log| + assert equal (values-of 'gh pr list --json ') ['author' 'number' 'title'] + assert equal (values-of 'gh pr list --json number,ti') ['number,title'] + } +} + +def "static values come from the help text" [] { + with-fake-gh {|log| + assert equal (values-of 'gh issue list --state ' | sort) ['all' 'closed' 'open'] + let reasons = 'gh issue close 1 --reason ' | commandline complete --detailed + let planned = $reasons | where display_override? == 'not planned' + assert equal ($planned.0.value | from nuon) 'not planned' + assert equal (values-of 'gh completion --shell ' | sort) ['bash' 'fish' 'powershell' 'zsh'] + } +} + +def "failures and flag values stay quiet" [] { + with-fake-gh {|log| + # The fake gh fails for issues, as gh does outside a repository or offline. + assert equal (values-of 'gh issue view ') [] + # A value with nothing to suggest (`-L `) gets no suggestions. + assert equal (values-of 'gh pr list -L ') [] + } +} + +def "arguments reach gh exactly as typed" [] { + with-fake-gh {|log| + let printer = '#!/bin/sh +for a in "$@"; do printf "%s\n" "$a"; done +' + $printer | save -f gh + ^chmod +x gh + assert equal (gh release edit v1.0 --draft=false | lines) [release edit v1.0 --draft=false] + assert equal (gh api x -f body='Hi there' | lines) [api x -f 'body=Hi there'] + assert equal (gh workflow view 0451 | lines) [workflow view '0451'] + let n = 5 + assert equal (gh pr view $n -R o/r | lines) [pr view '5' -R o/r] + assert equal (gh pr list -L5 | lines) [pr list -L5] + assert equal (gh release download v1 --pattern=*.tar.gz | lines) [release download v1 '--pattern=*.tar.gz'] + assert equal (gh co -p 12 | lines) [co -p '12'] + } +} + +if $nu.os-info.family == windows { + print 'skipped: the fake gh is a POSIX shell script' +} else { + top level offers aliases and extensions next to subcommands + user aliases complete like the command they stand for + pull requests are completed by state + flag names never reach the network + the second slot follows the first + labels follow --repo and quote names with spaces + json fields come from gh and accept comma lists + static values come from the help text + failures and flag values stay quiet + arguments reach gh exactly as typed +} diff --git a/custom-completions/git/git-completions.nu b/custom-completions/git/git-completions.nu index 647b4153..d0a0fa09 100644 --- a/custom-completions/git/git-completions.nu +++ b/custom-completions/git/git-completions.nu @@ -1,8 +1,25 @@ -# nu-version: 0.102.0 +# nu-version: 0.116.1 +# +# Completions for git and every git alias in your config. One `git` extern with no declared flags +# hands the whole command line to `nu-complete git`, which +# - skips global options (and completes in the repository `-C`/`--git-dir` point at), +# - expands git aliases (`git co` completes like `git checkout`), +# - reads a builtin's flags from its own `-h` output when you complete a word starting with `-` +# (never for aliases or scripts, which could run anything; see GIT_NO_HELP), +# - completes flag values, subcommands, branches, remotes, tags, commits, stashes, worktrees, +# submodules, config keys and changed files. +# Declaring no flags means nushell passes every argument to git exactly as typed. module git-completion-utils { export const GIT_SKIPABLE_FLAGS = ['-v', '--version', '-h', '--help', '-p', '--paginate', '-P', '--no-pager', '--no-replace-objects', '--bare'] + # Run git and return its stdout lines; empty when git fails (e.g. outside a repository), + # so completers never print git's errors over the prompt. Stdin is empty so nothing waits on it. + export def --wrapped git-lines [...args: string]: nothing -> list { + let result = try { '' | ^git ...$args | complete } catch { return [] } + if $result.exit_code == 0 { $result.stdout | lines } else { [] } + } + # Helper function to append token if non-empty def append-non-empty [token: string]: list -> list { if ($token | is-empty) { $in } else { $in | append $token } @@ -66,28 +83,74 @@ module git-completion-utils { $result } - # Porcelain v2's -z form contains literal pathnames, including quotes and newlines. - # Ordinary changes use type 1; every unmerged XY state uses type u. - def status-paths [--include-unmerged]: nothing -> list { - let pattern = if $include_unmerged { - '(?s)^(?:1 [.MD]{2} (?:\S+ ){6}|u (?:DD|AU|UD|UA|DU|AA|UU) (?:\S+ ){8})(?.+)$' - } else { - '(?s)^1 [.MD]{2} (?:\S+ ){6}(?.+)$' - } - ^git --no-optional-locks status -uno --porcelain=2 -z + # Path of the current directory inside the repository (`sub/dir/`), or '' at its top. + export def repo-prefix []: nothing -> string { + git-lines rev-parse --show-prefix | get -o 0 | default '' + } + + # Turn repository-root-relative paths into paths relative to the current directory. + export def from-repo-root [prefix?: string]: list -> list { + let paths = $in + let prefix = if $prefix == null { repo-prefix } else { $prefix } + if ($prefix | is-empty) { return $paths } + let up = $prefix | str trim --right --char '/' | split row '/' | each { '..' } | str join '/' + $paths | each {|path| if ($path starts-with $prefix) { $path | str substring ($prefix | str length).. } else { $"($up)/($path)" } } + } + + # Split `git status --porcelain=2 -z` output into records. A renamed/copied entry owns the next + # NUL field (its original pathname), which must not be read as a record of its own. + def status-records [text: string]: nothing -> list { + $text | split row "\u{0}" | generate {|record, skip_old_name| if $skip_old_name { {next: false} - } else if $record starts-with '2 ' { - # A renamed/copied entry owns the next NUL field: its original pathname. - {next: true} } else { - {out: $record, next: false} + {out: $record, next: ($record starts-with '2 ')} } } false - | parse --regex $pattern - | get value + } + + # Porcelain v2 `-z` records of `git status`; pathnames are literal (quotes and newlines kept). + # Each row: {xy: two status letters ('??' for untracked), path: repo-root-relative path}. + export def status-entries [--untracked, --prefix: string]: nothing -> list> { + let entries = status-parse (if $untracked { '--untracked-files=normal' } else { '--untracked-files=no' }) + if not $untracked { return $entries } + # Untracked directories are collapsed (`sub/`); when that is the current directory, list + # the files inside it instead. + let prefix = if $prefix == null { repo-prefix } else { $prefix } + if ($prefix | is-empty) or ($entries | where {|e| $e.xy == '??' and $e.path == $prefix } | is-empty) { return $entries } + $entries | where path != $prefix | append (status-parse '--untracked-files=all' '--' '.' | where xy == '??') + } + + def status-parse [...args: string]: nothing -> list> { + let result = try { '' | ^git --no-optional-locks status --porcelain=2 -z ...$args | complete } catch { return [] } + if $result.exit_code != 0 { return [] } + status-records $result.stdout + | each {|record| + let match = match ($record | str substring 0..0) { + '1' => ($record | parse --regex '(?s)^1 (?\S\S) (?:\S+ ){6}(?.+)$') + '2' => ($record | parse --regex '(?s)^2 (?\S\S) (?:\S+ ){7}(?.+)$') + 'u' => ($record | parse --regex '(?s)^u (?\S\S) (?:\S+ ){8}(?.+)$') + '?' => ($record | parse --regex '(?s)^\? (?.+)$' | insert xy '??') + _ => [] + } + $match | get -o 0 + } + | compact + | select xy path + } + + # Ordinary changes use type 1; every unmerged XY state uses type u. + def status-paths [--include-unmerged]: nothing -> list { + let pattern = if $include_unmerged { + '(?s)^(?:1 [.MD]{2} (?:\S+ ){6}|u (?:DD|AU|UD|UA|DU|AA|UU) (?:\S+ ){8})(?.+)$' + } else { + '(?s)^1 [.MD]{2} (?:\S+ ){6}(?.+)$' + } + let result = try { '' | ^git --no-optional-locks status -uno --porcelain=2 -z | complete } catch { return [] } + if $result.exit_code != 0 { return [] } + status-records $result.stdout | where not ($it starts-with '2 ') | parse --regex $pattern | get value } # Get changed files which can be restored by `git checkout --`. @@ -101,12 +164,39 @@ module git-completion-utils { $in | each {|path| {value: ($path | to nuon), display_override: $path, description: File, style: green} } } + # Describe a porcelain XY status pair for the completion menu. + export def describe-status [xy: string]: nothing -> string { + match $xy { + '??' => 'Untracked' + 'DD' | 'AU' | 'UD' | 'UA' | 'DU' | 'AA' | 'UU' => 'Unmerged' + _ => { + let staged = match ($xy | str substring 0..0) { + 'M' => 'modified', 'T' => 'type changed', 'A' => 'added', 'D' => 'deleted', 'R' => 'renamed', 'C' => 'copied', _ => '' + } + let unstaged = match ($xy | str substring 1..1) { + 'M' => 'modified', 'T' => 'type changed', 'D' => 'deleted', 'A' => 'added', _ => '' + } + [(if ($staged | is-empty) { null } else { $"Staged ($staged)" }) (if ($unstaged | is-empty) { null } else { $"Unstaged ($unstaged)" })] + | compact | str join ', ' + } + } + } + + # Completion rows for status entries, quoted as Nu source and relative to the current directory. + export def format-status-files [prefix?: string]: list> -> list { + let entries = $in + let paths = $entries | get path | from-repo-root $prefix + $entries | zip $paths | each {|pair| + {value: ($pair.1 | to nuon), display_override: $pair.1, description: (describe-status $pair.0.xy), style: green} + } + } + export def get-all-git-local-refs []: nothing -> list> { - ^git for-each-ref --format '%(refname:lstrip=2)%09%(objectname:short)%09%(upstream:remotename)%(upstream:track)%09%(contents:subject)' refs/heads | lines | parse "{ref}\t{obj}\t{upstream}\t{subject}" + git-lines for-each-ref '--format=%(refname:lstrip=2)%09%(objectname:short)%09%(upstream:remotename)%(upstream:track)%09%(contents:subject)' refs/heads | parse "{ref}\t{obj}\t{upstream}\t{subject}" } export def get-all-git-remote-refs []: nothing -> list> { - ^git for-each-ref --format '%(refname:lstrip=2)%09%(objectname:short)%09%(contents:subject)' refs/remotes | lines | parse "{ref}\t{obj}\t{subject}" + git-lines for-each-ref '--format=%(refname:lstrip=2)%09%(objectname:short)%09%(contents:subject)' refs/remotes | parse "{ref}\t{obj}\t{subject}" | where ref !~ '/HEAD$' } # Get local branches, remote branches which can be passed to `git merge` @@ -115,100 +205,1155 @@ module git-completion-utils { let remote = get-all-git-remote-refs | each {|x| {value: $x.ref description: $'Branch, Remote, ($x.obj) ($x.subject)'} } | insert style 'blue_italic' $local | append $remote } + + # Branches, remote branches, tags and pseudo refs, for any argument naming a revision. + export def get-refs []: nothing -> list> { + let refs = git-lines for-each-ref '--format=%(refname)%09%(objectname:short) %(contents:subject)' refs/heads refs/remotes refs/tags + | parse "{ref}\t{subject}" + | each {|row| + let kind = if ($row.ref starts-with 'refs/heads/') { 'Branch' } else if ($row.ref starts-with 'refs/tags/') { 'Tag' } else { 'Remote branch' } + {value: ($row.ref | str replace -r '^refs/(heads|tags|remotes)/' ''), description: $"($kind), ($row.subject)"} + } + | where value !~ '/HEAD$' + $refs | append ([HEAD FETCH_HEAD ORIG_HEAD MERGE_HEAD] | each {|ref| {value: $ref, description: 'Pseudo ref'} }) + } + + # The most recent commits reachable from any branch, newest first. + export def get-recent-commits [--limit: int = 300]: nothing -> list> { + git-lines log --branches --remotes --tags $'--max-count=($limit)' '--format=%h%x09%s' + | parse "{value}\t{description}" + | update description {|row| $"Commit, ($row.description)" } + } + + # The first argument that names a configured remote, if any. `words` is `place.command`, whose + # first element is the command name (e.g. "git pull"). + export def find-remote [words: list]: nothing -> any { + let remotes = git-lines remote + $words | skip 1 | where {|word| $word in $remotes } | get -o 0 + } + + # One option spec as git prints it (`-F, --[no-]file `, `--abbrev[=]`) as records: + # {short, long, neg, value: none|req|opt, ph}. + export def parse-spec [spec: string]: nothing -> list { + # `-NUM`, `-`: numeric shorthands such as `git log -5`. + if ($spec =~ '^-(NUM|<)') { return [] } + if ($spec | str contains ' | ') { + return ($spec | split row ' | ' | each {|s| parse-spec ($s | str trim) } | flatten) + } + mut rest = $spec + mut short: any = null + mut long: any = null + mut neg = false + mut value = 'none' + mut ph = '' + if ($rest =~ '^-[^-]') { + $short = ($rest | str substring 1..1) + $rest = ($rest | str substring 2..) + if ($rest | str starts-with ', ') { + $rest = ($rest | str substring 2..) + } else { + # short-only option; the rest is its value spec + if ($rest | is-not-empty) { + $value = if ($rest | str starts-with '[') { 'opt' } else { 'req' } + $ph = ($rest | str trim) + } + $rest = '' + } + } + if ($rest | str starts-with '--') { + if ($rest | str starts-with '--[no-]') { + $neg = true + $rest = '--' + ($rest | str substring 7..) + } + let m = $rest | parse --regex '^--(?[A-Za-z0-9][A-Za-z0-9-]*)(?.*)$' + if ($m | is-empty) { return [] } + $long = $m.0.name + let tail = $m.0.tail + if ($tail | str starts-with '[=') { + $value = 'opt' + } else if ($tail | str starts-with '=') or ($tail | str starts-with ' ') { + $value = 'req' + } else if ($tail | is-not-empty) { + $value = 'opt' + } + $ph = ($tail | str trim --left --char '=' | str trim) + } + let short = if $short != null and ($short =~ '^[A-Za-z0-9]$') { $short } else { null } + if $short == null and $long == null { return [] } + [{short: $short, long: $long, neg: $neg, value: $value, ph: $ph}] + } + + # Options from git's parse-options `-h` output. Descriptions start at column 26, on the same + # line or the next one. + export def parse-help [text: string]: nothing -> list { + let lines = $text | lines + let n = $lines | length + mut out = [] + mut i = 0 + while $i < $n { + let line = $lines | get $i + if not ($line =~ '^ {2,}-') { + $i += 1 + continue + } + let indent = ($line | str length) - ($line | str trim --left | str length) + let next_line = $lines | get -o ($i + 1) | default '' + let gap = $line | str substring 24..25 + # A one-space gap before column 26 also appears in long specs such as + # `--[no-]color-moved-ws `, whose description is on the next line. + let same_line = ($line | str length) > 26 and $indent == 4 and ($line | str substring 26..26) != ' ' and ($gap == ' ' or (($gap | str ends-with ' ') and not ($next_line =~ '^ {26}\S'))) + let parts = if $same_line { + {spec: ($line | str substring ..25 | str trim), desc: ($line | str substring 26.. | str trim)} + } else if ($line | str trim | str contains ' ') { + # Legacy layouts (diff-tree's common diff options) separate with 2+ spaces. + let cols = $line | str trim | split row -r '\s{2,}' + {spec: $cols.0, desc: ($cols | skip 1 | str join ' ')} + } else { + {spec: ($line | str trim), desc: ''} + } + mut desc = $parts.desc + mut j = $i + 1 + while $j < $n { + let next = $lines | get $j + let nindent = ($next | str length) - ($next | str trim --left | str length) + if ($next | str trim | is-empty) or $nindent < 24 or ($next =~ '^ {2,}-' and $nindent < 26) { break } + $desc = ($desc + ' ' + ($next | str trim) | str trim) + $j += 1 + } + let d = $desc + $out = ($out | append (parse-spec $parts.spec | each {|o| $o | insert desc $d })) + $i = $j + } + $out + } } +# Every command `git --list-cmds=main` knows. A word on the line that is not one of these is +# looked up as an alias. +const GIT_COMMANDS = [ + add am annotate apply archimport archive backfill bisect blame branch bugreport bundle + cat-file check-attr check-ignore check-mailmap check-ref-format checkout checkout--worker checkout-index cherry cherry-pick clean clone + column commit commit-graph commit-tree config count-objects credential credential-cache credential-cache--daemon credential-netrc credential-osxkeychain credential-store + cvsexportcommit cvsimport cvsserver daemon describe diagnose diff diff-files diff-index diff-pairs diff-tree difftool + difftool--helper fast-export fast-import fetch fetch-pack filter-branch fmt-merge-msg for-each-ref for-each-repo format-patch format-rev fsck + fsck-objects fsmonitor--daemon gc get-tar-commit-id grep hash-object help history hook http-backend http-fetch http-push + imap-send index-pack init init-db instaweb interpret-trailers jump last-modified log ls-files ls-remote ls-tree + mailinfo mailsplit maintenance merge merge-base merge-file merge-index merge-octopus merge-one-file merge-ours merge-recursive merge-recursive-ours + merge-recursive-theirs merge-resolve merge-subtree merge-tree mergetool mktag mktree multi-pack-index mv name-rev notes p4 + pack-objects pack-redundant pack-refs patch-id pickaxe prune prune-packed pull push quiltimport range-diff read-tree + rebase receive-pack reflog refs remote remote-ext remote-fd remote-ftp remote-ftps remote-http remote-https repack + replace replay repo request-pull rerere reset restore rev-list rev-parse revert rm send-email + send-pack sh-i18n--envsubst shell shortlog show show-branch show-index show-ref sparse-checkout stage stash status + stripspace submodule submodule--helper subtree switch symbolic-ref tag unpack-file unpack-objects update-index update-ref update-server-info + upload-archive upload-archive--writer upload-pack url-parse var verify-commit verify-pack verify-tag version web--browse whatchanged worktree + write-tree +] + +# Builtins whose `-h` lists their options. Only these are ever run with `-h`: an alias or a +# script could do anything when invoked, and bisect/credential/rerere take subcommands that +# are not option parsers. +const GIT_BUILTINS = [ + add am annotate apply archive backfill blame branch bugreport bundle cat-file + check-attr check-ignore check-mailmap check-ref-format checkout checkout-index cherry cherry-pick clean clone column commit + commit-graph commit-tree config count-objects describe diagnose diff diff-files diff-index diff-pairs diff-tree + difftool fast-export fast-import fetch fmt-merge-msg for-each-ref for-each-repo format-patch format-rev fsck fsck-objects gc + grep hash-object help history hook init init-db interpret-trailers last-modified log ls-files ls-remote + ls-tree maintenance merge merge-base merge-file merge-index merge-tree mktag mktree multi-pack-index mv name-rev + notes pack-redundant pack-refs patch-id pickaxe prune prune-packed pull push range-diff read-tree rebase + reflog refs remote repack replace replay repo reset restore rev-list rev-parse + revert rm shortlog show show-branch show-ref sparse-checkout stage stash status stripspace switch + symbolic-ref tag update-index update-ref update-server-info url-parse var verify-commit verify-pack verify-tag version whatchanged + worktree write-tree +] + +# Builtin subcommands that do not treat `-h` as a help request: `git stash create -h` writes a +# stash commit named "-h". The git tests run every other `-h` the completer can spawn and check +# that it prints usage and changes nothing. +const GIT_NO_HELP = ['stash create'] + +# Global options that take the next word as their value (`git -C log`). +const GIT_GLOBAL_VALUED = [-C -c --git-dir --work-tree --namespace --config-env --attr-source] + +# Commands that also take the revision options of `git log` / the diff options of `git diff`. +const GIT_WITH_REV = [log show whatchanged rev-list shortlog format-patch reflog "reflog show" last-modified fast-export "bisect visualize" "bisect view"] +const GIT_WITH_DIFF = [diff log show whatchanged format-patch diff-tree diff-index diff-files "stash show" reflog "reflog show" difftool "bisect visualize" "bisect view"] +# Their own `-h` is a legacy summary; the shared sets describe these options better. +const GIT_LEGACY_HELP = [rev-list diff-files diff-index diff-tree] + +# Short options whose value is usually attached (`-Xtheirs`): offer `-X` forms. +const GIT_STUCK_SHORTS = [X S G L I O] +# Revision options git only parses as `--opt=value`. +const GIT_EQ_ONLY = [format min-parents max-parents] +# Options documented as `--opt ` whose value git lets you omit. +const GIT_LASTARG_DEFAULT = [contains no-contains with without merged no-merged points-at] + +const GIT_PRETTY_FORMATS = [oneline short medium full fuller reference email raw mboxrd "format:" "tformat:"] +const GIT_DATE_FORMATS = [relative local iso iso8601 iso-strict iso8601-strict rfc rfc2822 short raw human unix default "format:" "format-local:"] +const GIT_CONFIG_TYPES = [bool int bool-or-int bool-or-str path expiry-date color] + +# Values for options, by long name: an inline list, a completer kind (see `git-complete-kind`), +# `path` for nushell's own path completion, or a record keyed by command (`_` = any other). +const GIT_FLAG_VALUES = { + onto: refs + source: {restore: refs, checkout: refs, check-attr: refs, _: null} + attr-source: refs + set-upstream-to: upstreams + contains: commits + no-contains: commits + with: commits + without: commits + merged: refs + no-merged: refs + points-at: refs + strategy: {notes: [manual ours theirs union cat_sort_uniq], _: [ort recursive resolve octopus ours subtree]} + strategy-option: [ours theirs ignore-space-change ignore-all-space ignore-space-at-eol ignore-cr-at-eol renormalize no-renormalize find-renames "find-renames=" "rename-threshold=" "subtree=" diff-algorithm=patience diff-algorithm=minimal diff-algorithm=histogram diff-algorithm=myers] + cleanup: [strip whitespace verbatim scissors default] + untracked-files: [no normal all] + ignored: [traditional no matching] + ignore-submodules: [none untracked dirty all] + color: [always never auto] + color-moved: [no default plain blocks zebra dimmed-zebra] + color-moved-ws: [no ignore-space-at-eol ignore-space-change ignore-all-space allow-indentation-change] + diff-algorithm: [default myers minimal patience histogram] + word-diff: [color plain porcelain none] + date: {commit: null, am: null, rebase: null, history: null, _: $GIT_DATE_FORMATS} + pretty: $GIT_PRETTY_FORMATS + format: { + log: $GIT_PRETTY_FORMATS, show: $GIT_PRETTY_FORMATS, whatchanged: $GIT_PRETTY_FORMATS + rev-list: $GIT_PRETTY_FORMATS, shortlog: $GIT_PRETTY_FORMATS, reflog: $GIT_PRETTY_FORMATS + "reflog show": $GIT_PRETTY_FORMATS, format-rev: $GIT_PRETTY_FORMATS, format-patch: $GIT_PRETTY_FORMATS + archive: [tar tgz tar.gz zip], "repo info": [lines nul], "repo structure": [table lines nul], _: null + } + decorate: [short full auto no] + diff-merges: [off none on first-parent 1 separate m combined c dense-combined cc remerge r] + recurse-submodules: {push: [check on-demand only no], fetch: [yes on-demand no], pull: [yes on-demand no], _: null} + conflict: [merge diff3 zdiff3] + rebase: {pull: [false true merges interactive], _: null} + whitespace: [nowarn warn fix error error-all] + empty: {rebase: [drop keep stop], cherry-pick: [drop keep stop], "history drop": [drop keep abort], "history fixup": [drop keep abort], _: null} + rebase-merges: [rebase-cousins no-rebase-cousins] + submodule: [short log diff] + ws-error-highlight: [context old new all default none] + column: [always never auto column row plain dense nodense] + sort: [refname -refname committerdate -committerdate creatordate -creatordate authordate -authordate taggerdate -taggerdate version:refname -version:refname objectsize -objectsize objecttype upstream HEAD] + type: {config: $GIT_CONFIG_TYPES, "config get": $GIT_CONFIG_TYPES, "config set": $GIT_CONFIG_TYPES, "config list": $GIT_CONFIG_TYPES, _: null} + mirror: [fetch push] + track: {"remote add": null, _: [direct inherit]} + chmod: ["+x" "-x"] + shared: [false true umask group all world everybody] + object-format: [sha1 sha256] + ref-format: [files reftable] + filter: ["blob:none" "blob:limit=" "tree:0" "tree:1" "sparse:oid=" "object:type=blob" "object:type=tree" "combine:"] + schedule: [hourly daily weekly] + task: [gc commit-graph prefetch loose-objects incremental-repack pack-refs reflog-expire rerere-gc worktree-prune] + scheduler: [auto crontab systemd-timer launchctl schtasks] + tool: [araxis bc bc3 bc4 codecompare deltawalker diffmerge diffuse ecmerge emerge examdiff guiffy gvimdiff kdiff3 kompare meld nvimdiff opendiff p4merge smerge tkdiff tortoisemerge vimdiff vscode winmerge xxdiff] + remote: {archive: remotes, _: null} + repo: {push: remotes, _: null} + author: {commit: null, _: authors} + committer: authors + fixup: commits + squash: {commit: commits, _: null} + reuse-message: commits + reedit-message: commits + template: {commit: path, clone: path, init: path, _: null} + file: path + output: path + output-directory: path + pathspec-from-file: path + git-dir: path + work-tree: path + reference: path + reference-if-able: path + separate-git-dir: path + to-stdin: path + object-dir: path + refs-snapshot: path + exec-path: path + base: {format-patch: refs, _: null} + interdiff: refs + range-diff: refs + notes: notes-refs + ref: {notes: notes-refs, _: null} + negotiation-tip: refs + shallow-exclude: refs + find-object: refs + ancestry-path: commits + merge-base: {merge-tree: refs, _: null} + signed: [true false if-asked] + show-current-patch: [diff raw] + patch-format: [mbox mboxrd stgit stgit-series hg] + quoted-cr: [nowarn warn strip] + update-refs: [branches head] + exclude-hidden: [fetch receive uploadpack] + disk-usage: [human] + missing: [error allow-any allow-promisor print] + confirm: [always never auto cc compose] + suppress-cc: [author self cc bodycc sob cccmd body all] + transfer-encoding: [7bit 8bit quoted-printable base64 auto] + thread: [shallow deep] + split: [no-merge replace] + component: [protocol user password host port path] + list-cmds: [main others alias nohelpers config parseopt] + path-format: [absolute relative] + show-object-format: [storage input output] + abbrev-ref: [strict loose] + output-object-format: [sha1 sha256] + stdin-mode: [revs objects] + no-walk: [sorted unsorted] + mode: {column: [always never auto column row plain dense nodense], _: null} + config: {clone: config-keys, _: null} +} +# Options of commands git cannot describe itself (scripts, non parse-options builtins) and the +# revision (@rev) and diff (@diff) options shared by log, show, diff, ... One option per line: +# command, short, long, value (none|req|opt), negatable (1 = also --no-), placeholder, description. +const GIT_OPTIONS = r#' + C req run as if git was started in + c req = pass a configuration parameter to the command + config-env req = pass a configuration parameter from an environment variable + exec-path opt [=] path to the core git programs, or print it + html-path none print the path where git's HTML documentation is installed + man-path none print the manpath for this version of git + info-path none print the path where the Info files are installed + p paginate none pipe all output into less (or $PAGER) + P no-pager none do not pipe git output into a pager + git-dir req set the path to the repository (".git" directory) + work-tree req set the path to the working tree + namespace req set the git namespace + bare none treat the repository as a bare repository + no-replace-objects none do not use replacement refs to replace git objects + no-lazy-fetch none do not fetch missing objects from the promisor remote on demand + no-optional-locks none do not perform optional operations that require locks + no-advice none disable all advice hints from being printed + literal-pathspecs none treat pathspecs literally + glob-pathspecs none add "glob" magic to all pathspecs + noglob-pathspecs none add "literal" magic to all pathspecs + icase-pathspecs none add "icase" magic to all pathspecs + list-cmds req list commands by group + attr-source req read gitattributes from instead of the worktree + v version none print the git suite version +bisect start term-new req term for the new (bad) state +bisect start term-bad req term for the bad (new) state +bisect start term-old req term for the old (good) state +bisect start term-good req term for the good (old) state +bisect start no-checkout none do not checkout the new working tree at each iteration +bisect start first-parent none follow only the first parent commit upon seeing a merge commit +bisect start reset-when-found opt [=] reset the bisection when the first bad commit is found +bisect terms term-good none show the term for the old state +bisect terms term-old none show the term for the old state +bisect terms term-bad none show the term for the new state +bisect terms term-new none show the term for the new state +bisect run reset-when-found opt [=] reset the bisection when the first bad commit is found +diff cached none show changes staged for the next commit relative to +diff staged none synonym for --cached +diff merge-base none use the merge base of and HEAD instead of +diff no-index none compare two paths on the filesystem +diff 1 base none compare the working tree with the base version +diff 2 ours none compare the working tree with our branch +diff 3 theirs none compare the working tree with their branch +diff 0 none omit diff output for unmerged entries and just show "Unmerged" +mergetool t tool req use the merge resolution program specified by +mergetool tool-help none print a list of merge tools that may be used with --tool +mergetool y no-prompt none do not prompt before launching a merge resolution program +mergetool prompt none prompt before each invocation of the merge resolution program +mergetool g gui none use the configured merge.guitool +mergetool no-gui none use the configured merge.tool +mergetool O req process files in the order specified in +submodule q quiet none only print error messages +submodule cached none use the commit stored in the index instead of the submodule HEAD +submodule add b branch req branch of repository to add as submodule +submodule add f force none allow adding an otherwise ignored submodule path +submodule add name req name of the new submodule +submodule add reference req reference repository +submodule add depth req create a shallow clone truncated to that many revisions +submodule add q quiet none only print error messages +submodule status cached none use the commit stored in the index +submodule status recursive none recurse into nested submodules +submodule status q quiet none only print error messages +submodule init q quiet none only print error messages +submodule deinit f force none unregister the submodule even if its working tree has local modifications +submodule deinit all none unregister all submodules +submodule deinit q quiet none only print error messages +submodule update init none initialize all submodules for which git submodule init has not been called +submodule update filter req use a partial clone filter when cloning +submodule update remote none use the status of the submodule's remote-tracking branch +submodule update N no-fetch none do not fetch new objects from the remote site +submodule update f force none throw away local changes in submodules when switching commits +submodule update checkout none check out the superproject's recorded commit in a detached HEAD +submodule update merge none merge the superproject's recorded commit into the submodule branch +submodule update rebase none rebase the submodule branch onto the superproject's recorded commit +submodule update recommend-shallow none use the shallow recommendation in .gitmodules +submodule update no-recommend-shallow none ignore the shallow recommendation in .gitmodules +submodule update reference req reference repository +submodule update dissociate none borrow objects from the reference repository only during the clone +submodule update recursive none recurse into nested submodules +submodule update depth req create a shallow clone truncated to that many revisions +submodule update j jobs req number of submodules fetched at the same time +submodule update single-branch none clone only one branch +submodule update no-single-branch none clone all branches +submodule update progress none force progress reporting +submodule update q quiet none only print error messages +submodule set-branch d default none remove the branch configuration and use the remote HEAD +submodule set-branch b branch req branch to track +submodule set-branch q quiet none only print error messages +submodule set-url q quiet none only print error messages +submodule summary cached none use the commit stored in the index +submodule summary files none compare the commit in the index with the submodule HEAD +submodule summary n summary-limit req limit the summary size +submodule summary q quiet none only print error messages +submodule foreach recursive none recurse into nested submodules +submodule foreach q quiet none only print error messages +submodule sync recursive none recurse into nested submodules +submodule sync q quiet none only print error messages +submodule absorbgitdirs q quiet none only print error messages +request-pull p none show patch text as well +jump stdout none print the quickfix list to stdout instead of opening an editor +rev-parse parseopt none use git rev-parse in option parsing mode +rev-parse sq-quote none use git rev-parse in shell quoting mode +rev-parse keep-dashdash none only meaningful in --parseopt mode +rev-parse stop-at-non-option none only meaningful in --parseopt mode +rev-parse stuck-long none only meaningful in --parseopt mode +rev-parse revs-only none do not output flags and parameters not meant for rev-list +rev-parse no-revs none do not output flags and parameters meant for rev-list +rev-parse flags none do not output non-flag parameters +rev-parse no-flags none do not output flag parameters +rev-parse default req use if there is no parameter given +rev-parse prefix req behave as if invoked from the subdirectory +rev-parse verify none verify that exactly one parameter is given and it can be turned into a raw SHA-1 +rev-parse q quiet none only meaningful in --verify mode; do not output an error message +rev-parse sq none output a single line properly quoted for shell consumption +rev-parse short opt [=] shorten the object name to a unique prefix +rev-parse not none prefix object names with ^ +rev-parse abbrev-ref opt [=] a non-ambiguous short name of the object's name +rev-parse symbolic none output names in a form as close to the original input as possible +rev-parse symbolic-full-name none like --symbolic, but omit input that are not refs +rev-parse output-object-format req output object names in this hash format +rev-parse all none show all refs found in refs/ +rev-parse branches opt [=] show all branches +rev-parse tags opt [=] show all tags +rev-parse remotes opt [=] show all remote-tracking branches +rev-parse glob req show all refs matching the shell glob pattern +rev-parse exclude req do not include refs matching the pattern +rev-parse exclude-hidden req
do not include refs hidden by the given section +rev-parse disambiguate req show every object whose name begins with the given prefix +rev-parse local-env-vars none list the GIT_* environment variables that are local to the repository +rev-parse path-format req control whether paths are absolute or relative +rev-parse git-dir none show $GIT_DIR if defined, otherwise the path to the .git directory +rev-parse git-common-dir none show $GIT_COMMON_DIR if defined, else $GIT_DIR +rev-parse resolve-git-dir req check if is a valid repository or a gitfile +rev-parse git-path req resolve $GIT_DIR/ taking relocation variables into account +rev-parse show-toplevel none show the absolute path of the top-level directory of the working tree +rev-parse show-superproject-working-tree none show the root of the superproject's working tree +rev-parse shared-index-path none show the path to the shared index file in split index mode +rev-parse absolute-git-dir none like --git-dir, but the output is always canonicalized +rev-parse is-inside-git-dir none print true if the cwd is below the repository directory +rev-parse is-inside-work-tree none print true if the cwd is inside the work tree +rev-parse is-bare-repository none print true if the repository is bare +rev-parse is-shallow-repository none print true if the repository is shallow +rev-parse show-cdup none show the path of the top-level directory relative to the cwd +rev-parse show-prefix none show the path of the cwd relative to the top-level directory +rev-parse show-object-format opt [=] show the object format (hash algorithm) used for the repository +rev-parse show-ref-format none show the reference storage format used for the repository +rev-parse since req parse the date and output the corresponding --max-age= parameter +rev-parse after req parse the date and output the corresponding --max-age= parameter +rev-parse until req parse the date and output the corresponding --min-age= parameter +rev-parse before req parse the date and output the corresponding --min-age= parameter +filter-branch setup req setup command run once before the loop +filter-branch subdirectory-filter req only look at the history which touches the given subdirectory +filter-branch env-filter req filter for modifying the commit environment +filter-branch tree-filter req filter for rewriting the tree and its contents +filter-branch index-filter req filter for rewriting the index +filter-branch parent-filter req filter for rewriting the commit's parent list +filter-branch msg-filter req filter for rewriting the commit messages +filter-branch commit-filter req filter for performing the commit +filter-branch tag-name-filter req filter for rewriting tag names +filter-branch original req namespace where the original commits will be stored +filter-branch d req use this temporary directory for rewriting +filter-branch f force none start even if there is an existing temporary directory or backup +filter-branch state-branch req load and store the mapping from old to new objects in this branch +filter-branch prune-empty none remove commits that become empty +rerere rerere-autoupdate none register clean resolutions in index +instaweb l local none 1 only bind on 127.0.0.1 +instaweb p port req 1 ... the port to bind to +instaweb d httpd req 1 ... the command to launch +instaweb b browser req 1 ... the browser to launch +instaweb m module-path req 1 ... the module path (only needed for apache2) +instaweb stop none 1 stop the web server +instaweb start none 1 start the web server +instaweb restart none 1 restart the web server +subtree q quiet none quiet +subtree d debug none show debug messages +subtree P prefix req 1 ... the name of the subdir to split out +subtree annotate req 1 ... add a prefix to commit message of new commits +subtree b branch req ... create a new branch from the split subtree +subtree ignore-joins none 1 ignore prior --rejoin commits +subtree onto req 1 ... try connecting new tree to an existing one +subtree rejoin none 1 merge the new branch back into HEAD +subtree squash none 1 merge subtree changes as a single commit +subtree m message req ... use the given message as the commit message for the merge commit +subtree S gpg-sign opt 1 [=] GPG-sign commits. The keyid argument is optional and defaults to the committer identity +send-email from req Email From: +send-email to req 1 Email To: +send-email cc req 1 Email Cc: +send-email bcc req 1 Email Bcc: +send-email subject req Email "Subject:" +send-email reply-to req Email "Reply-To:" +send-email in-reply-to req Email "In-Reply-To:" +send-email outlook-id-fix none 1 The SMTP host is an Outlook server that munges the Message-ID; retrieve it from the server +send-email xmailer none 1 Add "X-Mailer:" header (default). +send-email annotate none 1 Review each patch that will be sent in an editor. +send-email compose none Open an editor for introduction. +send-email compose-encoding req Encoding to assume for introduction. +send-email 8bit-encoding req Encoding to assume 8bit mails if undeclared +send-email transfer-encoding req Transfer encoding to use (quoted-printable, 8bit, base64) +send-email mailmap none 1 Use mailmap file to map all email addresses to canonical real names and email addresses +send-email envelope-sender req Email envelope sender. +send-email sendmail-cmd req Command to run to send email. +send-email smtp-server req Outgoing SMTP server to use; the port is optional (default 'localhost') +send-email smtp-server-option req Outgoing SMTP server option to use. +send-email smtp-server-port req Outgoing SMTP server port. +send-email smtp-user req Username for SMTP-AUTH. +send-email smtp-pass req Password for SMTP-AUTH; not necessary. +send-email smtp-encryption req tls or ssl; anything else disables. +send-email smtp-ssl none Deprecated. Use `--smtp-encryption ssl`. +send-email smtp-ssl-cert-path req Path to ca-certificates (either directory or file). +send-email smtp-ssl-client-cert req Path to the client certificate file +send-email smtp-ssl-client-key req Path to the private key file for the client certificate +send-email smtp-domain req The domain name sent to HELO/EHLO handshake +send-email smtp-auth req Space-separated list of allowed AUTH mechanisms, or "none" to disable authentication +send-email no-smtp-auth none Disable SMTP authentication; shorthand for `--smtp-auth=none` +send-email smtp-debug req <0|1> Disable, enable Net::SMTP debug. +send-email imap-sent-folder req IMAP folder where a copy of the emails should be sent. +send-email use-imap-only none 1 Only copy emails to the IMAP folder given by --imap-sent-folder instead of sending them +send-email batch-size req send max message per connection. +send-email relogin-delay req delay seconds between two successive login. +send-email identity req Use the sendemail. options. +send-email to-cmd req Email To: via ` $patch_path`. +send-email cc-cmd req Email Cc: via ` $patch_path`. +send-email header-cmd req Add headers via ` $patch_path`. +send-email no-header-cmd none Disable any header command in use. +send-email suppress-cc req author, self, sob, cc, cccmd, body, bodycc, misc-by, all. +send-email cc-cover none 1 Email Cc: addresses in the cover letter. +send-email to-cover none 1 Email To: addresses in the cover letter. +send-email signed-off-by-cc none 1 Send to Signed-off-by: addresses. Default on. +send-email suppress-from none 1 Send to self. Default off. +send-email chain-reply-to none 1 Chain In-Reply-To: fields. Default off. +send-email thread none 1 Use In-Reply-To: field. Default on. +send-email confirm req Confirm recipients before sending: auto, cc, compose, always or never +send-email quiet none Output one line of info per email. +send-email dry-run none Don't actually send the emails. +send-email validate none 1 Perform patch sanity checks. Default on. +send-email format-patch none 1 Understand any non-optional arguments as `git format-patch` ones +send-email force none Send even if safety checks would prevent it. +send-email dump-aliases none Dump configured aliases and exit. +send-email translate-aliases none Translate aliases read from standard input using the configured alias files +@rev n max-count req limit the number of commits to output +@rev skip req skip number commits before starting to show the output +@rev since req show commits more recent than a specific date +@rev after req show commits more recent than a specific date +@rev since-as-filter req show all commits more recent than a specific date +@rev until req show commits older than a specific date +@rev before req show commits older than a specific date +@rev max-age req limit output to commits newer than a timestamp +@rev min-age req limit output to commits older than a timestamp +@rev author req limit to commits whose author matches the pattern +@rev committer req limit to commits whose committer matches the pattern +@rev grep-reflog req limit to commits whose reflog message matches the pattern +@rev grep req limit to commits whose log message matches the pattern +@rev all-match none limit to commits that match all given --grep patterns +@rev invert-grep none limit to commits whose log message does not match --grep +@rev i regexp-ignore-case none match the limiting patterns without regard to case +@rev basic-regexp none treat the limiting patterns as basic regular expressions +@rev E extended-regexp none treat the limiting patterns as extended regular expressions +@rev F fixed-strings none treat the limiting patterns as fixed strings +@rev P perl-regexp none treat the limiting patterns as Perl-compatible regular expressions +@rev remove-empty none stop when a given path disappears from the tree +@rev merges none print only merge commits +@rev no-merges none do not print commits with more than one parent +@rev min-parents req show only commits with at least that many parents +@rev max-parents req show only commits with at most that many parents +@rev no-min-parents none reset the --min-parents limit +@rev no-max-parents none reset the --max-parents limit +@rev first-parent none follow only the first parent commit upon seeing a merge commit +@rev exclude-first-parent-only none follow only the first parent when excluding commits +@rev not none reverse the meaning of the ^ prefix for following revisions +@rev all none pretend all refs in refs/ and HEAD are listed on the command line +@rev branches opt [=] pretend all refs in refs/heads are listed +@rev tags opt [=] pretend all refs in refs/tags are listed +@rev remotes opt [=] pretend all refs in refs/remotes are listed +@rev glob req pretend all refs matching the shell glob are listed +@rev exclude req do not include refs matching the glob in the next --all/--branches/--tags/--remotes/--glob +@rev exclude-hidden req
do not include refs hidden by the given transfer section +@rev reflog none pretend all objects mentioned by reflogs are listed +@rev alternate-refs none pretend the tips of alternate repositories are listed +@rev single-worktree none examine only the current worktree's HEAD, index and reflogs +@rev ignore-missing none ignore invalid object names in the input +@rev bisect none pretend the bad bisection ref and good refs are listed +@rev stdin none read commits and pathspecs from standard input +@rev cherry-mark none like --cherry-pick but mark equivalent commits with = instead of omitting them +@rev cherry-pick none omit commits that introduce the same change as a commit on the other side +@rev left-only none list only commits on the left side of a symmetric difference +@rev right-only none list only commits on the right side of a symmetric difference +@rev cherry none synonym for --right-only --cherry-mark --no-merges +@rev g walk-reflogs none walk reflog entries instead of the commit ancestry chain +@rev merge none show commits touching conflicted paths in the range HEAD... +@rev boundary none output excluded boundary commits +@rev simplify-by-decoration none show only commits referred to by some branch or tag +@rev show-pulls none include merges that are not TREESAME to the first parent +@rev full-history none do not prune history when simplifying by path +@rev dense none show only commits that touch the given paths (default) +@rev sparse none show all walked commits +@rev simplify-merges none remove needless merges from the --full-history result +@rev ancestry-path opt [=] show only commits that are ancestors or descendants of the given commit +@rev date-order none show no parents before all children, in commit timestamp order +@rev author-date-order none show no parents before all children, in author timestamp order +@rev topo-order none show no parents before all children, avoiding interleaved histories +@rev reverse none output the selected commits in reverse order +@rev no-walk opt [=] only show the given commits, do not traverse their ancestors +@rev do-walk none override a previous --no-walk +@rev pretty opt [=] pretty-print the commit logs in the given format +@rev format req pretty-print the commit logs in the given format +@rev abbrev opt [=] show object names with at least hexdigits +@rev no-abbrev none show full object names +@rev abbrev-commit none show a prefix of the commit object name +@rev no-abbrev-commit none show the full commit object name +@rev oneline none shorthand for --pretty=oneline --abbrev-commit +@rev encoding req re-code the commit log message in this encoding +@rev expand-tabs opt [=] expand tabs in the log message +@rev no-expand-tabs none do not expand tabs in the log message +@rev notes opt [=] show the notes that annotate the commit +@rev no-notes none do not show notes +@rev show-notes-by-default none show the default notes unless options for displaying specific notes are given +@rev show-signature none check the validity of a signed commit object +@rev relative-date none synonym for --date=relative +@rev date req format for dates shown in human-readable form +@rev parents none also print the parents of the commit +@rev children none also print the children of the commit +@rev left-right none mark which side of a symmetric difference a commit is reachable from +@rev graph none draw a text-based graphical representation of the commit history +@rev show-linear-break opt [=] put a barrier between two consecutive commits that are not linear +@rev c none show combined diff format for merge commits +@rev cc none show dense combined diff format for merge commits +@rev dd none show diff relative to the first parent for merges and regular commits +@rev m none show diffs for merge commits in the default format +@rev diff-merges req specify the diff format to be used for merge commits +@rev no-diff-merges none disable output of diffs for merge commits +@rev combined-all-paths none show the name of the file from all parents in combined diffs +@rev t none show the tree objects in the diff output +@rev log-size none include a line with the log message length in bytes +@rev follow none continue listing the history of a file beyond renames +@rev count none print a number stating how many commits would have been listed +@diff p patch none generate patch +@diff s no-patch none suppress diff output +@diff u none generate patch +@diff U unified opt [=] generate diffs with lines context +@diff W function-context none 1 show the whole function as context lines +@diff raw none generate the diff in raw format +@diff patch-with-raw none synonym for '-p --raw' +@diff patch-with-stat none synonym for '-p --stat' +@diff numstat none machine friendly --stat +@diff shortstat none output only the last line of --stat +@diff X dirstat opt [=,...] output the distribution of relative amount of changes for each sub-directory +@diff cumulative none synonym for --dirstat=cumulative +@diff dirstat-by-file opt [=,...] synonym for --dirstat=files,,... +@diff check none warn if changes introduce conflict markers or whitespace errors +@diff summary none condensed summary such as creations, renames and mode changes +@diff name-only none show only names of changed files +@diff name-status none show only names and status of changed files +@diff stat opt [=[,[,]]] generate diffstat +@diff stat-width req generate diffstat with a given width +@diff stat-name-width req generate diffstat with a given name width +@diff stat-graph-width req generate diffstat with a given graph width +@diff stat-count req generate diffstat with limited lines +@diff compact-summary none 1 generate compact summary in diffstat +@diff binary none output a binary diff that can be applied +@diff full-index none 1 show full pre- and post-image object names on the "index" lines +@diff color opt 1 [=] show colored diff +@diff ws-error-highlight req highlight whitespace errors in the 'context', 'old' or 'new' lines in the diff +@diff z none do not munge pathnames and use NULs as output field terminators in --raw or --numstat +@diff abbrev opt 1 [=] use digits to display object names +@diff src-prefix req show the given source prefix instead of "a/" +@diff dst-prefix req show the given destination prefix instead of "b/" +@diff line-prefix req prepend an additional prefix to every line of output +@diff no-prefix none do not show any source or destination prefix +@diff default-prefix none use default prefixes a/ and b/ +@diff inter-hunk-context req show context between diff hunks up to the specified number of lines +@diff output-indicator-new req specify the character to indicate a new line instead of '+' +@diff output-indicator-old req specify the character to indicate an old line instead of '-' +@diff output-indicator-context req specify the character to indicate a context instead of ' ' +@diff B break-rewrites opt [=[/]] break complete rewrite changes into pairs of delete and create +@diff M find-renames opt [=] detect renames +@diff D irreversible-delete none omit the preimage for deletes +@diff C find-copies opt [=] detect copies +@diff find-copies-harder none 1 use unmodified files as source to find copies +@diff no-renames none disable rename detection +@diff rename-empty none 1 use empty blobs as rename source +@diff follow none 1 continue listing the history of a file beyond renames +@diff l req limit to cheap rename/copy detection if the number of rename/copy targets exceeds this value +@diff minimal none produce the smallest possible diff +@diff w ignore-all-space none ignore whitespace when comparing lines +@diff b ignore-space-change none ignore changes in amount of whitespace +@diff ignore-space-at-eol none ignore changes in whitespace at EOL +@diff ignore-cr-at-eol none ignore carrier-return at the end of line +@diff ignore-blank-lines none ignore changes whose lines are all blank +@diff I ignore-matching-lines req 1 ignore changes whose all lines match +@diff indent-heuristic none 1 heuristic to shift diff hunk boundaries for easy reading +@diff patience none generate diff using the "patience diff" algorithm +@diff histogram none generate diff using the "histogram diff" algorithm +@diff diff-algorithm req choose a diff algorithm +@diff anchored req generate diff using the "anchored diff" algorithm +@diff word-diff opt [=] show word diff, using to delimit changed words +@diff word-diff-regex req use to decide what a word is +@diff color-words opt [=] equivalent to --word-diff=color --word-diff-regex= +@diff color-moved opt 1 [=] moved lines of code are colored differently +@diff color-moved-ws req 1 how white spaces are ignored in --color-moved +@diff relative opt 1 [=] when run from subdir, exclude changes outside and show relative paths +@diff a text none 1 treat all files as text +@diff R none swap two inputs, reverse the diff +@diff exit-code none 1 exit with 1 if there were differences, 0 otherwise +@diff quiet none 1 disable all output of the program +@diff ext-diff none 1 allow an external diff helper to be executed +@diff textconv none 1 run external text conversion filters when comparing binary files +@diff ignore-submodules opt [=] ignore changes to submodules in the diff generation +@diff submodule opt [=] specify how differences in submodules are shown +@diff ita-invisible-in-index none hide 'git add -N' entries from the index +@diff ita-visible-in-index none treat 'git add -N' entries as real in the index +@diff S req look for differences that change the number of occurrences of the specified string +@diff G req look for differences that change the number of occurrences of the specified regex +@diff pickaxe-all none show all changes in the changeset with -S or -G +@diff pickaxe-regex none treat in -S as extended POSIX regular expression +@diff O req control the order in which files appear in the output +@diff rotate-to req show the change in the specified path first +@diff skip-to req skip the output to the specified path +@diff find-object req look for differences that change the number of occurrences of the specified object +@diff diff-filter req [(A|C|D|M|R|T|U|X|B)...[*]] select files by diff type +@diff max-depth req maximum tree depth to recurse +@diff output req output to a specific file +'# + +const GIT_SUBCOMMANDS = r#' +stash list List the stash entries that you currently have +stash show Show the changes recorded in a stash entry +stash drop Remove a single stash entry from the list of stash entries +stash pop Remove a single stashed state and apply it on top of the working tree +stash apply Like pop, but do not remove the state from the stash list +stash branch Create and check out a new branch starting from a stash entry +stash push Save local modifications to a new stash entry and roll them back to HEAD +stash save Save local modifications to a new stash entry (deprecated, use push) +stash clear Remove all the stash entries +stash create Create a stash entry and return its object name without storing it +stash store Store a stash entry created via git stash create +stash export Export the stash entries as a chain of commits +stash import Import stash entries from a chain of commits +remote add Add a remote named for the repository at +remote rename Rename the remote named to +remote remove Remove the remote named +remote rm Remove the remote named +remote set-head Set or delete the default branch for the named remote +remote show Give some information about the remote +remote prune Delete stale references associated with +remote update Fetch updates for remotes or remote groups +remote set-branches Change the list of branches tracked by the named remote +remote get-url Retrieve the URLs for a remote +remote set-url Change URLs for the remote +worktree add Create a worktree at and checkout into it +worktree list List details of each worktree +worktree lock Prevent a worktree from being pruned, moved or deleted +worktree move Move a worktree to a new location +worktree prune Prune worktree information in $GIT_DIR/worktrees +worktree remove Remove a worktree +worktree repair Repair worktree administrative files +worktree unlock Unlock a worktree, allowing it to be pruned, moved or deleted +notes list List the notes object for a given object, or all notes +notes add Add notes for a given object +notes copy Copy the notes for the first object onto the second object +notes append Append new message(s) to an existing note +notes edit Edit the notes for a given object +notes show Show the notes for a given object +notes merge Merge the given notes ref into the current notes ref +notes remove Remove the notes for given objects +notes prune Remove all notes for non-existing/unreachable objects +notes get-ref Print the current notes ref +reflog show Show the log of a reference +reflog list List all references which have a reflog +reflog exists Check whether a ref has a reflog +reflog write Write a new entry to the reflog of a reference +reflog delete Delete single entries from the reflog +reflog drop Remove the reflog of the given references completely +reflog expire Prune older reflog entries +config list List all variables set in config file, along with their values +config get Emit the value of the specified key +config set Set value for one or more config options +config unset Unset value for one or more config options +config rename-section Rename the given section to a new name +config remove-section Remove the given section from the configuration file +config edit Open an editor to modify the specified config file +bundle create Create a bundle file +bundle verify Check that a bundle file is valid and will apply cleanly +bundle list-heads List the references defined in the bundle +bundle unbundle Store the objects in the bundle in the repository +commit-graph verify Read the commit-graph file and verify its contents +commit-graph write Write a commit-graph file +multi-pack-index write Write a new multi-pack-index file +multi-pack-index compact Compact a range of incremental multi-pack-index layers +multi-pack-index verify Verify the contents of the multi-pack-index file +multi-pack-index expire Delete pack-files that are tracked by the multi-pack-index but unused +multi-pack-index repack Create a new pack-file containing objects in small pack-files +maintenance run Run one or more maintenance tasks +maintenance start Start running maintenance on the current repository +maintenance stop Halt the background maintenance schedule +maintenance register Add the current repository to the maintenance.repo config +maintenance unregister Remove the current repository from background maintenance +maintenance is-needed Check whether maintenance needs to be run +sparse-checkout init Enable the sparse-checkout setting (deprecated) +sparse-checkout list Describe the directories or patterns in the sparse-checkout file +sparse-checkout set Enable sparse-checkout and write a set of patterns +sparse-checkout add Add directories or patterns to the sparse-checkout +sparse-checkout reapply Reapply the sparsity pattern rules to paths in the working tree +sparse-checkout disable Disable sparse-checkout and restore the full working tree +sparse-checkout check-rules Check whether sparsity rules match one or more paths +sparse-checkout clean Remove files outside the sparse-checkout definition +hook run Run the hook with the given name +hook list List the commands configured for the given hook +refs migrate Migrate ref store between different formats +refs verify Verify reference database consistency +refs list List references in the repository +refs exists Check whether the given reference exists +refs optimize Optimize references to improve repository performance +refs create Create a reference +refs delete Delete a reference +refs update Update a reference +repo info Retrieve metadata-related information about the repository +repo structure Retrieve statistics about the repository structure +history drop Drop a commit from the history +history fixup Fix up a commit with the staged changes +history reword Rewrite the commit message of a commit +history split Split a commit into two +bisect start Start a bisect session +bisect bad Mark a revision as bad (containing the change) +bisect new Mark a revision as new (containing the change) +bisect good Mark revisions as good (before the change) +bisect old Mark revisions as old (before the change) +bisect terms Show the terms used for the current bisect session +bisect skip Skip the current or the given revisions +bisect next Find the next bisection commit to test +bisect reset End the bisect session and return to the original or given commit +bisect visualize Show the remaining suspects in a viewer +bisect view Show the remaining suspects in a viewer +bisect replay Replay a bisect log +bisect log Show the bisect log +bisect run Bisect automatically using a script +bisect help Show a short usage summary +submodule add Add the given repository as a submodule +submodule status Show the status of the submodules +submodule init Initialize the submodules recorded in the index +submodule deinit Unregister the given submodules +submodule update Update the registered submodules to match the superproject +submodule set-branch Set the default remote tracking branch for the submodule +submodule set-url Set the URL of the specified submodule +submodule summary Show a commit summary between the given commit and the working tree/index +submodule foreach Evaluate an arbitrary shell command in each checked out submodule +submodule sync Synchronize submodules' remote URL configuration +submodule absorbgitdirs Move the git directory of submodules into the superproject +subtree add Create the subtree by importing its contents +subtree merge Merge recent changes up to into the subtree +subtree split Extract a new, synthetic project history from the subtree +subtree pull Fetch from and merge into the subtree +subtree push Split the subtree and push it to +rerere clear Reset the metadata used by rerere +rerere forget Reset the conflict resolutions which rerere has recorded +rerere diff Display diffs for the current state of the resolution +rerere status Print paths with conflicts whose resolution rerere will record +rerere remaining Print paths with conflicts that have not been autoresolved by rerere +rerere gc Prune records of conflicted merges that occurred a long time ago +credential fill Fill in missing credential fields +credential approve Store a credential as good +credential reject Erase a credential +credential capability Announce the capabilities of git credential +'# + +const GIT_POSITIONALS = r#' + command?:git-command +add ...pathspec:add +stage ...pathspec:add +am ...mbox:paths +annotate ...args:paths-or-refs +apply ...patch:paths +archive tree_ish?:refs ...path:paths +bisect ...args:none +bisect start ...rev:commits +bisect bad rev?:commits +bisect new rev?:commits +bisect good ...rev:commits +bisect old ...rev:commits +bisect skip ...rev:commits +bisect reset commit?:commits +bisect replay logfile:paths +bisect run cmd:paths ...args:paths +bisect visualize ...args:refs-or-paths +bisect view ...args:refs-or-paths +blame ...args:paths-or-refs +branch ...args:branch +bundle create file:paths ...rev:refs +bundle verify file:paths +bundle list-heads file:paths ...refname:full-refs +bundle unbundle file:paths ...refname:full-refs +cat-file ...object:refs +check-attr ...pathname:paths +check-ignore ...pathname:paths +checkout ...targets:checkout +cherry upstream?:mergeable head?:mergeable limit?:commits +cherry-pick ...commit:commits +clean ...pathspec:untracked +clone repository?:none directory?:paths +commit ...pathspec:commit-files +commit-tree tree:refs +config name?:config-keys value?:none +config get name:config-keys +config set name:config-keys value:none +config unset name:config-keys +config rename-section old_name:config-sections new_name:none +config remove-section name:config-sections +credential ...args:none +daemon ...directory:paths +describe ...commit_ish:refs +diff ...args:diff +diff-files ...path:paths +diff-index tree_ish?:refs ...path:paths +diff-tree tree_ish?:refs ...args:refs-or-paths +difftool ...args:diff +fast-export ...rev:refs +fetch repository?:remotes ...refspec:remote-refs +filter-branch ...rev:refs +for-each-ref ...pattern:full-refs +format-patch ...revision:refs +fsck ...object:refs +grep ...args:paths-or-refs +hash-object ...file:paths +help command?:help +history drop commit:commits +history fixup commit:commits +history reword commit:commits +history split commit:commits ...pathspec:paths +hook run hook_name:hooks ...args:none +hook list hook_name:hooks +init directory?:paths +interpret-trailers ...file:paths +jump mode?:jump-mode ...args:paths +last-modified ...args:refs-or-paths +log ...args:refs-or-paths +ls-files ...file:paths +ls-remote repository?:remotes ...patterns:none +ls-tree tree_ish:refs ...path:paths +merge ...commit:mergeable +merge-base ...commit:refs +merge-file current:paths base:paths other:paths +merge-tree ...commit:refs +mergetool ...file:conflicted +mv ...source:paths +name-rev ...commit:refs +notes ...args:none +notes list object?:refs +notes add object?:refs +notes copy from_object:refs to_object:refs +notes append object?:refs +notes edit object?:refs +notes show object?:refs +notes merge notes_ref?:notes-refs +notes remove ...object:refs +prune ...head:refs +pull repository?:remotes ...refspec:remote-refs +push remote?:remotes ...refs:push +range-diff ...range:refs +read-tree ...tree_ish:refs +rebase upstream?:rebase branch?:branches +reflog ref?:refs ...args:refs-or-paths +reflog show ref?:refs ...args:refs-or-paths +reflog exists ref:full-refs +reflog write ref:full-refs old_oid:refs new_oid:refs message:none +reflog delete ...entry:reflog +reflog drop ...ref:full-refs +reflog expire ...ref:full-refs +refs exists ref:full-refs +refs list ...pattern:full-refs +refs create ref:full-refs new_value:refs +refs delete ref:full-refs old_value?:refs +refs update ref:full-refs new_value:refs old_value?:refs +remote ...args:none +remote add name:none url:none +remote rename old:remotes new:none +remote remove name:remotes +remote rm name:remotes +remote set-head name:remotes branch?:remote-refs +remote show ...name:remotes +remote prune ...name:remotes +remote update ...group_or_remote:remotes +remote set-branches name:remotes ...branch:remote-refs +remote get-url name:remotes +remote set-url name:remotes newurl:none oldurl?:none +replace object?:refs replacement?:refs +replay ...revision_range:refs +repo info ...key:repo-keys +request-pull start:refs url:none end?:refs +rerere forget ...pathspec:paths +reset ...targets:reset +restore ...pathspec:restore +rev-list ...commit:refs +rev-parse ...args:refs +revert ...commit:commits +rm ...pathspec:paths +send-email ...file:paths +shortlog ...revision_range:refs +show ...object:refs-or-paths +show-branch ...rev:refs +show-ref ...pattern:refs +sparse-checkout set ...dir:paths +sparse-checkout add ...dir:paths +stash ...pathspec:paths +stash show stash?:stashes +stash drop stash?:stashes +stash pop stash?:stashes +stash apply stash?:stashes +stash branch branchname:none stash?:stashes +stash push ...pathspec:paths +stash save message?:none +stash create message?:none +stash store commit:refs +stash export ...stash:stashes +stash import commit:refs +status ...pathspec:paths +submodule ...args:none +submodule add repository:none path?:paths +submodule status ...path:submodules +submodule init ...path:submodules +submodule deinit ...path:submodules +submodule update ...path:submodules +submodule set-branch path:submodules +submodule set-url path:submodules newurl:none +submodule summary commit?:refs ...path:submodules +submodule foreach command:none ...args:none +submodule sync ...path:submodules +submodule absorbgitdirs ...path:submodules +subtree add repository_or_commit:remotes ref?:none +subtree merge commit:refs +subtree split commit?:refs +subtree pull repository:remotes ref:none +subtree push repository:remotes refspec:none +switch branch?:switch start_point?:refs +symbolic-ref name:full-refs ref?:full-refs +tag ...args:tag +update-index ...file:paths +update-ref ref:full-refs new_value?:refs old_value?:refs +var variable?:git-var +verify-commit ...commit:commits +verify-tag ...tag:tags +whatchanged ...args:refs-or-paths +worktree ...args:none +worktree add path:paths commit_ish?:refs +worktree lock worktree:worktrees +worktree move worktree:worktrees new_path:paths +worktree remove worktree:worktrees +worktree repair ...path:paths +worktree unlock worktree:worktrees +'# + +const GIT_DESC_FALLBACK = r#' +grep or combine the surrounding patterns with OR (the default) +grep not negate the following pattern +grep and combine the surrounding patterns with AND +combined-all-paths show the name of the file from all parents in combined diffs +rev-list quiet do not print anything to standard output +rev-list objects also print the IDs of objects referenced by the listed commits +rev-list objects-edge like --objects, but also print the IDs of excluded commits +rev-list unpacked only print objects that are not in packs +rev-list header print the contents of the commit in raw format +rev-list object-names print the names of objects found by --objects +rev-list z separate commits and objects with NUL characters +rev-list bisect-vars print variables ready to be eval'ed by the shell for bisection +rev-list bisect-all output all commits between included and excluded commits, ordered by distance +'# + def "nu-complete git available upstream" [] { - ^git for-each-ref --format '%(refname:short)' refs/heads refs/remotes | lines + use git-completion-utils [git-lines] + git-lines for-each-ref '--format=%(refname:short)' refs/heads refs/remotes } def "nu-complete git remotes" [] { - ^git remote --verbose - | lines + use git-completion-utils [git-lines] + git-lines remote --verbose | parse --regex '^(?\S+)\s+(?.+) \((?:fetch|push)\)$' | uniq-by value # Deduplicate where fetch and push remotes are the same } -def "nu-complete git log" [] { - ^git log --pretty=%h | lines | each { |line| $line | str trim } -} - -# Yield all existing commits in descending chronological order. -def "nu-complete git commits all" [] { - ^git rev-list --all --remotes --pretty=oneline | lines | parse "{value} {description}" -} - -# Yield commits of current branch only. This is useful for e.g. cut points in -# `git rebase`. -def "nu-complete git commits current branch" [] { - ^git log --pretty="%h %s" | lines | parse "{value} {description}" +# Branches of the remote named earlier on the line (`git pull origin `). +def "nu-complete git remote refs" [place?: record] { + use git-completion-utils [git-lines find-remote] + let remote = find-remote ($place.command? | default []) + if $remote == null { return (git-lines for-each-ref '--format=%(refname:short)' refs/heads) } + let prefix = $'refs/remotes/($remote)/' + git-lines for-each-ref '--format=%(refname)' $prefix + | each {|ref| $ref | str replace $prefix '' } + | where $it != 'HEAD' } # Yield local branches like `main`, `feature/typo_fix` def "nu-complete git local branches" [] { - ^git for-each-ref --format '%(refname:short)' refs/heads | lines -} - -# Yield remote branches like `origin/main`, `upstream/feature-a` -def "nu-complete git remote branches with prefix" [] { - ^git for-each-ref --format='%(refname:lstrip=2)' refs/remotes | lines + use git-completion-utils [git-lines] + git-lines for-each-ref '--format=%(refname:short)' refs/heads } # Yield local and remote branch names which can be passed to `git merge` def "nu-complete git mergable sources" [] { - use git-completion-utils * - let branches = get-mergable-sources + use git-completion-utils [get-mergable-sources] { options: { case_sensitive: false, completion_algorithm: prefix, sort: false, }, - completions: $branches + completions: (get-mergable-sources) } } -def "nu-complete git switch" [] { - use git-completion-utils * - let branches = get-mergable-sources - { - options: { - case_sensitive: false, - completion_algorithm: prefix, - sort: false, - }, - completions: $branches - } +# Any revision: branches, remote branches, tags and pseudo refs. +def "nu-complete git refs" [] { + use git-completion-utils [get-refs] + {options: {sort: false}, completions: (get-refs)} } -def "nu-complete git checkout" [buffer: string, place?: record] { - use git-completion-utils * - let preceding = $buffer | str substring ..$place.cursor - # See what user typed before, like 'git checkout a-branch a-path'. - # We exclude some flags from previous tokens, to detect if a branch name has been used as the first argument. - # FIXME: This method is still naive, though. - let prev_tokens = $preceding | str trim | args-split | where ($it not-in $GIT_SKIPABLE_FLAGS) - # In these scenarios, we suggest only file paths, not branch: - # - After '--' - # - First arg is a branch - # If before '--' is just 'git checkout' (or its alias), we suggest "dirty" files only (user is about to reset file). - if $prev_tokens.2? == '--' { +# Revisions plus recent commits, for commands that usually take a single commit. +def "nu-complete git commits" [] { + use git-completion-utils [get-refs get-recent-commits] + {options: {sort: false}, completions: (get-refs | append (get-recent-commits))} +} + +# Fully qualified ref names, for plumbing that wants `refs/heads/main` rather than `main`. +def "nu-complete git full refs" [] { + use git-completion-utils [git-lines] + ['HEAD'] | append (git-lines for-each-ref '--format=%(refname)') +} + +# `git checkout` arguments. `words` are the arguments after `checkout`, ending with the word +# being completed. +def git-checkout-candidates [words: list]: nothing -> any { + use git-completion-utils [git-lines get-changed-files get-checkoutable-files format-checkout-files get-mergable-sources GIT_SKIPABLE_FLAGS] + # Earlier arguments, without flags that do not change what comes next. + let prev = $words | drop 1 | where ($it not-in $GIT_SKIPABLE_FLAGS) + # Only paths after `--`; right after a leading `--` only changed files (about to be reset). + if $prev.0? == '--' { return (get-changed-files | format-checkout-files) } - if '--' in $prev_tokens { + if '--' in $prev { return (get-checkoutable-files | format-checkout-files) } - # Already typed first argument. - if ($prev_tokens | length) > 2 and $preceding ends-with ' ' { - # If we are creating a new branch, we may want to specify a start point - if ("-b" not-in $prev_tokens) and ("-B" not-in $prev_tokens) and ("--orphan" not-in $prev_tokens) { - return (get-checkoutable-files | format-checkout-files) - } + # Past the first argument only paths follow, unless a new branch still takes a start point. + if ($prev | is-not-empty) and ([-b -B --orphan] | all {|flag| $flag not-in $prev }) { + return (get-checkoutable-files | format-checkout-files) } # The first argument can be local branches, remote branches, files and commits - # Get local and remote branches let branches = get-mergable-sources let files = get-checkoutable-files | format-checkout-files - let commits = ^git rev-list -n 400 --remotes --oneline | lines | split column -n 2 ' ' value description | upsert description {|x| $'Commit, ($x.value) ($x.description)' } | insert style 'light_cyan_dimmed' + let commits = git-lines rev-list -n 400 --remotes --oneline | split column -n 2 ' ' value description | upsert description {|x| $'Commit, ($x.value) ($x.description)' } | insert style 'light_cyan_dimmed' { options: { case_sensitive: false, @@ -219,227 +1364,39 @@ def "nu-complete git checkout" [buffer: string, place?: record] { } } -# Arguments to `git rebase --onto ` -def "nu-complete git rebase" [] { - (nu-complete git local branches) - | parse "{value}" - | insert description "local branch" - | append (nu-complete git remote branches with prefix - | parse "{value}" - | insert description "remote branch") - | append (nu-complete git commits all) -} - -def "nu-complete git stash-list" [] { - git stash list | lines | parse "{value}: {description}" -} - -def "nu-complete git tags" [] { - ^git tag --no-color | lines +# The words of the command line in `buffer` up to the cursor, ending with the word being +# completed ('' after a space). +def git-buffer-words [buffer: string, place?: record]: nothing -> list { + use git-completion-utils [args-split] + let preceding = $buffer | str substring ..($place.cursor? | default ($buffer | str length)) + let words = $preceding | args-split + if ($preceding | is-empty) or ($preceding ends-with ' ') { $words | append '' } else { $words } } -# See `man git-status` under "Short Format" -# This is incomplete, but should cover the most common cases. -const short_status_descriptions = { - ".D": "Deleted" - ".M": "Modified" - "!" : "Ignored" - "?" : "Untracked" - "AU": "Staged, not merged" - "MD": "Some modifications staged, file deleted in work tree" - "MM": "Some modifications staged, some modifications untracked" - "R.": "Renamed" - "UU": "Both modified (in merge conflict)" -} - -def "nu-complete git files" [path?: string] { - let relevant_statuses = ["?",".M", "MM", "MD", ".D", "UU"] - ^git status -uall --porcelain=2 (if ($path | describe) == 'string' and ($path | str length) != 0 { $"($path)" } else { "." } ) - | lines - | first 300 # limit the number of data for performance - | each { |$it| - if $it starts-with "1 " { - $it | parse --regex "1 (?P\\S+) (?:\\S+\\s?){6} (?P.+)" - } else if $it starts-with "2 " { - $it | parse --regex "2 (?P\\S+) (?:\\S+\\s?){6} (?P.+)" - } else if $it starts-with "u " { - $it | parse --regex "u (?P\\S+) (?:\\S+\\s?){8} (?P.+)" - } else if $it starts-with "? " { - $it | parse --regex "(?P.{1}) (?P.+)" - } else { - { short_status: 'unknown', value: $it } - } - } - | flatten - | where $it.short_status in $relevant_statuses - | update value { |row| if ($row.value | str contains " ") { $"`($row.value)`" } else { $row.value } } - | insert "description" { |e| $short_status_descriptions | get $e.short_status} -} - -def "nu-complete git built-in-refs" [] { - [HEAD FETCH_HEAD ORIG_HEAD] -} - -def "nu-complete git refs" [] { - nu-complete git local branches - | parse "{value}" - | insert description Branch - | append (nu-complete git remotes | parse '{value}' | insert description 'Remote branch') - | append (nu-complete git tags | parse "{value}" | insert description Tag) - | append (nu-complete git built-in-refs) -} - -def "nu-complete git files-or-refs" [] { - { - options: { sort: false }, - completions: ( - nu-complete git files | where description == "Modified" | select value description - | append (nu-complete git local branches | parse '{value}' | insert description 'Local branch') - | append (nu-complete git built-in-refs | parse '{value}' | insert description 'Built-in Refs') - | append (nu-complete git tags | parse '{value}' | insert description Tag) - | append (nu-complete git remotes | get 'value' | parse '{value}' | insert description 'Remote branch') - ) - } -} - -def "nu-complete git aliases" [] { - ^git config --get-regexp ^alias\. - | lines - | parse "alias.{value} {description}" -} - -def "nu-complete git subcommands" [] { - ^git help -a | lines | where $it starts-with " " | parse -r '\s*(?P[^ ]+) \s*(?P\w.*)' - | append (nu-complete git aliases) - | uniq-by value -} - -# Like the above, but leaves out subcommands that already have their own extern -# so they don't show up twice when completing `git ` -def "nu-complete git subcommands without externs" [] { - let externs = scope commands | where name starts-with "git " | get name | str substring 4.. - nu-complete git subcommands | where value not-in $externs -} - -def "nu-complete git add" [] { - nu-complete git files -} - -def "nu-complete git pull rebase" [] { - ["false","true","merges","interactive"] +def "nu-complete git checkout" [buffer: string, place?: record] { + git-checkout-candidates (git-buffer-words $buffer $place | skip 2) } -def "nu-complete git merge strategies" [] { - ['ort', 'octopus'] +def "nu-complete git stash-list" [] { + use git-completion-utils [git-lines] + git-lines stash list | parse "{value}: {description}" } -def "nu-complete git merge strategy options" [] { - ['ours', 'theirs'] +def "nu-complete git tags" [] { + use git-completion-utils [git-lines] + git-lines tag --no-color } -# Check out git branches and files -export extern "git checkout" [ - ...targets: string@"nu-complete git checkout" # name of the branch or files to checkout - --conflict: string # conflict style (merge or diff3) - --detach(-d) # detach HEAD at named commit - --force(-f) # force checkout (throw away local modifications) - --guess # second guess 'git checkout ' (default) - --ignore-other-worktrees # do not check if another worktree is holding the given ref - --ignore-skip-worktree-bits # do not limit pathspecs to sparse entries only - --merge(-m) # perform a 3-way merge with the new branch - --orphan: string # new unparented branch - --ours(-2) # checkout our version for unmerged files - --overlay # use overlay mode (default) - --overwrite-ignore # update ignored files (default) - --patch(-p) # select hunks interactively - --pathspec-from-file: string # read pathspec from file - --progress # force progress reporting - --quiet(-q) # suppress progress reporting - --recurse-submodules # control recursive updating of submodules - --theirs(-3) # checkout their version for unmerged files - --track(-t) # set upstream info for new branch - -b # create and checkout a new branch - -B: string # create/reset and checkout a branch - -l # create reflog for new branch -] - -export extern "git reset" [ - ...targets: string@"nu-complete git checkout" # name of commit, branch, or files to reset to - --hard # reset HEAD, index and working tree - --keep # reset HEAD but keep local changes - --merge # reset HEAD, index and working tree - --mixed # reset HEAD and index - --patch(-p) # select hunks interactively - --quiet(-q) # be quiet, only report errors - --soft # reset only HEAD - --pathspec-from-file: string # read pathspec from file - --pathspec-file-nul # with --pathspec-from-file, pathspec elements are separated with NUL character - --no-refresh # skip refreshing the index after reset - --recurse-submodules: string # control recursive updating of submodules - --no-recurse-submodules # don't recurse into submodules -] - -# Download objects and refs from another repository -export extern "git fetch" [ - repository?: string@"nu-complete git remotes" # name of the branch to fetch - --all # Fetch all remotes - --append(-a) # Append ref names and object names to .git/FETCH_HEAD - --atomic # Use an atomic transaction to update local refs. - --depth: int # Limit fetching to n commits from the tip - --deepen: int # Limit fetching to n commits from the current shallow boundary - --shallow-since: string # Deepen or shorten the history by date - --shallow-exclude: string # Deepen or shorten the history by branch/tag - --unshallow # Fetch all available history - --update-shallow # Update .git/shallow to accept new refs - --negotiation-tip: string # Specify which commit/glob to report while fetching - --negotiate-only # Do not fetch, only print common ancestors - --dry-run # Show what would be done - --write-fetch-head # Write fetched refs in FETCH_HEAD (default) - --no-write-fetch-head # Do not write FETCH_HEAD - --force(-f) # Always update the local branch - --keep(-k) # Keep downloaded pack - --multiple # Allow several arguments to be specified - --auto-maintenance # Run 'git maintenance run --auto' at the end (default) - --no-auto-maintenance # Don't run 'git maintenance' at the end - --auto-gc # Run 'git maintenance run --auto' at the end (default) - --no-auto-gc # Don't run 'git maintenance' at the end - --write-commit-graph # Write a commit-graph after fetching - --no-write-commit-graph # Don't write a commit-graph after fetching - --prefetch # Place all refs into the refs/prefetch/ namespace - --prune(-p) # Remove obsolete remote-tracking references - --prune-tags(-P) # Remove any local tags that do not exist on the remote - --no-tags(-n) # Disable automatic tag following - --refmap: string # Use this refspec to map the refs to remote-tracking branches - --tags(-t) # Fetch all tags - --recurse-submodules: string # Fetch new commits of populated submodules (yes/on-demand/no) - --jobs(-j): int # Number of parallel children - --no-recurse-submodules # Disable recursive fetching of submodules - --set-upstream # Add upstream (tracking) reference - --submodule-prefix: string # Prepend to paths printed in informative messages - --upload-pack: string # Non-default path for remote command - --quiet(-q) # Silence internally used git commands - --verbose(-v) # Be verbose - --progress # Report progress on stderr - --server-option(-o): string # Pass options for the server to handle - --show-forced-updates # Check if a branch is force-updated - --no-show-forced-updates # Don't check if a branch is force-updated - -4 # Use IPv4 addresses, ignore IPv6 addresses - -6 # Use IPv6 addresses, ignore IPv4 addresses -] - -# Yield local branches and (if remote is specified) remote branches with colon prefix -def "nu-complete git push" [buffer: string, place: record] { - use git-completion-utils * - let preceding = $buffer | str substring ..$place.cursor - let tokens = $preceding | str trim | args-split - let push_matches = $tokens | enumerate | where item == push - let push_index = $push_matches.0?.index? | default 1 +# Local branches, plus the named remote's branches as `:branch` (or bare after --delete). +# `words` are the arguments after `push`, ending with the word being completed. +def git-push-candidates [words: list]: nothing -> list { + use git-completion-utils [git-lines] mut remote = "" mut option_value = "" mut after_separator = false mut deleting = false # Scan through refspecs too: Git accepts flags before or after the remote. - for token in ($tokens | skip ($push_index + 1)) { + for token in ($words | drop 1) { if ($option_value | is-not-empty) { if $option_value == '--repo' { $remote = $token } $option_value = "" @@ -475,648 +1432,567 @@ def "nu-complete git push" [buffer: string, place: record] { if ($remote | is-empty) { $remote = $token } } - let local_branches = (nu-complete git local branches) + let local_branches = git-lines for-each-ref '--format=%(refname:short)' refs/heads if ($remote | is-empty) { return $local_branches } # The trailing slash excludes similarly named remotes such as upstream2. let prefix = $'refs/remotes/($remote)/' - let remote_branches = (^git for-each-ref --format='%(refname)' $prefix | lines | each {|ref| $ref | str replace $prefix '' } | where $it != 'HEAD') + let remote_branches = git-lines for-each-ref '--format=%(refname)' $prefix | each {|ref| $ref | str replace $prefix '' } | where $it != 'HEAD' if $deleting { return $remote_branches } $local_branches | append ($remote_branches | each { |branch| $":($branch)" }) } -# Push changes -export extern "git push" [ - remote?: string@"nu-complete git remotes", # the name of the remote - ...refs: string@"nu-complete git push" # the branch / refspec - --all # push all refs - --atomic # request atomic transaction on remote side - --delete(-d) # delete refs - --dry-run(-n) # dry run - --exec: string # receive pack program - --follow-tags # push missing but relevant tags - --force-with-lease # require old value of ref to be at this value - --force(-f) # force updates - --ipv4(-4) # use IPv4 addresses only - --ipv6(-6) # use IPv6 addresses only - --mirror # mirror all refs - --no-verify # bypass pre-push hook - --porcelain # machine-readable output - --progress # force progress reporting - --prune # prune locally removed refs - --push-option(-o): string # option to transmit - --quiet(-q) # be more quiet - --receive-pack: string # receive pack program - --recurse-submodules: string # control recursive pushing of submodules - --repo: string # repository - --set-upstream(-u) # set upstream for git pull/status - --signed: string # GPG sign the push - --tags # push tags (can't be used with --all or --mirror) - --thin # use thin pack - --verbose(-v) # be more verbose -] - -# Pull changes -export extern "git pull" [ - remote?: string@"nu-complete git remotes", # the name of the remote - ...refs: string@"nu-complete git local branches", # the branch / refspec - --rebase(-r): string@"nu-complete git pull rebase", # rebase current branch on top of upstream after fetching - --quiet(-q) # suppress output during transfer and merge - --verbose(-v) # be more verbose - --commit # perform the merge and commit the result - --no-commit # perform the merge but do not commit the result - --edit(-e) # edit the merge commit message - --no-edit # use the auto-generated merge commit message - --cleanup: string # specify how to clean up the merge commit message - --ff # fast-forward if possible - --no-ff # create a merge commit in all cases - --gpg-sign(-S) # GPG-sign the resulting merge commit - --no-gpg-sign # do not GPG-sign the resulting merge commit - --log: int # include log messages from merged commits - --no-log # do not include log messages from merged commits - --signoff # add Signed-off-by trailer - --no-signoff # do not add Signed-off-by trailer - --stat(-n) # show a diffstat at the end of the merge - --no-stat # do not show a diffstat at the end of the merge - --squash # produce working tree and index state as if a merge happened - --no-squash # perform the merge and commit the result - --verify # run pre-merge and commit-msg hooks - --no-verify # do not run pre-merge and commit-msg hooks - --strategy(-s): string # use the given merge strategy - --strategy-option(-X): string # pass merge strategy-specific option - --verify-signatures # verify the tip commit of the side branch being merged - --no-verify-signatures # do not verify the tip commit of the side branch being merged - --summary # show a summary of the merge - --no-summary # do not show a summary of the merge - --autostash # create a temporary stash entry before the operation - --no-autostash # do not create a temporary stash entry before the operation - --allow-unrelated-histories # allow merging histories without a common ancestor - --no-rebase # do not rebase the current branch on top of the upstream branch - --all # fetch all remotes - --append(-a) # append fetched refs to existing contents of FETCH_HEAD - --atomic # use an atomic transaction to update local refs - --depth: int # limit fetching to the specified number of commits - --deepen: int # deepen the history by the specified number of commits - --shallow-since: string # deepen or shorten the history since a specified date - --shallow-exclude: string # exclude commits reachable from a specified branch or tag - --unshallow # convert a shallow repository to a complete one - --update-shallow # update .git/shallow with new refs - --tags(-t) # fetch all tags from the remote - --jobs(-j): int # number of parallel children for fetching - --set-upstream # add upstream (tracking) reference - --upload-pack: string # specify non-default path for upload-pack on the remote - --progress # force progress status even if stderr is not a terminal - --server-option(-o): string # transmit the given string to the server -] - -# Switch between branches and commits -export extern "git switch" [ - switch?: string@"nu-complete git switch" # name of branch to switch to - start_point?: string@"nu-complete git rebase" # name of the start point - --create(-c) # create a new branch - --detach(-d): string@"nu-complete git log" # switch to a commit in a detached state - --force-create(-C): string # forces creation of new branch, if it exists then the existing branch will be reset to starting point - --force(-f) # alias for --discard-changes - --guess # if there is no local branch which matches then name but there is a remote one then this is checked out - --ignore-other-worktrees # switch even if the ref is held by another worktree - --merge(-m) # attempts to merge changes when switching branches if there are local changes - --no-guess # do not attempt to match remote branch names - --no-progress # do not report progress - --no-recurse-submodules # do not update the contents of sub-modules - --no-track # do not set "upstream" configuration - --orphan: string # create a new orphaned branch - --progress # report progress status - --quiet(-q) # suppress feedback messages - --recurse-submodules # update the contents of sub-modules - --track(-t) # set "upstream" configuration -] - -# Find commits yet to be applied to upstream -export extern "git cherry" [ - upstream?: string@"nu-complete git mergable sources" # Upstream branch to search for equivalent commits. Defaults to the upstream branch of HEAD. - head?: string@"nu-complete git mergable sources" # Working branch; defaults to HEAD. - limit?: string # Do not report commits up to (and including) limit. - --verbose(-v) # Show the commit subjects next to the SHA1s. -] - -# Apply the change introduced by an existing commit -export extern "git cherry-pick" [ - commit?: string@"nu-complete git commits all" # The commit ID to be cherry-picked - --edit(-e) # Edit the commit message prior to committing - --no-commit(-n) # Apply changes without making any commit - --signoff(-s) # Add Signed-off-by line to the commit message - --ff # Fast-forward if possible - --continue # Continue the operation in progress - --abort # Cancel the operation - --skip # Skip the current commit and continue with the rest of the sequence -] - -# Rebase the current branch -export extern "git rebase" [ - branch?: string@"nu-complete git rebase" # name of the branch to rebase onto - upstream?: string@"nu-complete git rebase" # upstream branch to compare against - --continue # restart rebasing process after editing/resolving a conflict - --abort # abort rebase and reset HEAD to original branch - --quit # abort rebase but do not reset HEAD - --interactive(-i) # rebase interactively with list of commits in editor - --onto?: string@"nu-complete git rebase" # starting point at which to create the new commits - --root # start rebase from root commit -] - -# Merge from a branch -export extern "git merge" [ - # For now, to make it simple, we only complete branches (not commits) and support single-parent case. - branch?: string@"nu-complete git mergable sources" # The source branch - --edit(-e) # Edit the commit message prior to committing - --no-edit # Do not edit commit message - --no-commit(-n) # Apply changes without making any commit - --signoff # Add Signed-off-by line to the commit message - --ff # Fast-forward if possible - --continue # Continue after resolving a conflict - --abort # Abort resolving conflict and go back to original state - --quit # Forget about the current merge in progress - --strategy(-s): string@"nu-complete git merge strategies" # Merge strategy - -X: string@"nu-complete git merge strategy options" # Option for merge strategy - --verbose(-v) - --help -] - -# List or change branches -export extern "git branch" [ - ...branch: string@"nu-complete git local branches" # name of branch (or branches) to operate on - --abbrev # use short commit hash prefixes - --edit-description # open editor to edit branch description - --merged # list reachable branches - --no-merged # list unreachable branches - --set-upstream-to: string@"nu-complete git available upstream" # set upstream for branch - --unset-upstream # remote upstream for branch - --all(-a) # list both remote and local branches - --copy(-c) # copy branch together with config and reflog - --format # specify format for listing branches - --move(-m) # rename branch - --points-at # list branches that point at an object - --show-current # print the name of the current branch - --verbose(-v) # show commit and upstream for each branch - --color # use color in output - --quiet(-q) # suppress messages except errors - --delete(-d) # delete branch - -D # force delete branch - --list(-l) # list branches - --contains: string@"nu-complete git commits all" # show only branches that contain the specified commit - --no-contains # show only branches that don't contain specified commit - --track(-t) # when creating a branch, set upstream -] - -# List all variables set in config file, along with their values. -export extern "git config list" [ -] - -# Emits the value of the specified key. -export extern "git config get" [ -] - -# Set value for one or more config options. -export extern "git config set" [ -] - -# Unset value for one or more config options. -export extern "git config unset" [ -] - -# Rename the given section to a new name. -export extern "git config rename-section" [ -] - -# Remove the given section from the configuration file. -export extern "git config remove-section" [ -] - -# Opens an editor to modify the specified config file -export extern "git config edit" [ -] - -# List or change tracked repositories -export extern "git remote" [ - --verbose(-v) # Show URL for remotes -] +def "nu-complete git push" [buffer: string, place: record] { + let words = git-buffer-words $buffer $place + let push_index = $words | enumerate | where item == push | get -o 0.index | default 1 + git-push-candidates ($words | skip ($push_index + 1)) +} -# Add a new tracked repository -export extern "git remote add" [ -] +# Changed and untracked files that `git add` would stage. +def "nu-complete git add" [] { + use git-completion-utils [repo-prefix status-entries format-status-files] + let prefix = repo-prefix + status-entries --untracked --prefix $prefix | where {|e| ($e.xy | str substring 1..1) != '.' } | format-status-files $prefix +} -# Rename a tracked repository -export extern "git remote rename" [ - remote: string@"nu-complete git remotes" # remote to rename - new_name: string # new name for remote -] +# Files with staged or unstaged changes, for `git commit `. +def "nu-complete git commit files" [] { + use git-completion-utils [status-entries format-status-files] + status-entries | format-status-files +} -# Remove a tracked repository -export extern "git remote remove" [ - remote: string@"nu-complete git remotes" # remote to remove -] +# Untracked files and directories, for `git clean`. +def "nu-complete git untracked" [] { + use git-completion-utils [repo-prefix status-entries format-status-files] + let prefix = repo-prefix + status-entries --untracked --prefix $prefix | where xy == '??' | format-status-files $prefix +} -# Get the URL for a tracked repository -export extern "git remote get-url" [ - remote: string@"nu-complete git remotes" # remote to get URL for -] +# Paths with merge conflicts, for `git mergetool`. +def "nu-complete git conflicted" [] { + use git-completion-utils [status-entries describe-status format-status-files] + status-entries | where {|e| (describe-status $e.xy) == 'Unmerged' } | format-status-files +} -# Set the URL for a tracked repository -export extern "git remote set-url" [ - remote: string@"nu-complete git remotes" # remote to set URL for - url: string # new URL for remote -] +# `git restore` restores the worktree by default and the index with --staged. +def "nu-complete git restore" [place?: record] { + use git-completion-utils [status-entries format-status-files] + let words = $place.command? | default [] + let staged = ($words | any {|w| $w in ['--staged' '-S'] or ($w =~ '^-[^-]*S') }) + let worktree = ($words | any {|w| $w in ['--worktree' '-W'] }) + let column = if $staged and not $worktree { 0 } else { 1 } + status-entries | where {|e| ($e.xy | str substring $column..$column) != '.' } | format-status-files +} -# Show changes between commits, working tree etc -export extern "git diff" [ - rev1_or_file?: string@"nu-complete git files-or-refs" - rev2?: string@"nu-complete git refs" - --cached # show staged changes - --name-only # only show names of changed files - --name-status # show changed files and kind of change - --no-color # disable color output -] +# `git diff`: changed files (staged ones with --cached/--staged) and revisions. +def "nu-complete git diff" [place?: record] { + use git-completion-utils [status-entries format-status-files get-refs] + let words = $place.command? | default [] + let column = if ($words | any {|w| $w in ['--cached' '--staged'] }) { 0 } else { 1 } + let files = status-entries | where {|e| ($e.xy | str substring $column..$column) != '.' } | format-status-files + if '--' in ($words | drop 1) { return $files } + {options: {sort: false}, completions: ($files | append (get-refs))} +} -# Commit changes -export extern "git commit" [ - --all(-a) # automatically stage all modified and deleted files - --amend # amend the previous commit rather than adding a new one - --message(-m): string # specify the commit message rather than opening an editor - --reuse-message(-C): string # reuse the message from a previous commit - --reedit-message(-c): string # reuse and edit message from a commit - --fixup: string # create a fixup/amend commit - --squash: string # squash commit for autosquash rebase - --reset-author # reset author information - --short # short-format output for dry-run - --branch # show branch info in short-format - --porcelain # porcelain-ready format for dry-run - --long # long-format output for dry-run - --null(-z) # use NUL instead of LF in output - --file(-F): string # read commit message from file - --author: string # override commit author - --date: string # override author date - --template(-t): string # use commit message template file - --signoff(-s) # add Signed-off-by trailer - --no-signoff # do not add Signed-off-by trailer - --trailer: string # add trailer to commit message - --no-verify(-n) # bypass pre-commit and commit-msg hooks - --verify # do not bypass pre-commit and commit-msg hooks - --allow-empty # allow commit with no changes - --allow-empty-message # allow commit with empty message - --cleanup: string # cleanup commit message - --edit(-e) # edit commit message - --no-edit # do not edit commit message - --include(-i) # include given paths in commit - --only(-o) # commit only specified paths - --pathspec-from-file: string # read pathspec from file - --pathspec-file-nul # use NUL character for pathspec file - --untracked-files(-u): string # show untracked files - --verbose(-v) # show diff in commit message template - --quiet(-q) # suppress commit summary - --dry-run # show paths to be committed without committing - --status # include git-status output in commit message - --no-status # do not include git-status output - --gpg-sign(-S) # GPG-sign commit - --no-gpg-sign # do not GPG-sign commit - ...pathspec: string # commit files matching pathspec -] +# `git reset`: a commit to reset to, or staged paths to unstage (only paths after `--`). +def "nu-complete git reset" [place?: record] { + use git-completion-utils [status-entries format-status-files get-refs get-recent-commits] + let staged = status-entries | where {|e| ($e.xy | str substring 0..0) not-in ['.' '?'] } | format-status-files + if '--' in ($place.command? | default [] | drop 1) { return $staged } + {options: {sort: false}, completions: (get-refs | append (get-recent-commits) | append $staged)} +} -# List commits -export extern "git log" [ - # Ideally we'd allow completion of revisions here, but that would make completion of filenames not work. - -U # show diffs - --follow # show history beyond renames (single file only) - --grep: string # show log entries matching supplied regular expression -] +# Revisions first; falls back to path completion after `--` or when no ref matches. +def "nu-complete git refs or paths" [token?: record, place?: record] { + use git-completion-utils [get-refs] + if '--' in ($place.command? | default [] | drop 1) { return null } + let text = $token.text? | default '' | str lowercase + let refs = get-refs + if ($text | is-not-empty) and not ($refs | any {|r| $r.value | str lowercase | str starts-with $text }) { return null } + {options: {sort: false}, completions: $refs} +} -# Show or change the reflog -export extern "git reflog" [ -] +# Paths first; offers revisions only when the typed prefix matches one. +def "nu-complete git paths or refs" [token?: record, place?: record] { + use git-completion-utils [get-refs] + let text = $token.text? | default '' | str lowercase + if ($text | is-empty) or '--' in ($place.command? | default [] | drop 1) { return null } + let refs = get-refs | where {|r| $r.value | str lowercase | str starts-with $text } + if ($refs | is-empty) { null } else { $refs } +} -# Stage files -export extern "git add" [ - ...file: string@"nu-complete git add" # file to add - --all(-A) # add changes from all tracked and untracked files (same as --no-ignore-removal) - --no-all # ignore paths removed in the working tree (same as --ignore-removal) - --chmod: string # '(+|-)x'; override the executable bit of the listed files - --dry-run(-n) # don't actually add the file(s), just show if they exist and/or will be ignored - --edit(-e) # open the diff vs. the index in an editor and let the user edit it - --force(-f) # allow adding otherwise ignored files - --ignore-errors # continue add operation when adding a file to the index fails - --ignore-missing # can only be used with --dry-run; check if any of the given files would be ignored, no matter if they are already present in the work tree or notcheck if - even missing - files are ignored in dry run - --ignore-removal # ignore paths removed in the working tree (same as --no-all) - --no-ignore-removal # add changes from all tracked and untracked files (same as --all) - --intent-to-add(-N) # record only the fact that the path will be added later - --inter-hunk-context: int # show context between diff hunks up to the specified number of lines - --interactive(-i) # add modified contents in the working tree interactively to the index - --patch(-p) # interactively choose hunks to stage - --pathspec-from-file: string # read pathspec from file - --pathspec-file-nul # with --pathspec-from-file, pathspec elements are separated with NUL character - --refresh # don't add, only refresh the index - --renormalize # Apply the "clean" process freshly to all tracked files to forcibly add them again to the index. This is useful after changing core.autocrlf configuration or the text attribute in order to correct files added with wrong CRLF/LF line endings. This option implies -u. Lone CR characters are untouched, thus while a CRLF cleans to LF, a CRCRLF sequence is only partially cleaned to CRLF. - --resolved # Update the index for unmerged paths matching where no conflict markers remain in the working tree. Unmerged paths without conflict markers (including binary files and file deletions) are staged as resolved, while any path with leftover conflict markers causes the command to refuse to stage any files. Cannot be combined with -u or -A. - --sparse # Allow updating index entries outside of the sparse-checkout cone. Normally, git add refuses to update index entries whose paths do not fit within the sparse-checkout cone, since those files might be removed from the working tree without warning. (See git-sparse-checkout docs for more details.) - --unified(-U): int # Generate diffs with lines of context. The number of context lines defaults to diff.context or 3 if the configuration variable is unset. (-U without is silently accepted as a synonym for -p due to a historical accident). - --update(-u) # Update the index not only where the working tree has a file matching but also where the index already has an entry. This adds, modifies, and removes index entries to match the working tree. - # If no is given when -A option is used, all files in the entire working tree are updated (old versions of Git used to limit the update to the current directory and its subdirectories). - --verbose(-v) # be verbose - --no-warn-embedded-repo # By default, git add will warn when adding an embedded repository to the index without using git submodule add to create an entry in .gitmodules. This option will suppress the warning (e.g., if you are manually performing operations on submodules). -] +# `git branch`: branch names to delete/rename/configure, and a start point for a new branch. +def "nu-complete git branch" [place?: record] { + use git-completion-utils [git-lines get-refs] + let words = $place.command? | default [] + let flags = $words | where {|w| $w starts-with '-' } + let remote = $flags | any {|f| $f in ['-r' '--remotes'] or ($f =~ '^-[^-]*r') } + let manage = $flags | any {|f| $f in ['-d' '-D' '--delete' '-m' '-M' '--move' '-c' '-C' '--copy' '--edit-description' '--unset-upstream' '-u' '--set-upstream-to'] or ($f =~ '^-[^-]*[dDmMcC]') } + let branches = if $remote { + git-lines for-each-ref '--format=%(refname:lstrip=2)' refs/remotes | where $it !~ '/HEAD$' + } else { + git-lines for-each-ref '--format=%(refname:short)' refs/heads + } + let positionals = git-positional-words branch ($words | skip 1 | drop 1) + if $manage or ($positionals | is-empty) { $branches } else { {options: {sort: false}, completions: (get-refs)} } +} -# Delete file from the working tree and the index -export extern "git rm" [ - -r # recursive - --force(-f) # override the up-to-date check - --dry-run(-n) # Don't actually remove any file(s) - --cached # unstage and remove paths only from the index -] +# `git tag`: existing tags (to delete/verify or overwrite), then a commit for a new tag. +def "nu-complete git tag" [place?: record] { + use git-completion-utils [git-lines get-refs] + let words = $place.command? | default [] + let manage = $words | any {|w| $w in ['-d' '--delete' '-v' '--verify'] } + let positionals = git-positional-words tag ($words | skip 1 | drop 1) + if $manage or ($positionals | is-empty) { git-lines tag --no-color } else { {options: {sort: false}, completions: (get-refs)} } +} -# Show the working tree status -export extern "git status" [ - --verbose(-v) # be verbose - --short(-s) # show status concisely - --branch(-b) # show branch information - --show-stash # show stash information -] +def "nu-complete git worktrees" [] { + let result = try { '' | ^git worktree list --porcelain -z | complete } catch { return [] } + if $result.exit_code != 0 { return [] } + $result.stdout + | split row "\u{0}\u{0}" + | where {|block| $block starts-with 'worktree ' } + | skip 1 # the main worktree cannot be locked, moved or removed + | each {|block| + let fields = $block | split row "\u{0}" + let path = $fields.0 | str substring 9.. + let branch = $fields | where {|f| $f starts-with 'branch ' } | get -o 0 | default 'detached' | str replace 'branch refs/heads/' '' + {value: ($path | to nuon), display_override: $path, description: $branch} + } +} -# Stash changes for later -export extern "git stash push" [ - --patch(-p) # interactively choose hunks to stash -] +def "nu-complete git submodules" [] { + use git-completion-utils [git-lines from-repo-root] + let root = git-lines rev-parse --show-toplevel | get -o 0 + if $root == null { return [] } + git-lines config --file ($root | path join .gitmodules) --get-regexp '^submodule\..*\.path$' + | parse --regex '^\S+ (?.+)$' + | get path + | from-repo-root + | each {|path| {value: ($path | to nuon), display_override: $path, description: Submodule} } +} -# Unstash previously stashed changes -export extern "git stash pop" [ - stash?: string@"nu-complete git stash-list" # stash to pop - --index(-i) # try to reinstate not only the working tree's changes, but also the index's ones -] +# Every config key git knows about, with the current value for keys that are set. +def "nu-complete git config keys" [] { + use git-completion-utils [git-lines] + let set = git-lines config list | parse --regex '^(?[^=]+)(?:=(?.*))?$' | uniq-by value + | update description {|row| $row.description | default '' } + let known = git-lines help --config-for-completion | where {|key| $key not-in $set.value } | each {|key| {value: $key, description: ''} } + {options: {sort: false}, completions: ($set | append $known)} +} -# List stashed changes -export extern "git stash list" [ -] +def "nu-complete git config sections" [] { + use git-completion-utils [git-lines] + git-lines config list --name-only | each {|key| $key | str replace -r '\.[^.]+$' '' } | uniq +} -# Show a stashed change -export extern "git stash show" [ - stash?: string@"nu-complete git stash-list" - -U # show diff -] +def "nu-complete git aliases" [] { + use git-completion-utils [git-lines] + git-lines config --get-regexp '^alias\.' + | parse --regex '^alias\.(?\S+) (?.*)$' +} -# Drop a stashed change -export extern "git stash drop" [ - stash?: string@"nu-complete git stash-list" -] +# Commands and aliases for `git `. +def "nu-complete git subcommands" [] { + use git-completion-utils [git-lines] + # `git help -a` also lists concept guides ("User-facing ...", "Developer-facing ..."); skip them. + git-lines help -a + | reduce -f {guide: false, rows: []} {|line, acc| + if not ($line starts-with ' ') { + $acc | update guide ($line =~ '^(User|Developer)-facing') + } else if $acc.guide or not ($line starts-with ' ') { + $acc + } else { + $acc | update rows ($acc.rows | append $line) + } + } + | get rows + | parse -r '\s*(?P[^ ]+)(?: \s*(?P\S.*))?' + | append (nu-complete git aliases) + | append ($GIT_COMMANDS | where $it !~ '--' | each {|name| {value: $name, description: ''} }) + | uniq-by value +} -# Create a new git repository -export extern "git init" [ - --initial-branch(-b): string # initial branch name -] +# Commands, aliases and concept guides for `git help`. +def "nu-complete git help" [] { + use git-completion-utils [git-lines] + let guides = git-lines help -g | where $it starts-with " " | parse -r '\s*(?P[^ ]+) \s*(?P\w.*)' + nu-complete git subcommands | append $guides +} -# List or manipulate tags -export extern "git tag" [ - --delete(-d): string@"nu-complete git tags" # delete a tag -] +def "nu-complete git notes refs" [] { + use git-completion-utils [git-lines] + git-lines for-each-ref '--format=%(refname)' refs/notes +} -# Prune all unreachable objects -export extern "git prune" [ - --dry-run(-n) # dry run - --expire: string # expire objects older than - --progress # show progress - --verbose(-v) # report all removed objects -] +def "nu-complete git reflog entries" [] { + use git-completion-utils [git-lines] + git-lines reflog --max-count=200 '--format=%gd%x09%gs' | parse "{value}\t{description}" +} -# Start a binary search to find the commit that introduced a bug -export extern "git bisect start" [ - bad?: string # a commit that has the bug - good?: string # a commit that doesn't have the bug -] +def "nu-complete git authors" [] { + use git-completion-utils [git-lines] + git-lines log --max-count=1000 '--format=%aN <%aE>' + | uniq + | each {|author| {value: ($author | to nuon), display_override: $author} } +} -# Mark the current (or specified) revision as bad -export extern "git bisect bad" [ -] +# --------------------------------------------------------------------------------------------- +# Dispatch + +# Completions for one kind of argument. `place.command` starts with the command (`git pull`) +# followed by its arguments; the last one is the word being completed. +def git-complete-kind [kind: string, token: record, place: record]: nothing -> any { + use git-completion-utils [git-lines] + match $kind { + none => [] + paths => null + add => (nu-complete git add) + untracked => (nu-complete git untracked) + commit-files => (nu-complete git commit files) + restore => (nu-complete git restore $place) + conflicted => (nu-complete git conflicted) + diff => (nu-complete git diff $place) + reset => (nu-complete git reset $place) + refs => (nu-complete git refs) + commits | rebase => (nu-complete git commits) + branches => (nu-complete git local branches) + upstreams => (nu-complete git available upstream) + mergeable | switch => (nu-complete git mergable sources) + tags => (nu-complete git tags) + remotes => (nu-complete git remotes) + remote-refs => (nu-complete git remote refs $place) + stashes => (nu-complete git stash-list) + worktrees => (nu-complete git worktrees) + submodules => (nu-complete git submodules) + config-keys => (nu-complete git config keys) + config-sections => (nu-complete git config sections) + help => (nu-complete git help) + notes-refs => (nu-complete git notes refs) + reflog => (nu-complete git reflog entries) + full-refs => (nu-complete git full refs) + refs-or-paths => (nu-complete git refs or paths $token $place) + paths-or-refs => (nu-complete git paths or refs $token $place) + branch => (nu-complete git branch $place) + tag => (nu-complete git tag $place) + authors => (nu-complete git authors) + repo-keys => (git-lines repo info --keys) + hooks => [ + applypatch-msg pre-applypatch post-applypatch pre-commit pre-merge-commit prepare-commit-msg + commit-msg post-commit pre-rebase post-checkout post-merge pre-push pre-receive update + proc-receive post-receive post-update reference-transaction push-to-checkout pre-auto-gc + post-rewrite sendemail-validate fsmonitor-watchman p4-changelist p4-prepare-changelist + p4-post-changelist p4-pre-submit post-index-change + ] + jump-mode => [diff merge grep ws] + git-var => [ + GIT_AUTHOR_IDENT GIT_COMMITTER_IDENT GIT_EDITOR GIT_SEQUENCE_EDITOR GIT_PAGER + GIT_DEFAULT_BRANCH GIT_SHELL_PATH GIT_ATTR_SYSTEM GIT_ATTR_GLOBAL GIT_CONFIG_SYSTEM + GIT_CONFIG_GLOBAL + ] + checkout => (git-checkout-candidates ($place.command | skip 1 | each { git-unquote })) + push => (git-push-candidates ($place.command | skip 1 | each { git-unquote })) + _ => [] + } +} -# Mark the current (or specified) revision as good -export extern "git bisect good" [ -] +# Options recorded in GIT_OPTIONS for `key` (`@rev` and `@diff` are the shared sets). +def git-table-opts [key: string]: nothing -> list { + let src = $key | str trim --left --char '@' + $GIT_OPTIONS | lines | where {|line| $line starts-with $"($key)\t" } + | split column "\t" key short long value neg ph desc + | each {|r| + { + short: (if $r.short == '' { null } else { $r.short }) + long: (if $r.long == '' { null } else { $r.long }) + neg: ($r.neg == '1'), value: $r.value, ph: $r.ph, desc: $r.desc, src: $src + } + } +} -# Skip the current (or specified) revision -export extern "git bisect skip" [ -] +# `-h` output of a builtin, or nothing for anything else. +def git-help-text [...words: string]: nothing -> string { + if $words.0 not-in $GIT_BUILTINS or ($words | str join ' ') in $GIT_NO_HELP { return '' } + let result = try { '' | ^git ...$words -h | complete } catch { return '' } + $result.stdout + $result.stderr +} -# End bisection -export extern "git bisect reset" [ -] +# Every option of `git `: its own `-h` (or the hand-written table for scripts and commands +# without parse-options help) plus the shared revision and diff options. +def git-options [key: string]: nothing -> list { + use git-completion-utils [parse-help] + let words = $key | split row ' ' + let hand = git-table-opts $key + let own = if ($hand | is-not-empty) or $key == '' { + $hand + } else if $key == stash { + parse-help (git-help-text stash push) + } else if $key == config { + parse-help (git-help-text config '--get') + } else { + parse-help (git-help-text ...$words) + } + let diff = if $key in $GIT_WITH_DIFF { git-table-opts '@diff' } else { [] } + let rev = if $key in $GIT_WITH_REV { git-table-opts '@rev' } else { [] } + let shared = $diff | append $rev + let all = if $key in $GIT_LEGACY_HELP { $shared | append $own } else { $own | append $shared } + let fallback = $GIT_DESC_FALLBACK | lines | where $it != '' | each { split row "\t" } + $all + | where {|o| $o.long != help and $o.short != h } + | uniq-by long short + | each {|o| + if ($o.desc | is-not-empty) { return $o } + let name = $o.long | default $o.short + let found = $fallback | where {|f| $f.0 in [$"($key) ($name)" $name] } | get -o 0.1 + $o | update desc ($found | default '') + } +} -# Show help for a git subcommand -export extern "git help" [ - command?: string@"nu-complete git subcommands" # subcommand to show help for -] +# What completes the value of an option: a list, a completer kind, `path`, or null. +def git-value-source [key: string, opt: record]: nothing -> any { + let spec = $GIT_FLAG_VALUES | get -o ($opt.long | default '') + if ($spec | describe | str starts-with 'record') { + # A null for this command means "no values", so look keys up instead of using `default`. + let names = $spec | columns + let parent = $key | split row ' ' | first + return (if $key in $names { $spec | get $key } else if $parent in $names { $spec | get $parent } else { $spec | get -o _ }) + } + if $spec != null { return $spec } + if ($opt.ph =~ '(?i)file|path|dir') { 'path' } else { null } +} -# git worktree -export extern "git worktree" [ - --help(-h) # display the help message for this command - ...args -] +# Completion rows for a value, each prefixed (`--color=`, `-X`) as typed. +def git-value-rows [source: any, token: record, place: record, prefix: string]: nothing -> any { + let rows = if ($source | describe | str starts-with 'list') { + $source | each {|v| {value: ($v | into string)} } + } else if $source == path { + return (if ($prefix | is-empty) { null } else { [] }) + } else if $source == null { + return [] + } else { + let out = git-complete-kind $source $token $place + if $out == null { return null } + let out = if ($out | describe | str starts-with 'record') { $out.completions } else { $out } + $out | each {|row| if ($row | describe) == string { {value: $row} } else { $row } } + } + if ($prefix | is-empty) { return {options: {sort: false}, completions: $rows} } + $rows | each {|row| + let shown = $row.display_override? | default $row.value + let full = $"($prefix)($shown)" + if 'display_override' in $row { $row | update value ($full | to nuon) | update display_override $full } else { $row | update value $full } + } +} -# create a new working tree -export extern "git worktree add" [ - path: path # directory to clone the branch - branch?: string@"nu-complete git available upstream" # Branch to clone - --help(-h) # display the help message for this command - --force(-f) # checkout even if already checked out in other worktree - -b # create a new branch - -B # create or reset a branch - --detach(-d) # detach HEAD at named commit - --checkout # populate the new working tree - --lock # keep the new working tree locked - --reason # reason for locking - --quiet(-q) # suppress progress reporting - --track # set up tracking mode (see git-branch(1)) - --guess-remote # try to match the new branch name with a remote-tracking branch - ...args -] +# Flag names (and `--flag=value` forms) for `git `. +def git-flag-rows [key: string, opts: list, token: record, place: record]: nothing -> any { + let text = $token.text + let eq = $text | parse --regex '^(?--[^=]+)=' | get -o 0.flag + if $eq != null { + let opt = $opts | where long == ($eq | str substring 2..) | get -o 0 + if $opt == null { return [] } + return (git-value-rows (git-value-source $key $opt) $token $place $"($eq)=") + } + let negated = $text starts-with '--no' + let rows = $opts | each {|o| + let values = git-value-source $key $o + let enum = if ($values | describe | str starts-with 'list') { $values | each { into string } } else { [] } + let row = {|value| {value: $value, description: $o.desc} } + let eq_only = $o.value == req and (($o.src? == rev and $o.long in $GIT_EQ_ONLY) or $key == '' and $o.long == list-cmds) + let long = if $o.long == null { [] } else if $eq_only { + [(do $row $"--($o.long)=")] | append ($enum | each {|v| do $row $"--($o.long)=($v)" }) + } else if $o.value == opt { + [(do $row $"--($o.long)")] | append ($enum | each {|v| do $row $"--($o.long)=($v)" }) + } else { + [(do $row $"--($o.long)")] + } + let stuck = $o.value == opt or ($o.value == req and $o.short in $GIT_STUCK_SHORTS) + let short = if $o.short == null { [] } else { + [(do $row $"-($o.short)")] | append (if $stuck { $enum | each {|v| do $row $"-($o.short)($v)" } } else { [] }) + } + let negation = if $negated and $o.neg { [{value: $"--no-($o.long)", description: $"negate --($o.long)"}] } else { [] } + $long | append $short | append $negation + } | flatten + $rows | uniq-by value +} -# list details of each worktree -export extern "git worktree list" [ - --help(-h) # display the help message for this command - --porcelain # machine-readable output - --verbose(-v) # show extended annotations and reasons, if available - --expire # add 'prunable' annotation to worktrees older than