SHA256
fix: closed pull requests, releases, teams and long descriptions
- find closed and merged pull requests by branch for checkout and edit - edit and delete inline review comments, seed issue create from a template - prefer the upstream remote in a fork clone - load the create forms concurrently - release create --verify-tag, create download directories and refuse duplicate asset names - man pages for help topics, version from go install builds - teams: send the permission before the units, keep admin teams admin, refuse to rename the owner team - repo readme, long non-ASCII descriptions, -R NAME vs a directory - skip the reviewer team check for hidden private organizations - update dependencies and workflow actions Signed-off-by: bircni <[email protected]>
This commit is contained in:
@@ -34,7 +34,7 @@ jobs:
|
||||
gpg_private_key: ${{ secrets.GPGSIGN_KEY }}
|
||||
passphrase: ${{ secrets.GPGSIGN_PASSPHRASE }}
|
||||
- name: goreleaser
|
||||
uses: goreleaser/goreleaser-action@f06c13b6b1a9625abc9e6e439d9c05a8f2190e94 # v7
|
||||
uses: goreleaser/goreleaser-action@a4f02ab5355a589de60d917a659ce617ed19b3de # v7
|
||||
with:
|
||||
distribution: goreleaser-pro
|
||||
version: "~> v2"
|
||||
@@ -61,10 +61,10 @@ jobs:
|
||||
fetch-depth: 0 # all history for all branches and tags
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@96fe6ef7f33517b61c61be40b68a1882f3264fb8 # v4
|
||||
uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4
|
||||
|
||||
- name: Set up Docker BuildX
|
||||
uses: docker/setup-buildx-action@bb05f3f5519dd87d3ba754cc423b652a5edd6d2c # v4
|
||||
uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4
|
||||
|
||||
- name: Login to DockerHub
|
||||
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4
|
||||
@@ -73,7 +73,7 @@ jobs:
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7
|
||||
uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7
|
||||
env:
|
||||
ACTIONS_RUNTIME_TOKEN: '' # See https://gitea.com/gitea/act_runner/issues/119
|
||||
with:
|
||||
|
||||
@@ -35,7 +35,7 @@ jobs:
|
||||
gpg_private_key: ${{ secrets.GPGSIGN_KEY }}
|
||||
passphrase: ${{ secrets.GPGSIGN_PASSPHRASE }}
|
||||
- name: goreleaser
|
||||
uses: goreleaser/goreleaser-action@f06c13b6b1a9625abc9e6e439d9c05a8f2190e94 # v7
|
||||
uses: goreleaser/goreleaser-action@a4f02ab5355a589de60d917a659ce617ed19b3de # v7
|
||||
with:
|
||||
distribution: goreleaser-pro
|
||||
version: "~> v2"
|
||||
@@ -62,10 +62,10 @@ jobs:
|
||||
fetch-depth: 0 # all history for all branches and tags
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@96fe6ef7f33517b61c61be40b68a1882f3264fb8 # v4
|
||||
uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4
|
||||
|
||||
- name: Set up Docker BuildX
|
||||
uses: docker/setup-buildx-action@bb05f3f5519dd87d3ba754cc423b652a5edd6d2c # v4
|
||||
uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4
|
||||
|
||||
- name: Login to DockerHub
|
||||
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4
|
||||
@@ -78,7 +78,7 @@ jobs:
|
||||
run: echo "VERSION=${GITHUB_REF#refs/tags/v}" >> $GITHUB_ENV
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7
|
||||
uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7
|
||||
env:
|
||||
ACTIONS_RUNTIME_TOKEN: '' # See https://gitea.com/gitea/act_runner/issues/119
|
||||
with:
|
||||
|
||||
@@ -15,7 +15,8 @@
|
||||
devShells.default = pkgs.mkShell {
|
||||
name = "gitea-cli-dev-environment";
|
||||
buildInputs = with pkgs; [
|
||||
go_1_27
|
||||
# flake.lock may pin a nixpkgs that predates Go 1.27; go.mod's toolchain line then fetches it.
|
||||
(pkgs.go_1_27 or pkgs.go)
|
||||
gopls
|
||||
gnumake
|
||||
# Add other dependencies here if needed
|
||||
|
||||
@@ -11,19 +11,19 @@ require (
|
||||
code.gitea.io/gitea-vet v0.2.3
|
||||
gitea.com/noerw/unidiff-comments v0.0.0-20220822113322-50f4daa0e35c
|
||||
gitea.dev/sdk v1.3.0
|
||||
github.com/42wim/httpsig v1.2.4
|
||||
github.com/42wim/httpsig v1.3.0
|
||||
github.com/adrg/xdg v0.5.3
|
||||
github.com/araddon/dateparse v0.0.0-20210429162001-6b43995a97de
|
||||
github.com/davidmz/go-pageant v1.0.2
|
||||
github.com/itchyny/gojq v0.12.17
|
||||
github.com/itchyny/gojq v0.12.19
|
||||
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51
|
||||
github.com/mattn/go-runewidth v0.0.23
|
||||
github.com/mattn/go-runewidth v0.0.31
|
||||
github.com/spf13/cobra v1.10.2
|
||||
github.com/spf13/pflag v1.0.9
|
||||
github.com/spf13/pflag v1.0.10
|
||||
github.com/stretchr/testify v1.12.1
|
||||
github.com/zalando/go-keyring v0.2.8
|
||||
golang.org/x/crypto v0.58.0
|
||||
golang.org/x/oauth2 v0.36.0
|
||||
golang.org/x/oauth2 v0.37.0
|
||||
golang.org/x/sys v0.49.0
|
||||
golang.org/x/term v0.47.0
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
@@ -55,7 +55,7 @@ require (
|
||||
github.com/gorilla/css v1.0.1 // indirect
|
||||
github.com/hashicorp/go-version v1.9.0 // indirect
|
||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||
github.com/itchyny/timefmt-go v0.1.6 // indirect
|
||||
github.com/itchyny/timefmt-go v0.1.8 // indirect
|
||||
github.com/lucasb-eyer/go-colorful v1.4.0 // indirect
|
||||
github.com/microcosm-cc/bluemonday v1.0.27 // indirect
|
||||
github.com/mitchellh/hashstructure/v2 v2.0.2 // indirect
|
||||
|
||||
@@ -14,8 +14,8 @@ gitea.com/noerw/unidiff-comments v0.0.0-20220822113322-50f4daa0e35c h1:8fTkq2UaV
|
||||
gitea.com/noerw/unidiff-comments v0.0.0-20220822113322-50f4daa0e35c/go.mod h1:Fc8iyPm4NINRWujeIk2bTfcbGc4ZYY29/oMAAGcr4qI=
|
||||
gitea.dev/sdk v1.3.0 h1:4U95+Ou6WHCQiRPDEyAzvl1Q7cxg5RUTWkqmOXr5w4I=
|
||||
gitea.dev/sdk v1.3.0/go.mod h1:85EBqSAqUn1KlFCk40y3sTjWjBsB/KouL3slGXMA/2o=
|
||||
github.com/42wim/httpsig v1.2.4 h1:mI5bH0nm4xn7K18fo1K3okNDRq8CCJ0KbBYWyA6r8lU=
|
||||
github.com/42wim/httpsig v1.2.4/go.mod h1:yKsYfSyTBEohkPik224QPFylmzEBtda/kjyIAJjh3ps=
|
||||
github.com/42wim/httpsig v1.3.0 h1:HK2bieeZ99X9IvOoc1ST6yrhLek0f4MqlEGES2JCP3g=
|
||||
github.com/42wim/httpsig v1.3.0/go.mod h1:lgC3Yrvp4lxi1odEF1ge3kQBu/VM+SRcZQu5YwiR3dU=
|
||||
github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ=
|
||||
github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE=
|
||||
github.com/adrg/xdg v0.5.3 h1:xRnxJXne7+oWDatRhR1JLnvuccuIeCoBu2rtuLqQB78=
|
||||
@@ -82,8 +82,8 @@ github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkp
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/godbus/dbus/v5 v5.2.2 h1:TUR3TgtSVDmjiXOgAAyaZbYmIeP3DPkld3jgKGV8mXQ=
|
||||
github.com/godbus/dbus/v5 v5.2.2/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c=
|
||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8=
|
||||
github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0=
|
||||
github.com/hashicorp/go-version v1.9.0 h1:CeOIz6k+LoN3qX9Z0tyQrPtiB1DFYRPfCIBtaXPSCnA=
|
||||
@@ -92,17 +92,17 @@ github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUq
|
||||
github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg=
|
||||
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||
github.com/itchyny/gojq v0.12.17 h1:8av8eGduDb5+rvEdaOO+zQUjA04MS0m3Ps8HiD+fceg=
|
||||
github.com/itchyny/gojq v0.12.17/go.mod h1:WBrEMkgAfAGO1LUcGOckBl5O726KPp+OlkKug0I/FEY=
|
||||
github.com/itchyny/timefmt-go v0.1.6 h1:ia3s54iciXDdzWzwaVKXZPbiXzxxnv1SPGFfM/myJ5Q=
|
||||
github.com/itchyny/timefmt-go v0.1.6/go.mod h1:RRDZYC5s9ErkjQvTvvU7keJjxUYzIISJGxm9/mAERQg=
|
||||
github.com/itchyny/gojq v0.12.19 h1:ttXA0XCLEMoaLOz5lSeFOZ6u6Q3QxmG46vfgI4O0DEs=
|
||||
github.com/itchyny/gojq v0.12.19/go.mod h1:5galtVPDywX8SPSOrqjGxkBeDhSxEW1gSxoy7tn1iZY=
|
||||
github.com/itchyny/timefmt-go v0.1.8 h1:1YEo1JvfXeAHKdjelbYr/uCuhkybaHCeTkH8Bo791OI=
|
||||
github.com/itchyny/timefmt-go v0.1.8/go.mod h1:5E46Q+zj7vbTgWY8o5YkMeYb4I6GeWLFnetPy5oBrAI=
|
||||
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs=
|
||||
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8=
|
||||
github.com/lucasb-eyer/go-colorful v1.4.0 h1:UtrWVfLdarDgc44HcS7pYloGHJUjHV/4FwW4TvVgFr4=
|
||||
github.com/lucasb-eyer/go-colorful v1.4.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
|
||||
github.com/mattn/go-runewidth v0.0.10/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=
|
||||
github.com/mattn/go-runewidth v0.0.23 h1:7ykA0T0jkPpzSvMS5i9uoNn2Xy3R383f9HDx3RybWcw=
|
||||
github.com/mattn/go-runewidth v0.0.23/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
|
||||
github.com/mattn/go-runewidth v0.0.31 h1:1oCV4ReTlosDBc6rYRw5cL8S/4y8iv5oRl4SJ5IBgwo=
|
||||
github.com/mattn/go-runewidth v0.0.31/go.mod h1:3qAiGCV4Koz/yuveO58qUefmUTRm8r0IGEXZ9jeHp/8=
|
||||
github.com/microcosm-cc/bluemonday v1.0.27 h1:MpEUotklkwCSLeH+Qdx1VJgNqLlpY2KXwXFM08ygZfk=
|
||||
github.com/microcosm-cc/bluemonday v1.0.27/go.mod h1:jFi9vgW+H7c3V0lb6nR74Ib/DIB5OBs92Dimizgw2cA=
|
||||
github.com/mitchellh/hashstructure/v2 v2.0.2 h1:vGKWl0YJqUNxE8d+h8f6NJLcCJrgbhC4NcD46KavDd4=
|
||||
@@ -120,8 +120,9 @@ github.com/seletskiy/tplutil v0.0.0-20200921103632-f880f6245597 h1:nZY1S2jo+VtDr
|
||||
github.com/seletskiy/tplutil v0.0.0-20200921103632-f880f6245597/go.mod h1:F8CBHSOjnzjx9EeXyWJTAzJyVxN+Y8JH2WjLMn4utiw=
|
||||
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
|
||||
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
|
||||
github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=
|
||||
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
|
||||
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4=
|
||||
github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+QYS+U0=
|
||||
@@ -157,8 +158,8 @@ golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLL
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.61.0 h1:RR+6j/BTBCrggOLugxa+66R8FvoN6MHlzDlZIbN9YFw=
|
||||
golang.org/x/net v0.61.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
|
||||
golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
|
||||
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
|
||||
golang.org/x/oauth2 v0.37.0 h1:JUlcxA8oAtauLfiH8FX2/FkAWHAdi0QtGCGc+hofE98=
|
||||
golang.org/x/oauth2 v0.37.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
|
||||
|
||||
@@ -320,12 +320,12 @@ func parseEnvFile(data []byte) ([]envEntry, error) {
|
||||
}
|
||||
if quote := value[:min(len(value), 1)]; quote == `"` || quote == "'" {
|
||||
// The value ends at the closing quote; only a # comment may follow it.
|
||||
closing := strings.Index(value[1:], quote) + 1
|
||||
closing := closingQuote(value, quote)
|
||||
rest := strings.TrimSpace(value[min(closing+1, len(value)):])
|
||||
if closing > 0 && (rest == "" || strings.HasPrefix(rest, "#")) {
|
||||
value = value[1:closing]
|
||||
if quote == `"` {
|
||||
value = strings.ReplaceAll(value, `\n`, "\n")
|
||||
value = strings.NewReplacer(`\n`, "\n", `\"`, `"`, `\\`, `\`).Replace(value)
|
||||
}
|
||||
entries = append(entries, envEntry{name, value})
|
||||
continue
|
||||
@@ -340,6 +340,20 @@ func parseEnvFile(data []byte) ([]envEntry, error) {
|
||||
return entries, scanner.Err()
|
||||
}
|
||||
|
||||
// closingQuote returns the index of the quote that closes the quoted value, or 0 when it is not
|
||||
// closed. Inside double quotes a backslash escapes the next character.
|
||||
func closingQuote(value, quote string) int {
|
||||
for i := 1; i < len(value); i++ {
|
||||
switch {
|
||||
case quote == `"` && value[i] == '\\':
|
||||
i++
|
||||
case string(value[i]) == quote:
|
||||
return i
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (a *application) actionValueDeleteCommand(secret bool, kind string) *cobra.Command {
|
||||
var scope actionScopeFlags
|
||||
cmd := &cobra.Command{
|
||||
|
||||
@@ -209,3 +209,10 @@ func TestVariableSetCountsCharactersNotBytes(t *testing.T) {
|
||||
deps.Streams.In = strings.NewReader(strings.Repeat("é", 65537))
|
||||
require.ErrorContains(t, Execute(context.Background(), deps, []string{"variable", "set", "WIDE", "-o", "acme"}), "65536 characters")
|
||||
}
|
||||
|
||||
func TestParseEnvFileKeepsEscapedQuotes(t *testing.T) {
|
||||
entries, err := parseEnvFile([]byte("A=\"say \\\"hi\\\" now\" # note\nB='it''s'\nC=\"back\\\\slash\\nline\"\n"))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "say \"hi\" now", entries[0].value)
|
||||
require.Equal(t, "back\\slash\nline", entries[2].value)
|
||||
}
|
||||
|
||||
@@ -169,6 +169,10 @@ Inputs are checked against the inputs that the workflow declares: unknown inputs
|
||||
required inputs and values that a choice or boolean input does not accept are refused. In a
|
||||
terminal, gt asks for missing required inputs, or for every input when none is given.
|
||||
|
||||
The workflow is looked up among those the server lists from the default branch, so it must exist
|
||||
there; --ref only selects the branch or tag whose version of it runs, as in gh. List them with
|
||||
gt workflow list.
|
||||
|
||||
Without --ref, the workflow runs on the checked-out branch, which must be on the server, or on
|
||||
the default branch when the repository does not come from the working directory.`,
|
||||
Example: `# run a workflow on the default or current branch
|
||||
@@ -196,6 +200,10 @@ $ gt workflow run nightly --follow`,
|
||||
}
|
||||
service := services.Actions{Client: t.client, Repository: t.Repo}
|
||||
workflow, err := service.FindWorkflow(cmd.Context(), args[0])
|
||||
if notFound, ok := errors.AsType[*services.NotFoundError](err); ok && notFound.Kind == "workflow" {
|
||||
// Like gh, the workflow comes from the server's list, so --ref cannot add one.
|
||||
return fmt.Errorf("%w; workflows are listed from the default branch and must exist there, even with --ref; see gt workflow list%s", err, a.suggestedRepo(t))
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -109,6 +109,14 @@ func TestWorkflowRunChecksInputsBeforeDispatching(t *testing.T) {
|
||||
"workflow nightly.yaml is disabled; enable it with: gt workflow enable nightly.yaml -R alice/project")
|
||||
}
|
||||
|
||||
func TestWorkflowRunExplainsWorkflowsComeFromTheDefaultBranch(t *testing.T) {
|
||||
server, requests := actionsAPI(t, map[string]string{"GET actions/workflows": workflowsFixture})
|
||||
deps, _, _ := actionsDeps(t, server.URL, false)
|
||||
err := Execute(context.Background(), deps, []string{"workflow", "run", "branch-only", "-R", "alice/project", "--ref", "feature"})
|
||||
require.EqualError(t, err, `workflow "branch-only" not found in alice/project; workflows are listed from the default branch and must exist there, even with --ref; see gt workflow list -R alice/project`)
|
||||
require.Equal(t, []string{"GET actions/workflows"}, *requests)
|
||||
}
|
||||
|
||||
// dispatchingPrompter answers workflow inputs: selections with their first choice, confirmations
|
||||
// with yes, and text by title.
|
||||
type dispatchingPrompter struct {
|
||||
|
||||
@@ -56,6 +56,22 @@ func complete(t *testing.T, deps Dependencies, out *bytes.Buffer, args ...string
|
||||
return lines[:len(lines)-1], cobra.ShellCompDirective(directive)
|
||||
}
|
||||
|
||||
func TestPullCompletionStopsAfterTheLastPositionalArgument(t *testing.T) {
|
||||
requests := 0
|
||||
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requests++
|
||||
_, _ = w.Write([]byte(`[{"id":9,"number":9,"title":"More"}]`))
|
||||
}))
|
||||
defer server.Close()
|
||||
deps, out, _ := serverDeps(t, server.URL)
|
||||
for _, args := range []string{"pr view 5 ", "pr review list 5 ", "pr review view 5 9 ", "pr review submit 5 9 ", "pr review reply 5 9 "} {
|
||||
items, directive := complete(t, deps, out, append(strings.Fields(args), "-R", "owner/repo", "")...)
|
||||
require.Empty(t, items, args)
|
||||
require.Equal(t, cobra.ShellCompDirectiveNoFileComp, directive, args)
|
||||
}
|
||||
require.Zero(t, requests, "no argument is left to complete")
|
||||
}
|
||||
|
||||
func TestEnumFlagsShareValidationAndCompletion(t *testing.T) {
|
||||
deps, out, _ := testDeps(t)
|
||||
var state string
|
||||
@@ -385,6 +401,20 @@ func TestInstanceCompletions(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompleteArgumentBranchesUsesTheNamedRepository(t *testing.T) {
|
||||
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
require.Equal(t, "/api/v1/repos/bob/tool/branches", r.URL.Path)
|
||||
_, _ = w.Write([]byte(`[{"name":"develop"}]`))
|
||||
}))
|
||||
defer server.Close()
|
||||
deps, _, _ := serverDeps(t, server.URL)
|
||||
a := &application{deps: deps}
|
||||
cmd := &cobra.Command{}
|
||||
cmd.SetContext(context.Background())
|
||||
values, _ := a.completeArgumentBranches()(cmd, []string{"bob/tool"}, "")
|
||||
require.Equal(t, []string{"develop"}, values)
|
||||
}
|
||||
|
||||
func TestCompletionInstallHelp(t *testing.T) {
|
||||
deps, out, _ := testDeps(t)
|
||||
require.NoError(t, Execute(context.Background(), deps, []string{"completion", "bash", "--help"}))
|
||||
|
||||
@@ -539,6 +539,9 @@ func commandOutputFields(cmd *cobra.Command) []string {
|
||||
case "org":
|
||||
return jsonFields[services.Organization]()
|
||||
case "member":
|
||||
if cmd.Parent().Parent() != nil && cmd.Parent().Parent().Name() == "team" {
|
||||
return jsonFields[services.TeamMember]()
|
||||
}
|
||||
return jsonFields[services.OrganizationMember]()
|
||||
case "asset":
|
||||
return jsonFields[services.ReleaseAsset]()
|
||||
|
||||
@@ -312,6 +312,15 @@ func TestHelpConfirmAndArgumentsAnnotations(t *testing.T) {
|
||||
require.Contains(t, out.String(), "\nEXAMPLES\n # Drop issue 7\n $ gt issue drop 7\n")
|
||||
}
|
||||
|
||||
func TestHelpDefaultsToCurrentBranchOnlyWhereThePullRequestIsOptional(t *testing.T) {
|
||||
deps, out, _ := testDeps(t)
|
||||
for path, defaults := range map[string]bool{"pr review list": true, "pr view": true, "pr review view": false, "pr review dismiss": false, "pr checkout": false} {
|
||||
out.Reset()
|
||||
require.NoError(t, Execute(context.Background(), deps, append(strings.Fields(path), "--help")))
|
||||
require.Equal(t, defaults, strings.Contains(out.String(), "Without an argument, the pull request of the current branch"), path)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHelpTopicsAndUnknownTopics(t *testing.T) {
|
||||
deps, out, _ := testDeps(t)
|
||||
for args, want := range map[string]string{
|
||||
|
||||
+22
-12
@@ -107,7 +107,8 @@ func (a *application) authCommand() *cobra.Command {
|
||||
gt keeps the accounts of each instance in hosts.yml and their tokens in the system
|
||||
keyring, or in a private file when you choose so. One account per instance is active;
|
||||
--user or GITEA_CLI_USER selects another for a single command. GITEA_TOKEN, together with
|
||||
GITEA_INSTANCE_URL or GITEA_CLI_HOST, replaces the stored credentials of its instance. See
|
||||
GITEA_INSTANCE_URL or GITEA_CLI_HOST, replaces the stored credentials of its instance for the
|
||||
active account too; it must belong to the account that --user or GITEA_CLI_USER names. See
|
||||
gt help environment for how commands select the instance.`}
|
||||
group.AddCommand(a.loginCommand(), a.logoutCommand(), a.authStatusCommand(), a.authSwitchCommand(), a.authRefreshCommand(), a.authTokenCommand(), a.setupGitCommand(), a.gitCredentialCommand())
|
||||
return group
|
||||
@@ -424,7 +425,7 @@ func (a *application) authStatusCommand() *cobra.Command {
|
||||
Use: "status", Short: "Show the accounts gt can use", Args: argsExact(0),
|
||||
Long: `Show the accounts gt can use on each instance, the active one, and how they
|
||||
authenticate. Fails with exit code 4 when there is no account, or when a credential is
|
||||
missing or rejected.`,
|
||||
missing or rejected. With --json it exits 0 either way; read credential_available, verified and error.`,
|
||||
Example: `$ gt auth status
|
||||
# Check the credentials against their instances
|
||||
$ gt auth status --verify
|
||||
@@ -654,6 +655,9 @@ selects another. With two accounts, gt auth switch toggles between them; with mo
|
||||
asks which one on a terminal.`,
|
||||
Example: "$ gt auth switch\n$ gt auth switch bob\n$ gt auth switch bob --host gitea.com",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
if err := a.positionalAccount(args); err != nil {
|
||||
return err
|
||||
}
|
||||
t, err := a.instanceTarget(cmd.Context())
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -664,9 +668,6 @@ asks which one on a terminal.`,
|
||||
}
|
||||
names := slices.Sorted(maps.Keys(users))
|
||||
requested := a.options.user
|
||||
if len(args) == 1 {
|
||||
requested = args[0]
|
||||
}
|
||||
var user string
|
||||
switch {
|
||||
case requested != "":
|
||||
@@ -709,6 +710,18 @@ asks which one on a terminal.`,
|
||||
}
|
||||
}
|
||||
|
||||
// positionalAccount treats the account argument of auth switch and auth logout like --user.
|
||||
func (a *application) positionalAccount(args []string) error {
|
||||
if len(args) == 0 {
|
||||
return nil
|
||||
}
|
||||
if a.options.user != "" && !strings.EqualFold(a.options.user, args[0]) {
|
||||
return clierr.Wrap(clierr.Usage, fmt.Errorf("--user %s and the account %s differ", a.options.user, args[0]))
|
||||
}
|
||||
a.options.user = args[0]
|
||||
return nil
|
||||
}
|
||||
|
||||
// chooseAccount asks which of the accounts of instance to use, or explains how to name one.
|
||||
func (a *application) chooseAccount(cmd *cobra.Command, instance string, names []string, active string) (string, error) {
|
||||
chooser, ok := a.chooser()
|
||||
@@ -734,11 +747,8 @@ other credential helpers are asked to forget what they stored for the account on
|
||||
instance, such as a copy of its token that a keychain kept after a push.`,
|
||||
Example: "$ gt auth logout\n$ gt auth logout bob --host gitea.com\n# Without confirmation\n$ gt auth logout alice --yes",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
if len(args) == 1 {
|
||||
if a.options.user != "" && !strings.EqualFold(a.options.user, args[0]) {
|
||||
return clierr.Wrap(clierr.Usage, fmt.Errorf("--user %s and the account %s differ", a.options.user, args[0]))
|
||||
}
|
||||
a.options.user = args[0]
|
||||
if err := a.positionalAccount(args); err != nil {
|
||||
return err
|
||||
}
|
||||
t, err := a.instanceTarget(cmd.Context())
|
||||
if err != nil {
|
||||
@@ -836,8 +846,8 @@ $ gt auth token --host gitea.com --user alice`,
|
||||
if instance, err := settings.ResolveHost(a.tokenInstance(), s.Hosts.Hosts); err != nil || instance != t.Host {
|
||||
token = ""
|
||||
}
|
||||
if token != "" && t.User != "" {
|
||||
// Like connect, print the environment token only for the account it authenticates.
|
||||
if token != "" && t.explicitUser() {
|
||||
// Like connect, print the environment token only for the account --user or GITEA_CLI_USER names.
|
||||
actual, err := services.CurrentAccount(cmd.Context(), a.deps.Client(t.Host, token, t.host.Insecure))
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -841,3 +841,35 @@ func TestAuthStatusVerifyHonorsInstanceInsecureForEnvironmentToken(t *testing.T)
|
||||
require.NoError(t, Execute(context.Background(), deps, []string{"auth", "status", "--verify", "--json=user,verified"}))
|
||||
require.JSONEq(t, `[{"user":"alice","verified":true}]`, out.String())
|
||||
}
|
||||
|
||||
// An instance with REQUIRE_SIGNIN_VIEW answers every unsigned request, /api/v1/version included,
|
||||
// with 403; login must only make the signed requests.
|
||||
func TestAuthLoginSSHKeyNeverAsksTheVersionOfAPrivateInstance(t *testing.T) {
|
||||
keyPath := writeAppTempSSHKey(t, "")
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Signature") == "" {
|
||||
http.Error(w, `{"message":"Only signed in user is allowed to call APIs."}`, http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"login":"alice"}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
deps, _, _ := testDeps(t)
|
||||
require.NoError(t, Execute(context.Background(), deps, []string{
|
||||
"auth", "login", "--host", server.URL, "--ssh-key", keyPath, "--no-input", "--yes",
|
||||
}))
|
||||
}
|
||||
|
||||
func TestAuthSwitchTreatsThePositionalAccountLikeUser(t *testing.T) {
|
||||
const instance = "https://example.org"
|
||||
deps, _, _ := terminalDeps(t)
|
||||
configureAccounts(t, deps, instance, "alice", "alice", "bob")
|
||||
err := Execute(context.Background(), deps, []string{"auth", "switch", "bob", "--user", "alice"})
|
||||
require.Equal(t, clierr.Usage, clierr.ExitCode(err), "%v", err)
|
||||
require.EqualError(t, err, "--user alice and the account bob differ")
|
||||
s, err := deps.Settings.Load()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "alice", s.Hosts.Hosts[instance].User)
|
||||
require.NoError(t, Execute(context.Background(), deps, []string{"auth", "switch", "BOB", "--user", "bob"}))
|
||||
}
|
||||
|
||||
@@ -76,14 +76,14 @@ func (a *application) pullCheckoutCommand() *cobra.Command {
|
||||
var branch string
|
||||
var detached, update bool
|
||||
cmd := &cobra.Command{Use: "checkout {<number> | <url> | <branch>}", Aliases: []string{"co"}, Short: "Check out a pull request", Long: `Check out the head of a pull request in a local branch that tracks the head branch, so
|
||||
that git push updates it and pr commands without an argument select the pull request.`, Annotations: pullArgumentsAnnotation(nil), Args: argsExact(1), RunE: func(cmd *cobra.Command, args []string) error {
|
||||
that git push updates it and pr commands without an argument select the pull request.`, Annotations: pullArgumentRequiredAnnotation(nil), Args: argsExact(1), RunE: func(cmd *cobra.Command, args []string) error {
|
||||
if detached && (cmd.Flags().Changed("branch") || update) {
|
||||
return clierr.Wrap(clierr.Usage, errors.New("--detach and --branch/--update are mutually exclusive"))
|
||||
}
|
||||
if cmd.Flags().Changed("branch") && strings.TrimSpace(branch) == "" {
|
||||
return clierr.Wrap(clierr.Usage, errors.New("--branch cannot be empty"))
|
||||
}
|
||||
target, n, err := a.pullSelector(cmd, args)
|
||||
target, n, err := a.pullSelectorAny(cmd, args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -149,7 +149,7 @@ that git push updates it and pr commands without an argument select the pull req
|
||||
cmd.Flags().BoolVar(&update, "update", false, "Fast-forward an existing branch to the PR head; reject divergence")
|
||||
cmd.Flags().BoolVar(&detached, "detach", false, "Check out the PR commit without creating or changing a branch")
|
||||
cmd.Flags().StringVarP(&branch, "branch", "b", "", "Local branch name (default: the head branch name when free, else OWNER/BRANCH or pr/NUMBER)")
|
||||
cmd.ValidArgsFunction = a.completePulls("open")
|
||||
cmd.ValidArgsFunction = firstArg(a.completePulls("open"))
|
||||
cmd.Example = `$ gt pr checkout 13
|
||||
$ gt pr co feature/login
|
||||
$ gt pr checkout 13 --update`
|
||||
|
||||
@@ -29,7 +29,7 @@ gt exits with 8 while checks are pending and with 1 when a check failed, like gh
|
||||
if interval <= 0 || timeout <= 0 {
|
||||
return clierr.Wrap(clierr.Usage, errors.New("--interval and --timeout must be positive"))
|
||||
}
|
||||
t, n, err := a.pullSelector(cmd, args)
|
||||
t, n, err := a.pullSelectorAny(cmd, args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -86,7 +86,7 @@ gt exits with 8 while checks are pending and with 1 when a check failed, like gh
|
||||
cmd.Flags().DurationVar(&interval, "interval", 5*time.Second, "Time between refreshes with --watch")
|
||||
cmd.Flags().DurationVar(&timeout, "timeout", time.Hour, "Longest time to wait with --watch")
|
||||
cmd.Flags().BoolVarP(&web, "web", "w", false, "Open the pull request in the browser")
|
||||
cmd.ValidArgsFunction = a.completePulls("open")
|
||||
cmd.ValidArgsFunction = firstArg(a.completePulls("open"))
|
||||
cmd.Example = `# Show the checks of the current branch's pull request
|
||||
$ gt pr checks
|
||||
|
||||
|
||||
@@ -61,6 +61,10 @@ func issueCommandPath(cmd *cobra.Command) string {
|
||||
|
||||
// commentName names a comment in messages: "comment 81 on alice/x#1".
|
||||
func commentName(t target, comment services.Comment) string {
|
||||
if comment.IssueNumber == 0 {
|
||||
// Inline review comments cannot be fetched, so their discussion is unknown.
|
||||
return fmt.Sprintf("comment %d on %s", comment.ID, t.Repo)
|
||||
}
|
||||
return fmt.Sprintf("comment %d on %s#%d", comment.ID, t.Repo, comment.IssueNumber)
|
||||
}
|
||||
|
||||
@@ -159,8 +163,10 @@ func lastComment(cmd *cobra.Command, t target, n int64) (services.Comment, error
|
||||
}
|
||||
|
||||
// comment returns the comment that the ID argument names, which a command of kind may change: pr
|
||||
// commands refuse comments on issues.
|
||||
func (a *application) comment(cmd *cobra.Command, arg string, kind refKind) (target, services.Comment, error) {
|
||||
// commands refuse comments on issues. With changing set, as for edit and delete, a comment that
|
||||
// cannot be fetched, such as an inline review comment, is returned by its ID alone: the edit and
|
||||
// delete endpoints accept it.
|
||||
func (a *application) comment(cmd *cobra.Command, arg string, kind refKind, changing bool) (target, services.Comment, error) {
|
||||
id, err := number(arg)
|
||||
if err != nil {
|
||||
return target{}, services.Comment{}, err
|
||||
@@ -170,6 +176,9 @@ func (a *application) comment(cmd *cobra.Command, arg string, kind refKind) (tar
|
||||
return t, services.Comment{}, err
|
||||
}
|
||||
current, err := (services.Comments{Client: t.client, Repository: t.Repo}).View(cmd.Context(), id)
|
||||
if notPlain := (services.NotPlainCommentError{}); changing && errors.As(err, ¬Plain) {
|
||||
return t, services.Comment{ID: id}, nil
|
||||
}
|
||||
if err == nil && kind == pullRef && !current.Pull {
|
||||
err = fmt.Errorf("comment %d in %s is on an issue, not a pull request; use %s %d", id, t.Repo, issueCommandPath(cmd), id)
|
||||
}
|
||||
@@ -178,6 +187,10 @@ func (a *application) comment(cmd *cobra.Command, arg string, kind refKind) (tar
|
||||
|
||||
// editComment replaces the text of comment, prefilling the prompt or editor with it.
|
||||
func (a *application) editComment(cmd *cobra.Command, t target, comment services.Comment, f commentFlags) (runErr error) {
|
||||
// An inline review comment is not fetched, so there is no text to start from.
|
||||
if comment.Author == "" && !cmd.Flags().Changed("body") && !cmd.Flags().Changed("body-file") {
|
||||
return clierr.Wrap(clierr.Usage, errors.New("an inline review comment cannot be prefilled; supply --body or --body-file"))
|
||||
}
|
||||
body, draft, err := a.readComment(cmd, f, comment.Body)
|
||||
defer finishDraft(&draft, &runErr)
|
||||
if err != nil {
|
||||
@@ -328,17 +341,20 @@ $ gt %[1]s comment list %[2]s --json id,author,body`, words.group, words.example
|
||||
return err
|
||||
}
|
||||
}
|
||||
items, err := (services.Comments{Client: t.client, Repository: t.Repo}).Page(cmd.Context(), n, limit, page)
|
||||
result, err := (services.Comments{Client: t.client, Repository: t.Repo}).Page(cmd.Context(), n, limit, page)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return a.writeComments(cmd, t, n, items)
|
||||
if err := a.writeComments(cmd, t, n, result.Items); err != nil {
|
||||
return err
|
||||
}
|
||||
return a.morePagesHint(cmd, result.More, page)
|
||||
}}
|
||||
pageFlags(list, &limit, &page)
|
||||
list.ValidArgsFunction = a.completeDiscussions(kind)
|
||||
|
||||
view := &cobra.Command{Use: "view <comment-id>", Short: "View a comment", Example: fmt.Sprintf("$ gt %s comment view 81", words.group), Args: argsExact(1), RunE: func(cmd *cobra.Command, args []string) error {
|
||||
t, comment, err := a.comment(cmd, args[0], kind)
|
||||
t, comment, err := a.comment(cmd, args[0], kind, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -366,7 +382,7 @@ $ gt %[1]s comment edit 81`, words.group), Args: argsExact(1), RunE: func(cmd *c
|
||||
if err := editFlags.validate(cmd); err != nil {
|
||||
return err
|
||||
}
|
||||
t, comment, err := a.comment(cmd, args[0], kind)
|
||||
t, comment, err := a.comment(cmd, args[0], kind, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -375,7 +391,7 @@ $ gt %[1]s comment edit 81`, words.group), Args: argsExact(1), RunE: func(cmd *c
|
||||
editFlags.register(edit)
|
||||
|
||||
remove := &cobra.Command{Use: "delete <comment-id>", Short: "Delete a comment", Example: fmt.Sprintf("$ gt %s comment delete 81 --yes", words.group), Annotations: map[string]string{"gt.text": "comment deletion does not return a resource", "gt.confirm": "true"}, Args: argsExact(1), RunE: func(cmd *cobra.Command, args []string) error {
|
||||
t, comment, err := a.comment(cmd, args[0], kind)
|
||||
t, comment, err := a.comment(cmd, args[0], kind, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -192,3 +192,33 @@ func TestViewCommentsCannotBeCombinedWithJSON(t *testing.T) {
|
||||
require.ErrorContains(t, err, "gt pr review list <number> --json")
|
||||
require.Empty(t, out.String())
|
||||
}
|
||||
|
||||
func TestCommentEditAndDeleteReachInlineReviewComments(t *testing.T) {
|
||||
var calls []string
|
||||
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls = append(calls, r.Method+" "+r.URL.Path)
|
||||
switch r.Method + " " + r.URL.Path {
|
||||
case "GET /api/v1/repos/alice/project/issues/comments/40":
|
||||
w.WriteHeader(http.StatusNoContent) // Gitea's answer for inline review comments
|
||||
case "PATCH /api/v1/repos/alice/project/issues/comments/40":
|
||||
require.Equal(t, "Fixed", payloadField(t, r, "body"))
|
||||
_, _ = w.Write([]byte(`{"id":40,"body":"Fixed"}`))
|
||||
case "DELETE /api/v1/repos/alice/project/issues/comments/40":
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
default:
|
||||
t.Errorf("unexpected %s %s", r.Method, r.URL.Path)
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
deps, _, _ := serverDeps(t, server.URL)
|
||||
run := func(args ...string) error {
|
||||
return Execute(context.Background(), deps, append([]string{"pr", "comment"}, append(args, "-R", "alice/project", "--no-input")...))
|
||||
}
|
||||
require.NoError(t, run("edit", "40", "--body", "Fixed"))
|
||||
require.NoError(t, run("delete", "40", "--yes"))
|
||||
require.Contains(t, calls, "PATCH /api/v1/repos/alice/project/issues/comments/40")
|
||||
require.Contains(t, calls, "DELETE /api/v1/repos/alice/project/issues/comments/40")
|
||||
// Viewing still explains why an inline review comment cannot be shown.
|
||||
require.ErrorContains(t, run("view", "40"), "not a plain comment")
|
||||
}
|
||||
|
||||
@@ -413,15 +413,29 @@ func (a *application) completeUsers() cobra.CompletionFunc {
|
||||
|
||||
// completeBranches completes the local branches, then the repository's branches.
|
||||
func (a *application) completeBranches() cobra.CompletionFunc {
|
||||
return mergeCompletions(a.completeLocalBranches, a.apiCompletion(true, func(ctx context.Context, t target, _ string) ([]cobra.Completion, error) {
|
||||
items, err := services.Branches{Client: t.client}.ListPage(ctx, t.Repo, completionLimit, 1)
|
||||
return describe(items.Items, func(item services.Branch) (string, string) {
|
||||
if item.Protected {
|
||||
return item.Name, "protected"
|
||||
}
|
||||
return item.Name, ""
|
||||
}), err
|
||||
}))
|
||||
return mergeCompletions(a.completeLocalBranches, a.apiCompletion(true, listBranches))
|
||||
}
|
||||
|
||||
// completeArgumentBranches is completeBranches for a command with a positional [<repository>]:
|
||||
// once that argument is given, it completes that repository's branches, not those of the clone here.
|
||||
func (a *application) completeArgumentBranches() cobra.CompletionFunc {
|
||||
inClone := a.completeBranches()
|
||||
return func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
|
||||
if len(args) == 0 || a.options.repo != "" {
|
||||
return inClone(cmd, args, toComplete)
|
||||
}
|
||||
return a.apiCompletionIn(args[0], true, listBranches)(cmd, args, toComplete)
|
||||
}
|
||||
}
|
||||
|
||||
func listBranches(ctx context.Context, t target, _ string) ([]cobra.Completion, error) {
|
||||
items, err := services.Branches{Client: t.client}.ListPage(ctx, t.Repo, completionLimit, 1)
|
||||
return describe(items.Items, func(item services.Branch) (string, string) {
|
||||
if item.Protected {
|
||||
return item.Name, "protected"
|
||||
}
|
||||
return item.Name, ""
|
||||
}), err
|
||||
}
|
||||
|
||||
// completeTags completes the repository's tags.
|
||||
|
||||
@@ -238,10 +238,7 @@ func pullReviewComments(cmd *cobra.Command, t target, n int64, reviews []service
|
||||
return nil, err
|
||||
}
|
||||
for _, comment := range inline {
|
||||
location := comment.Path
|
||||
if comment.Line > 0 {
|
||||
location = fmt.Sprintf("%s:%d", comment.Path, comment.Line)
|
||||
}
|
||||
location := comment.Location()
|
||||
result = append(result, discussionComment{
|
||||
author: comment.Author, createdAt: comment.CreatedAt, body: comment.Body, id: comment.ID,
|
||||
heading: "commented on " + location, meta: [2]string{"path", location},
|
||||
|
||||
@@ -87,6 +87,9 @@ func (a *application) download(cmd *cobra.Command, f downloadFlags, path string,
|
||||
if path == "-" {
|
||||
return writeTerminalSafe(cmd.OutOrStdout(), a.deps.Streams.OutTTY, body)
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o777); err != nil {
|
||||
return err
|
||||
}
|
||||
return publish(cmd, path, false, f.clobber, func(destination io.Writer) error {
|
||||
_, err := io.Copy(destination, body)
|
||||
return err
|
||||
@@ -169,6 +172,38 @@ func publish(cmd *cobra.Command, output string, private, replace bool, write fun
|
||||
if errors.Is(err, os.ErrExist) {
|
||||
return clierr.Wrap(clierr.Usage, fmt.Errorf("%s already exists", output))
|
||||
}
|
||||
if err != nil {
|
||||
// Some filesystems, such as FAT and many network mounts, cannot hard link.
|
||||
return copyExclusive(file.Name(), output, private, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// copyExclusive copies the finished temporary file to output, which must not exist, when linking
|
||||
// failed with linkErr. A failed copy removes the partial output.
|
||||
func copyExclusive(temporary, output string, private bool, linkErr error) error {
|
||||
mode := os.FileMode(0o666)
|
||||
if private {
|
||||
mode = 0o600
|
||||
}
|
||||
destination, err := os.OpenFile(output, os.O_WRONLY|os.O_CREATE|os.O_EXCL, mode)
|
||||
if errors.Is(err, os.ErrExist) {
|
||||
return clierr.Wrap(clierr.Usage, fmt.Errorf("%s already exists", output))
|
||||
}
|
||||
if err != nil {
|
||||
return linkErr
|
||||
}
|
||||
source, err := os.Open(temporary)
|
||||
if err == nil {
|
||||
defer source.Close()
|
||||
_, err = io.Copy(destination, source)
|
||||
}
|
||||
if closeErr := destination.Close(); err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
if err != nil {
|
||||
_ = os.Remove(output)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
@@ -184,3 +184,32 @@ func TestDownloadFlagsRegisterGhNames(t *testing.T) {
|
||||
require.Equal(t, "dir", flags.dir)
|
||||
require.True(t, cmd.Flags().Lookup("output-file").Hidden)
|
||||
}
|
||||
|
||||
func TestDownloadCreatesTheMissingDirectory(t *testing.T) {
|
||||
t.Chdir(t.TempDir())
|
||||
deps, _, _ := testDeps(t)
|
||||
a := &application{deps: deps}
|
||||
cmd := &cobra.Command{}
|
||||
cmd.SetContext(context.Background())
|
||||
flags := downloadFlags{dir: filepath.Join("dist", "assets")}
|
||||
path, _, err := flags.destination("asset.bin")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, a.download(cmd, flags, path, strings.NewReader("new")))
|
||||
data, err := os.ReadFile(filepath.Join("dist", "assets", "asset.bin"))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "new", string(data))
|
||||
}
|
||||
|
||||
func TestCopyExclusiveStandsInForFilesystemsWithoutHardLinks(t *testing.T) {
|
||||
directory := t.TempDir()
|
||||
temporary := filepath.Join(directory, ".gt-download-1")
|
||||
require.NoError(t, os.WriteFile(temporary, []byte("body"), 0o600))
|
||||
output := filepath.Join(directory, "asset.bin")
|
||||
linkErr := errors.New("operation not supported")
|
||||
require.NoError(t, copyExclusive(temporary, output, true, linkErr))
|
||||
data, err := os.ReadFile(output)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "body", string(data))
|
||||
require.ErrorContains(t, copyExclusive(temporary, output, true, linkErr), "already exists")
|
||||
require.ErrorIs(t, copyExclusive(temporary, filepath.Join(directory, "missing", "asset.bin"), true, linkErr), linkErr)
|
||||
}
|
||||
|
||||
@@ -68,7 +68,7 @@ func TestCommentEditEditorSeedsCurrentBody(t *testing.T) {
|
||||
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.Method == http.MethodGet && r.URL.Path == "/api/v1/repos/alice/project/issues/comments/7":
|
||||
_, _ = w.Write([]byte(`{"id":7,"body":"current comment"}`))
|
||||
_, _ = w.Write([]byte(`{"id":7,"body":"current comment","user":{"login":"alice"}}`))
|
||||
case r.Method == http.MethodPatch && r.URL.Path == "/api/v1/repos/alice/project/issues/comments/7":
|
||||
var options struct{ Body string }
|
||||
require.NoError(t, json.NewDecoder(r.Body).Decode(&options))
|
||||
@@ -293,9 +293,8 @@ func TestReviewLifecycleEditorRejectsEmptyRequiredText(t *testing.T) {
|
||||
for _, verb := range []string{"submit", "dismiss"} {
|
||||
t.Run(verb, func(t *testing.T) {
|
||||
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
require.Equal(t, "submit", verb)
|
||||
require.Equal(t, http.MethodGet, r.Method)
|
||||
_, _ = w.Write([]byte(`{"id":7,"body":"Saved draft"}`))
|
||||
_, _ = w.Write([]byte(`{"id":7,"body":"Saved draft","state":"APPROVED","user":{"login":"bob"}}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
deps, out, _ := testDeps(t)
|
||||
|
||||
@@ -292,9 +292,11 @@ func helpTopics(globals *pflag.FlagSet) []*cobra.Command {
|
||||
|
||||
` + indent(flagUsages(flags)) + `
|
||||
|
||||
gt selects the repository from --repo, GITEA_CLI_REPO, git config gt.repository or a
|
||||
Git remote (--remote, else the current branch's remote, upstream or origin, skipping
|
||||
remotes on instances without an account, or not on --host or the GITEA_TOKEN instance),
|
||||
gt selects the repository from --repo, GITEA_CLI_REPO, git config gt.repository (gt repo
|
||||
set-default) or a Git remote (--remote, else the base remote pr checkout recorded, the
|
||||
current branch's remote, upstream or origin, skipping remotes on instances without an
|
||||
account, or not on --host or the GITEA_TOKEN instance). Like gh, a clone with upstream
|
||||
and origin targets upstream: a branch tracking origin does not select the fork,
|
||||
and the instance from the repository URL, --host, GITEA_CLI_HOST or GITEA_INSTANCE_URL,
|
||||
default_host, or the only configured instance.
|
||||
|
||||
|
||||
@@ -83,6 +83,10 @@ func writeTable[T any](a *application, cmd *cobra.Command, items []T, spec listS
|
||||
}
|
||||
d := a.display()
|
||||
if len(items) == 0 {
|
||||
// A filtered page can be empty while later pages are not.
|
||||
if page.More {
|
||||
return a.morePagesHint(cmd, true, page.Number)
|
||||
}
|
||||
if !d.TTY || spec.Empty == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -281,7 +281,10 @@ func TestWriteTable(t *testing.T) {
|
||||
stderr: "more results available; use --page 3\n",
|
||||
},
|
||||
{name: "empty message on a terminal", tty: true, page: listPage{Number: 1}, stderr: "no open issues in alice/x\n"},
|
||||
{name: "next-page hint instead of the empty message on a filtered page", tty: true, page: listPage{Number: 1, More: true}, stderr: "more results available; use --page 2\n"},
|
||||
{name: "nothing when empty and piped", page: listPage{Number: 1}},
|
||||
{name: "next-page hint when an empty page has more", tty: true, page: listPage{Number: 1, More: true}, stderr: "more results available; use --page 2\n"},
|
||||
{name: "next-page hint when an empty page has more and piped", page: listPage{Number: 1, More: true}, stderr: "more results available; use --page 2\n"},
|
||||
{name: "JSON", tty: true, json: "number", items: items[:1], page: listPage{Number: 1, More: true}, out: "[\n {\n \"number\": 12\n }\n]\n"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
|
||||
@@ -477,7 +477,8 @@ func TestGiteaMetadataLifecycle(t *testing.T) {
|
||||
publicKey, err := ssh.NewPublicKey(privateKey.Public())
|
||||
require.NoError(t, err)
|
||||
keyFile := filepath.Join(t.TempDir(), "integration.pub")
|
||||
require.NoError(t, os.WriteFile(keyFile, ssh.MarshalAuthorizedKey(publicKey), 0o600))
|
||||
// The title defaults to the key comment.
|
||||
require.NoError(t, os.WriteFile(keyFile, append(bytes.TrimSpace(ssh.MarshalAuthorizedKey(publicKey)), " integration\n"...), 0o600))
|
||||
var key services.SSHKey
|
||||
require.NoError(t, json.Unmarshal(execute("ssh-key", "create", keyFile, "--json"), &key))
|
||||
require.Positive(t, key.ID)
|
||||
|
||||
@@ -42,30 +42,50 @@ func TestIssueCreateSeedsFromTemplate(t *testing.T) {
|
||||
run := func(args ...string) error {
|
||||
return Execute(context.Background(), deps, append([]string{"issue", "create", "-R", "alice/project", "--no-input", "--json=number"}, args...))
|
||||
}
|
||||
require.NoError(t, run("--template", "bug report"))
|
||||
err := run("--template", "bug report")
|
||||
require.ErrorContains(t, err, "missing required input: supply --title", "the template title is a placeholder and is never filed")
|
||||
require.NoError(t, run("--template", "bug report", "--title", "Crash"))
|
||||
require.NoError(t, run("--template", "Bug Report", "--title", "Explicit", "--body", "Override"))
|
||||
require.NoError(t, run("--template", "feature", "--title", "Idea", "--editor"))
|
||||
require.Equal(t, "Describe the idea", editor.initial)
|
||||
err := run("--template", "missing", "--title", "x")
|
||||
err = run("--template", "missing", "--title", "x")
|
||||
require.ErrorContains(t, err, `issue template "missing" does not exist; available: Bug Report, Feature`)
|
||||
require.Equal(t, clierr.Failure, clierr.ExitCode(err))
|
||||
err = run("--template", "feature")
|
||||
require.ErrorContains(t, err, "missing required input: supply --title")
|
||||
deps.Streams.In = strings.NewReader("From stdin")
|
||||
require.NoError(t, run("--template", "bug report", "--body-file", "-"))
|
||||
require.NoError(t, run("--template", "bug report", "--title", "Crash", "--body-file", "-"))
|
||||
err = run("--template", "feature", "--body-file", "-")
|
||||
require.ErrorContains(t, err, "--body-file - requires --title")
|
||||
require.Len(t, created, 4)
|
||||
for i, want := range []string{
|
||||
`{"title":"[bug] ","body":"Steps:"}`,
|
||||
`{"title":"Crash","body":"Steps:"}`,
|
||||
`{"title":"Explicit","body":"Override"}`,
|
||||
`{"title":"Idea","body":"edited idea"}`,
|
||||
`{"title":"[bug] ","body":"From stdin"}`,
|
||||
`{"title":"Crash","body":"From stdin"}`,
|
||||
} {
|
||||
requirePayload(t, want, strings.NewReader(created[i]))
|
||||
}
|
||||
}
|
||||
|
||||
func TestIssueCreateTemplateOpensFormWithTemplateBody(t *testing.T) {
|
||||
var createPayload map[string]any
|
||||
server := newAuthenticatedServer(selectablesHandler(t, true, func(w http.ResponseWriter, r *http.Request) {
|
||||
require.NoError(t, json.NewDecoder(r.Body).Decode(&createPayload))
|
||||
_, _ = w.Write([]byte(`{"number":9,"title":"Mine"}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
form := &recordingIssueForm{values: terminal.IssueFormValues{Title: "Mine", Body: "## Steps"}}
|
||||
deps, _, _ := serverDeps(t, server.URL)
|
||||
deps.IssueForm = form
|
||||
deps.Prompter = &scriptedPrompter{accept: true}
|
||||
deps.Streams.InTTY, deps.Streams.ErrTTY = true, true
|
||||
require.NoError(t, Execute(context.Background(), deps, []string{"issue", "create", "-R", "alice/project", "--json=number", "--interactive", "--template", "bug"}))
|
||||
require.Equal(t, 1, form.calls)
|
||||
require.Equal(t, &terminal.IssueTemplateChoice{Name: "Bug", About: "Report", Body: "## Steps"}, form.choices.Template, "the form starts with the template body and an empty title")
|
||||
require.Equal(t, "Mine", createPayload["title"])
|
||||
}
|
||||
|
||||
func TestIssueCreateUploadsAttachmentsAndKeepsIssueOnFailure(t *testing.T) {
|
||||
var requests, uploaded []string
|
||||
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
+17
-7
@@ -203,7 +203,11 @@ func (a *application) issueCreateCommand() *cobra.Command {
|
||||
var useEditor, web bool
|
||||
var assignees, labelNames, attachmentPaths []string
|
||||
cmd := &cobra.Command{Use: "create", Aliases: []string{"new"}, Short: "Create an issue", Long: `Create an issue in a repository. Without flags on a terminal, a form asks for the title and
|
||||
body, then optionally for assignees, a milestone, labels and a due date.`, Example: `$ gt issue create
|
||||
body, then optionally for assignees, a milestone, labels and a due date.
|
||||
|
||||
--template starts from the body of a repository issue template; on a terminal the form opens with
|
||||
that body and an empty title. Without a terminal, --title is required, and --body or --body-file
|
||||
replace the template body.`, Example: `$ gt issue create
|
||||
$ gt issue create --title "Crash on start" --body "Steps to reproduce…" --label bug --milestone v1.0
|
||||
$ gt issue create --template "Bug report"`, Args: argsExact(0), RunE: func(cmd *cobra.Command, _ []string) (runErr error) {
|
||||
var draft terminal.Draft
|
||||
@@ -243,8 +247,8 @@ $ gt issue create --template "Bug report"`, Args: argsExact(0), RunE: func(cmd *
|
||||
}
|
||||
}
|
||||
}
|
||||
if !localFlagsChanged(cmd) && a.canPrompt() && a.deps.IssueForm != nil {
|
||||
return a.createIssueInteractively(cmd)
|
||||
if !localFlagsChanged(cmd, "template") && a.canPrompt() && a.deps.IssueForm != nil {
|
||||
return a.createIssueInteractively(cmd, strings.TrimSpace(templateName))
|
||||
}
|
||||
var target target
|
||||
var templateBody string
|
||||
@@ -258,9 +262,7 @@ $ gt issue create --template "Bug report"`, Args: argsExact(0), RunE: func(cmd *
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !cmd.Flags().Changed("title") {
|
||||
title = template.Title
|
||||
}
|
||||
// Like gh, the template only seeds the body; its title is a placeholder, so --title is required.
|
||||
templateBody = issueTemplateBody(template)
|
||||
}
|
||||
if web {
|
||||
@@ -344,7 +346,8 @@ func (a *application) issueCreated(cmd *cobra.Command, t target, item services.I
|
||||
return a.created(cmd, item, item.URL)
|
||||
}
|
||||
|
||||
func (a *application) createIssueInteractively(cmd *cobra.Command) (runErr error) {
|
||||
// createIssueInteractively runs the create form; a non-empty templateName pre-fills its body.
|
||||
func (a *application) createIssueInteractively(cmd *cobra.Command, templateName string) (runErr error) {
|
||||
target, err := a.resolve(cmd.Context(), true)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -363,6 +366,13 @@ func (a *application) createIssueInteractively(cmd *cobra.Command) (runErr error
|
||||
choices.Templates = append(choices.Templates, terminal.IssueTemplateChoice{Name: template.Name, About: template.About, Title: template.Title, Body: issueTemplateBody(template)})
|
||||
}
|
||||
choices.Milestones, choices.Labels = milestoneChoices(selectables.Milestones), labelChoices(selectables.Labels)
|
||||
if templateName != "" {
|
||||
template, err := issueTemplate(cmd.Context(), service, templateName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
choices.Template = &terminal.IssueTemplateChoice{Name: template.Name, About: template.About, Body: issueTemplateBody(template)}
|
||||
}
|
||||
values, err := a.deps.IssueForm.CreateIssue(cmd.Context(), choices)
|
||||
defer finishDraft(&values.Draft, &runErr)
|
||||
if err != nil {
|
||||
|
||||
+13
-4
@@ -40,10 +40,7 @@ func (a *application) manCommand() *cobra.Command {
|
||||
return err
|
||||
}
|
||||
if len(args) == 0 {
|
||||
for _, child := range page.Commands() {
|
||||
if child.Hidden {
|
||||
continue
|
||||
}
|
||||
for _, child := range ManualCommands(page) {
|
||||
if err := render(child); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -67,3 +64,15 @@ func ManualDate(getenv func(string) string) time.Time {
|
||||
}
|
||||
return time.Date(2026, time.January, 1, 0, 0, 0, 0, time.UTC)
|
||||
}
|
||||
|
||||
// ManualCommands lists the subcommands that get a page in the manual: the available commands,
|
||||
// without the generated help command, and the help topics such as environment and exit-codes.
|
||||
func ManualCommands(page *cobra.Command) []*cobra.Command {
|
||||
var children []*cobra.Command
|
||||
for _, child := range page.Commands() {
|
||||
if child.Annotations[topicAnnotation] != "" || (child.IsAvailableCommand() && !child.IsAdditionalHelpTopicCommand()) {
|
||||
children = append(children, child)
|
||||
}
|
||||
}
|
||||
return children
|
||||
}
|
||||
|
||||
@@ -66,3 +66,12 @@ func TestCanceledManDoesNotPublishOutputFile(t *testing.T) {
|
||||
require.True(t, os.IsNotExist(err))
|
||||
require.Empty(t, out.String())
|
||||
}
|
||||
|
||||
func TestManIncludesHelpTopicsButNotHelpCommands(t *testing.T) {
|
||||
deps, out, _ := testDeps(t)
|
||||
require.NoError(t, Execute(context.Background(), deps, []string{"man"}))
|
||||
manual := out.String()
|
||||
require.Contains(t, manual, `.TH "GT-ENVIRONMENT"`)
|
||||
require.Contains(t, manual, `.TH "GT-EXIT-CODES"`)
|
||||
require.NotContains(t, manual, `.TH "GT-PR-HELP"`)
|
||||
}
|
||||
|
||||
@@ -193,7 +193,7 @@ func (a *application) notificationWatchCommand(scope func(*cobra.Command) (notif
|
||||
Long: `Print notifications as they arrive or change, until Ctrl-C or --timeout. On a terminal
|
||||
it runs until stopped; otherwise it stops after a minute unless --timeout says otherwise.
|
||||
With --json it prints one JSON object per line.`,
|
||||
Example: "$ gt notification watch\n# Stream new pull request notifications to a script\n$ gt notification watch --type pull --json id,repository,title | ./notify.sh",
|
||||
Example: "$ gt notification watch\n# Stream pull request notifications to a script, starting with the current ones\n$ gt notification watch --type pull --json id,repository,title --timeout 0 | ./notify.sh",
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
listed, err := a.notificationOptions(opts, updated)
|
||||
if err != nil {
|
||||
@@ -284,10 +284,14 @@ pinned.`,
|
||||
if err := writeView(a, cmd, item, func(item services.Notification) terminal.View { return notificationView(item, comment, a.display()) }); err != nil {
|
||||
return err
|
||||
}
|
||||
// Marking is a side effect of viewing: a token without write:notification, or an
|
||||
// administrator reading another user's thread, still gets the view.
|
||||
if item.Unread && !item.Pinned {
|
||||
_, err = s.Mark(cmd.Context(), id, "read")
|
||||
if _, err := s.Mark(cmd.Context(), id, "read"); err != nil {
|
||||
a.warn(cmd, "Could not mark notification %d as read: %v", id, err)
|
||||
}
|
||||
}
|
||||
return err
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -380,17 +384,24 @@ func notificationView(item services.Notification, comment *services.Comment, d t
|
||||
Title: item.Title, Meta: meta, Kind: notificationKinds[item.Type], URL: item.URL,
|
||||
Badges: []terminal.Cell{{Text: titleCase(item.State), Color: stateColors[item.State]}, {Text: notificationStatus(item), Muted: true}},
|
||||
Fields: []terminal.Field{{Label: "Notification", Value: strconv.FormatInt(item.ID, 10)}, {Label: "Type", Value: notificationKinds[item.Type]}, {Label: "Repository", Value: item.Repository}},
|
||||
Body: "_No comments yet._",
|
||||
}
|
||||
if d.TTY {
|
||||
view.Body = "_No comments yet._"
|
||||
}
|
||||
view.Fields = append(view.Fields,
|
||||
terminal.Field{Label: "State", Value: item.State, PipedOnly: true},
|
||||
terminal.Field{Label: "Status", Value: notificationStatus(item), PipedOnly: true})
|
||||
if item.Number != 0 {
|
||||
view.ID = "#" + strconv.FormatInt(item.Number, 10)
|
||||
}
|
||||
if comment != nil {
|
||||
when := ""
|
||||
if created := terminal.ParseTime(comment.CreatedAt); !created.IsZero() {
|
||||
if created := terminal.ParseTime(comment.CreatedAt); d.TTY && !created.IsZero() {
|
||||
when = ", " + terminal.RelativeTime(d.Now, created)
|
||||
}
|
||||
view.Fields = append(view.Fields, terminal.Field{Label: "Latest comment", Value: comment.Author + when})
|
||||
commented := timeField("Commented", comment.CreatedAt, d)
|
||||
commented.PipedOnly = true
|
||||
view.Fields = append(view.Fields, terminal.Field{Label: "Latest comment", Value: comment.Author + when}, commented)
|
||||
view.Body = comment.Body
|
||||
}
|
||||
return view
|
||||
|
||||
@@ -155,3 +155,23 @@ func TestNotificationMarkAllNamesTheBeforeCutoff(t *testing.T) {
|
||||
require.NoError(t, Execute(context.Background(), deps, []string{"notification", "mark-read", "--all", "--before=1h"}))
|
||||
require.Contains(t, withoutANSI(diagnostics.String()), "No unread notifications updated before 2028-02-01 11:00 in your inbox")
|
||||
}
|
||||
|
||||
func TestNotificationViewSurvivesARefusedMark(t *testing.T) {
|
||||
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.Method {
|
||||
case http.MethodPatch:
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
_, _ = w.Write([]byte(`{"message":"token does not have write:notification scope"}`))
|
||||
default:
|
||||
_, _ = w.Write([]byte(`{"id":12,"unread":true,"repository":{"full_name":"alice/project"},"subject":{"title":"Improve greeting","type":"Pull","state":"open","url":"https://gitea.test/api/v1/repos/alice/project/issues/17"}}`))
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
deps, out, diagnostics := serverDeps(t, server.URL)
|
||||
require.NoError(t, Execute(context.Background(), deps, []string{"notification", "view", "12"}))
|
||||
require.Contains(t, out.String(), "title:\tImprove greeting\n")
|
||||
require.Contains(t, out.String(), "state:\topen\n")
|
||||
require.Contains(t, out.String(), "status:\tunread\n")
|
||||
require.NotContains(t, out.String(), "_No comments yet._")
|
||||
require.Contains(t, diagnostics.String(), "Could not mark notification 12 as read")
|
||||
}
|
||||
|
||||
@@ -4,6 +4,9 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"gitea.dev/cli/internal/clierr"
|
||||
"gitea.dev/cli/internal/terminal"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
@@ -52,5 +55,9 @@ func (a *application) requireInput(cmd *cobra.Command, value *string, flag, labe
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if hidden := cmd.Flags().Lookup(flag); *value == "" && hidden != nil && hidden.Hidden && !a.policy(s).CanPrompt(a.deps.Streams) {
|
||||
// --help does not list the flag, so point at the argument it stands in for.
|
||||
return false, clierr.Wrap(clierr.Usage, fmt.Errorf("missing required input: %s (pass it as an argument)", label))
|
||||
}
|
||||
return terminal.RequireInput(cmd.Context(), value, flag, label, validate, a.deps.Streams, a.policy(s), a.deps.Prompter)
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ import (
|
||||
func (a *application) pullCleanCommand() *cobra.Command {
|
||||
var ignoreSHA bool
|
||||
cmd := &cobra.Command{Use: "clean [<number> | <url> | <branch>]", Short: "Delete the branches of a merged or closed pull request", Annotations: pullArgumentsAnnotation(map[string]string{"gt.confirm": "true"}), Args: usageArgs(cobra.MaximumNArgs(1)), RunE: func(cmd *cobra.Command, args []string) error {
|
||||
target, n, err := a.pullSelector(cmd, args)
|
||||
target, n, err := a.pullSelectorAny(cmd, args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -120,7 +120,7 @@ func (a *application) pullCleanCommand() *cobra.Command {
|
||||
return a.jsonResult(cmd, result)
|
||||
}}
|
||||
cmd.Flags().BoolVar(&ignoreSHA, "ignore-sha", false, "Find the local branch by name instead of commit hash")
|
||||
cmd.ValidArgsFunction = a.completePulls("closed")
|
||||
cmd.ValidArgsFunction = firstArg(a.completePulls("closed"))
|
||||
cmd.Example = `# After #13 was merged, delete its branch locally and on Gitea
|
||||
$ gt pr clean 13`
|
||||
return cmd
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// closedLookupServer has one open pull request, for feat, and closed ones for gone, listed
|
||||
// newest first like sort=recentupdate.
|
||||
func closedLookupServer(t *testing.T, requests *[]string) string {
|
||||
t.Helper()
|
||||
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
*requests = append(*requests, r.Method+" "+r.URL.Path+"?state="+r.URL.Query().Get("state"))
|
||||
if number, ok := strings.CutPrefix(r.URL.Path, "/api/v1/repos/alice/project/pulls/"); ok {
|
||||
_, _ = fmt.Fprintf(w, `{"number":%s,"title":"Old","state":"closed","merged":true,"head":{"ref":"gone","sha":"abc","repo":{"full_name":"alice/project"}}}`, number)
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/api/v1/repos/alice/project" {
|
||||
_, _ = fmt.Fprint(w, `{"full_name":"alice/project","default_branch":"main"}`)
|
||||
return
|
||||
}
|
||||
if r.URL.Path != "/api/v1/repos/alice/project/pulls" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if r.URL.Query().Get("state") == "open" {
|
||||
writeFirstPage(w, r, `[{"number":3,"head":{"ref":"feat","repo":{"full_name":"alice/project"}}}]`)
|
||||
return
|
||||
}
|
||||
require.Equal(t, "closed", r.URL.Query().Get("state"))
|
||||
require.Equal(t, "recentupdate", r.URL.Query().Get("sort"))
|
||||
writeFirstPage(w, r, `[
|
||||
{"number":40,"head":{"ref":"gone","repo":{"full_name":"bob/project"}}},
|
||||
{"number":31,"head":{"ref":"gone","repo":{"full_name":"alice/project"}}},
|
||||
{"number":30,"head":{"ref":"gone","repo":{"full_name":"alice/project"}}}
|
||||
]`)
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
return server.URL
|
||||
}
|
||||
|
||||
func TestPullSelectorAnyFallsBackToTheNewestClosedPull(t *testing.T) {
|
||||
var requests []string
|
||||
serverURL := closedLookupServer(t, &requests)
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
arg string
|
||||
want int64
|
||||
err string
|
||||
}{
|
||||
{"open one wins", "feat", 3, ""},
|
||||
{"newest closed", "gone", 40, ""},
|
||||
{"owner qualified", "alice:gone", 31, ""},
|
||||
{"unknown", "nothing", 0, `no open pull request for branch "nothing"`},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
a, _ := refApplicationWith(t, serverURL, nil)
|
||||
_, n, err := a.pullSelectorAny(commandContext(), []string{tc.arg})
|
||||
if tc.err != "" {
|
||||
require.ErrorContains(t, err, tc.err)
|
||||
return
|
||||
}
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, tc.want, n)
|
||||
})
|
||||
}
|
||||
// Commands that need an open pull request still do not see closed ones.
|
||||
requests = nil
|
||||
a, _ := refApplicationWith(t, serverURL, nil)
|
||||
_, _, err := a.pullSelector(commandContext(), []string{"gone"})
|
||||
require.ErrorContains(t, err, `no open pull request for branch "gone"`)
|
||||
require.NotContains(t, strings.Join(requests, "\n"), "state=closed")
|
||||
}
|
||||
|
||||
func TestPullSelectorAnyFallsBackForTheCheckedOutBranch(t *testing.T) {
|
||||
var requests []string
|
||||
serverURL := closedLookupServer(t, &requests)
|
||||
a, _ := refApplicationWith(t, serverURL, map[string]string{"symbolic-ref --quiet HEAD": "gone"})
|
||||
// The fork's newer pull request for a branch named like the local one is not this repository's.
|
||||
_, n, err := a.pullSelectorAny(commandContext(), nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, int64(31), n)
|
||||
_, _, err = a.pullSelector(commandContext(), nil)
|
||||
require.ErrorContains(t, err, `no open pull request for branch "gone"`)
|
||||
}
|
||||
|
||||
func TestPullCommandsFindClosedPullsByBranch(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
args []string
|
||||
err string
|
||||
// request is the request that proves the closed pull request was found.
|
||||
request string
|
||||
}{
|
||||
{"view", []string{"pr", "view", "alice:gone", "--json=number"}, "", ""},
|
||||
{"checks", []string{"pr", "checks", "alice:gone", "--web", "--no-input"}, "", ""},
|
||||
{"reopen", []string{"pr", "reopen", "alice:gone"}, "already merged", ""},
|
||||
{"clean", []string{"pr", "clean", "alice:gone", "--no-input"}, "", ""},
|
||||
{"edit", []string{"pr", "edit", "alice:gone", "--title", "New"}, "", "PATCH /api/v1/repos/alice/project/pulls/31?state="},
|
||||
{"checkout", []string{"pr", "checkout", "alice:gone", "--detach"}, "missing fake", "GET /api/v1/repos/alice/project/pulls?state=closed"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var requests []string
|
||||
serverURL := closedLookupServer(t, &requests)
|
||||
deps, _, _ := serverDeps(t, serverURL)
|
||||
deps.Getenv = serverEnv(serverURL, map[string]string{"GITEA_CLI_REPO": "alice/project"})
|
||||
deps.Git = &fakeGit{results: map[string]string{}}
|
||||
err := Execute(context.Background(), deps, tc.args)
|
||||
if tc.err != "" {
|
||||
require.ErrorContains(t, err, tc.err)
|
||||
}
|
||||
if err != nil {
|
||||
require.NotContains(t, err.Error(), "no open pull request")
|
||||
}
|
||||
request := cmp.Or(tc.request, "GET /api/v1/repos/alice/project/pulls/31?state=")
|
||||
require.Contains(t, requests, request, "err: %v", err)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPullMergeKeepsOpenOnlyLookup(t *testing.T) {
|
||||
var requests []string
|
||||
serverURL := closedLookupServer(t, &requests)
|
||||
deps, _, _ := serverDeps(t, serverURL)
|
||||
deps.Getenv = serverEnv(serverURL, map[string]string{"GITEA_CLI_REPO": "alice/project"})
|
||||
deps.Git = &fakeGit{results: map[string]string{}}
|
||||
err := Execute(context.Background(), deps, []string{"pr", "merge", "gone", "--yes", "--no-input"})
|
||||
require.ErrorContains(t, err, `no open pull request for branch "gone"`)
|
||||
require.NotContains(t, strings.Join(requests, "\n"), "state=closed")
|
||||
}
|
||||
@@ -326,24 +326,17 @@ func (a *application) createPullInteractively(cmd *cobra.Command, snapshot setti
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
repo, err := (services.Repositories{Client: target.client}).View(cmd.Context(), target.Repo)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
service := services.Pulls{Client: target.client, Repository: target.Repo}
|
||||
selectables, err := service.CreateSelectables(cmd.Context())
|
||||
loaded, err := service.CreateChoices(cmd.Context())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
repo, selectables := loaded.Repository, loaded.CreateSelectables
|
||||
baseOwner, _, _ := strings.Cut(target.Repo, "/")
|
||||
headOwner, headBranch := a.defaultPullHead(cmd.Context())
|
||||
template, err := service.Template(cmd.Context(), repo.DefaultBranch)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
title, body, _ := a.singleCommitMessage(cmd.Context(), repo.DefaultBranch, headBranch)
|
||||
if template != "" {
|
||||
body = template
|
||||
if loaded.Template != "" {
|
||||
body = loaded.Template
|
||||
}
|
||||
choices := terminal.PullFormChoices{
|
||||
Repo: target.Repo, BaseOwner: baseOwner, Base: repo.DefaultBranch, HeadOwner: headOwner, HeadBranch: headBranch, Title: title, Body: body,
|
||||
|
||||
@@ -76,7 +76,7 @@ pull request, or mark it as a draft or ready for review.`, Annotations: pullArgu
|
||||
if opts == (services.PullEdit{}) && !useEditor && !draft && !ready && !metadata.changed(cmd) && !cmd.Flags().Changed("milestone") && !removeMilestone {
|
||||
return clierr.Wrap(clierr.Usage, errors.New("nothing to edit; pass a flag such as --title (see gt pr edit --help)"))
|
||||
}
|
||||
t, n, err := a.pullSelector(cmd, args)
|
||||
t, n, err := a.pullSelectorAny(cmd, args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -149,7 +149,7 @@ pull request, or mark it as a draft or ready for review.`, Annotations: pullArgu
|
||||
}
|
||||
_ = cmd.RegisterFlagCompletionFunc("base", a.completeBranches())
|
||||
_ = cmd.RegisterFlagCompletionFunc("milestone", a.completeMilestones())
|
||||
cmd.ValidArgsFunction = a.completePulls("open")
|
||||
cmd.ValidArgsFunction = firstArg(a.completePulls("open"))
|
||||
cmd.Example = `$ gt pr edit 13 --title "Add login support" --add-reviewer carol
|
||||
$ gt pr edit --base develop
|
||||
$ gt pr edit 13 --editor`
|
||||
@@ -206,7 +206,7 @@ removes or adds that marker.`, Annotations: pullArgumentsAnnotation(nil), Args:
|
||||
return a.jsonResult(cmd, item)
|
||||
}}
|
||||
cmd.Flags().BoolVar(&undo, "undo", false, "Turn the pull request back into a draft")
|
||||
cmd.ValidArgsFunction = a.completePulls("open")
|
||||
cmd.ValidArgsFunction = firstArg(a.completePulls("open"))
|
||||
cmd.Example = `$ gt pr ready
|
||||
$ gt pr ready 15
|
||||
$ gt pr ready 15 --undo`
|
||||
|
||||
@@ -326,7 +326,7 @@ func testTeamReviewRequests(t *testing.T, deps *Dependencies, execute func(...st
|
||||
t.Errorf("team review repository cleanup: %v", err)
|
||||
}
|
||||
})
|
||||
execute("team", "repo", "add", teamID, "-R", repo.FullName)
|
||||
execute("team", "repo", "add", teamID, repo.FullName)
|
||||
execute("branch", "create", "feature", "-R", repo.FullName)
|
||||
deps.Streams.In = strings.NewReader(`{"branch":"feature","content":"dGVzdAo=","message":"Disposable team review change"}`)
|
||||
execute("api", "repos/"+repo.FullName+"/contents/change.txt", "--input", "-")
|
||||
|
||||
@@ -79,7 +79,7 @@ func (a *application) pullStateCommand(closing bool) *cobra.Command {
|
||||
var comment string
|
||||
var deleteBranch bool
|
||||
cmd := &cobra.Command{Use: verb + " [<number> | <url> | <branch>]", Short: titleCase(verb) + " a pull request", Annotations: pullArgumentsAnnotation(nil), Args: usageArgs(cobra.MaximumNArgs(1)), RunE: func(cmd *cobra.Command, args []string) error {
|
||||
t, n, err := a.pullSelector(cmd, args)
|
||||
t, n, err := a.pullSelectorAny(cmd, args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -111,7 +111,7 @@ func (a *application) pullStateCommand(closing bool) *cobra.Command {
|
||||
return a.jsonResult(cmd, item)
|
||||
}}
|
||||
cmd.Flags().StringVarP(&comment, "comment", "c", "", "Leave a comment before changing the state")
|
||||
cmd.ValidArgsFunction = a.completePulls(map[bool]string{true: "open", false: "closed"}[closing])
|
||||
cmd.ValidArgsFunction = firstArg(a.completePulls(map[bool]string{true: "open", false: "closed"}[closing]))
|
||||
if closing {
|
||||
cmd.Flags().BoolVarP(&deleteBranch, "delete-branch", "d", false, "Delete the head branch on Gitea and, when it is checked out, locally")
|
||||
cmd.Example = `$ gt pr close 13
|
||||
@@ -176,7 +176,7 @@ func (a *application) pullDiffCommand() *cobra.Command {
|
||||
|
||||
On a terminal the diff is colored and paged. Piped, it is written unchanged, so that
|
||||
gt pr diff 13 | git apply works.`, Annotations: pullArgumentsAnnotation(textOutput("diff returns patch text")), Args: usageArgs(cobra.MaximumNArgs(1)), RunE: func(cmd *cobra.Command, args []string) error {
|
||||
t, n, err := a.pullSelector(cmd, args)
|
||||
t, n, err := a.pullSelectorAny(cmd, args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -219,7 +219,7 @@ gt pr diff 13 | git apply works.`, Annotations: pullArgumentsAnnotation(textOutp
|
||||
cmd.Flags().BoolVar(&nameOnly, "name-only", false, "List only the names of the changed files")
|
||||
enumFlag(cmd, &color, "color", "", "auto", "Color the diff", "auto", "always", "never")
|
||||
cmd.Flags().BoolVarP(&web, "web", "w", false, "Open the changed files in the browser")
|
||||
cmd.ValidArgsFunction = a.completePulls("all")
|
||||
cmd.ValidArgsFunction = firstArg(a.completePulls("all"))
|
||||
cmd.Example = `$ gt pr diff
|
||||
$ gt pr diff 13 --name-only
|
||||
$ gt pr diff 13 | git apply`
|
||||
@@ -384,7 +384,7 @@ the base branch.`, Annotations: pullArgumentsAnnotation(map[string]string{"gt.co
|
||||
}
|
||||
return c.Root().FlagErrorFunc()(c, err)
|
||||
})
|
||||
cmd.ValidArgsFunction = a.completePulls("open")
|
||||
cmd.ValidArgsFunction = firstArg(a.completePulls("open"))
|
||||
cmd.Example = `# Merge the pull request of the current branch with the repository's default style
|
||||
$ gt pr merge
|
||||
|
||||
|
||||
+32
-21
@@ -19,18 +19,30 @@ import (
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
const pullArguments = `A pull request can be supplied as argument in any of the following formats:
|
||||
const pullArgumentFormats = `A pull request can be supplied as argument in any of the following formats:
|
||||
- by number, such as "13" or "#13"
|
||||
- by URL, such as "https://gitea.com/OWNER/REPO/pulls/13"
|
||||
- by the name of its head branch, such as "feature/login" or "bob:feature/login"
|
||||
- by the name of its head branch, such as "feature/login" or "bob:feature/login"`
|
||||
|
||||
const pullArguments = pullArgumentFormats + `
|
||||
|
||||
Without an argument, the pull request of the current branch is selected.`
|
||||
|
||||
// pullArgumentsAnnotation documents a pull request argument that may be left out.
|
||||
func pullArgumentsAnnotation(annotations map[string]string) map[string]string {
|
||||
return argumentsAnnotation(annotations, pullArguments)
|
||||
}
|
||||
|
||||
// pullArgumentRequiredAnnotation documents a pull request argument that has no default.
|
||||
func pullArgumentRequiredAnnotation(annotations map[string]string) map[string]string {
|
||||
return argumentsAnnotation(annotations, pullArgumentFormats)
|
||||
}
|
||||
|
||||
func argumentsAnnotation(annotations map[string]string, text string) map[string]string {
|
||||
if annotations == nil {
|
||||
annotations = map[string]string{}
|
||||
}
|
||||
annotations["gt.arguments"] = pullArguments
|
||||
annotations["gt.arguments"] = text
|
||||
return annotations
|
||||
}
|
||||
|
||||
@@ -242,7 +254,7 @@ func (a *application) reviewCreateCommand(use, short string) *cobra.Command {
|
||||
cmd.Flags().BoolVarP(&useEditor, "editor", "e", false, "Write the body in your editor")
|
||||
cmd.Flags().StringVar(&commentsFile, "comments-file", "", "Read inline comments from a JSON `file`: an array of path, body, and new_position or old_position")
|
||||
cmd.Flags().StringVar(&commit, "commit", "", "Commit `sha` to review (default: the head of the pull request)")
|
||||
cmd.ValidArgsFunction = a.completePulls("open")
|
||||
cmd.ValidArgsFunction = firstArg(a.completePulls("open"))
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -442,7 +454,7 @@ func reviewPossessive(item services.Review) string {
|
||||
case "REQUEST_CHANGES":
|
||||
noun = "change request"
|
||||
}
|
||||
return item.Author + "'s " + noun
|
||||
return item.Reviewer() + "'s " + noun
|
||||
}
|
||||
|
||||
// pullAndID resolves the pull request and the ID that review subcommands take as their two arguments.
|
||||
@@ -462,17 +474,17 @@ func (a *application) pullReviewListCommand() *cobra.Command {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
items, err := (services.Reviews{Client: t.client, Repository: t.Repo}).List(cmd.Context(), n, limit, page)
|
||||
window, err := (services.Reviews{Client: t.client, Repository: t.Repo}).ListPage(cmd.Context(), n, limit, page)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ref := fmt.Sprintf("%s#%d", t.Repo, n)
|
||||
return writeTable(a, cmd, items, listSpec[services.Review]{
|
||||
return writeTable(a, cmd, window.Items, listSpec[services.Review]{
|
||||
Columns: []terminal.Column{{Header: "ID"}, {Header: "Reviewer"}, {Header: "State"}, {Header: "Submitted"}, {Header: "Comments"}, {Header: "Body", Flex: true}},
|
||||
Row: func(item services.Review) []terminal.Cell {
|
||||
return []terminal.Cell{
|
||||
{Text: strconv.FormatInt(item.ID, 10), Link: item.URL},
|
||||
{Text: item.Author},
|
||||
{Text: item.Reviewer()},
|
||||
reviewStateCell(item),
|
||||
{Time: terminal.ParseTime(item.SubmittedAt)},
|
||||
{Text: strconv.Itoa(item.CommentsCount)},
|
||||
@@ -480,17 +492,17 @@ func (a *application) pullReviewListCommand() *cobra.Command {
|
||||
}
|
||||
},
|
||||
Empty: "no reviews on " + ref, Context: "reviews on " + ref,
|
||||
}, listPage{Number: page, More: len(items) == limit})
|
||||
}, servicePage(window, page))
|
||||
}}
|
||||
pageFlags(cmd, &limit, &page)
|
||||
cmd.Example = `$ gt pr review list 13
|
||||
$ gt pr review list --json id,author,state`
|
||||
cmd.ValidArgsFunction = a.completePulls("all")
|
||||
cmd.ValidArgsFunction = firstArg(a.completePulls("all"))
|
||||
return cmd
|
||||
}
|
||||
|
||||
func (a *application) pullReviewViewCommand() *cobra.Command {
|
||||
cmd := &cobra.Command{Use: "view <number> <review-id>", Short: "View a review", Annotations: pullArgumentsAnnotation(nil), Args: argsExact(2), RunE: func(cmd *cobra.Command, args []string) error {
|
||||
cmd := &cobra.Command{Use: "view <number> <review-id>", Short: "View a review", Annotations: pullArgumentRequiredAnnotation(nil), Args: argsExact(2), RunE: func(cmd *cobra.Command, args []string) error {
|
||||
t, n, id, err := a.pullAndID(cmd, args)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -501,14 +513,14 @@ func (a *application) pullReviewViewCommand() *cobra.Command {
|
||||
}
|
||||
now := a.deps.Now()
|
||||
return writeView(a, cmd, item, func(item services.Review) terminal.View {
|
||||
meta := item.Author
|
||||
meta := item.Reviewer()
|
||||
if submitted := terminal.ParseTime(item.SubmittedAt); !submitted.IsZero() {
|
||||
meta += " • " + terminal.RelativeTime(now, submitted)
|
||||
}
|
||||
return terminal.View{
|
||||
Title: fmt.Sprintf("Review on %s#%d", t.Repo, n), ID: strconv.FormatInt(item.ID, 10), Badges: []terminal.Cell{reviewStateCell(item)}, Meta: meta,
|
||||
Fields: []terminal.Field{
|
||||
{Label: "Reviewer", Value: item.Author, PipedOnly: true},
|
||||
{Label: "Reviewer", Value: item.Reviewer(), PipedOnly: true},
|
||||
{Label: "State", Value: item.State, PipedOnly: true},
|
||||
{Label: "Inline comments", Value: strconv.Itoa(item.CommentsCount)},
|
||||
{Label: "Commit", Value: item.Commit},
|
||||
@@ -541,11 +553,7 @@ func (a *application) pullReviewCommentsCommand() *cobra.Command {
|
||||
return writeTable(a, cmd, items, listSpec[services.ReviewComment]{
|
||||
Columns: []terminal.Column{{Header: "ID"}, {Header: "File"}, {Header: "Author"}, {Header: "Resolved"}, {Header: "Body", Flex: true}},
|
||||
Row: func(item services.ReviewComment) []terminal.Cell {
|
||||
location := item.Path
|
||||
if item.Line > 0 {
|
||||
location = fmt.Sprintf("%s:%d", item.Path, item.Line)
|
||||
}
|
||||
return []terminal.Cell{{Text: strconv.FormatInt(item.ID, 10), Link: item.URL}, {Text: location}, {Text: item.Author}, {Text: item.Resolver}, {Text: item.Body}}
|
||||
return []terminal.Cell{{Text: strconv.FormatInt(item.ID, 10), Link: item.URL}, {Text: item.Location()}, {Text: item.Author}, {Text: item.Resolver}, {Text: item.Body}}
|
||||
},
|
||||
Empty: "no inline review comments on " + ref, Context: "inline review comments on " + ref,
|
||||
}, listPage{Number: page, More: len(items) == limit})
|
||||
@@ -554,7 +562,7 @@ func (a *application) pullReviewCommentsCommand() *cobra.Command {
|
||||
cmd.Flags().Int64Var(&reviewID, "review", 0, "Limit comments to one review `ID`")
|
||||
cmd.Example = `$ gt pr review comments 13
|
||||
$ gt pr review comments 13 --review 6`
|
||||
cmd.ValidArgsFunction = a.completePulls("all")
|
||||
cmd.ValidArgsFunction = firstArg(a.completePulls("all"))
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -585,7 +593,7 @@ func (a *application) pullReviewResolveCommand(resolve bool) *cobra.Command {
|
||||
func (a *application) pullReviewReplyCommand() *cobra.Command {
|
||||
var body, file string
|
||||
var useEditor bool
|
||||
cmd := &cobra.Command{Use: "reply <number> <comment-id>", Short: "Reply to an inline review comment", Annotations: pullArgumentsAnnotation(nil), Args: argsExact(2), RunE: func(cmd *cobra.Command, args []string) (runErr error) {
|
||||
cmd := &cobra.Command{Use: "reply <number> <comment-id>", Short: "Reply to an inline review comment", Annotations: pullArgumentRequiredAnnotation(nil), Args: argsExact(2), RunE: func(cmd *cobra.Command, args []string) (runErr error) {
|
||||
var draft terminal.Draft
|
||||
defer finishDraft(&draft, &runErr)
|
||||
if err := validateBodySources(cmd); err != nil {
|
||||
@@ -639,6 +647,9 @@ func (a *application) completeReviewArgs(inline bool) cobra.CompletionFunc {
|
||||
if len(args) == 0 {
|
||||
return pulls(cmd, args, toComplete)
|
||||
}
|
||||
if len(args) > 1 {
|
||||
return nil, cobra.ShellCompDirectiveNoFileComp
|
||||
}
|
||||
n, err := number(args[0])
|
||||
if err != nil {
|
||||
return nil, cobra.ShellCompDirectiveNoFileComp
|
||||
@@ -653,7 +664,7 @@ func (a *application) completeReviewArgs(inline bool) cobra.CompletionFunc {
|
||||
}
|
||||
items, err := service.List(ctx, n, completionLimit, 1)
|
||||
return describe(items, func(item services.Review) (string, string) {
|
||||
return strconv.FormatInt(item.ID, 10), reviewStateCell(item).Text + " by " + item.Author
|
||||
return strconv.FormatInt(item.ID, 10), reviewStateCell(item).Text + " by " + item.Reviewer()
|
||||
}), err
|
||||
})(cmd, args, toComplete)
|
||||
}
|
||||
|
||||
@@ -123,7 +123,7 @@ func (a *application) pendingReview(cmd *cobra.Command, service services.Reviews
|
||||
}
|
||||
|
||||
func (a *application) pullReviewDeleteCommand() *cobra.Command {
|
||||
cmd := &cobra.Command{Use: "delete <number> <review-id>", Short: "Delete a review", Annotations: pullArgumentsAnnotation(textOutput("review deletion does not return a resource")), Args: argsExact(2), RunE: func(cmd *cobra.Command, args []string) error {
|
||||
cmd := &cobra.Command{Use: "delete <number> <review-id>", Short: "Delete a review", Annotations: pullArgumentRequiredAnnotation(textOutput("review deletion does not return a resource")), Args: argsExact(2), RunE: func(cmd *cobra.Command, args []string) error {
|
||||
t, n, id, err := a.pullAndID(cmd, args)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -133,7 +133,7 @@ func (a *application) pullReviewDeleteCommand() *cobra.Command {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
subject := fmt.Sprintf("review %d by %s on %s#%d", id, item.Author, t.Repo, n)
|
||||
subject := fmt.Sprintf("review %d by %s on %s#%d", id, item.Reviewer(), t.Repo, n)
|
||||
return a.deleteConfirmed(cmd, subject, func() error { return service.Delete(cmd.Context(), n, id) })
|
||||
}}
|
||||
cmd.Annotations["gt.confirm"] = "true"
|
||||
@@ -149,14 +149,13 @@ func (a *application) pullReviewDismissCommand(dismiss bool) *cobra.Command {
|
||||
if dismiss {
|
||||
use, short = "dismiss <number> <review-id>", "Dismiss an approval or change request"
|
||||
}
|
||||
cmd := &cobra.Command{Use: use, Short: short, Annotations: pullArgumentsAnnotation(nil), Args: argsExact(2), RunE: func(cmd *cobra.Command, args []string) (runErr error) {
|
||||
cmd := &cobra.Command{Use: use, Short: short, Annotations: pullArgumentRequiredAnnotation(nil), Args: argsExact(2), RunE: func(cmd *cobra.Command, args []string) (runErr error) {
|
||||
var draft terminal.Draft
|
||||
defer finishDraft(&draft, &runErr)
|
||||
var err error
|
||||
if dismiss {
|
||||
if err := validateBodySources(cmd); err != nil {
|
||||
return err
|
||||
}
|
||||
// The reason is collected before any request when it comes from flags or cannot be
|
||||
// prompted for; an editor or prompt waits until the review is known to be dismissable.
|
||||
collect := func() error {
|
||||
switch {
|
||||
case useEditor:
|
||||
draft, err = a.editDraft(cmd, "")
|
||||
@@ -172,6 +171,24 @@ func (a *application) pullReviewDismissCommand(dismiss bool) *cobra.Command {
|
||||
if strings.TrimSpace(body) == "" {
|
||||
return clierr.Wrap(clierr.Usage, errors.New("a dismissal needs a reason; pass --body, --body-file or --editor"))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
collected := false
|
||||
if dismiss {
|
||||
if err := validateBodySources(cmd); err != nil {
|
||||
return err
|
||||
}
|
||||
snapshot, err := a.settings()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
flagged := cmd.Flags().Changed("body") || cmd.Flags().Changed("body-file")
|
||||
if !useEditor && (flagged || !a.policy(snapshot).CanPrompt(a.deps.Streams)) {
|
||||
if err := collect(); err != nil {
|
||||
return err
|
||||
}
|
||||
collected = true
|
||||
}
|
||||
}
|
||||
t, n, id, err := a.pullAndID(cmd, args)
|
||||
if err != nil {
|
||||
@@ -183,6 +200,19 @@ func (a *application) pullReviewDismissCommand(dismiss bool) *cobra.Command {
|
||||
return err
|
||||
}
|
||||
subject := fmt.Sprintf("%s on %s#%d", reviewPossessive(current), t.Repo, n)
|
||||
switch {
|
||||
case dismiss && current.State != "APPROVED" && current.State != "REQUEST_CHANGES":
|
||||
// Gitea refuses other review types with a misleading "permission denied".
|
||||
return clierr.Wrap(clierr.Usage, fmt.Errorf("only approvals and change requests can be dismissed; %s is not one", subject))
|
||||
case !dismiss && !current.Dismissed:
|
||||
a.warn(cmd, "%s is not dismissed", subject)
|
||||
return a.jsonResult(cmd, current)
|
||||
}
|
||||
if dismiss && !collected {
|
||||
if err := collect(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if dismiss {
|
||||
if err := a.confirmAction(cmd, terminal.Confirmation{Prompt: "Dismiss " + subject + "?"}); err != nil {
|
||||
return err
|
||||
|
||||
@@ -47,7 +47,7 @@ func (a *application) pullReviewRequestCommand(add bool) *cobra.Command {
|
||||
cmd.Flags().StringSliceVarP(&input.Users, "reviewer", "r", nil, "Reviewer usernames or email addresses; @me for yourself")
|
||||
cmd.Flags().StringSliceVar(&input.Teams, "team", nil, "Teams of the repository's organization")
|
||||
_ = cmd.RegisterFlagCompletionFunc("reviewer", a.completeUsers())
|
||||
cmd.ValidArgsFunction = a.completePulls("open")
|
||||
cmd.ValidArgsFunction = firstArg(a.completePulls("open"))
|
||||
if add {
|
||||
cmd.Example = `$ gt pr review request 13 --reviewer carol,dave
|
||||
$ gt pr review request --team developers`
|
||||
|
||||
@@ -270,6 +270,39 @@ func TestReviewCommentsFileValidatedBeforeRequests(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestReviewDismissChecksTheReviewStateFirst(t *testing.T) {
|
||||
mutations := 0
|
||||
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
mutations++
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"id":2,"state":"COMMENT","user":{"login":"bob"}}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
deps, _, diagnostics := serverDeps(t, server.URL)
|
||||
err := Execute(context.Background(), deps, []string{"pr", "review", "dismiss", "1", "2", "-R", "owner/repo", "--body", "Reason", "--yes"})
|
||||
require.Equal(t, clierr.Usage, clierr.ExitCode(err))
|
||||
require.ErrorContains(t, err, "only approvals and change requests can be dismissed")
|
||||
require.NoError(t, Execute(context.Background(), deps, []string{"pr", "review", "undismiss", "1", "2", "-R", "owner/repo"}))
|
||||
require.Contains(t, diagnostics.String(), "is not dismissed")
|
||||
require.Zero(t, mutations)
|
||||
}
|
||||
|
||||
func TestReviewDismissOpensNoEditorForAnUndismissableReview(t *testing.T) {
|
||||
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
require.Equal(t, http.MethodGet, r.Method)
|
||||
_, _ = w.Write([]byte(`{"id":2,"state":"COMMENT","user":{"login":"bob"}}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
deps, _, _ := testDeps(t)
|
||||
editor, _ := newDraftEditor(t, "Reason")
|
||||
deps.Editor = editor
|
||||
deps.Getenv = serverEnv(server.URL, map[string]string{"EDITOR": "editor"})
|
||||
err := Execute(context.Background(), deps, []string{"pr", "review", "dismiss", "1", "2", "-R", "alice/project", "--editor", "--no-input", "--yes"})
|
||||
require.ErrorContains(t, err, "only approvals and change requests can be dismissed")
|
||||
require.Empty(t, editor.command, "the editor must not open")
|
||||
}
|
||||
|
||||
func TestReviewDeleteAndDismissRequireYesWithoutInput(t *testing.T) {
|
||||
mutations := 0
|
||||
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -150,7 +150,7 @@ func (a *application) pullViewCommand() *cobra.Command {
|
||||
if comments && a.options.json != "" {
|
||||
return clierr.Wrap(clierr.Usage, errors.New("--comments cannot be combined with --json or --jq; use gt pr comment list <number> --json or gt pr review list <number> --json"))
|
||||
}
|
||||
t, n, err := a.pullSelector(cmd, args)
|
||||
t, n, err := a.pullSelectorAny(cmd, args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -166,7 +166,7 @@ func (a *application) pullViewCommand() *cobra.Command {
|
||||
if details.reviews, err = (services.Reviews{Client: t.client, Repository: t.Repo}).All(cmd.Context(), n); err != nil {
|
||||
return err
|
||||
}
|
||||
item.ReviewDecision = services.ReviewDecision(services.LatestReviews(details.reviews), len(item.Reviewers)+len(item.ReviewerTeams) > 0)
|
||||
item.ReviewDecision = services.ReviewDecision(details.reviews, len(item.Reviewers)+len(item.ReviewerTeams) > 0)
|
||||
if a.options.json != "" {
|
||||
return a.writeJSON(cmd, item)
|
||||
}
|
||||
@@ -179,7 +179,7 @@ func (a *application) pullViewCommand() *cobra.Command {
|
||||
}}
|
||||
cmd.Flags().BoolVarP(&web, "web", "w", false, "Open the pull request in the browser")
|
||||
cmd.Flags().BoolVarP(&comments, "comments", "c", false, "Show comments and reviews")
|
||||
cmd.ValidArgsFunction = a.completePulls("all")
|
||||
cmd.ValidArgsFunction = firstArg(a.completePulls("all"))
|
||||
cmd.Example = `# View the pull request of the current branch
|
||||
$ gt pr view
|
||||
|
||||
|
||||
+69
-5
@@ -176,7 +176,10 @@ func (a *application) resolveRefs(cmd *cobra.Command, raws []string, kind refKin
|
||||
if selected.Repo != "" && !a.sameRepository(selected.Repo, parsed.Repo) {
|
||||
return target{}, nil, clierr.Wrap(clierr.Usage, fmt.Errorf("%s and %s are in different repositories; run one command per repository", source, raw))
|
||||
}
|
||||
selected, source = parsed, raw
|
||||
// A reference without an instance must not replace one that names it, whatever the order.
|
||||
if selected.Repo == "" || a.namesInstance(parsed.Repo) {
|
||||
selected, source = parsed, raw
|
||||
}
|
||||
}
|
||||
t, err := a.resolveRequest(cmd.Context(), targetRequest{requireRepo: true, authenticate: true, repo: selected.Repo, repoSource: source})
|
||||
return t, numbers, err
|
||||
@@ -193,16 +196,40 @@ func (a *application) sameRepository(first, second string) bool {
|
||||
return oneErr == nil && twoErr == nil && strings.EqualFold(one.Slug(), two.Slug()) && (one.Host == "" || two.Host == "" || one.Host == two.Host)
|
||||
}
|
||||
|
||||
// namesInstance reports whether a repository argument names its instance, as a URL or
|
||||
// HOST/OWNER/REPO does.
|
||||
func (a *application) namesInstance(raw string) bool {
|
||||
s, err := a.settings()
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
parsed, err := settings.ParseRepository(raw, s.Hosts.Hosts)
|
||||
return err == nil && parsed.Host != ""
|
||||
}
|
||||
|
||||
// pullSelector resolves the pull request a pr command addresses: N, #N, OWNER/REPO#N, a pull
|
||||
// request URL, a head branch, OWNER:BRANCH, or, without an argument, the pull request of the
|
||||
// checked-out branch.
|
||||
//
|
||||
// A branch names an open pull request only; commands that mutate open pull requests use it
|
||||
// as is, and the others use pullSelectorAny.
|
||||
func (a *application) pullSelector(cmd *cobra.Command, args []string) (target, int64, error) {
|
||||
return a.selectPull(cmd, args, false)
|
||||
}
|
||||
|
||||
// pullSelectorAny is pullSelector that, when no open pull request has the branch, falls back
|
||||
// to the most recently updated closed or merged one, like gh.
|
||||
func (a *application) pullSelectorAny(cmd *cobra.Command, args []string) (target, int64, error) {
|
||||
return a.selectPull(cmd, args, true)
|
||||
}
|
||||
|
||||
func (a *application) selectPull(cmd *cobra.Command, args []string, closed bool) (target, int64, error) {
|
||||
if len(args) == 0 || args[0] == "" {
|
||||
// The checked-out branch says nothing about a repository chosen with --repo.
|
||||
if a.options.repo != "" {
|
||||
return target{}, 0, clierr.Wrap(clierr.Usage, errors.New("pass a pull request number, URL or branch with --repo"))
|
||||
}
|
||||
return a.currentPull(cmd.Context())
|
||||
return a.currentPull(cmd.Context(), closed)
|
||||
}
|
||||
raw := args[0]
|
||||
if _, err := parseRef(raw, pullRef); !errors.Is(err, errNotRef) {
|
||||
@@ -216,7 +243,8 @@ func (a *application) pullSelector(cmd *cobra.Command, args []string) (target, i
|
||||
if !qualified {
|
||||
owner, branch = "", raw
|
||||
}
|
||||
pulls, err := (services.Pulls{Client: t.client, Repository: t.Repo}).ListOpen(cmd.Context())
|
||||
service := services.Pulls{Client: t.client, Repository: t.Repo}
|
||||
pulls, err := service.ListOpen(cmd.Context())
|
||||
if err != nil {
|
||||
return t, 0, err
|
||||
}
|
||||
@@ -224,6 +252,14 @@ func (a *application) pullSelector(cmd *cobra.Command, args []string) (target, i
|
||||
if err != nil {
|
||||
return t, 0, err
|
||||
}
|
||||
if n == 0 && closed {
|
||||
if n, err = newestClosedForBranch(cmd.Context(), service, owner, branch, false, t.Repo); err != nil {
|
||||
return t, 0, err
|
||||
}
|
||||
if n > 0 {
|
||||
return t, n, nil
|
||||
}
|
||||
}
|
||||
if n == 0 {
|
||||
return t, 0, fmt.Errorf("no open pull request for branch %q in %s; pass a number, URL or branch", raw, t.Repo)
|
||||
}
|
||||
@@ -233,8 +269,9 @@ func (a *application) pullSelector(cmd *cobra.Command, args []string) (target, i
|
||||
// currentPull finds the pull request of the checked-out branch: the one pr checkout recorded
|
||||
// while it is open, else the open pull request whose head is the branch's upstream (and the
|
||||
// upstream remote's owner), else one of this repository whose head has the local branch's name, else N from a pr/N
|
||||
// branch, else the recorded pull request even though it is no longer open.
|
||||
func (a *application) currentPull(ctx context.Context) (target, int64, error) {
|
||||
// branch, else the recorded pull request even though it is no longer open. With closed, the
|
||||
// newest closed or merged pull request for the branch comes last.
|
||||
func (a *application) currentPull(ctx context.Context, closed bool) (target, int64, error) {
|
||||
branch, err := git.CurrentBranchConfig(ctx, a.gitProbe(), a.options.cwd)
|
||||
if err != nil {
|
||||
return target{}, 0, clierr.Wrap(clierr.Usage, errors.New("not on a branch; pass a pull request number, URL or branch"))
|
||||
@@ -256,6 +293,7 @@ func (a *application) currentPull(ctx context.Context) (target, int64, error) {
|
||||
if err != nil {
|
||||
return t, 0, err
|
||||
}
|
||||
upstreamOwner := ""
|
||||
if branch.Merge != "" {
|
||||
owner := ""
|
||||
if remoteURL, err := a.gitProbe().Output(ctx, a.options.cwd, false, "remote", "get-url", branch.Remote); err == nil {
|
||||
@@ -266,6 +304,7 @@ func (a *application) currentPull(ctx context.Context) (target, int64, error) {
|
||||
if n, err := pullForBranch(pulls, owner, branch.Merge, t.Repo); owner != "" && (n > 0 || err != nil) {
|
||||
return t, n, err
|
||||
}
|
||||
upstreamOwner = owner
|
||||
}
|
||||
// A bare branch name only identifies the repository's own pull requests: a contributor's
|
||||
// fork may use main or fix as its head branch too.
|
||||
@@ -281,9 +320,34 @@ func (a *application) currentPull(ctx context.Context) (target, int64, error) {
|
||||
if recorded > 0 {
|
||||
return t, recorded, nil
|
||||
}
|
||||
if closed {
|
||||
// Same matching as above: the upstream's owner first, then the repository's own branches.
|
||||
if upstreamOwner != "" {
|
||||
if n, err := newestClosedForBranch(ctx, service, upstreamOwner, branch.Merge, false, t.Repo); n > 0 || err != nil {
|
||||
return t, n, err
|
||||
}
|
||||
}
|
||||
if n, err := newestClosedForBranch(ctx, service, "", branch.Name, true, t.Repo); n > 0 || err != nil {
|
||||
return t, n, err
|
||||
}
|
||||
}
|
||||
return t, 0, fmt.Errorf("no open pull request for branch %q in %s; pass a number, URL or branch", branch.Name, t.Repo)
|
||||
}
|
||||
|
||||
// newestClosedForBranch returns the number of the most recently updated closed or merged pull
|
||||
// request whose head is branch in a repository of owner (any owner when empty), or 0. With own,
|
||||
// only pull requests from the repository itself count, as a fork may reuse the branch name.
|
||||
func newestClosedForBranch(ctx context.Context, service services.Pulls, owner, branch string, own bool, repo string) (int64, error) {
|
||||
pull, found, err := service.NewestClosed(ctx, func(pull services.Pull) bool {
|
||||
headOwner, _, _ := strings.Cut(pull.HeadRepo, "/")
|
||||
return pull.Head == branch && (owner == "" || strings.EqualFold(headOwner, owner)) && (!own || strings.EqualFold(pull.HeadRepo, repo))
|
||||
})
|
||||
if err != nil || !found {
|
||||
return 0, err
|
||||
}
|
||||
return pull.Number, nil
|
||||
}
|
||||
|
||||
// remoteOwns reports whether the Git remote named remote points at the target's repository.
|
||||
func (a *application) remoteOwns(ctx context.Context, t target, remote string) bool {
|
||||
raw, err := a.gitProbe().Output(ctx, a.options.cwd, false, "remote", "get-url", remote)
|
||||
|
||||
@@ -82,19 +82,25 @@ func refApplication(t *testing.T, gitResults map[string]string) (*application, s
|
||||
]`)
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
return refApplicationWith(t, server.URL, gitResults)
|
||||
}
|
||||
|
||||
// refApplicationWith is refApplication for an existing server.
|
||||
func refApplicationWith(t *testing.T, serverURL string, gitResults map[string]string) (*application, string) {
|
||||
t.Helper()
|
||||
deps, _, _ := testDeps(t)
|
||||
deps.Getenv = serverEnv(server.URL, map[string]string{"GITEA_CLI_REPO": "alice/project"})
|
||||
deps.Getenv = serverEnv(serverURL, map[string]string{"GITEA_CLI_REPO": "alice/project"})
|
||||
results := map[string]string{
|
||||
"remote get-url origin": server.URL + "/alice/project.git",
|
||||
"remote get-url pulls/bob/project": server.URL + "/bob/project.git",
|
||||
"remote get-url fork": server.URL + "/bob/project.git",
|
||||
"remote get-url pulls/carol/project": server.URL + "/carol/project.git",
|
||||
"remote get-url origin": serverURL + "/alice/project.git",
|
||||
"remote get-url pulls/bob/project": serverURL + "/bob/project.git",
|
||||
"remote get-url fork": serverURL + "/bob/project.git",
|
||||
"remote get-url pulls/carol/project": serverURL + "/carol/project.git",
|
||||
}
|
||||
for key, value := range gitResults {
|
||||
results[key] = value
|
||||
}
|
||||
deps.Git = &fakeGit{results: results}
|
||||
return &application{deps: deps}, server.URL
|
||||
return &application{deps: deps}, serverURL
|
||||
}
|
||||
|
||||
func commandContext() *cobra.Command {
|
||||
@@ -229,3 +235,20 @@ func TestExpandMeUsesTheLoginTeaActsAs(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "bob", resolved.expandMe("@me"))
|
||||
}
|
||||
|
||||
func TestResolveRefsKeepsTheReferenceThatNamesAnInstance(t *testing.T) {
|
||||
a, serverURL := refApplication(t, nil)
|
||||
// GITEA_TOKEN belongs to serverURL, so selecting the other instance is what fails here.
|
||||
other := strings.Replace(serverURL, "127.0.0.1", "localhost", 1)
|
||||
const mismatch = "matching the selected instance"
|
||||
for _, raws := range [][]string{
|
||||
{other + "/bob/tool/issues/1", "bob/tool#2"},
|
||||
{"bob/tool#2", other + "/bob/tool/issues/1"},
|
||||
} {
|
||||
_, _, err := a.resolveRefs(commandContext(), raws, issueRef)
|
||||
require.ErrorContains(t, err, mismatch, raws)
|
||||
}
|
||||
a.options.repo = other + "/bob/tool"
|
||||
_, _, err := a.resolveRef(commandContext(), "bob/tool#2", issueRef)
|
||||
require.ErrorContains(t, err, mismatch, "an argument without an instance keeps the --repo one")
|
||||
}
|
||||
|
||||
@@ -217,10 +217,15 @@ $ gt release download v1.0.0 --archive zip`,
|
||||
}
|
||||
paths := make([]string, len(assets))
|
||||
skipped := make([]bool, len(assets))
|
||||
seen := map[string]services.ReleaseAsset{}
|
||||
for i, asset := range assets {
|
||||
if paths[i], skipped[i], err = flags.destination(asset.Name); err != nil {
|
||||
return err
|
||||
}
|
||||
if first, dup := seen[paths[i]]; dup && paths[i] != "-" {
|
||||
return clierr.Wrap(clierr.Usage, fmt.Errorf("assets %d and %d are both named %s; download one at a time with --output", first.ID, asset.ID, asset.Name))
|
||||
}
|
||||
seen[paths[i]] = asset
|
||||
}
|
||||
for i, asset := range assets {
|
||||
if skipped[i] {
|
||||
|
||||
@@ -121,3 +121,29 @@ func TestReleaseDownloadSelectsAssetsOfTheLatestRelease(t *testing.T) {
|
||||
err = Execute(context.Background(), deps, []string{"release", "download", "v1", "notes.txt", "gt-linux", "-O", filepath.Join(dir, "one"), "-R", "owner/repo"})
|
||||
require.ErrorContains(t, err, "--output names one file, but 2 assets match; pass --dir")
|
||||
}
|
||||
|
||||
func TestReleaseDownloadCreatesDirAndRefusesDuplicateNames(t *testing.T) {
|
||||
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.URL.Path == "/api/v1/repos/owner/repo/releases/tags/v1":
|
||||
_, _ = w.Write([]byte(`{"id":1,"tag_name":"v1","assets":[{"id":1,"name":"app","size":5,"uuid":"aaa"},{"id":2,"name":"app","size":5,"uuid":"bbb"},{"id":3,"name":"other","size":5,"uuid":"ccc"}]}`))
|
||||
case strings.HasPrefix(r.URL.Path, "/api/v1/repos/owner/repo/releases/1/assets/"):
|
||||
id := strings.TrimPrefix(r.URL.Path, "/api/v1/repos/owner/repo/releases/1/assets/")
|
||||
_, _ = w.Write([]byte(`{"id":` + id + `,"uuid":"ccc"}`))
|
||||
case strings.HasPrefix(r.URL.Path, "/attachments/"):
|
||||
_, _ = w.Write([]byte("bytes"))
|
||||
default:
|
||||
t.Errorf("unexpected request %s", r.URL.Path)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
deps, _, _ := repoTTYDeps(t, server.URL)
|
||||
dir := filepath.Join(t.TempDir(), "new", "dist")
|
||||
err := Execute(context.Background(), deps, []string{"release", "download", "v1", "--dir", dir, "-R", "owner/repo"})
|
||||
require.ErrorContains(t, err, "assets 1 and 2 are both named app")
|
||||
_, statErr := os.Stat(filepath.Join(dir, "other"))
|
||||
require.Error(t, statErr, "nothing is downloaded before the duplicate is reported")
|
||||
require.NoError(t, Execute(context.Background(), deps, []string{"release", "download", "v1", "other", "--dir", dir, "-R", "owner/repo"}))
|
||||
_, statErr = os.Stat(filepath.Join(dir, "other"))
|
||||
require.NoError(t, statErr)
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ package app
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
@@ -220,12 +221,16 @@ func (f *releaseFields) options(a *application, cmd *cobra.Command) (services.Re
|
||||
func (a *application) releaseCreateCommand() *cobra.Command {
|
||||
var fields releaseFields
|
||||
var assets []string
|
||||
var verifyTag bool
|
||||
command := &cobra.Command{
|
||||
Use: "create [<tag>] [<file>...]",
|
||||
Aliases: []string{"new"},
|
||||
Short: "Create a release",
|
||||
Long: `Create a release for a tag, and upload the files that follow the tag as its assets. Gitea creates
|
||||
the tag at --target (the default branch) when it does not exist yet. The title defaults to the tag.`,
|
||||
the tag at --target (the default branch) when it does not exist yet. The title defaults to the tag.
|
||||
|
||||
gt never pushes: commits and tags that only exist in your clone are not on the server, so push them
|
||||
first (git push <remote> <tag>), or pass --verify-tag to fail when the tag is not on the server yet.`,
|
||||
Example: `# Create a release with notes from a file and two assets
|
||||
$ gt release create v1.0.0 dist/gt-linux dist/gt-darwin --notes-file CHANGELOG.md
|
||||
|
||||
@@ -267,6 +272,9 @@ $ gt release create v1.1.0-rc1 --target release/1.1 --draft --prerelease --title
|
||||
return err
|
||||
}
|
||||
service := services.Releases{Client: target.client, Repository: target.Repo}
|
||||
if err := a.checkReleaseTag(cmd, target, service, fields.tag, opts.Target != nil, verifyTag); err != nil {
|
||||
return err
|
||||
}
|
||||
if fields.editor {
|
||||
if editorDraft, err = a.editDraft(cmd, ""); err != nil {
|
||||
return err
|
||||
@@ -279,6 +287,11 @@ $ gt release create v1.1.0-rc1 --target release/1.1 --draft --prerelease --title
|
||||
}
|
||||
}
|
||||
item, err := service.Create(cmd.Context(), opts)
|
||||
if notFound, ok := errors.AsType[*services.NotFoundError](err); ok && notFound.Kind == "target" {
|
||||
if hint := a.pushHint(cmd.Context(), target, *opts.Target); hint != "" {
|
||||
err = explain(err, "%s; %s", err, hint)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -305,10 +318,63 @@ $ gt release create v1.1.0-rc1 --target release/1.1 --draft --prerelease --title
|
||||
command.Flags().StringVar(&fields.tag, "tag", "", "Release tag")
|
||||
_ = command.Flags().MarkHidden("tag")
|
||||
command.Flags().StringSliceVar(&assets, "asset", nil, "File to upload as an asset (repeatable)")
|
||||
command.Flags().BoolVar(&verifyTag, "verify-tag", false, "Fail if the tag does not exist on the server yet")
|
||||
command.ValidArgsFunction = pathArgs(1, true, completeFiles, a.completeTags())
|
||||
return command
|
||||
}
|
||||
|
||||
// checkReleaseTag guards against a release whose tag Gitea would create from the default branch
|
||||
// instead of from the local commit the tag names: --verify-tag refuses a tag the server lacks, and
|
||||
// without it a tag that only exists locally is warned about.
|
||||
func (a *application) checkReleaseTag(cmd *cobra.Command, t target, service services.Releases, tag string, hasTarget, verify bool) error {
|
||||
local := a.localRefExists(cmd.Context(), "refs/tags/"+tag)
|
||||
if !verify && (!local || hasTarget) {
|
||||
return nil
|
||||
}
|
||||
exists, err := service.TagExists(cmd.Context(), tag)
|
||||
if err != nil || exists {
|
||||
return err
|
||||
}
|
||||
hint := ""
|
||||
if local {
|
||||
hint = "push it first: git push " + a.releaseRemote(t) + " " + tag
|
||||
}
|
||||
if verify {
|
||||
missing := services.NotFound("tag", tag, t.Repo)
|
||||
return explain(missing, "%s; %s", missing, cmp.Or(hint, "create it first or drop --verify-tag"))
|
||||
}
|
||||
a.warn(cmd, "Tag %s exists in your clone but not in %s; the release creates it at the default branch, not at your local commit; %s", tag, t.Repo, hint)
|
||||
return nil
|
||||
}
|
||||
|
||||
// pushHint tells how to publish a ref that only the local clone has, or returns "".
|
||||
func (a *application) pushHint(ctx context.Context, t target, ref string) string {
|
||||
remote := a.releaseRemote(t)
|
||||
for _, prefix := range []string{"refs/tags/", "refs/heads/"} {
|
||||
if a.localRefExists(ctx, prefix+ref) {
|
||||
return "push it first: git push " + remote + " " + ref
|
||||
}
|
||||
}
|
||||
if ref != "" && a.localRefExists(ctx, ref+"^{commit}") {
|
||||
return "push the branch that has this commit first: git push " + remote
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// localRefExists reports whether the working directory's checkout resolves ref.
|
||||
func (a *application) localRefExists(ctx context.Context, ref string) bool {
|
||||
_, err := a.gitProbe().Output(ctx, a.options.cwd, false, "rev-parse", "--verify", "--quiet", ref)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// releaseRemote is the remote of the target repository, else origin.
|
||||
func (a *application) releaseRemote(t target) string {
|
||||
if remote, ok := strings.CutPrefix(t.RepoSource, "remote "); ok {
|
||||
return remote
|
||||
}
|
||||
return cmp.Or(a.options.remote, "origin")
|
||||
}
|
||||
|
||||
// rejectSwitchValue refuses the old gt syntax "--draft false": a switch reads no value, so the
|
||||
// word would be edited as one more release after the switch was applied as true.
|
||||
func rejectSwitchValue(cmd *cobra.Command, args []string, switches ...string) error {
|
||||
@@ -349,6 +415,9 @@ $ gt release edit v1.0.0-rc1 v1.0.0-rc2 --prerelease=false`,
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if opts.Body != nil && *opts.Body == "" {
|
||||
return clierr.Wrap(clierr.Usage, errors.New("release notes cannot be cleared because Gitea ignores empty notes; edit them to a placeholder, or delete and recreate the release"))
|
||||
}
|
||||
if cmd.Flags().Changed("tag") {
|
||||
if len(args) != 1 || strings.TrimSpace(fields.tag) == "" {
|
||||
return clierr.Wrap(clierr.Usage, errors.New("--tag requires one release and a nonempty new tag"))
|
||||
@@ -373,6 +442,9 @@ $ gt release edit v1.0.0-rc1 v1.0.0-rc2 --prerelease=false`,
|
||||
}
|
||||
opts.Body = &editorDraft.Body
|
||||
}
|
||||
if editorDraft.Body == "" && fields.editor {
|
||||
return clierr.Wrap(clierr.Usage, errors.New("release notes cannot be cleared because Gitea ignores empty notes; edit them to a placeholder, or delete and recreate the release"))
|
||||
}
|
||||
return batchDone(a, cmd, args, func(tag string) string { return "release " + tag }, func(tag string) (services.Release, error) {
|
||||
item, err := service.View(cmd.Context(), tag)
|
||||
if err != nil {
|
||||
|
||||
@@ -104,3 +104,33 @@ func TestReleaseCreateUploadsPositionalFiles(t *testing.T) {
|
||||
require.Equal(t, "https://gitea.test/alice/project/releases/tag/v1.1.0\n", out.String())
|
||||
require.Equal(t, "✓ Created draft release v1.1.0 in alice/project\n✓ Uploaded gt.bin (2 B)\n", diagnostics.String())
|
||||
}
|
||||
|
||||
func TestReleaseCreateWithUnknownTargetNamesTheTargetAndHintsAtPushing(t *testing.T) {
|
||||
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
_, _ = w.Write([]byte(`{"message":"target not found"}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
deps, _, _ := serverDeps(t, server.URL)
|
||||
deps.Git = &fakeGit{results: map[string]string{"rev-parse --verify --quiet refs/tags/v2": "abc"}}
|
||||
err := Execute(context.Background(), deps, []string{"release", "create", "v1", "--target", "v2", "-R", "alice/project"})
|
||||
require.EqualError(t, Explain(context.Background(), deps, err), `target "v2" not found in alice/project; push it first: git push origin v2`)
|
||||
deps.Git = &fakeGit{}
|
||||
err = Execute(context.Background(), deps, []string{"release", "create", "v1", "--target", "nowhere", "-R", "alice/project"})
|
||||
require.EqualError(t, Explain(context.Background(), deps, err), `target "nowhere" not found in alice/project`)
|
||||
}
|
||||
|
||||
func TestReleaseCreateVerifyTagRefusesATagTheServerLacks(t *testing.T) {
|
||||
var requests []string
|
||||
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requests = append(requests, r.Method+" "+r.URL.Path)
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
_, _ = w.Write([]byte(`{"message":"tag does not exist"}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
deps, _, _ := serverDeps(t, server.URL)
|
||||
deps.Git = &fakeGit{results: map[string]string{"rev-parse --verify --quiet refs/tags/v1": "abc"}}
|
||||
err := Execute(context.Background(), deps, []string{"release", "create", "v1", "--verify-tag", "-R", "alice/project"})
|
||||
require.EqualError(t, err, "tag v1 not found in alice/project; push it first: git push origin v1")
|
||||
require.Equal(t, []string{"GET /api/v1/repos/alice/project/tags/v1"}, requests)
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
@@ -99,6 +100,25 @@ var repositorySwitches = []struct {
|
||||
// validTopic is the form Gitea accepts for a lowercased topic name.
|
||||
var validTopic = regexp.MustCompile(`^[a-z0-9][-.a-z0-9]{0,34}$`)
|
||||
|
||||
// maxTopics is the number of topics Gitea allows per repository.
|
||||
const maxTopics = 25
|
||||
|
||||
// finalTopics returns current without the removed topics and with the added ones, lowercased like Gitea does.
|
||||
func finalTopics(current, add, remove []string) []string {
|
||||
removed := make(map[string]bool, len(remove))
|
||||
for _, topic := range remove {
|
||||
removed[strings.ToLower(topic)] = true
|
||||
}
|
||||
var topics []string
|
||||
for _, topic := range slices.Concat(current, add) {
|
||||
topic = strings.ToLower(topic)
|
||||
if !removed[topic] && !slices.Contains(topics, topic) {
|
||||
topics = append(topics, topic)
|
||||
}
|
||||
}
|
||||
return topics
|
||||
}
|
||||
|
||||
func (a *application) repoEditCommand() *cobra.Command {
|
||||
var name, website, defaultBranch, description, visibility, mergeStyle string
|
||||
var addTopics, removeTopics []string
|
||||
@@ -162,6 +182,9 @@ $ gt repo edit --default-merge-style squash --add-topic cli --add-topic go`,
|
||||
return clierr.Wrap(clierr.Usage, fmt.Errorf("invalid topic %q: use up to 35 letters, digits, - or ., starting with a letter or digit", topic))
|
||||
}
|
||||
}
|
||||
if len(addTopics) > maxTopics {
|
||||
return clierr.Wrap(clierr.Usage, fmt.Errorf("a repository has at most %d topics, got %d to add", maxTopics, len(addTopics)))
|
||||
}
|
||||
if options == (services.RepositoryEdit{}) && len(addTopics)+len(removeTopics) == 0 {
|
||||
return clierr.Wrap(clierr.Usage, errors.New("supply a setting to change; see gt repo edit --help"))
|
||||
}
|
||||
@@ -181,6 +204,20 @@ $ gt repo edit --default-merge-style squash --add-topic cli --add-topic go`,
|
||||
}
|
||||
}
|
||||
}
|
||||
// Topics are replaced in one request; compute and check them before anything changes.
|
||||
var topics []string
|
||||
setTopics := false
|
||||
if len(addTopics)+len(removeTopics) > 0 {
|
||||
current, err := service.Topics(cmd.Context(), t.Repo)
|
||||
if err != nil {
|
||||
return fmt.Errorf("list topics: %w", err)
|
||||
}
|
||||
topics = finalTopics(current, addTopics, removeTopics)
|
||||
if len(topics) > maxTopics {
|
||||
return clierr.Wrap(clierr.Usage, fmt.Errorf("a repository has at most %d topics, the edit would leave %d", maxTopics, len(topics)))
|
||||
}
|
||||
setTopics = !slices.Equal(slices.Sorted(slices.Values(topics)), slices.Sorted(slices.Values(finalTopics(current, nil, nil))))
|
||||
}
|
||||
// Gitea refuses topic changes on an archived repository, so archiving comes last.
|
||||
repo, archive := t.Repo, options.Archived != nil && *options.Archived
|
||||
if archive {
|
||||
@@ -193,26 +230,27 @@ $ gt repo edit --default-merge-style squash --add-topic cli --add-topic go`,
|
||||
}
|
||||
options.Archived = nil
|
||||
}
|
||||
if options != (services.RepositoryEdit{}) {
|
||||
settings := options != (services.RepositoryEdit{})
|
||||
if settings {
|
||||
item, err := service.Edit(cmd.Context(), t.Repo, options)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
repo = item.FullName
|
||||
}
|
||||
for _, topic := range addTopics {
|
||||
if err := service.AddTopic(cmd.Context(), repo, topic); err != nil {
|
||||
return fmt.Errorf("add topic %q: %w", topic, err)
|
||||
}
|
||||
}
|
||||
for _, topic := range removeTopics {
|
||||
// A topic the repository does not have is already removed.
|
||||
if err := service.RemoveTopic(cmd.Context(), repo, topic); err != nil && !services.IsNotFound(err) {
|
||||
return fmt.Errorf("remove topic %q: %w", topic, err)
|
||||
if setTopics {
|
||||
if err := service.SetTopics(cmd.Context(), repo, topics); err != nil {
|
||||
if settings {
|
||||
return fmt.Errorf("repository settings were changed, but setting the topics failed: %w", err)
|
||||
}
|
||||
return fmt.Errorf("set topics: %w", err)
|
||||
}
|
||||
}
|
||||
if archive {
|
||||
if _, err := service.Edit(cmd.Context(), repo, services.RepositoryEdit{Archived: &archive}); err != nil {
|
||||
if settings || setTopics {
|
||||
return fmt.Errorf("the other changes were applied, but archiving failed: %w", err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -273,7 +273,7 @@ $ gt repo view alice/project --web`,
|
||||
}
|
||||
view.Flags().BoolVarP(&web, "web", "w", false, "Open the repository in the browser")
|
||||
view.Flags().StringVarP(&branch, "branch", "b", "", "Show the README of this branch (default: the default branch)")
|
||||
_ = view.RegisterFlagCompletionFunc("branch", a.completeBranches())
|
||||
_ = view.RegisterFlagCompletionFunc("branch", a.completeArgumentBranches())
|
||||
view.ValidArgsFunction = a.completeRepos()
|
||||
return view
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"gitea.dev/cli/internal/clierr"
|
||||
"gitea.dev/cli/internal/services"
|
||||
@@ -147,7 +148,14 @@ $ gt repo create project --source . --push`,
|
||||
target.Repo = item.FullName
|
||||
switch {
|
||||
case clone:
|
||||
_, err = a.cloneRepository(cmd, target, item, cloneOptions{upstream: "upstream"})
|
||||
// Record the new repository first so a failed clone does not hide that it exists.
|
||||
if err := a.created(cmd, item, item.URL); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := a.cloneRepository(cmd, target, item, cloneOptions{upstream: "upstream"}); err != nil {
|
||||
return fmt.Errorf("created %s, but could not clone it: %w", item.FullName, err)
|
||||
}
|
||||
return nil
|
||||
case localSource != "":
|
||||
err = a.publishRepository(cmd, target, item, localSource, remote, push)
|
||||
}
|
||||
@@ -202,8 +210,8 @@ func validateCreateFlags(cmd *cobra.Command, opts services.RepositoryOptions, or
|
||||
return clierr.Wrap(clierr.Usage, errors.New("--team requires --org and a team name"))
|
||||
case changed("template") && template == "":
|
||||
return clierr.Wrap(clierr.Usage, errors.New("--template requires owner/repo or a repository URL"))
|
||||
case len(opts.Description) > 2048:
|
||||
return clierr.Wrap(clierr.Usage, errors.New("description cannot exceed 2048 bytes"))
|
||||
case utf8.RuneCountInString(opts.Description) > 2048:
|
||||
return clierr.Wrap(clierr.Usage, errors.New("description cannot exceed 2048 characters"))
|
||||
case template == "" && (opts.Gitignores != "" || opts.License != "" || opts.Readme != "" || opts.DefaultBranch != "") && !opts.AutoInit:
|
||||
return clierr.Wrap(clierr.Usage, errors.New("initial content and default branch options require --auto-init"))
|
||||
case template != "" && changed("auto-init", "label-template", "gitignores", "license", "readme", "as-template", "trust-model", "object-format"):
|
||||
|
||||
@@ -63,6 +63,18 @@ func TestRepositoryCreateClonesNewRepository(t *testing.T) {
|
||||
require.JSONEq(t, `{"id":7,"full_name":"alice/project"}`, out.String())
|
||||
}
|
||||
|
||||
func TestRepositoryCreateReportsFailedCloneAfterCreating(t *testing.T) {
|
||||
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = fmt.Fprintf(w, `{"id":7,"name":"project","full_name":"alice/project","clone_url":%q}`, "http://"+r.Host+"/alice/project.git")
|
||||
}))
|
||||
defer server.Close()
|
||||
deps, out, _ := serverDeps(t, server.URL)
|
||||
deps.Git = &fakeGit{}
|
||||
err := Execute(context.Background(), deps, []string{"repo", "create", "project", "--clone", "--no-input", "--json=full_name"})
|
||||
require.ErrorContains(t, err, "created alice/project, but could not clone it")
|
||||
require.JSONEq(t, `{"full_name":"alice/project"}`, out.String())
|
||||
}
|
||||
|
||||
func TestRepositoryCreateValidatesTemplatesBeforeCreating(t *testing.T) {
|
||||
var requests []string
|
||||
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -108,6 +120,17 @@ func TestRepositoryCreatePublishesALocalRepository(t *testing.T) {
|
||||
require.ErrorContains(t, err, "--source publishes a local repository")
|
||||
}
|
||||
|
||||
func TestRepositoryMigrateAcceptsZeroMirrorInterval(t *testing.T) {
|
||||
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requirePayload(t, `{"repo_name":"gitea","clone_addr":"https://github.com/go-gitea/gitea.git","service":"git","mirror":true,"mirror_interval":"0"}`, r.Body)
|
||||
_, _ = w.Write([]byte(`{"full_name":"alice/gitea","mirror":true,"html_url":"https://gitea.test/alice/gitea"}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
deps, _, diagnostics := repoTTYDeps(t, server.URL)
|
||||
require.NoError(t, Execute(context.Background(), deps, []string{"repo", "migrate", "https://github.com/go-gitea/gitea.git", "--mirror", "--mirror-interval", "0"}))
|
||||
require.Equal(t, "✓ Imported https://github.com/go-gitea/gitea.git into alice/gitea (pull mirror, synced manually)\n", diagnostics.String())
|
||||
}
|
||||
|
||||
func TestRepositoryMigrateNamesTheRepositoryAfterItsSource(t *testing.T) {
|
||||
for _, test := range []struct{ source, want string }{
|
||||
{"https://github.com/go-gitea/gitea.git", "gitea"},
|
||||
|
||||
@@ -5,6 +5,8 @@ package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
@@ -54,15 +56,23 @@ func TestRepositoryEditReportsTheChangedSettings(t *testing.T) {
|
||||
var requests []string
|
||||
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requests = append(requests, r.Method+" "+r.URL.Path)
|
||||
if r.Method == http.MethodPatch {
|
||||
switch r.Method + " " + r.URL.Path {
|
||||
case "PATCH /api/v1/repos/alice/project":
|
||||
requirePayload(t, `{"description":"CLI","private":true}`, r.Body)
|
||||
case "GET /api/v1/repos/alice/project/topics":
|
||||
_, _ = w.Write([]byte(`{"topics":["old","keep"]}`))
|
||||
return
|
||||
case "PUT /api/v1/repos/alice/project/topics":
|
||||
requirePayload(t, `{"topics":["keep","cli","go"]}`, r.Body)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"full_name":"alice/project"}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
deps, out, diagnostics := repoTTYDeps(t, server.URL)
|
||||
require.NoError(t, Execute(context.Background(), deps, []string{"repo", "edit", "alice/project", "-d", "CLI", "--visibility", "private", "--add-topic", "cli,go", "--remove-topic", "old"}))
|
||||
require.Equal(t, []string{"PATCH /api/v1/repos/alice/project", "PUT /api/v1/repos/alice/project/topics/cli", "PUT /api/v1/repos/alice/project/topics/go", "DELETE /api/v1/repos/alice/project/topics/old"}, requests)
|
||||
require.Equal(t, []string{"GET /api/v1/repos/alice/project/topics", "PATCH /api/v1/repos/alice/project", "PUT /api/v1/repos/alice/project/topics"}, requests)
|
||||
require.Empty(t, out.String())
|
||||
require.Equal(t, "✓ Edited repository alice/project (add-topic, description, remove-topic, visibility)\n", diagnostics.String())
|
||||
}
|
||||
@@ -82,8 +92,9 @@ func TestRepositoryEditArchivesAfterTheOtherChanges(t *testing.T) {
|
||||
deps, _, _ := serverDeps(t, server.URL)
|
||||
require.NoError(t, Execute(context.Background(), deps, []string{"repo", "edit", "alice/project", "-d", "CLI", "--archived", "--add-topic", "cli", "--yes"}))
|
||||
require.Equal(t, []string{
|
||||
"GET /api/v1/repos/alice/project/topics",
|
||||
"PATCH /api/v1/repos/alice/project",
|
||||
"PUT /api/v1/repos/alice/project/topics/cli",
|
||||
"PUT /api/v1/repos/alice/project/topics",
|
||||
"PATCH /api/v1/repos/alice/project archived",
|
||||
}, requests)
|
||||
}
|
||||
@@ -128,14 +139,44 @@ func TestRepositoryEditIgnoresRemovingAMissingTopic(t *testing.T) {
|
||||
var requests []string
|
||||
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requests = append(requests, r.Method+" "+r.URL.Path)
|
||||
if r.Method == http.MethodDelete {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
_, _ = w.Write([]byte(`{"full_name":"alice/project","topics":["other"]}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
deps, _, _ := serverDeps(t, server.URL)
|
||||
require.NoError(t, Execute(context.Background(), deps, []string{"repo", "edit", "alice/project", "-d", "new", "--remove-topic", "legacy"}))
|
||||
require.Equal(t, []string{"GET /api/v1/repos/alice/project/topics", "PATCH /api/v1/repos/alice/project"}, requests)
|
||||
}
|
||||
|
||||
func TestRepositoryEditRejectsTooManyTopicsBeforeChangingAnything(t *testing.T) {
|
||||
var requests []string
|
||||
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requests = append(requests, r.Method+" "+r.URL.Path)
|
||||
var topics []string
|
||||
for i := range 25 {
|
||||
topics = append(topics, fmt.Sprintf("t%d", i))
|
||||
}
|
||||
data, _ := json.Marshal(map[string]any{"topics": topics})
|
||||
_, _ = w.Write(data)
|
||||
}))
|
||||
defer server.Close()
|
||||
deps, _, _ := serverDeps(t, server.URL)
|
||||
err := Execute(context.Background(), deps, []string{"repo", "edit", "alice/project", "-d", "new", "--add-topic", "extra"})
|
||||
require.Equal(t, clierr.Usage, clierr.ExitCode(err), "%v", err)
|
||||
require.ErrorContains(t, err, "at most 25 topics")
|
||||
require.Equal(t, []string{"GET /api/v1/repos/alice/project/topics"}, requests)
|
||||
}
|
||||
|
||||
func TestRepositoryEditReportsSettingsAppliedWhenTheTopicsFail(t *testing.T) {
|
||||
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodPut {
|
||||
w.WriteHeader(http.StatusUnprocessableEntity)
|
||||
_, _ = w.Write([]byte(`{"message":"Topic names are invalid"}`))
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"full_name":"alice/project"}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
deps, _, _ := serverDeps(t, server.URL)
|
||||
require.NoError(t, Execute(context.Background(), deps, []string{"repo", "edit", "alice/project", "-d", "new", "--remove-topic", "legacy"}))
|
||||
require.Equal(t, []string{"PATCH /api/v1/repos/alice/project", "DELETE /api/v1/repos/alice/project/topics/legacy"}, requests)
|
||||
err := Execute(context.Background(), deps, []string{"repo", "edit", "alice/project", "-d", "new", "--add-topic", "cli"})
|
||||
require.ErrorContains(t, err, "repository settings were changed, but setting the topics failed")
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"path"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"gitea.dev/cli/internal/clierr"
|
||||
"gitea.dev/cli/internal/services"
|
||||
@@ -133,7 +134,10 @@ $ gt repo migrate https://github.com/acme/tool --service github --issues --pull-
|
||||
return err
|
||||
}
|
||||
detail := ""
|
||||
interval, _ := time.ParseDuration(opts.MirrorInterval)
|
||||
switch {
|
||||
case item.Mirror && opts.MirrorInterval != "" && interval == 0:
|
||||
detail = " (pull mirror, synced manually)"
|
||||
case item.Mirror && opts.MirrorInterval != "":
|
||||
detail = " (pull mirror, every " + opts.MirrorInterval + ")"
|
||||
case item.Mirror:
|
||||
@@ -161,7 +165,7 @@ $ gt repo migrate https://github.com/acme/tool --service github --issues --pull-
|
||||
flags.BoolVar(&opts.PullRequests, "pull-requests", false, "Copy pull requests")
|
||||
flags.BoolVar(&opts.Releases, "releases", false, "Copy releases")
|
||||
flags.BoolVar(&opts.Milestones, "milestones", false, "Copy milestones")
|
||||
flags.StringVar(&opts.MirrorInterval, "mirror-interval", "", "Mirror interval, for example 8h")
|
||||
flags.StringVar(&opts.MirrorInterval, "mirror-interval", "", "Mirror interval, for example 8h (0 turns off periodic sync)")
|
||||
flags.BoolVar(&opts.LFS, "lfs", false, "Copy LFS objects")
|
||||
flags.StringVar(&opts.LFSEndpoint, "lfs-endpoint", "", "Source LFS endpoint")
|
||||
flags.StringVar(&opts.AuthUser, "auth-user", "", "Source authentication username")
|
||||
@@ -183,8 +187,8 @@ func validateMigrationFlags(cmd *cobra.Command, opts services.RepositoryMigratio
|
||||
return clierr.Wrap(clierr.Usage, errors.New("server path imports use --service git without remote credentials"))
|
||||
case opts.Timeout <= 0:
|
||||
return clierr.Wrap(clierr.Usage, errors.New("--timeout must be positive"))
|
||||
case len(opts.Description) > 2048:
|
||||
return clierr.Wrap(clierr.Usage, errors.New("description cannot exceed 2048 bytes"))
|
||||
case utf8.RuneCountInString(opts.Description) > 2048:
|
||||
return clierr.Wrap(clierr.Usage, errors.New("description cannot exceed 2048 characters"))
|
||||
case opts.LFSEndpoint != "" && !opts.LFS:
|
||||
return clierr.Wrap(clierr.Usage, errors.New("--lfs-endpoint requires --lfs"))
|
||||
case opts.Mirror && metadata:
|
||||
@@ -201,8 +205,8 @@ func validateMigrationFlags(cmd *cobra.Command, opts services.RepositoryMigratio
|
||||
}
|
||||
if opts.MirrorInterval != "" {
|
||||
interval, err := time.ParseDuration(opts.MirrorInterval)
|
||||
if err != nil || interval <= 0 || !opts.Mirror {
|
||||
return clierr.Wrap(clierr.Usage, errors.New("--mirror-interval requires --mirror and a positive duration"))
|
||||
if err != nil || interval < 0 || !opts.Mirror {
|
||||
return clierr.Wrap(clierr.Usage, errors.New("--mirror-interval requires --mirror and a duration of 0 or more"))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -100,7 +100,7 @@ $ gt repo sync bob/project`,
|
||||
},
|
||||
}
|
||||
command.Flags().StringVarP(&branch, "branch", "b", "", "Branch to sync (default: the repository's default branch)")
|
||||
_ = command.RegisterFlagCompletionFunc("branch", a.completeBranches())
|
||||
_ = command.RegisterFlagCompletionFunc("branch", a.completeArgumentBranches())
|
||||
command.ValidArgsFunction = a.completeRepos()
|
||||
return command
|
||||
}
|
||||
|
||||
@@ -62,7 +62,7 @@ $ gt search repo go --topic --sort updated --order desc`,
|
||||
pageFlags(command, &opts.Limit, &opts.Page)
|
||||
flags.StringVar(&opts.Owner, "owner", "", "Only repositories of this user or organization")
|
||||
enumFlag(command, &opts.Kind, "type", "", "", "Only repositories of this kind", "fork", "source", "mirror")
|
||||
enumFlag(command, &opts.Sort, "sort", "", "alpha", "Sort by", "alpha", "created", "updated", "size", "id")
|
||||
enumFlag(command, &opts.Sort, "sort", "", "", "Sort by (default: alphabetical, your own repositories first)", "alpha", "created", "updated", "size", "id")
|
||||
enumFlag(command, &opts.Order, "order", "", "asc", "Sort order", "asc", "desc")
|
||||
flags.BoolVar(&opts.Topic, "topic", false, "Match repository topics")
|
||||
flags.BoolVar(&private, "private", false, "Only private repositories (use =false for public)")
|
||||
|
||||
@@ -96,7 +96,7 @@ func (a *application) currentPullStatus(cmd *cobra.Command) (*services.Pull, pul
|
||||
if err != nil {
|
||||
return nil, details, ""
|
||||
}
|
||||
t, n, err := a.pullSelector(cmd, nil)
|
||||
t, n, err := a.pullSelectorAny(cmd, nil)
|
||||
if err != nil {
|
||||
return nil, details, branch
|
||||
}
|
||||
@@ -106,7 +106,7 @@ func (a *application) currentPullStatus(cmd *cobra.Command) (*services.Pull, pul
|
||||
return nil, details, branch
|
||||
}
|
||||
if details.reviews, err = (services.Reviews{Client: t.client, Repository: t.Repo}).All(cmd.Context(), n); err == nil {
|
||||
pull.ReviewDecision = services.ReviewDecision(services.LatestReviews(details.reviews), len(pull.Reviewers)+len(pull.ReviewerTeams) > 0)
|
||||
pull.ReviewDecision = services.ReviewDecision(details.reviews, len(pull.Reviewers)+len(pull.ReviewerTeams) > 0)
|
||||
}
|
||||
if pull.HeadSHA != "" {
|
||||
details.checks, _ = service.CommitChecks(cmd.Context(), pull.HeadSHA)
|
||||
|
||||
+21
-3
@@ -9,6 +9,8 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -102,6 +104,10 @@ func (a *application) resolveRequest(ctx context.Context, req targetRequest) (ta
|
||||
}
|
||||
// A bare repository NAME belongs to the account gt acts as, which is known only now.
|
||||
if t.Repo != "" && !strings.Contains(t.Repo, "/") {
|
||||
// A name that is also a directory here may be meant as that checkout, as in gt -R ./project.
|
||||
if info, statErr := os.Stat(filepath.Join(cmp.Or(a.options.cwd, "."), t.Repo)); statErr == nil && info.IsDir() && t.RepoSource == "--repo" {
|
||||
return t, clierr.Wrap(clierr.Usage, fmt.Errorf("%q is both a repository name and a directory here; use OWNER/%s for the repository, or --cwd %s for that checkout", t.Repo, t.Repo, t.Repo))
|
||||
}
|
||||
owner := cmp.Or(a.options.sudo, t.User)
|
||||
if owner == "" {
|
||||
return t, clierr.Wrap(clierr.Usage, fmt.Errorf("cannot tell who owns repository %q; use OWNER/%s", t.Repo, t.Repo))
|
||||
@@ -186,11 +192,13 @@ func (a *application) connect(ctx context.Context, req targetRequest) (target, e
|
||||
if err != nil {
|
||||
return t, err
|
||||
}
|
||||
// The message must not reveal which account the token belongs to.
|
||||
if !services.MatchAccount(t.User, actual) {
|
||||
// Like GH_TOKEN, the token overrides the stored credentials whichever account is active;
|
||||
// only an account that --user or GITEA_CLI_USER names must match. The message must not reveal
|
||||
// which account the token belongs to.
|
||||
if t.explicitUser() && !services.MatchAccount(t.User, actual) {
|
||||
return t, clierr.Wrap(clierr.Authentication, errEnvironmentAccount)
|
||||
}
|
||||
if t.User == "" {
|
||||
if !t.explicitUser() {
|
||||
t.UserSource = "GITEA_TOKEN authenticated account"
|
||||
}
|
||||
t.User = actual
|
||||
@@ -207,6 +215,11 @@ func (a *application) repositorySource(ctx context.Context, t *target, s setting
|
||||
if err := a.agreesWithRepoFlag(req, s.Hosts.Hosts); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if a.options.repo != "" && !a.namesInstance(req.repo) && a.namesInstance(a.options.repo) {
|
||||
// The argument agrees with --repo and only lacks its instance.
|
||||
t.RepoSource = "--repo"
|
||||
return a.options.repo, nil
|
||||
}
|
||||
t.RepoSource = req.repoSource
|
||||
return req.repo, nil
|
||||
}
|
||||
@@ -425,6 +438,11 @@ func (a *application) selectAccount(ctx context.Context, t *target, s settings.S
|
||||
return nil
|
||||
}
|
||||
|
||||
// explicitUser reports whether the user named the account with --user or GITEA_CLI_USER.
|
||||
func (t target) explicitUser() bool {
|
||||
return t.User != "" && (t.UserSource == "--user" || t.UserSource == "GITEA_CLI_USER")
|
||||
}
|
||||
|
||||
// accountError explains why user has no stored credential on the target's instance.
|
||||
func (t target) accountError(user string) error {
|
||||
users := t.host.Users
|
||||
|
||||
@@ -88,7 +88,7 @@ func TestAccountNamesMatchCaseInsensitively(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestEnvironmentCredentialVerifiesSelectedAccountBeforeMutation(t *testing.T) {
|
||||
for _, selection := range []string{"--user", "GITEA_CLI_USER", "active instance account"} {
|
||||
for _, selection := range []string{"--user", "GITEA_CLI_USER"} {
|
||||
t.Run(selection, func(t *testing.T) {
|
||||
reads, mutations := 0, 0
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -113,9 +113,6 @@ func TestEnvironmentCredentialVerifiesSelectedAccountBeforeMutation(t *testing.T
|
||||
if selection == "--user" {
|
||||
args = append(args, "--user", "bob")
|
||||
}
|
||||
if selection == "active instance account" {
|
||||
configureHost(t, deps, host, settings.Host{User: "bob", Users: tokenAccounts(settings.StoreKeyring, "bob")})
|
||||
}
|
||||
err := Execute(context.Background(), deps, args)
|
||||
require.ErrorContains(t, err, "does not belong to the selected account")
|
||||
require.Equal(t, clierr.Authentication, clierr.ExitCode(err))
|
||||
@@ -358,3 +355,42 @@ func TestRepositoryDiscoveryOutsideCheckoutWritesNoGitDiagnostics(t *testing.T)
|
||||
require.Empty(t, out.String())
|
||||
require.Empty(t, diagnostics.String())
|
||||
}
|
||||
|
||||
func TestEnvironmentCredentialOverridesTheActiveAccount(t *testing.T) {
|
||||
created := false
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
require.Equal(t, "token private-test-token", r.Header.Get("Authorization"))
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if r.Method == http.MethodGet && r.URL.Path == "/base/api/v1/user" {
|
||||
_, _ = w.Write([]byte(`{"login":"alice"}`))
|
||||
return
|
||||
}
|
||||
created = true
|
||||
_, _ = w.Write([]byte(`{"id":9,"number":3,"title":"Issue","state":"open"}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
deps, _, _ := testDeps(t)
|
||||
host := server.URL + "/base"
|
||||
deps.Getenv = envFunc(map[string]string{"GITEA_CLI_HOST": host, "GITEA_TOKEN": "private-test-token"})
|
||||
configureHost(t, deps, host, settings.Host{User: "bob", Users: tokenAccounts(settings.StoreKeyring, "bob")})
|
||||
require.NoError(t, Execute(context.Background(), deps, []string{"issue", "create", "-R", "alice/project", "--title", "Issue", "--body", "Body", "--no-input", "--json"}))
|
||||
require.True(t, created)
|
||||
}
|
||||
|
||||
func TestRepositoryFlagNamedLikeADirectoryIsAmbiguous(t *testing.T) {
|
||||
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write([]byte(`{"full_name":"` + strings.TrimPrefix(r.URL.Path, "/api/v1/repos/") + `"}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
dir := t.TempDir()
|
||||
require.NoError(t, os.Mkdir(filepath.Join(dir, "project"), 0o755))
|
||||
deps, out, _ := testDeps(t)
|
||||
configureAccounts(t, deps, server.URL, "alice", "alice")
|
||||
err := Execute(context.Background(), deps, []string{"repo", "view", "-R", "project", "--cwd", dir, "--no-input", "--json=full_name"})
|
||||
require.Equal(t, clierr.Usage, clierr.ExitCode(err))
|
||||
require.ErrorContains(t, err, `"project" is both a repository name and a directory here; use OWNER/project`)
|
||||
// A qualified name, or a bare name without such a directory, is unambiguous.
|
||||
require.NoError(t, Execute(context.Background(), deps, []string{"repo", "view", "-R", "alice/project", "--cwd", dir, "--no-input", "--json=full_name"}))
|
||||
require.NoError(t, Execute(context.Background(), deps, []string{"repo", "view", "-R", "other", "--cwd", dir, "--no-input", "--json=full_name"}))
|
||||
require.Contains(t, out.String(), "alice/other")
|
||||
}
|
||||
|
||||
+13
-5
@@ -197,13 +197,13 @@ $ gt team view 2 --json units`,
|
||||
return writeView(a, cmd, team, func(team services.Team) terminal.View {
|
||||
var units []string
|
||||
for _, unit := range slices.Concat(services.TeamUnits, services.ExternalTeamUnits) {
|
||||
if access := team.Units[unit]; access != "" && access != "none" {
|
||||
if access := team.UnitLevel(unit); access != "none" {
|
||||
units = append(units, strings.TrimPrefix(unit, "repo.")+": "+access)
|
||||
}
|
||||
}
|
||||
memberNames := ""
|
||||
if !membersHidden {
|
||||
memberNames = listedNames(members, func(member services.OrganizationMember) string { return member.Username })
|
||||
memberNames = listedNames(members, func(member services.TeamMember) string { return member.Username })
|
||||
}
|
||||
repositories := listedNames(repos, func(repo services.Repository) string { return repo.FullName })
|
||||
if team.AllRepositories {
|
||||
@@ -425,11 +425,19 @@ $ gt team edit acme/developers --name devs --description "Core developers"`,
|
||||
if opts.Units != nil && !opts.ReplaceUnits && (team.Permission == "admin" || team.Permission == "owner") {
|
||||
return clierr.Wrap(clierr.Usage, fmt.Errorf("--unit cannot restrict the %s access of team %s; pass --permission read or write, or --unit-replace", team.Permission, team.Slug()))
|
||||
}
|
||||
// Gitea finds the owner team by its name, so renaming it leaves the organization without owners.
|
||||
if team.Permission == "owner" && opts.Name != nil && !strings.EqualFold(*opts.Name, team.Name) {
|
||||
return clierr.Wrap(clierr.Usage, fmt.Errorf("team %s is the organization's owner team and cannot be renamed", team.Slug()))
|
||||
}
|
||||
edited, err := service.Edit(cmd.Context(), team.ID, opts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
edited.Organization = team.Organization
|
||||
// Some Gitea versions keep an admin team admin when permission and units_map are sent together.
|
||||
if opts.Permission != nil && edited.Permission != "" && edited.Permission != *opts.Permission {
|
||||
return fmt.Errorf("team %s was edited, but its permission is %s instead of the requested %s; other changes were applied", edited.Slug(), edited.Permission, *opts.Permission)
|
||||
}
|
||||
a.done(cmd, "Edited team %s (ID %d)", edited.Slug(), edited.ID)
|
||||
return a.jsonResult(cmd, edited)
|
||||
},
|
||||
@@ -502,9 +510,9 @@ also makes them a member of the organization.`}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return writeTable(a, cmd, members.Items, listSpec[services.OrganizationMember]{
|
||||
return writeTable(a, cmd, members.Items, listSpec[services.TeamMember]{
|
||||
Columns: []terminal.Column{{Header: "Username"}, {Header: "Name", Flex: true}},
|
||||
Row: func(member services.OrganizationMember) []terminal.Cell {
|
||||
Row: func(member services.TeamMember) []terminal.Cell {
|
||||
return []terminal.Cell{{Text: member.Username, Link: webURL(target, member.Username), Bold: true}, {Text: member.FullName}}
|
||||
},
|
||||
Context: "members of team " + team.Slug(), Empty: "no members in team " + team.Slug(),
|
||||
@@ -543,7 +551,7 @@ $ gt team member add 2 bob carol`,
|
||||
Annotations: map[string]string{"gt.text": "team membership changes do not return a resource", "gt.confirm": "true", "gt.arguments": teamArguments},
|
||||
ValidArgsFunction: a.completeTeamThen(func(ctx context.Context, t target, team services.Team) ([]cobra.Completion, error) {
|
||||
members, err := services.Teams{Client: t.client}.Members(ctx, team.ID, completionLimit, 1)
|
||||
return describe(members.Items, func(member services.OrganizationMember) (string, string) { return member.Username, member.FullName }), err
|
||||
return describe(members.Items, func(member services.TeamMember) (string, string) { return member.Username, member.FullName }), err
|
||||
}),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
_, service, team, err := a.team(cmd, args[0])
|
||||
|
||||
@@ -81,6 +81,24 @@ func TestTeamEditMergesUnitsIntoTheCurrentPolicy(t *testing.T) {
|
||||
require.Len(t, sent, 2)
|
||||
}
|
||||
|
||||
func TestTeamEditRefusesToRenameTheOwnerTeam(t *testing.T) {
|
||||
var patched int
|
||||
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodPatch {
|
||||
patched++
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"id":3,"name":"Owners","permission":"owner","organization":{"username":"acme"}}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
deps, _, _ := serverDeps(t, server.URL)
|
||||
err := Execute(context.Background(), deps, []string{"team", "edit", "3", "--name", "Admins"})
|
||||
require.Equal(t, clierr.Usage, clierr.ExitCode(err), "%v", err)
|
||||
require.ErrorContains(t, err, "owner team and cannot be renamed")
|
||||
require.Zero(t, patched)
|
||||
require.NoError(t, Execute(context.Background(), deps, []string{"team", "edit", "3", "--description", "Owners", "--json"}))
|
||||
require.Equal(t, 1, patched)
|
||||
}
|
||||
|
||||
func TestTeamRepoAddTakesRepositoriesAsArguments(t *testing.T) {
|
||||
var granted []string
|
||||
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -181,7 +199,11 @@ func TestTeamPermissionSetsEveryUnit(t *testing.T) {
|
||||
require.NoError(t, json.NewDecoder(r.Body).Decode(&body))
|
||||
sent = append(sent, body)
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"id":5,"name":"devs","permission":"none","organization":{"username":"acme"}}`))
|
||||
permission := "none"
|
||||
if len(sent) > 0 {
|
||||
permission, _ = sent[len(sent)-1]["permission"].(string)
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"id":5,"name":"devs","permission":"` + permission + `","organization":{"username":"acme"}}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
deps, _, _ := serverDeps(t, server.URL)
|
||||
@@ -194,12 +216,14 @@ func TestTeamPermissionSetsEveryUnit(t *testing.T) {
|
||||
}
|
||||
require.NoError(t, Execute(context.Background(), deps, []string{"team", "create", "acme/devs", "--permission", "write"}))
|
||||
require.NoError(t, Execute(context.Background(), deps, []string{"team", "edit", "5", "--permission", "read", "--unit", "repo.wiki=write"}))
|
||||
require.Len(t, sent, 2)
|
||||
require.Len(t, sent, 3)
|
||||
require.Equal(t, "devs", sent[0]["name"])
|
||||
require.Equal(t, every("write"), sent[0]["units_map"])
|
||||
// The permission goes first on its own, because Gitea 28 keeps an admin team admin otherwise.
|
||||
require.Equal(t, map[string]any{"name": "devs", "permission": "read"}, sent[1])
|
||||
wikiWrite := every("read")
|
||||
wikiWrite["repo.wiki"] = "write"
|
||||
require.Equal(t, map[string]any{"permission": "read", "units_map": wikiWrite}, sent[1])
|
||||
require.Equal(t, map[string]any{"permission": "read", "units_map": wikiWrite}, sent[2])
|
||||
}
|
||||
|
||||
func TestTeamMemberRemoveConfirmsOnce(t *testing.T) {
|
||||
|
||||
+13
-4
@@ -106,7 +106,7 @@ $ gt time list --mine --since 168h`, Args: argsExact(0), RunE: func(cmd *cobra.C
|
||||
}
|
||||
spec := listSpec[services.TrackedTime]{
|
||||
Columns: []terminal.Column{{Header: "ID"}, {Header: "Issue", Flex: true}, {Header: "User"}, {Header: "Spent"}, {Header: "When"}},
|
||||
Row: trackedTimeRow(target.Repo), Empty: "no time tracked " + where, Context: "time records " + where,
|
||||
Row: trackedTimeRow(target.Repo, !a.display().TTY), Empty: "no time tracked " + where, Context: "time records " + where,
|
||||
}
|
||||
return a.writeTimes(cmd, page, opts.Page, spec, total)
|
||||
}}
|
||||
@@ -135,7 +135,7 @@ func (a *application) writeTimes(cmd *cobra.Command, page services.Page[services
|
||||
sum += item.Seconds
|
||||
rows[i] = spec.Row(item)
|
||||
}
|
||||
text := terminal.Table(spec.Columns, rows, d) + "Total: " + spent(sum) + "\n"
|
||||
text := terminal.Table(spec.Columns, rows, d) + "Total: " + spentFor(!d.TTY, sum) + "\n"
|
||||
if d.TTY {
|
||||
text = showing(len(page.Items), servicePage(page, number), spec.Context) + "\n\n" + text
|
||||
}
|
||||
@@ -149,8 +149,17 @@ func (a *application) writeTimes(cmd *cobra.Command, page services.Page[services
|
||||
return a.morePagesHint(cmd, page.More, number)
|
||||
}
|
||||
|
||||
// spentFor is spent on a terminal; when exact (piped output) it keeps every second as a Go
|
||||
// duration such as 1h2m3s, which spent drops from durations of an hour or more.
|
||||
func spentFor(exact bool, seconds int64) string {
|
||||
if exact {
|
||||
return trackedDuration(seconds).String()
|
||||
}
|
||||
return spent(seconds)
|
||||
}
|
||||
|
||||
// trackedTimeRow shows a record in repo; records of other repositories name theirs.
|
||||
func trackedTimeRow(repo string) func(services.TrackedTime) []terminal.Cell {
|
||||
func trackedTimeRow(repo string, exact bool) func(services.TrackedTime) []terminal.Cell {
|
||||
return func(item services.TrackedTime) []terminal.Cell {
|
||||
issue := "#" + strconv.FormatInt(item.IssueNumber, 10)
|
||||
if !strings.EqualFold(item.Repository, repo) {
|
||||
@@ -160,7 +169,7 @@ func trackedTimeRow(repo string) func(services.TrackedTime) []terminal.Cell {
|
||||
{Text: strconv.FormatInt(item.ID, 10)},
|
||||
{Text: strings.TrimSpace(issue + " " + item.IssueTitle)},
|
||||
{Text: item.User},
|
||||
{Text: spent(item.Seconds)},
|
||||
{Text: spentFor(exact, item.Seconds)},
|
||||
{Time: terminal.ParseTime(item.CreatedAt)},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,9 +24,9 @@ func TestTimeListShowsRepositoryAndDurations(t *testing.T) {
|
||||
defer server.Close()
|
||||
deps, out, _ := serverDeps(t, server.URL)
|
||||
require.NoError(t, Execute(context.Background(), deps, []string{"time", "list", "--mine", "--total"}))
|
||||
require.Equal(t, "1\talice/project#3\talice\t1h 25m\t2026-10-01T10:00:00Z\n"+
|
||||
"2\tbob/tools#3\talice\t15m\t2026-10-02T10:00:00Z\n"+
|
||||
"Total: 1h 40m\n", out.String())
|
||||
require.Equal(t, "1\talice/project#3\talice\t1h25m0s\t2026-10-01T10:00:00Z\n"+
|
||||
"2\tbob/tools#3\talice\t15m0s\t2026-10-02T10:00:00Z\n"+
|
||||
"Total: 1h40m0s\n", out.String())
|
||||
out.Reset()
|
||||
require.NoError(t, Execute(context.Background(), deps, []string{"time", "list", "--mine", "--json=repository,issue_number"}))
|
||||
require.JSONEq(t, `[{"repository":"alice/project","issue_number":3},{"repository":"bob/tools","issue_number":3}]`, out.String())
|
||||
@@ -125,6 +125,27 @@ func TestTimeListTotalPipedCoversEmptyAndPagedListings(t *testing.T) {
|
||||
out.Reset()
|
||||
empty = false
|
||||
require.NoError(t, Execute(context.Background(), deps, []string{"time", "list", "--mine", "--total", "--limit", "1"}))
|
||||
require.Equal(t, "1\talice/project#3\talice\t1m\t2026-10-01T10:00:00Z\nTotal: 1m\n", out.String())
|
||||
require.Equal(t, "1\talice/project#3\talice\t1m0s\t2026-10-01T10:00:00Z\nTotal: 1m0s\n", out.String())
|
||||
require.Equal(t, "more results available; use --page 2\n", diagnostics.String())
|
||||
}
|
||||
|
||||
func TestCommentListHintsAtTheNextClientSidePage(t *testing.T) {
|
||||
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write([]byte(`[{"id":1,"body":"a","user":{"login":"alice"}},{"id":2,"body":"b","user":{"login":"alice"}}]`))
|
||||
}))
|
||||
defer server.Close()
|
||||
deps, _, diagnostics := serverDeps(t, server.URL)
|
||||
require.NoError(t, Execute(context.Background(), deps, []string{"issue", "comment", "list", "3", "-R", "alice/project", "--limit", "1"}))
|
||||
require.Equal(t, "more results available; use --page 2\n", diagnostics.String())
|
||||
}
|
||||
|
||||
func TestPipedTimeKeepsExactSeconds(t *testing.T) {
|
||||
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write([]byte(`[{"id":1,"time":3723,"created":"2026-10-01T10:00:00Z","user_name":"alice","issue":{"number":3,"repository":{"full_name":"alice/project"}}}]`))
|
||||
}))
|
||||
defer server.Close()
|
||||
deps, out, _ := serverDeps(t, server.URL)
|
||||
require.NoError(t, Execute(context.Background(), deps, []string{"time", "list", "--mine", "--total"}))
|
||||
require.Equal(t, "1\talice/project#3\talice\t1h2m3s\t2026-10-01T10:00:00Z\nTotal: 1h2m3s\n", out.String())
|
||||
require.Equal(t, "1h 2m", spent(3723))
|
||||
}
|
||||
|
||||
@@ -147,11 +147,12 @@ func TestUsageErrorsPrecedeRequests(t *testing.T) {
|
||||
{[]string{"release", "create", "v1", "--tag", "v2"}, "supply a tag argument or --tag, not both"},
|
||||
{[]string{"release", "create", "--body-file", "-"}, "--notes-file - requires a tag"},
|
||||
{[]string{"release", "edit", "v1"}, "supply release fields to edit"},
|
||||
{[]string{"release", "edit", "v1", "--notes", ""}, "release notes cannot be cleared"},
|
||||
{[]string{"release", "edit", "v1", "v2", "--tag", "v3"}, "--tag requires one release and a nonempty new tag"},
|
||||
{[]string{"release", "edit", "v1", "--draft", "false"}, "--draft takes no value; use --draft or --draft=false"},
|
||||
{[]string{"release", "edit", "v1", "-d", "false", "-p", "False"}, "--draft takes no value; use --draft or --draft=false"},
|
||||
{[]string{"release", "edit", "v1", "v2", "--prerelease", "TRUE"}, "--prerelease takes no value; use --prerelease or --prerelease=false"},
|
||||
{[]string{"repo", "create"}, "missing required input: supply --name"},
|
||||
{[]string{"repo", "create"}, "missing required input: Repository name (pass it as an argument)"},
|
||||
{[]string{"repo", "create", "acme/bad/name"}, "repository name must be nonempty, at most 100 bytes, and contain no path separators or whitespace"},
|
||||
{[]string{"repo", "create", "name", "--name", "other"}, "supply name as an argument or --name, not both"},
|
||||
{[]string{"repo", "create", "name", "--default-branch", "bad..branch", "--auto-init"}, "invalid branch name"},
|
||||
@@ -174,11 +175,12 @@ func TestUsageErrorsPrecedeRequests(t *testing.T) {
|
||||
{[]string{"repo", "list", "--type", "invalid"}, "--type must be fork, source, or mirror"},
|
||||
{[]string{"repo", "set-default", "--json"}, "set-default configures Git"},
|
||||
{[]string{"repo", "sync", "--branch="}, "--branch cannot be empty"},
|
||||
{[]string{"repo", "migrate", "--name", "new"}, "missing required input: Clone URL (pass it as an argument)"},
|
||||
{[]string{"repo", "migrate", "https://source.test/repo", "--name", "new", "--clone-url", "https://other.test/repo"}, "supply clone URL as an argument or --clone-url, not both"},
|
||||
{[]string{"repo", "migrate", "https://user:[email protected]/repo", "--name", "new"}, "clone URL must be an HTTP(S) or git URL without embedded credentials"},
|
||||
{[]string{"repo", "migrate", "https://source.test/repo", "--name", "new", "--service", "unknown"}, "--service must be git, gitea, gitlab, gogs, or github"},
|
||||
{[]string{"repo", "migrate", "https://source.test/repo", "--name", "new", "--issues"}, "plain Git migration cannot copy forge metadata"},
|
||||
{[]string{"repo", "migrate", "https://source.test/repo", "--name", "new", "--mirror-interval", "8h"}, "--mirror-interval requires --mirror and a positive duration"},
|
||||
{[]string{"repo", "migrate", "https://source.test/repo", "--name", "new", "--mirror-interval", "8h"}, "--mirror-interval requires --mirror and a duration of 0 or more"},
|
||||
{[]string{"repo", "migrate", "https://source.test/repo", "--name", "new", "--mirror", "--issues"}, "mirrors cannot copy issues, milestones, labels, pull requests, or releases"},
|
||||
{[]string{"repo", "migrate", "https://source.test/repo", "--name", "new", "--lfs-endpoint", "https://lfs.test"}, "--lfs-endpoint requires --lfs"},
|
||||
{[]string{"repo", "migrate", "https://source.test/repo", "--name", "new", "--auth-password", "secret"}, "--auth-password requires --auth-user"},
|
||||
|
||||
@@ -120,7 +120,7 @@ func (a *application) wikiRevisionsCommand() *cobra.Command {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
items, err := (services.Wiki{Client: target.client, Repository: target.Repo}).Revisions(cmd.Context(), args[0], page)
|
||||
revisions, err := (services.Wiki{Client: target.client, Repository: target.Repo}).Revisions(cmd.Context(), args[0], page)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -136,7 +136,7 @@ func (a *application) wikiRevisionsCommand() *cobra.Command {
|
||||
},
|
||||
Context: "revisions of wiki page " + strconv.Quote(args[0]), Empty: "no revisions of wiki page " + strconv.Quote(args[0]),
|
||||
}
|
||||
return writeTable(a, cmd, items, spec, listPage{Number: page})
|
||||
return writeTable(a, cmd, revisions.Items, spec, servicePage(revisions, page))
|
||||
},
|
||||
}
|
||||
positiveIntVar(command, &page, "page", 1, math.MaxInt, "Revision page (server controls page size)")
|
||||
@@ -280,11 +280,11 @@ $ gt wiki edit Home --editor`,
|
||||
}
|
||||
}
|
||||
}
|
||||
item, err := service.Edit(cmd.Context(), args[0], services.WikiOptions{Title: content.title, Body: body, Message: content.message})
|
||||
item, renamed, err := service.Edit(cmd.Context(), args[0], services.WikiOptions{Title: content.title, Body: body, Message: content.message})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if item.Title != args[0] {
|
||||
if renamed {
|
||||
a.done(cmd, "Renamed wiki page %q to %q in %s", args[0], item.Title, target.Repo)
|
||||
} else {
|
||||
a.done(cmd, "Edited wiki page %q in %s", item.Title, target.Repo)
|
||||
|
||||
@@ -20,12 +20,19 @@ func TestWikiEditRenamesAndKeepsTheContent(t *testing.T) {
|
||||
_, _ = w.Write([]byte(`{"title":"New Title","content_base64":"S2VlcCBtZQ=="}`))
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/api/v1/repos/alice/x/wiki/page/New Title" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"title":"Old Title","content_base64":"S2VlcCBtZQ=="}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
deps, out, diagnostics := repoTTYDeps(t, server.URL)
|
||||
require.NoError(t, Execute(context.Background(), deps, []string{"wiki", "edit", "Old Title", "--title", "New Title", "-R", "alice/x", "--no-input"}))
|
||||
require.Equal(t, []string{"GET /api/v1/repos/alice/x/wiki/page/Old Title", "PATCH /api/v1/repos/alice/x/wiki/page/Old Title"}, requests)
|
||||
require.Equal(t, []string{
|
||||
"GET /api/v1/repos/alice/x/wiki/page/Old Title", "GET /api/v1/repos/alice/x/wiki/page/Old Title",
|
||||
"GET /api/v1/repos/alice/x/wiki/page/New Title", "PATCH /api/v1/repos/alice/x/wiki/page/Old Title",
|
||||
}, requests)
|
||||
require.Empty(t, out.String())
|
||||
require.Equal(t, "✓ Renamed wiki page \"Old Title\" to \"New Title\" in alice/x\n", diagnostics.String())
|
||||
err := Execute(context.Background(), deps, []string{"wiki", "edit", "Home", "-R", "alice/x"})
|
||||
@@ -65,3 +72,45 @@ func TestWikiViewAndCreate(t *testing.T) {
|
||||
require.Equal(t, "https://gitea.test/alice/x/wiki/Page-Two\n", out.String())
|
||||
require.Equal(t, "✓ Created wiki page \"Page Two\" in alice/x\n", diagnostics.String())
|
||||
}
|
||||
|
||||
func TestWikiEditRefusesToOverwriteOrCreate(t *testing.T) {
|
||||
patched := 0
|
||||
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.Method == http.MethodPatch:
|
||||
patched++
|
||||
_, _ = w.Write([]byte(`{"title":"Getting Started","content_base64":"eA=="}`))
|
||||
case r.URL.Path == "/api/v1/repos/alice/x":
|
||||
_, _ = w.Write([]byte(`{"full_name":"alice/x","has_wiki":true}`))
|
||||
case r.URL.Path == "/api/v1/repos/alice/x/wiki/page/Draft":
|
||||
_, _ = w.Write([]byte(`{"title":"Draft","content_base64":"ZHJhZnQ="}`))
|
||||
case r.URL.Path == "/api/v1/repos/alice/x/wiki/page/Page B":
|
||||
_, _ = w.Write([]byte(`{"title":"Page B","content_base64":"Yg=="}`))
|
||||
case r.URL.Path == "/api/v1/repos/alice/x/wiki/page/Getting-Started":
|
||||
_, _ = w.Write([]byte(`{"title":"Getting Started","content_base64":"Zw=="}`))
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
deps, _, diagnostics := repoTTYDeps(t, server.URL)
|
||||
err := Execute(context.Background(), deps, []string{"wiki", "edit", "Draft", "--title", "Page B", "-R", "alice/x", "--no-input"})
|
||||
require.ErrorContains(t, err, `wiki page "Page B" already exists in alice/x`)
|
||||
err = Execute(context.Background(), deps, []string{"wiki", "edit", "Drfat", "--body", "x", "-R", "alice/x", "--no-input"})
|
||||
require.ErrorContains(t, err, `wiki page "Drfat" not found`)
|
||||
require.Zero(t, patched, "neither refused edit may reach the PATCH")
|
||||
// Editing by the URL slug is not a rename.
|
||||
require.NoError(t, Execute(context.Background(), deps, []string{"wiki", "edit", "Getting-Started", "--body", "x", "-R", "alice/x", "--no-input"}))
|
||||
require.Equal(t, "✓ Edited wiki page \"Getting Started\" in alice/x\n", diagnostics.String())
|
||||
require.Equal(t, 1, patched)
|
||||
}
|
||||
|
||||
func TestWikiRevisionsCountsTheWholeHistory(t *testing.T) {
|
||||
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write([]byte(`{"commits":[{"sha":"abc","message":"Edit","author":{"name":"alice","date":"2026-10-11T18:00:00Z"}}],"count":56}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
deps, out, _ := repoTTYDeps(t, server.URL)
|
||||
require.NoError(t, Execute(context.Background(), deps, []string{"wiki", "revisions", "Home", "-R", "alice/x"}))
|
||||
require.Contains(t, out.String(), "Showing 1 of 56 revisions of wiki page \"Home\" · next: --page 2")
|
||||
}
|
||||
|
||||
@@ -87,6 +87,12 @@ func (m Manager) register(instance, user string, account settings.Account, optio
|
||||
}
|
||||
undo = append(undo, func() error { return m.credentials.Delete(instance, user, account.CredentialStore) })
|
||||
}
|
||||
if exists && credential != nil && !previous.Tokenless() {
|
||||
// Logging in again replaces the credential; settings made with gt config set stay.
|
||||
kept := previous
|
||||
kept.AuthMethod, kept.CredentialStore = account.AuthMethod, account.CredentialStore
|
||||
account = kept
|
||||
}
|
||||
host.Users[user] = account
|
||||
host.User = user
|
||||
if options.OAuthClientID != "" {
|
||||
|
||||
@@ -237,3 +237,22 @@ func TestFailedReplacementRestoresTheCredential(t *testing.T) {
|
||||
_, err = credentials.Load("https://example.org", "alice", settings.StoreFile)
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
func TestReplacingATokenKeepsTheAccountSSHSettings(t *testing.T) {
|
||||
config := settings.New(t.TempDir())
|
||||
credentials := &Store{Dir: config.Dir, Keyring: &memoryKeyring{values: map[string]string{}}}
|
||||
manager := newTestManager(t, config, credentials)
|
||||
require.NoError(t, manager.Register("https://example.org", "alice", settings.StoreFile, settings.AuthToken, HostOptions{}, Credential{AccessToken: "old"}))
|
||||
require.NoError(t, config.Transaction(settings.TargetHosts, func(s *settings.Snapshot) (func() error, error) {
|
||||
host := s.Hosts.Hosts["https://example.org"]
|
||||
account := host.Users["alice"]
|
||||
account.SSHKey, account.SSHAgent = "/keys/id", true
|
||||
host.Users["alice"] = account
|
||||
s.Hosts.Hosts["https://example.org"] = host
|
||||
return nil, nil
|
||||
}))
|
||||
require.NoError(t, manager.Register("https://example.org", "alice", settings.StoreKeyring, settings.AuthOAuth, HostOptions{Replace: true}, Credential{AccessToken: "new"}))
|
||||
s, err := config.Load()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, settings.Account{AuthMethod: settings.AuthOAuth, CredentialStore: settings.StoreKeyring, SSHKey: "/keys/id", SSHAgent: true}, s.Hosts.Hosts["https://example.org"].Users["alice"])
|
||||
}
|
||||
|
||||
@@ -99,6 +99,11 @@ func CheckoutPull(ctx context.Context, runner Runner, options CheckoutOptions) (
|
||||
}
|
||||
}
|
||||
}
|
||||
if existing {
|
||||
if err := requireBranchFreeElsewhere(run, options.Branch); err != nil {
|
||||
return CheckoutResult{}, err
|
||||
}
|
||||
}
|
||||
fetchRemote := options.Remote
|
||||
fetchRef := fmt.Sprintf("refs/pull/%d/head", options.Number)
|
||||
tracking := ""
|
||||
@@ -168,3 +173,25 @@ func CheckoutPull(ctx context.Context, runner Runner, options CheckoutOptions) (
|
||||
}
|
||||
return CheckoutResult{Branch: options.Branch, Commit: commit, Detached: options.Detached, Remote: fetchRemote, Tracking: tracking}, nil
|
||||
}
|
||||
|
||||
// requireBranchFreeElsewhere fails when branch is checked out in a linked worktree other than
|
||||
// the current one, which git switch would refuse with a message that does not say where.
|
||||
func requireBranchFreeElsewhere(run func(...string) (string, error), branch string) error {
|
||||
top, err := run("rev-parse", "--show-toplevel")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
listing, err := run("worktree", "list", "--porcelain")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
path := ""
|
||||
for line := range strings.SplitSeq(listing, "\n") {
|
||||
if value, ok := strings.CutPrefix(line, "worktree "); ok {
|
||||
path = value
|
||||
} else if line == "branch refs/heads/"+branch && path != top {
|
||||
return fmt.Errorf("branch %q is checked out in the worktree %s; pass --detach to check out the pull request without a branch, or choose another branch with --branch", branch, path)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ type checkoutRunner struct {
|
||||
dirty, collision bool
|
||||
localCommit string
|
||||
diverged bool
|
||||
worktrees string
|
||||
}
|
||||
|
||||
func (r *checkoutRunner) Output(_ context.Context, dir string, prompt bool, args ...string) (string, error) {
|
||||
@@ -38,6 +39,8 @@ func (r *checkoutRunner) Output(_ context.Context, dir string, prompt bool, args
|
||||
return "true", nil
|
||||
}
|
||||
return "abc123", nil
|
||||
case "worktree":
|
||||
return r.worktrees, nil
|
||||
case "status":
|
||||
if r.dirty {
|
||||
return "?? file", nil
|
||||
@@ -172,3 +175,19 @@ func TestPullCheckoutTracksHeadBranch(t *testing.T) {
|
||||
require.NotContains(t, call, "refs/pull/")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPullCheckoutRejectsBranchCheckedOutInAnotherWorktree(t *testing.T) {
|
||||
options := CheckoutOptions{Directory: "/work", Remote: "origin", Number: 7, Branch: "pr/7", ExpectedCommit: "abc123", Update: true}
|
||||
runner := &checkoutRunner{collision: true, localCommit: "abc123", worktrees: "worktree abc123\nHEAD 1\nbranch refs/heads/main\n\nworktree /other/tree\nHEAD 2\nbranch refs/heads/pr/7\n"}
|
||||
_, err := CheckoutPull(context.Background(), runner, options)
|
||||
require.ErrorContains(t, err, `branch "pr/7" is checked out in the worktree /other/tree`)
|
||||
require.ErrorContains(t, err, "--detach")
|
||||
for _, call := range runner.calls {
|
||||
require.NotContains(t, call, "fetch")
|
||||
require.NotContains(t, call, "switch")
|
||||
}
|
||||
// The current worktree holding the branch is fine.
|
||||
runner = &checkoutRunner{collision: true, localCommit: "abc123", worktrees: "worktree abc123\nHEAD 1\nbranch refs/heads/pr/7\n"}
|
||||
_, err = CheckoutPull(context.Background(), runner, options)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ var ErrAmbiguousRemote = errors.New("ambiguous repository: select --remote or --
|
||||
|
||||
// DiscoverRemote names the remote used for repository discovery: preferred when set, otherwise
|
||||
// the base remote pr checkout recorded for the current branch, the current branch's upstream
|
||||
// remote unless it is a pulls/<owner>/<repo> head remote, then upstream, origin, or the only remote.
|
||||
// remote unless it is a pulls/<owner>/<repo> head remote or origin beside an upstream remote (a fork clone), then upstream, origin, or the only remote.
|
||||
// When repository is not nil, it names the repository of a remote gt can act on, or returns ""
|
||||
// for one on another forge. Those steps then skip such remotes, and the other remotes decide when
|
||||
// they name exactly one repository; with none of them usable the choice is the name-based one.
|
||||
@@ -43,19 +43,23 @@ func DiscoverRemote(ctx context.Context, runner Runner, dir, preferred string, r
|
||||
if strings.HasPrefix(tracking, "pulls/") {
|
||||
tracking = ""
|
||||
}
|
||||
names, namesErr := runner.Output(ctx, dir, false, "remote")
|
||||
available := strings.Fields(names)
|
||||
// In a fork clone, branches pushed to the fork track origin, but the base repository is upstream.
|
||||
if tracking == "origin" && slices.Contains(available, "upstream") {
|
||||
tracking = ""
|
||||
}
|
||||
for _, remote := range []string{pullBaseRemote(ctx, runner, dir, branch), tracking} {
|
||||
if try(remote) {
|
||||
return remote, nil
|
||||
}
|
||||
}
|
||||
names, err := runner.Output(ctx, dir, false, "remote")
|
||||
if err != nil {
|
||||
if namesErr != nil {
|
||||
if fallback != "" {
|
||||
return fallback, nil
|
||||
}
|
||||
return "", err
|
||||
return "", namesErr
|
||||
}
|
||||
available := strings.Fields(names)
|
||||
for _, name := range []string{"upstream", "origin"} {
|
||||
if slices.Contains(available, name) && try(name) {
|
||||
return name, nil
|
||||
|
||||
@@ -38,6 +38,8 @@ func TestDiscoverRemote(t *testing.T) {
|
||||
{name: "recorded pull base", runner: discoverRunner{head: "main", tracking: "fork", base: "upstream", "remote": "origin\nupstream\nfork"}, want: "upstream"},
|
||||
{name: "removed pull base", runner: discoverRunner{head: "main", tracking: "fork", base: "gone", "remote": "origin\nfork"}, want: "fork"},
|
||||
{name: "local branch upstream", runner: discoverRunner{head: "main", tracking: ".", "remote": "origin\nfork"}, want: "origin"},
|
||||
{name: "fork clone branch tracking origin", runner: discoverRunner{head: "main", tracking: "origin", "remote": "origin\nupstream"}, want: "upstream"},
|
||||
{name: "branch tracking origin without upstream", runner: discoverRunner{head: "main", tracking: "origin", "remote": "origin\nfork"}, want: "origin"},
|
||||
{name: "upstream remote", runner: discoverRunner{"remote": "origin\nupstream"}, want: "upstream"},
|
||||
{name: "origin remote", runner: discoverRunner{"remote": "fork\norigin"}, want: "origin"},
|
||||
{name: "sole remote", runner: discoverRunner{"remote": "fork"}, want: "fork"},
|
||||
|
||||
@@ -53,12 +53,27 @@ func (s Comments) List(ctx context.Context, n int64) ([]Comment, error) {
|
||||
}
|
||||
|
||||
// Page applies CLI pagination to the unpaginated comment collection.
|
||||
func (s Comments) Page(ctx context.Context, n int64, limit, page int) ([]Comment, error) {
|
||||
func (s Comments) Page(ctx context.Context, n int64, limit, page int) (Page[Comment], error) {
|
||||
items, err := s.List(ctx, n)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return Page[Comment]{}, err
|
||||
}
|
||||
return pageOf(items, limit, page)
|
||||
window, err := pageOf(items, limit, page)
|
||||
if err != nil {
|
||||
return Page[Comment]{}, err
|
||||
}
|
||||
return Page[Comment]{Items: window, More: len(items) > page*limit, Total: len(items), Counted: true}, nil
|
||||
}
|
||||
|
||||
// NotPlainCommentError reports a comment that the single-comment endpoint answers with no body,
|
||||
// such as an inline review comment. Such comments can still be edited and deleted by ID.
|
||||
type NotPlainCommentError struct {
|
||||
ID int64
|
||||
Repository string
|
||||
}
|
||||
|
||||
func (e NotPlainCommentError) Error() string {
|
||||
return fmt.Sprintf("comment %d in %s is not a plain comment, such as an inline review comment, which this command cannot show", e.ID, e.Repository)
|
||||
}
|
||||
|
||||
// View retrieves a comment by its repository-scoped ID.
|
||||
@@ -73,7 +88,7 @@ func (s Comments) View(ctx context.Context, id int64) (Comment, error) {
|
||||
})
|
||||
if status == http.StatusNoContent {
|
||||
// Gitea answers without a body for the comments that are not plain ones, such as inline review comments.
|
||||
return Comment{}, fmt.Errorf("comment %d in %s is not a plain comment, such as an inline review comment, which this command cannot show", id, s.Repository)
|
||||
return Comment{}, NotPlainCommentError{ID: id, Repository: s.Repository}
|
||||
}
|
||||
return item, Classify(err, "comment", strconv.FormatInt(id, 10), s.Repository)
|
||||
}
|
||||
|
||||
@@ -34,12 +34,17 @@ func TestCommentPaginationIsLocal(t *testing.T) {
|
||||
service := Comments{Client: client, Repository: "alice/project"}
|
||||
items, err := service.Page(context.Background(), 7, 2, 2)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, items, 1)
|
||||
require.Equal(t, int64(3), items[0].ID)
|
||||
require.Len(t, items.Items, 1)
|
||||
require.Equal(t, int64(3), items.Items[0].ID)
|
||||
require.False(t, items.More)
|
||||
first, err := service.Page(context.Background(), 7, 2, 1)
|
||||
require.NoError(t, err)
|
||||
require.True(t, first.More)
|
||||
require.Equal(t, 3, first.Total)
|
||||
items, err = service.Page(context.Background(), 7, 2, 3)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, items)
|
||||
require.NotNil(t, items)
|
||||
require.Empty(t, items.Items)
|
||||
require.NotNil(t, items.Items)
|
||||
item, err := service.Create(context.Background(), 7, "text")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "alice", item.Author)
|
||||
|
||||
@@ -33,6 +33,11 @@ func pageOf[T any](items []T, limit, page int) ([]T, error) {
|
||||
return items[start:min(start+limit, len(items))], nil
|
||||
}
|
||||
|
||||
// loadTogether runs the loaders concurrently and returns their errors joined.
|
||||
func loadTogether(loaders ...func() error) error {
|
||||
return concurrently(len(loaders), func(i int) error { return loaders[i]() })
|
||||
}
|
||||
|
||||
// listAll collects pages until the server returns an empty one.
|
||||
func listAll[T any](fetch func(page int) ([]T, error)) ([]T, error) {
|
||||
result := []T{}
|
||||
|
||||
@@ -41,12 +41,21 @@ type IssueCreateSelectables struct {
|
||||
Templates []IssueTemplate
|
||||
}
|
||||
|
||||
// CreateSelectables loads templates and, when the user can push, assignees/milestones/labels.
|
||||
// CreateSelectables concurrently loads templates and, when the user can push, assignees/milestones/labels.
|
||||
func (s Issues) CreateSelectables(ctx context.Context) (IssueCreateSelectables, error) {
|
||||
choices, err := loadCreateSelectables(ctx, s.Client, s.Repository)
|
||||
var result IssueCreateSelectables
|
||||
err := loadTogether(
|
||||
func() (err error) {
|
||||
result.CreateSelectables, err = loadCreateSelectables(ctx, s.Client, s.Repository)
|
||||
return err
|
||||
},
|
||||
func() (err error) {
|
||||
result.Templates, err = s.IssueTemplates(ctx)
|
||||
return err
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
return IssueCreateSelectables{}, err
|
||||
}
|
||||
templates, err := s.IssueTemplates(ctx)
|
||||
return IssueCreateSelectables{CreateSelectables: choices, Templates: templates}, err
|
||||
return result, nil
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -57,9 +58,12 @@ func TestCreateSelectablesLoadWriteFieldsOnlyWithPush(t *testing.T) {
|
||||
}
|
||||
for _, push := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("push=%t", push), func(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
calls := map[string]int{}
|
||||
client := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
mu.Lock()
|
||||
calls[r.URL.Path]++
|
||||
mu.Unlock()
|
||||
switch r.URL.Path {
|
||||
case "/api/v1/repos/alice/project":
|
||||
_, _ = fmt.Fprintf(w, `{"full_name":"alice/project","permissions":{"push":%t,"pull":true}}`, push)
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"slices"
|
||||
"strconv"
|
||||
"sync"
|
||||
|
||||
@@ -163,7 +164,7 @@ func (s Organizations) Create(ctx context.Context, opts OrganizationOptions) (Or
|
||||
})
|
||||
})
|
||||
if err != nil {
|
||||
return Organization{}, Classify(err, "organization", "", "")
|
||||
return Organization{}, Classify(err, "name", strconv.Quote(deref(opts.Name)), "")
|
||||
}
|
||||
return organizationFrom(org), nil
|
||||
}
|
||||
@@ -210,40 +211,84 @@ type MemberListOptions struct {
|
||||
Limit, Page int
|
||||
}
|
||||
|
||||
// publicScanPages bounds the server pages Members reads to find public memberships.
|
||||
const publicScanPages = 20
|
||||
|
||||
// Members lists the members of an organization.
|
||||
func (s Organizations) Members(ctx context.Context, name string, opts MemberListOptions) (Page[OrganizationMember], error) {
|
||||
users, err := callPage(ctx, s.Client, opts.Limit, opts.Page, func(ctx context.Context, c *gitea.Client, list gitea.ListOptions) ([]*gitea.User, *gitea.Response, error) {
|
||||
if opts.Public {
|
||||
return s.publicMembers(ctx, name, opts)
|
||||
}
|
||||
members, err := s.memberPage(ctx, name, opts.Limit, opts.Page, false)
|
||||
if err != nil || !opts.Visibility {
|
||||
return members, err
|
||||
}
|
||||
members.Items, _, err = s.withVisibility(ctx, name, members.Items)
|
||||
return members, err
|
||||
}
|
||||
|
||||
// memberPage lists one server page of members, or of the memberships Gitea reports as public.
|
||||
func (s Organizations) memberPage(ctx context.Context, name string, limit, page int, public bool) (Page[OrganizationMember], error) {
|
||||
users, err := callPage(ctx, s.Client, limit, page, func(ctx context.Context, c *gitea.Client, list gitea.ListOptions) ([]*gitea.User, *gitea.Response, error) {
|
||||
membership := gitea.ListOrgMembershipOption{ListOptions: list}
|
||||
if opts.Public {
|
||||
if public {
|
||||
return c.Organizations.ListPublicOrgMembership(ctx, name, membership)
|
||||
}
|
||||
return c.Organizations.ListOrgMembership(ctx, name, membership)
|
||||
})
|
||||
members := convertPage(users, memberFrom)
|
||||
if err != nil || !(opts.Public || opts.Visibility) {
|
||||
return members, err
|
||||
}
|
||||
public := make([]bool, len(members.Items))
|
||||
err = concurrently(len(members.Items), func(i int) (err error) {
|
||||
public[i], err = s.IsPublicMember(ctx, name, members.Items[i].Username)
|
||||
return convertPage(users, memberFrom), err
|
||||
}
|
||||
|
||||
// withVisibility checks the membership of each member and reports which ones are public.
|
||||
func (s Organizations) withVisibility(ctx context.Context, name string, members []OrganizationMember) ([]OrganizationMember, []bool, error) {
|
||||
public := make([]bool, len(members))
|
||||
err := concurrently(len(members), func(i int) (err error) {
|
||||
public[i], err = s.IsPublicMember(ctx, name, members[i].Username)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return Page[OrganizationMember]{}, err
|
||||
return nil, nil, err
|
||||
}
|
||||
shown := members.Items[:0]
|
||||
for i, member := range members.Items {
|
||||
member.Visibility = MembershipConcealed
|
||||
members = slices.Clone(members)
|
||||
for i := range members {
|
||||
members[i].Visibility = MembershipConcealed
|
||||
if public[i] {
|
||||
member.Visibility = MembershipPublic
|
||||
}
|
||||
if !opts.Public || public[i] {
|
||||
shown = append(shown, member)
|
||||
members[i].Visibility = MembershipPublic
|
||||
}
|
||||
}
|
||||
members.Items = shown
|
||||
members.Counted = members.Counted && !opts.Public
|
||||
return members, nil
|
||||
return members, public, nil
|
||||
}
|
||||
|
||||
// publicMembers lists the public memberships. Gitea lists concealed members as public to
|
||||
// administrators, so it reads server pages until the requested page of confirmed ones is full.
|
||||
func (s Organizations) publicMembers(ctx context.Context, name string, opts MemberListOptions) (Page[OrganizationMember], error) {
|
||||
const size = 50
|
||||
skip := (opts.Page - 1) * opts.Limit
|
||||
var matches []OrganizationMember
|
||||
more := false
|
||||
for page := 1; page <= publicScanPages && len(matches) <= skip+opts.Limit; page++ {
|
||||
batch, err := s.memberPage(ctx, name, size, page, true)
|
||||
if err != nil {
|
||||
return Page[OrganizationMember]{}, err
|
||||
}
|
||||
checked, public, err := s.withVisibility(ctx, name, batch.Items)
|
||||
if err != nil {
|
||||
return Page[OrganizationMember]{}, err
|
||||
}
|
||||
for i, member := range checked {
|
||||
if public[i] {
|
||||
matches = append(matches, member)
|
||||
}
|
||||
}
|
||||
more = batch.More
|
||||
if !more {
|
||||
break
|
||||
}
|
||||
}
|
||||
// Running out of the scan bound leaves later pages unread, which counts as more results.
|
||||
more = more || len(matches) > skip+opts.Limit
|
||||
matches = matches[min(len(matches), skip):]
|
||||
return Page[OrganizationMember]{Items: matches[:min(len(matches), opts.Limit)], More: more}, nil
|
||||
}
|
||||
|
||||
// concurrentRequests bounds the requests that concurrently keeps in flight.
|
||||
@@ -285,7 +330,15 @@ func (s Organizations) IsPublicMember(ctx context.Context, name, username string
|
||||
// check runs a membership check that answers no with a 404.
|
||||
func (s Organizations) check(ctx context.Context, op func(context.Context, *gitea.Client) (*gitea.Response, error)) (bool, error) {
|
||||
err := do(ctx, s.Client, op)
|
||||
// Gitea redirects callers who are not members, and gt does not follow the redirect.
|
||||
if failure, ok := errors.AsType[*transport.APIError](err); ok && failure.Status == http.StatusSeeOther {
|
||||
return false, &transport.APIError{Status: http.StatusForbidden, Method: failure.Method, Endpoint: failure.Endpoint, Message: "only organization members can check memberships"}
|
||||
}
|
||||
if IsNotFound(err) {
|
||||
// A mistyped user is not a missing membership.
|
||||
if missing, ok := errors.AsType[*NotFoundError](Classify(err, "", "", "")); ok && missing.Kind == "user" {
|
||||
return false, missing
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
return err == nil, err
|
||||
|
||||
@@ -6,7 +6,9 @@ package services
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitea.dev/cli/internal/transport"
|
||||
@@ -108,6 +110,38 @@ func TestOrganizationCreateSendsSuppliedPreferences(t *testing.T) {
|
||||
require.Equal(t, Organization{ID: 5, Name: "acme", Visibility: "limited", RepoAdminChangeTeamAccess: true}, item)
|
||||
}
|
||||
|
||||
func TestOrganizationMembershipChecksReportWhatGiteaRefuses(t *testing.T) {
|
||||
client := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/api/v1/orgs/acme/members/bob":
|
||||
http.Redirect(w, r, "/org/acme/public_members", http.StatusSeeOther)
|
||||
case "/api/v1/orgs/acme/members/bbo":
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
_, _ = w.Write([]byte(`{"message":"user does not exist [uid: 0, name: bbo]"}`))
|
||||
default:
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
service := Organizations{Client: client}
|
||||
_, err := service.IsMember(context.Background(), "acme", "bob")
|
||||
require.True(t, IsForbidden(err), "%v", err)
|
||||
_, err = service.IsMember(context.Background(), "acme", "bbo")
|
||||
require.EqualError(t, err, `user "bbo" not found`)
|
||||
member, err := service.IsMember(context.Background(), "acme", "carol")
|
||||
require.NoError(t, err)
|
||||
require.False(t, member)
|
||||
}
|
||||
|
||||
func TestOrganizationCreateNamesTheTakenName(t *testing.T) {
|
||||
client := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusUnprocessableEntity)
|
||||
_, _ = w.Write([]byte(`{"message":"user already exists [name: bob]"}`))
|
||||
}))
|
||||
name := "bob"
|
||||
_, err := (Organizations{Client: client}).Create(context.Background(), OrganizationOptions{Name: &name})
|
||||
require.EqualError(t, err, `name "bob" already exists`)
|
||||
}
|
||||
|
||||
func TestOrganizationMembershipRequests(t *testing.T) {
|
||||
var requests []string
|
||||
client := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -162,3 +196,30 @@ func TestOrganizationMembersCheckEachMembership(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrganizationPublicMembersReadLaterPages(t *testing.T) {
|
||||
// The first server page holds only concealed members; a public one follows on page 2.
|
||||
client := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.URL.Path == "/api/v1/orgs/acme/public_members" && r.URL.Query().Get("page") == "1":
|
||||
var users []string
|
||||
for i := range 50 {
|
||||
users = append(users, fmt.Sprintf(`{"id":%d,"login":"hidden%d"}`, i+10, i))
|
||||
}
|
||||
w.Header().Set("Link", `<http://x/api/v1/orgs/acme/public_members?page=2>; rel="next"`)
|
||||
_, _ = w.Write([]byte("[" + strings.Join(users, ",") + "]"))
|
||||
case r.URL.Path == "/api/v1/orgs/acme/public_members":
|
||||
_, _ = w.Write([]byte(`[{"id":1,"login":"alice"}]`))
|
||||
case r.URL.Path == "/api/v1/orgs/acme/public_members/alice":
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
case strings.HasPrefix(r.URL.Path, "/api/v1/orgs/acme/public_members/hidden"):
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
default:
|
||||
t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
|
||||
}
|
||||
}))
|
||||
members, err := (Organizations{Client: client}).Members(context.Background(), "acme", MemberListOptions{Public: true, Visibility: true, Limit: 1, Page: 1})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []OrganizationMember{{ID: 1, Username: "alice", Visibility: MembershipPublic}}, members.Items)
|
||||
require.False(t, members.More)
|
||||
}
|
||||
|
||||
@@ -23,30 +23,77 @@ func (s Pulls) CreateSelectables(ctx context.Context) (CreateSelectables, error)
|
||||
return loadCreateSelectables(ctx, s.Client, s.Repository)
|
||||
}
|
||||
|
||||
// PullCreateChoices seed the interactive create form: the repository, its pull request template
|
||||
// on the default branch, and the metadata selectables.
|
||||
type PullCreateChoices struct {
|
||||
Repository Repository
|
||||
Template string
|
||||
CreateSelectables
|
||||
}
|
||||
|
||||
// CreateChoices fetches the repository once for its default branch and permissions, then loads
|
||||
// the pull request template and the selectables concurrently.
|
||||
func (s Pulls) CreateChoices(ctx context.Context) (PullCreateChoices, error) {
|
||||
item, err := (Repositories{Client: s.Client}).get(ctx, s.Repository)
|
||||
if err != nil {
|
||||
return PullCreateChoices{}, err
|
||||
}
|
||||
result := PullCreateChoices{Repository: repositoryFrom(item)}
|
||||
err = loadTogether(
|
||||
func() (err error) {
|
||||
result.Template, err = s.Template(ctx, result.Repository.DefaultBranch)
|
||||
return err
|
||||
},
|
||||
func() (err error) {
|
||||
result.CreateSelectables, err = createSelectablesFor(ctx, s.Client, s.Repository, permissionsFrom(item).Push)
|
||||
return err
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
return PullCreateChoices{}, err
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func loadCreateSelectables(ctx context.Context, client *transport.Client, repository string) (CreateSelectables, error) {
|
||||
result := CreateSelectables{Assignees: []string{}, Milestones: []Milestone{}, Labels: []Label{}}
|
||||
permissions, err := (Repositories{Client: client}).viewPermissions(ctx, repository)
|
||||
if err != nil || !permissions.Push {
|
||||
return result, err
|
||||
if err != nil {
|
||||
return CreateSelectables{Assignees: []string{}, Milestones: []Milestone{}, Labels: []Label{}}, err
|
||||
}
|
||||
return createSelectablesFor(ctx, client, repository, permissions.Push)
|
||||
}
|
||||
|
||||
// createSelectablesFor loads assignees, milestones, and labels concurrently when canPush.
|
||||
func createSelectablesFor(ctx context.Context, client *transport.Client, repository string, canPush bool) (CreateSelectables, error) {
|
||||
result := CreateSelectables{Assignees: []string{}, Milestones: []Milestone{}, Labels: []Label{}}
|
||||
if !canPush {
|
||||
return result, nil
|
||||
}
|
||||
result.CanPush = true
|
||||
if result.Assignees, err = (Repositories{Client: client}).assignees(ctx, repository); err != nil {
|
||||
return result, err
|
||||
}
|
||||
if result.Milestones, err = listAll(func(page int) ([]Milestone, error) {
|
||||
return (Milestones{Client: client, Repository: repository}).List(ctx, "open", 100, page)
|
||||
}); err != nil {
|
||||
return result, err
|
||||
}
|
||||
if result.Labels, err = (Labels{Client: client, Repository: repository}).All(ctx); err != nil {
|
||||
return result, err
|
||||
}
|
||||
// Like --label, offer the labels shared by the organization that owns the repository.
|
||||
owner, _, _ := strings.Cut(repository, "/")
|
||||
if _, isOrg, err := organization(ctx, client, owner); err != nil || !isOrg {
|
||||
return result, err
|
||||
}
|
||||
orgLabels, err := (Labels{Client: client, Organization: owner}).All(ctx)
|
||||
result.Labels = append(result.Labels, orgLabels...)
|
||||
err := loadTogether(
|
||||
func() (err error) {
|
||||
result.Assignees, err = (Repositories{Client: client}).assignees(ctx, repository)
|
||||
return err
|
||||
},
|
||||
func() (err error) {
|
||||
result.Milestones, err = listAll(func(page int) ([]Milestone, error) {
|
||||
return (Milestones{Client: client, Repository: repository}).List(ctx, "open", 100, page)
|
||||
})
|
||||
return err
|
||||
},
|
||||
func() (err error) {
|
||||
if result.Labels, err = (Labels{Client: client, Repository: repository}).All(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
// Like --label, offer the labels shared by the organization that owns the repository.
|
||||
owner, _, _ := strings.Cut(repository, "/")
|
||||
if _, isOrg, err := organization(ctx, client, owner); err != nil || !isOrg {
|
||||
return err
|
||||
}
|
||||
orgLabels, err := (Labels{Client: client, Organization: owner}).All(ctx)
|
||||
result.Labels = append(result.Labels, orgLabels...)
|
||||
return err
|
||||
},
|
||||
)
|
||||
return result, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestPullCreateChoicesFetchRepositoryOnce(t *testing.T) {
|
||||
for _, push := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("push=%t", push), func(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
calls := map[string]int{}
|
||||
client := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
mu.Lock()
|
||||
calls[r.URL.Path]++
|
||||
mu.Unlock()
|
||||
switch {
|
||||
case r.URL.Path == "/api/v1/orgs/alice":
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
case r.URL.Path == "/api/v1/repos/alice/project":
|
||||
_, _ = fmt.Fprintf(w, `{"full_name":"alice/project","default_branch":"trunk","permissions":{"push":%t}}`, push)
|
||||
case strings.HasPrefix(r.URL.Path, "/api/v1/repos/alice/project/raw/"):
|
||||
assert.Equal(t, "trunk", r.URL.Query().Get("ref"))
|
||||
if r.URL.Path != "/api/v1/repos/alice/project/raw/.gitea/PULL_REQUEST_TEMPLATE.md" {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte("## Checklist\n"))
|
||||
case r.URL.Path == "/api/v1/repos/alice/project/assignees":
|
||||
_, _ = w.Write([]byte(`[{"login":"alice"}]`))
|
||||
case r.URL.Path == "/api/v1/repos/alice/project/milestones" && r.URL.Query().Get("page") == "1":
|
||||
_, _ = w.Write([]byte(`[{"id":1,"title":"v1"}]`))
|
||||
case r.URL.Path == "/api/v1/repos/alice/project/labels" && r.URL.Query().Get("page") == "1":
|
||||
_, _ = w.Write([]byte(`[{"id":2,"name":"bug"}]`))
|
||||
case r.URL.Path == "/api/v1/repos/alice/project/milestones", r.URL.Path == "/api/v1/repos/alice/project/labels":
|
||||
_, _ = w.Write([]byte(`[]`))
|
||||
default:
|
||||
t.Errorf("unexpected path %s", r.URL.Path)
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
choices, err := (Pulls{Client: client, Repository: "alice/project"}).CreateChoices(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "alice/project", choices.Repository.FullName)
|
||||
require.Equal(t, "trunk", choices.Repository.DefaultBranch)
|
||||
require.Equal(t, "## Checklist\n", choices.Template)
|
||||
want := CreateSelectables{Assignees: []string{}, Milestones: []Milestone{}, Labels: []Label{}}
|
||||
if push {
|
||||
want = CreateSelectables{
|
||||
CanPush: true,
|
||||
Assignees: []string{"alice"},
|
||||
Milestones: []Milestone{{ID: 1, Title: "v1"}},
|
||||
Labels: []Label{{ID: 2, Name: "bug"}},
|
||||
}
|
||||
}
|
||||
require.Equal(t, want, choices.CreateSelectables)
|
||||
require.Equal(t, 1, calls["/api/v1/repos/alice/project"])
|
||||
if !push {
|
||||
require.Zero(t, calls["/api/v1/repos/alice/project/assignees"])
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPullCreateChoicesLoadConcurrently(t *testing.T) {
|
||||
// The template, assignees, milestones, and labels requests only complete once all four are in flight.
|
||||
paths := []string{"raw/PULL_REQUEST_TEMPLATE.md", "assignees", "milestones", "labels"}
|
||||
arrived := map[string]chan struct{}{}
|
||||
for _, path := range paths {
|
||||
arrived[path] = make(chan struct{})
|
||||
}
|
||||
var once sync.Map
|
||||
client := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
path := strings.TrimPrefix(r.URL.Path, "/api/v1/repos/alice/project/")
|
||||
if r.URL.Path == "/api/v1/orgs/alice" {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/api/v1/repos/alice/project" {
|
||||
_, _ = w.Write([]byte(`{"full_name":"alice/project","default_branch":"main","permissions":{"push":true}}`))
|
||||
return
|
||||
}
|
||||
if ch, ok := arrived[path]; ok {
|
||||
if _, loaded := once.LoadOrStore(path, true); !loaded {
|
||||
close(ch)
|
||||
}
|
||||
for _, other := range paths {
|
||||
select {
|
||||
case <-arrived[other]:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Errorf("%s did not run concurrently with %s", other, path)
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
if strings.HasPrefix(path, "raw/") {
|
||||
_, _ = w.Write([]byte("template"))
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(`[]`))
|
||||
}))
|
||||
choices, err := (Pulls{Client: client, Repository: "alice/project"}).CreateChoices(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "template", choices.Template)
|
||||
}
|
||||
|
||||
func TestPullCreateChoicesReportFailures(t *testing.T) {
|
||||
for _, failing := range []string{"/api/v1/repos/alice/project", "/api/v1/repos/alice/project/labels", "/api/v1/repos/alice/project/raw/PULL_REQUEST_TEMPLATE.md"} {
|
||||
t.Run(failing, func(t *testing.T) {
|
||||
client := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.URL.Path == failing:
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
case r.URL.Path == "/api/v1/repos/alice/project":
|
||||
_, _ = w.Write([]byte(`{"full_name":"alice/project","default_branch":"main","permissions":{"push":true}}`))
|
||||
default:
|
||||
_, _ = w.Write([]byte(`[]`))
|
||||
}
|
||||
}))
|
||||
_, err := (Pulls{Client: client, Repository: "alice/project"}).CreateChoices(context.Background())
|
||||
require.ErrorContains(t, err, "500")
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -254,7 +254,7 @@ func (s Pulls) DecideAll(ctx context.Context, items []Pull) ([]Pull, error) {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
item.ReviewDecision = ReviewDecision(LatestReviews(all), len(item.Reviewers)+len(item.ReviewerTeams) > 0)
|
||||
item.ReviewDecision = ReviewDecision(all, len(item.Reviewers)+len(item.ReviewerTeams) > 0)
|
||||
viewed[i] = item
|
||||
return nil
|
||||
})
|
||||
@@ -276,6 +276,26 @@ func (s Pulls) ListOpen(ctx context.Context) ([]Pull, error) {
|
||||
})
|
||||
}
|
||||
|
||||
// NewestClosed returns the most recently updated closed or merged pull request that keep
|
||||
// accepts, and whether there is one. It reads pages newest first and stops at the first match.
|
||||
func (s Pulls) NewestClosed(ctx context.Context, keep func(Pull) bool) (Pull, bool, error) {
|
||||
for page := 1; page <= maxListPages; page++ {
|
||||
items, _, err := s.List(ctx, PullListOptions{State: "closed", Sort: "recentupdate", Limit: 50, Page: page})
|
||||
if err != nil {
|
||||
return Pull{}, false, err
|
||||
}
|
||||
if len(items) == 0 {
|
||||
return Pull{}, false, nil
|
||||
}
|
||||
for _, item := range items {
|
||||
if keep(item) {
|
||||
return item, true, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return Pull{}, false, nil
|
||||
}
|
||||
|
||||
// Create opens a pull request.
|
||||
func (s Pulls) Create(ctx context.Context, opts PullOptions) (Pull, error) {
|
||||
// TODO(sdk): CreatePullRequestOption lacks allow_maintainer_edit.
|
||||
|
||||
@@ -5,9 +5,12 @@ package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"gitea.dev/cli/internal/transport"
|
||||
gitea "gitea.dev/sdk"
|
||||
@@ -103,9 +106,24 @@ func (s Releases) Create(ctx context.Context, opts ReleaseOptions) (Release, err
|
||||
IsDraft: deref(opts.Draft), IsPrerelease: deref(opts.Prerelease),
|
||||
})
|
||||
})
|
||||
if apiErr, ok := errors.AsType[*transport.APIError](err); ok && apiErr.Status == http.StatusNotFound && strings.Contains(apiErr.Message, "target") {
|
||||
// The release does not exist yet, so a 404 here names the unresolvable target, not the release.
|
||||
return item, &NotFoundError{Kind: "target", Key: strconv.Quote(deref(opts.Target)), Scope: s.Repository, Err: err}
|
||||
}
|
||||
return item, Classify(err, "release", deref(opts.Tag), s.Repository)
|
||||
}
|
||||
|
||||
// TagExists reports whether the repository on the server has the tag.
|
||||
func (s Releases) TagExists(ctx context.Context, tag string) (bool, error) {
|
||||
_, err := repoCall(ctx, s.Client, s.Repository, func(ctx context.Context, c *gitea.Client, owner, repo string) (*gitea.Tag, *gitea.Response, error) {
|
||||
return c.Repositories.GetTag(ctx, owner, repo, tag)
|
||||
})
|
||||
if IsNotFound(err) {
|
||||
return false, nil
|
||||
}
|
||||
return err == nil, err
|
||||
}
|
||||
|
||||
// Edit changes only supplied release fields; Gitea ignores empty text fields.
|
||||
func (s Releases) Edit(ctx context.Context, id int64, opts ReleaseOptions) (Release, error) {
|
||||
return repoConvert(ctx, s.Client, s.Repository, releaseFrom, func(ctx context.Context, c *gitea.Client, owner, repo string) (*gitea.Release, *gitea.Response, error) {
|
||||
|
||||
@@ -234,3 +234,30 @@ func TestReleaseAssetRenameAndDelete(t *testing.T) {
|
||||
require.Equal(t, ReleaseAsset{ID: 2, Name: "renamed.bin"}, asset)
|
||||
require.NoError(t, service.DeleteAsset(context.Background(), 1, 2))
|
||||
}
|
||||
|
||||
func TestReleaseCreateReportsAnUnresolvableTargetNotAMissingRelease(t *testing.T) {
|
||||
client := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
_, _ = w.Write([]byte(`{"message":"target not found"}`))
|
||||
}))
|
||||
target, tag := "deadbeef", "v1"
|
||||
_, err := Releases{Client: client, Repository: "alice/project"}.Create(context.Background(), ReleaseOptions{Tag: &tag, Title: &tag, Target: &target})
|
||||
var notFound *NotFoundError
|
||||
require.ErrorAs(t, err, ¬Found)
|
||||
require.EqualError(t, err, `target "deadbeef" not found in alice/project`)
|
||||
}
|
||||
|
||||
func TestReleaseTagExistsDistinguishesMissingFromFailing(t *testing.T) {
|
||||
status := http.StatusNotFound
|
||||
client := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(status)
|
||||
_, _ = w.Write([]byte(`{"message":"x"}`))
|
||||
}))
|
||||
service := Releases{Client: client, Repository: "alice/project"}
|
||||
exists, err := service.TagExists(context.Background(), "v1")
|
||||
require.NoError(t, err)
|
||||
require.False(t, exists)
|
||||
status = http.StatusInternalServerError
|
||||
_, err = service.TagExists(context.Background(), "v1")
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
@@ -6,8 +6,10 @@ package services
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"gitea.dev/cli/internal/transport"
|
||||
@@ -99,35 +101,75 @@ func (s Repositories) get(ctx context.Context, repo string) (*gitea.Repository,
|
||||
return item, Classify(err, "repository", repo, "")
|
||||
}
|
||||
|
||||
// readmeNames are the README file names that Gitea shows, in order of preference.
|
||||
var readmeNames = []string{"readme.md", "readme.markdown", "readme", "readme.txt"}
|
||||
// readmeDirs are the directories Gitea searches for a README, in order; "" is the repository root.
|
||||
var readmeDirs = []string{".gitea", ".github", "", "docs"}
|
||||
|
||||
// Readme returns the README in the top directory of the repository at ref: its file name and its
|
||||
// content, or "" when there is none.
|
||||
func (s Repositories) Readme(ctx context.Context, repo, ref string) (name, content string, err error) {
|
||||
entries, err := repoCall(ctx, s.Client, repo, func(ctx context.Context, c *gitea.Client, owner, name string) ([]*gitea.ContentsResponse, *gitea.Response, error) {
|
||||
return c.Repositories.ListContents(ctx, owner, name, ref, "")
|
||||
})
|
||||
// readmeRank orders README file names as Gitea does: Markdown first, then text, then any other
|
||||
// README.* such as README.rst. It returns -1 for names that are not a README.
|
||||
func readmeRank(name string) int {
|
||||
switch lower := strings.ToLower(name); {
|
||||
case lower == "readme.md":
|
||||
return 0
|
||||
case lower == "readme.markdown":
|
||||
return 1
|
||||
case lower == "readme.txt":
|
||||
return 2
|
||||
case lower == "readme":
|
||||
return 3
|
||||
case strings.HasPrefix(lower, "readme."):
|
||||
return 4
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// Readme returns the README of the repository at ref as Gitea's web view finds it, searching .gitea,
|
||||
// .github, the root and docs: its path and its content, or "" when there is none. An explicit ref
|
||||
// that does not exist is an error.
|
||||
func (s Repositories) Readme(ctx context.Context, repo, ref string) (path, content string, err error) {
|
||||
list := func(dir string) ([]*gitea.ContentsResponse, error) {
|
||||
return repoCall(ctx, s.Client, repo, func(ctx context.Context, c *gitea.Client, owner, name string) ([]*gitea.ContentsResponse, *gitea.Response, error) {
|
||||
return c.Repositories.ListContents(ctx, owner, name, ref, dir)
|
||||
})
|
||||
}
|
||||
root, err := list("")
|
||||
if err != nil {
|
||||
if IsNotFound(err) && ref != "" {
|
||||
return "", "", NotFound("branch", strconv.Quote(ref), repo)
|
||||
}
|
||||
// A reader without code access sees the repository but not its files.
|
||||
if IsNotFound(err) || IsForbidden(err) {
|
||||
return "", "", nil
|
||||
}
|
||||
return "", "", err
|
||||
}
|
||||
rank := len(readmeNames)
|
||||
for _, entry := range entries {
|
||||
if i := slices.Index(readmeNames, strings.ToLower(entry.Name)); entry.Type == "file" && i >= 0 && i < rank {
|
||||
name, rank = entry.Name, i
|
||||
for _, dir := range readmeDirs {
|
||||
entries := root
|
||||
if dir != "" {
|
||||
i := slices.IndexFunc(root, func(e *gitea.ContentsResponse) bool { return e.Type == "dir" && e.Name == dir })
|
||||
if i < 0 {
|
||||
continue
|
||||
}
|
||||
if entries, err = list(dir); err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
}
|
||||
rank := -1
|
||||
for _, entry := range entries {
|
||||
if r := readmeRank(entry.Name); entry.Type == "file" && r >= 0 && (rank < 0 || r < rank) {
|
||||
path, rank = strings.TrimPrefix(dir+"/"+entry.Name, "/"), r
|
||||
}
|
||||
}
|
||||
if path != "" {
|
||||
break
|
||||
}
|
||||
}
|
||||
if name == "" {
|
||||
if path == "" {
|
||||
return "", "", nil
|
||||
}
|
||||
data, err := repoCall(ctx, s.Client, repo, func(ctx context.Context, c *gitea.Client, owner, repo string) ([]byte, *gitea.Response, error) {
|
||||
return c.Repositories.GetFile(ctx, owner, repo, ref, name)
|
||||
data, err := repoCall(ctx, s.Client, repo, func(ctx context.Context, c *gitea.Client, owner, name string) ([]byte, *gitea.Response, error) {
|
||||
return c.Repositories.GetFile(ctx, owner, name, ref, path)
|
||||
})
|
||||
return name, string(data), err
|
||||
return path, string(data), err
|
||||
}
|
||||
|
||||
// RepositoryPermissions holds server-side access flags used only for local decisions.
|
||||
@@ -141,10 +183,17 @@ type RepositoryPermissions struct {
|
||||
// viewPermissions reads repository access flags without exposing them on Repository results.
|
||||
func (s Repositories) viewPermissions(ctx context.Context, repo string) (RepositoryPermissions, error) {
|
||||
item, err := s.get(ctx, repo)
|
||||
if err != nil || item.Permissions == nil {
|
||||
if err != nil {
|
||||
return RepositoryPermissions{}, err
|
||||
}
|
||||
return RepositoryPermissions{Admin: item.Permissions.Admin, Push: item.Permissions.Push, Pull: item.Permissions.Pull}, nil
|
||||
return permissionsFrom(item), nil
|
||||
}
|
||||
|
||||
func permissionsFrom(item *gitea.Repository) RepositoryPermissions {
|
||||
if item.Permissions == nil {
|
||||
return RepositoryPermissions{}
|
||||
}
|
||||
return RepositoryPermissions{Admin: item.Permissions.Admin, Push: item.Permissions.Push, Pull: item.Permissions.Pull}
|
||||
}
|
||||
|
||||
// Assignee is a user that can be assigned on repository issues.
|
||||
@@ -190,6 +239,13 @@ func (s Repositories) Create(ctx context.Context, org string, opts RepositoryOpt
|
||||
Readme: opts.Readme, DefaultBranch: opts.DefaultBranch, TrustModel: gitea.TrustModel(opts.TrustModel),
|
||||
ObjectFormatName: opts.ObjectFormat,
|
||||
}
|
||||
// TODO(sdk): CreateRepoOption.Validate counts the description in bytes, but Gitea allows 2048
|
||||
// characters; a longer one is set by an edit once the repository exists.
|
||||
description := opts.Description
|
||||
later := len(description) > sdkDescriptionLimit
|
||||
if later {
|
||||
options.Description = ""
|
||||
}
|
||||
item, _, err := call(ctx, s.Client, func(ctx context.Context, c *gitea.Client) (*gitea.Repository, *gitea.Response, error) {
|
||||
if org != "" {
|
||||
return c.Repositories.CreateOrgRepo(ctx, org, options)
|
||||
@@ -197,11 +253,26 @@ func (s Repositories) Create(ctx context.Context, org string, opts RepositoryOpt
|
||||
return c.Repositories.CreateRepo(ctx, options)
|
||||
})
|
||||
if err != nil {
|
||||
if org != "" && IsNotFound(err) {
|
||||
// The repository cannot be missing before it exists: the organization is.
|
||||
return Repository{}, &NotFoundError{Kind: "organization", Key: strconv.Quote(org), Err: err}
|
||||
}
|
||||
return Repository{}, Classify(err, "repository", "", "")
|
||||
}
|
||||
return repositoryFrom(item), nil
|
||||
created := repositoryFrom(item)
|
||||
if later {
|
||||
edited, err := s.Edit(ctx, created.FullName, RepositoryEdit{Description: &description})
|
||||
if err != nil {
|
||||
return created, fmt.Errorf("repository %s was created, but setting its description failed: %w", created.FullName, err)
|
||||
}
|
||||
return edited, nil
|
||||
}
|
||||
return created, nil
|
||||
}
|
||||
|
||||
// sdkDescriptionLimit is the length in bytes that the SDK accepts for a new repository's description.
|
||||
const sdkDescriptionLimit = 2048
|
||||
|
||||
// Edit updates only explicitly supplied resource fields.
|
||||
func (s Repositories) Edit(ctx context.Context, repo string, opts RepositoryEdit) (Repository, error) {
|
||||
var mergeStyle *gitea.MergeStyle
|
||||
@@ -221,17 +292,17 @@ func (s Repositories) Edit(ctx context.Context, repo string, opts RepositoryEdit
|
||||
return item, Classify(err, "repository", repo, "")
|
||||
}
|
||||
|
||||
// AddTopic adds a topic to the repository.
|
||||
func (s Repositories) AddTopic(ctx context.Context, repo, topic string) error {
|
||||
return repoDo(ctx, s.Client, repo, func(ctx context.Context, c *gitea.Client, owner, name string) (*gitea.Response, error) {
|
||||
return c.Repositories.AddRepoTopic(ctx, owner, name, topic)
|
||||
// Topics lists the topics of the repository. Gitea allows at most 25, so one page holds them all.
|
||||
func (s Repositories) Topics(ctx context.Context, repo string) ([]string, error) {
|
||||
return repoCall(ctx, s.Client, repo, func(ctx context.Context, c *gitea.Client, owner, name string) ([]string, *gitea.Response, error) {
|
||||
return c.Repositories.ListRepoTopics(ctx, owner, name, gitea.ListRepoTopicsOptions{ListOptions: gitea.ListOptions{Page: 1, PageSize: 50}})
|
||||
})
|
||||
}
|
||||
|
||||
// RemoveTopic removes a topic from the repository.
|
||||
func (s Repositories) RemoveTopic(ctx context.Context, repo, topic string) error {
|
||||
// SetTopics replaces the topics of the repository.
|
||||
func (s Repositories) SetTopics(ctx context.Context, repo string, topics []string) error {
|
||||
return repoDo(ctx, s.Client, repo, func(ctx context.Context, c *gitea.Client, owner, name string) (*gitea.Response, error) {
|
||||
return c.Repositories.DeleteRepoTopic(ctx, owner, name, topic)
|
||||
return c.Repositories.SetRepoTopics(ctx, owner, name, topics)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ package services
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -79,3 +80,63 @@ func TestRepositoryAssigneesTagsAndMissingPermissions(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, RepositoryPermissions{}, permissions)
|
||||
}
|
||||
|
||||
func TestRepositoryCreateReportsMissingOrganization(t *testing.T) {
|
||||
client := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
_, _ = w.Write([]byte(`{"message":"GetOrgByName"}`))
|
||||
}))
|
||||
_, err := (Repositories{Client: client}).Create(context.Background(), "acme-typo", RepositoryOptions{Name: "tool"})
|
||||
require.EqualError(t, err, `organization "acme-typo" not found`)
|
||||
}
|
||||
|
||||
func TestRepositoryReadme(t *testing.T) {
|
||||
dirEntry := func(name string) string { return `{"name":"` + name + `","path":"` + name + `","type":"dir"}` }
|
||||
fileEntry := func(dir, name string) string {
|
||||
return `{"name":"` + name + `","path":"` + dir + name + `","type":"file"}`
|
||||
}
|
||||
listings := map[string]string{
|
||||
"/api/v1/repos/alice/project/contents/": "[" + fileEntry("", "README.rst") + "," + fileEntry("", "readme.txt") + "," + dirEntry(".github") + "]",
|
||||
"/api/v1/repos/alice/project/contents/.github": "[" + fileEntry(".github/", "README.md") + "]",
|
||||
}
|
||||
client := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Query().Get("ref") == "develp" {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
if body, ok := listings[r.URL.Path]; ok {
|
||||
_, _ = w.Write([]byte(body))
|
||||
return
|
||||
}
|
||||
assert.Equal(t, "/api/v1/repos/alice/project/raw/.github/README.md", r.URL.Path)
|
||||
_, _ = w.Write([]byte("hello"))
|
||||
}))
|
||||
path, content, err := (Repositories{Client: client}).Readme(context.Background(), "alice/project", "")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, ".github/README.md", path)
|
||||
assert.Equal(t, "hello", content)
|
||||
|
||||
_, _, err = (Repositories{Client: client}).Readme(context.Background(), "alice/project", "develp")
|
||||
require.EqualError(t, err, `branch "develp" not found in alice/project`)
|
||||
}
|
||||
|
||||
func TestRepositoryCreateSetsADescriptionBeyondTheSDKByteLimitByEdit(t *testing.T) {
|
||||
description := strings.Repeat("日", 800) // 2400 bytes, 800 characters: Gitea accepts it, the SDK would not
|
||||
var methods []string
|
||||
client := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
methods = append(methods, r.Method)
|
||||
body := requestJSON(t, r)
|
||||
switch r.Method {
|
||||
case http.MethodPost:
|
||||
require.Empty(t, body["description"])
|
||||
_, _ = w.Write([]byte(`{"id":1,"name":"project","full_name":"alice/project"}`))
|
||||
case http.MethodPatch:
|
||||
require.Equal(t, description, body["description"])
|
||||
_, _ = w.Write([]byte(`{"id":1,"name":"project","full_name":"alice/project","description":"` + description + `"}`))
|
||||
}
|
||||
}))
|
||||
created, err := (Repositories{Client: client}).Create(context.Background(), "", RepositoryOptions{Name: "project", Description: description})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{http.MethodPost, http.MethodPatch}, methods)
|
||||
require.Equal(t, description, created.Description)
|
||||
}
|
||||
|
||||
@@ -121,7 +121,10 @@ func (s Repositories) Search(ctx context.Context, opts RepositorySearchOptions)
|
||||
if err != nil {
|
||||
return Page[Repository]{}, err
|
||||
}
|
||||
options.PrioritizedByOwnerID = account.ID
|
||||
// Gitea groups results by owner ahead of the requested sort, so an explicit sort cannot keep it.
|
||||
if opts.Sort == "" {
|
||||
options.PrioritizedByOwnerID = account.ID
|
||||
}
|
||||
window, err := callPage(ctx, s.Client, opts.Limit, opts.Page, func(ctx context.Context, c *gitea.Client, list gitea.ListOptions) ([]*gitea.Repository, *gitea.Response, error) {
|
||||
options.ListOptions = list
|
||||
return c.Repositories.SearchRepos(ctx, options)
|
||||
|
||||
@@ -118,6 +118,22 @@ func TestRepositorySearchSendsExplicitFalseFilters(t *testing.T) {
|
||||
require.Empty(t, page.Items)
|
||||
}
|
||||
|
||||
func TestRepositorySearchSortDropsOwnerPriority(t *testing.T) {
|
||||
client := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/api/v1/user" {
|
||||
_, _ = w.Write([]byte(`{"id":7}`))
|
||||
return
|
||||
}
|
||||
query := r.URL.Query()
|
||||
assert.False(t, query.Has("priority_owner_id"))
|
||||
assert.Equal(t, "updated", query.Get("sort"))
|
||||
assert.Equal(t, "desc", query.Get("order"))
|
||||
_, _ = w.Write([]byte(`{"data":[]}`))
|
||||
}))
|
||||
_, err := (Repositories{Client: client}).Search(context.Background(), RepositorySearchOptions{Query: "go", Sort: "updated", Order: "desc", Limit: 30, Page: 1})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestRepositorySearchScopesOwner(t *testing.T) {
|
||||
client := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
|
||||
@@ -6,6 +6,7 @@ package services
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
@@ -101,6 +102,13 @@ func (s Repositories) Migrate(ctx context.Context, opts RepositoryMigrationOptio
|
||||
defer cancel()
|
||||
s.Client = s.Client.WithTimeout(opts.Timeout)
|
||||
}
|
||||
// TODO(sdk): MigrateRepoOption.Validate counts the description in bytes, but Gitea allows 2048
|
||||
// characters; a longer one is set by an edit once the (synchronous) migration is done.
|
||||
description := opts.Description
|
||||
later := len(description) > sdkDescriptionLimit
|
||||
if later {
|
||||
opts.Description = ""
|
||||
}
|
||||
item, _, err := call(ctx, s.Client, func(ctx context.Context, c *gitea.Client) (*gitea.Repository, *gitea.Response, error) {
|
||||
return c.Repositories.MigrateRepo(ctx, gitea.MigrateRepoOption{
|
||||
RepoName: opts.Name, RepoOwner: opts.Owner, CloneAddr: opts.CloneURL, Service: gitea.GitServiceType(opts.Service),
|
||||
@@ -117,5 +125,13 @@ func (s Repositories) Migrate(ctx context.Context, opts RepositoryMigrationOptio
|
||||
}
|
||||
return Repository{}, err
|
||||
}
|
||||
return repositoryFrom(item), nil
|
||||
migrated := repositoryFrom(item)
|
||||
if later {
|
||||
edited, err := s.Edit(ctx, migrated.FullName, RepositoryEdit{Description: &description})
|
||||
if err != nil {
|
||||
return migrated, fmt.Errorf("repository %s was imported, but setting its description failed: %w", migrated.FullName, err)
|
||||
}
|
||||
return edited, nil
|
||||
}
|
||||
return migrated, nil
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -89,3 +90,25 @@ func TestRepositoryMigrationKeepsMessageWithoutCredentials(t *testing.T) {
|
||||
_, err := (Repositories{Client: client}).Migrate(context.Background(), RepositoryMigrationOptions{Name: "imported", CloneURL: "https://source.test/repo", Service: "git"})
|
||||
require.ErrorContains(t, err, "repository already exists")
|
||||
}
|
||||
|
||||
func TestRepositoryMigrateSetsADescriptionBeyondTheSDKByteLimitByEdit(t *testing.T) {
|
||||
description := strings.Repeat("日", 800) // 2400 bytes, 800 characters
|
||||
var methods []string
|
||||
client := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
methods = append(methods, r.Method)
|
||||
body := requestJSON(t, r)
|
||||
switch r.Method {
|
||||
case http.MethodPost:
|
||||
require.Empty(t, body["description"])
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
_, _ = w.Write([]byte(`{"id":2,"name":"imported","full_name":"alice/imported"}`))
|
||||
case http.MethodPatch:
|
||||
require.Equal(t, description, body["description"])
|
||||
_, _ = w.Write([]byte(`{"id":2,"name":"imported","full_name":"alice/imported","description":"` + description + `"}`))
|
||||
}
|
||||
}))
|
||||
migrated, err := (Repositories{Client: client}).Migrate(context.Background(), RepositoryMigrationOptions{Name: "imported", CloneURL: "https://source.test/repo", Service: "git", Description: description})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{http.MethodPost, http.MethodPatch}, methods)
|
||||
require.Equal(t, description, migrated.Description)
|
||||
}
|
||||
|
||||
@@ -97,17 +97,37 @@ func (s Reviews) changeRequests(ctx context.Context, n int64, changes ReviewRequ
|
||||
return nil
|
||||
}
|
||||
|
||||
// CheckRequestTeams verifies that every named team exists in the repository's organization.
|
||||
// CheckRequestTeams verifies that every named team exists in the repository's organization. Gitea
|
||||
// lets only organization members list teams, though outside collaborators and the pull request
|
||||
// author may request reviews; when the lookup is forbidden, or the organization is hidden from the
|
||||
// caller (a private organization answers 404 to non-members), the server checks the names, as for gh.
|
||||
func (s Reviews) CheckRequestTeams(ctx context.Context, names []string) error {
|
||||
owner, _, _ := strings.Cut(s.Repository, "/")
|
||||
_, isOrg, err := organization(ctx, s.Client, owner)
|
||||
if IsForbidden(err) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !isOrg {
|
||||
// A private organization answers 404 to non-members, like a name nobody owns; a user that
|
||||
// exists is certainly not an organization.
|
||||
_, _, err := call(ctx, s.Client, func(ctx context.Context, c *gitea.Client) (*gitea.User, *gitea.Response, error) {
|
||||
return c.Users.GetUserInfo(ctx, owner)
|
||||
})
|
||||
if IsNotFound(err) || IsForbidden(err) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return errors.New("team reviews require an organization repository")
|
||||
}
|
||||
teams, err := (Teams{Client: s.Client}).ByName(ctx, owner)
|
||||
if IsForbidden(err) || IsNotFound(err) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -54,6 +54,30 @@ func TestReviewRequestPartialFailureStopsFurtherEdits(t *testing.T) {
|
||||
require.Equal(t, 2, mutations)
|
||||
}
|
||||
|
||||
func TestReviewerTeamCheckSkippedWhenTeamListingIsForbidden(t *testing.T) {
|
||||
var posted bool
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.URL.Path == "/api/v1/orgs/owner":
|
||||
_, _ = w.Write([]byte(`{"id":1}`))
|
||||
case r.URL.Path == "/api/v1/orgs/owner/teams":
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
_, _ = w.Write([]byte(`{"message":"Must be an organization member"}`))
|
||||
case r.Method == http.MethodPost && r.URL.Path == "/api/v1/repos/owner/repo/pulls/1/requested_reviewers":
|
||||
posted = true
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
_, _ = w.Write([]byte(`[]`))
|
||||
default:
|
||||
_, _ = w.Write([]byte(`{"number":1}`))
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
changes := ReviewRequestChanges{Add: ReviewRequestInput{Teams: []string{"devs"}}}
|
||||
_, err := (Reviews{Client: transport.New(server.URL, "", false), Repository: "owner/repo"}).ChangeRequests(context.Background(), 1, changes)
|
||||
require.NoError(t, err)
|
||||
require.True(t, posted, "the server decides whether the team exists")
|
||||
}
|
||||
|
||||
func TestUnknownReviewerTeamRejectsBeforeUserRemoval(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
require.Equal(t, http.MethodGet, r.Method)
|
||||
@@ -71,3 +95,25 @@ func TestUnknownReviewerTeamRejectsBeforeUserRemoval(t *testing.T) {
|
||||
_, err := (Reviews{Client: transport.New(server.URL, "", false), Repository: "owner/repo"}).ChangeRequests(context.Background(), 1, changes)
|
||||
require.ErrorContains(t, err, `team "missing" is unavailable`)
|
||||
}
|
||||
|
||||
func TestReviewerTeamCheckSkippedForAHiddenPrivateOrganization(t *testing.T) {
|
||||
var posted bool
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.URL.Path == "/api/v1/orgs/owner" || r.URL.Path == "/api/v1/users/owner":
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
_, _ = w.Write([]byte(`{"message":"GetUserByName"}`))
|
||||
case r.Method == http.MethodPost && r.URL.Path == "/api/v1/repos/owner/repo/pulls/1/requested_reviewers":
|
||||
posted = true
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
_, _ = w.Write([]byte(`[]`))
|
||||
default:
|
||||
_, _ = w.Write([]byte(`{"number":1}`))
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
changes := ReviewRequestChanges{Add: ReviewRequestInput{Teams: []string{"devs"}}}
|
||||
_, err := (Reviews{Client: transport.New(server.URL, "", false), Repository: "owner/repo"}).ChangeRequests(context.Background(), 1, changes)
|
||||
require.NoError(t, err)
|
||||
require.True(t, posted, "a non-member cannot see the organization, so the server decides")
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ type Review struct {
|
||||
Body string `json:"body"`
|
||||
State string `json:"state"`
|
||||
Author string `json:"author"`
|
||||
Team string `json:"team"`
|
||||
URL string `json:"url"`
|
||||
Commit string `json:"commit"`
|
||||
SubmittedAt string `json:"submitted_at"`
|
||||
@@ -31,9 +32,21 @@ type Review struct {
|
||||
Dismissed bool `json:"dismissed"`
|
||||
}
|
||||
|
||||
// Reviewer names who the review is by, or for a request to a team, "team NAME".
|
||||
func (r Review) Reviewer() string {
|
||||
if r.Author == "" && r.Team != "" {
|
||||
return "team " + r.Team
|
||||
}
|
||||
return r.Author
|
||||
}
|
||||
|
||||
func reviewFrom(review *gitea.PullReview) Review {
|
||||
team := ""
|
||||
if review.ReviewerTeam != nil {
|
||||
team = review.ReviewerTeam.Name
|
||||
}
|
||||
return Review{
|
||||
ID: review.ID, Body: review.Body, State: string(review.State), Author: login(review.Reviewer), URL: review.HTMLURL,
|
||||
ID: review.ID, Body: review.Body, State: string(review.State), Author: login(review.Reviewer), Team: team, URL: review.HTMLURL,
|
||||
Commit: review.CommitID, SubmittedAt: timestamp(review.Submitted), CommentsCount: review.CodeCommentsCount, Dismissed: review.Dismissed,
|
||||
}
|
||||
}
|
||||
@@ -48,6 +61,7 @@ type ReviewComment struct {
|
||||
URL string `json:"url"`
|
||||
Path string `json:"path"`
|
||||
Line int64 `json:"line"`
|
||||
OldLine int64 `json:"old_line"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
@@ -55,10 +69,22 @@ type ReviewComment struct {
|
||||
func reviewCommentFrom(comment *gitea.PullReviewComment) ReviewComment {
|
||||
return ReviewComment{
|
||||
ID: comment.ID, ReviewID: comment.ReviewID, Body: comment.Body, Author: login(comment.Reviewer), Resolver: login(comment.Resolver),
|
||||
URL: comment.HTMLURL, Path: comment.Path, Line: int64(comment.LineNum), CreatedAt: timestamp(comment.Created), UpdatedAt: timestamp(comment.Updated),
|
||||
URL: comment.HTMLURL, Path: comment.Path, Line: int64(comment.LineNum), OldLine: int64(comment.OldLineNum), CreatedAt: timestamp(comment.Created), UpdatedAt: timestamp(comment.Updated),
|
||||
}
|
||||
}
|
||||
|
||||
// Location names the file and line a comment is on: "app.go:8", or "app.go:4 (old)" for a
|
||||
// removed line, which has only an old position.
|
||||
func (c ReviewComment) Location() string {
|
||||
switch {
|
||||
case c.Line > 0:
|
||||
return fmt.Sprintf("%s:%d", c.Path, c.Line)
|
||||
case c.OldLine > 0:
|
||||
return fmt.Sprintf("%s:%d (old)", c.Path, c.OldLine)
|
||||
}
|
||||
return c.Path
|
||||
}
|
||||
|
||||
// InlineComment supplies an explicit file position for review creation.
|
||||
type InlineComment struct {
|
||||
Path string `json:"path"`
|
||||
@@ -106,6 +132,24 @@ func (s Reviews) List(ctx context.Context, n int64, limit, page int) ([]Review,
|
||||
return convertAll(reviews, reviewFrom), nil
|
||||
}
|
||||
|
||||
// ListPage lists a window of reviews of pull request n. It reaches past the server's smaller
|
||||
// page size, which List would silently take as the whole window.
|
||||
func (s Reviews) ListPage(ctx context.Context, n int64, limit, page int) (Page[Review], error) {
|
||||
window, err := listPage(limit, page, func(limit, page int) ([]*gitea.PullReview, http.Header, error) {
|
||||
var headers http.Header
|
||||
reviews, err := repoCall(ctx, s.Client, s.Repository, func(ctx context.Context, c *gitea.Client, owner, name string) ([]*gitea.PullReview, *gitea.Response, error) {
|
||||
reviews, resp, err := c.PullRequests.ListPullReviews(ctx, owner, name, n, gitea.ListPullReviewsOptions{ListOptions: listOptions(limit, page)})
|
||||
headers = headerOf(resp)
|
||||
return reviews, resp, err
|
||||
})
|
||||
return reviews, headers, err
|
||||
})
|
||||
if err != nil {
|
||||
return Page[Review]{}, err
|
||||
}
|
||||
return convertPage(window, reviewFrom), nil
|
||||
}
|
||||
|
||||
// Pending returns the reviews that login started on pull request n and has not submitted yet.
|
||||
func (s Reviews) Pending(ctx context.Context, n int64, login string) ([]Review, error) {
|
||||
reviews, err := s.All(ctx, n)
|
||||
@@ -243,12 +287,19 @@ func LatestReviews(reviews []Review) []Review {
|
||||
return latest
|
||||
}
|
||||
|
||||
// ReviewDecision summarizes the latest reviews like gh: changes_requested when a reviewer's latest
|
||||
// ReviewDecision summarizes reviews like gh: changes_requested when a reviewer's latest decisive
|
||||
// review requests changes, else approved when one approves, else review_required while reviews
|
||||
// are requested, else "". Dismissed reviews do not count.
|
||||
func ReviewDecision(latest []Review, requested bool) string {
|
||||
// are requested, else "". Comment reviews are not decisive (as in gh and Gitea) and dismissed
|
||||
// reviews do not count.
|
||||
func ReviewDecision(reviews []Review, requested bool) string {
|
||||
decisive := make([]Review, 0, len(reviews))
|
||||
for _, review := range reviews {
|
||||
if review.State != string(gitea.ReviewStateComment) {
|
||||
decisive = append(decisive, review)
|
||||
}
|
||||
}
|
||||
decision := ""
|
||||
for _, review := range latest {
|
||||
for _, review := range LatestReviews(decisive) {
|
||||
switch {
|
||||
case review.Dismissed:
|
||||
case review.State == string(gitea.ReviewStateRequestChanges):
|
||||
@@ -268,7 +319,8 @@ func ReviewDecision(latest []Review, requested bool) string {
|
||||
func (s Reviews) reviewComments(ctx context.Context, n int64, reviews []Review, skipEmpty bool) ([]ReviewComment, error) {
|
||||
results := []ReviewComment{}
|
||||
for _, review := range reviews {
|
||||
if skipEmpty && review.CommentsCount == 0 {
|
||||
// Pending reviews are drafts that only their author and admins see; an explicit review ID still lists them.
|
||||
if skipEmpty && (review.CommentsCount == 0 || review.State == string(gitea.ReviewStatePending)) {
|
||||
continue
|
||||
}
|
||||
comments, err := repoCall(ctx, s.Client, s.Repository, func(ctx context.Context, c *gitea.Client, owner, name string) ([]*gitea.PullReviewComment, *gitea.Response, error) {
|
||||
|
||||
@@ -8,6 +8,8 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
gitea "gitea.dev/sdk"
|
||||
@@ -53,6 +55,43 @@ func TestReviewCommentsContinueWhenServerCapsPageSize(t *testing.T) {
|
||||
require.Equal(t, 2, collections)
|
||||
}
|
||||
|
||||
func TestInlineCommentsSkipPendingReviews(t *testing.T) {
|
||||
var fetched []string
|
||||
client := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
fetched = append(fetched, r.URL.Path)
|
||||
_, _ = w.Write([]byte(`[{"id":5,"pull_request_review_id":1}]`))
|
||||
}))
|
||||
reviews := []Review{{ID: 1, State: "COMMENT", CommentsCount: 1}, {ID: 2, State: "PENDING", CommentsCount: 1}}
|
||||
items, err := (Reviews{Client: client, Repository: "owner/repo"}).Inline(context.Background(), 3, reviews)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, items, 1)
|
||||
require.Equal(t, []string{"/api/v1/repos/owner/repo/pulls/3/reviews/1/comments"}, fetched)
|
||||
}
|
||||
|
||||
func TestReviewListPageReachesPastServerPageCap(t *testing.T) {
|
||||
client := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
size, _ := strconv.Atoi(r.URL.Query().Get("limit"))
|
||||
page, _ := strconv.Atoi(r.URL.Query().Get("page"))
|
||||
size = min(size, 2) // the server caps its pages at two items
|
||||
var reviews []string
|
||||
for id := (page-1)*size + 1; id <= min(page*size, 5); id++ {
|
||||
reviews = append(reviews, fmt.Sprintf(`{"id":%d}`, id))
|
||||
}
|
||||
w.Header().Set("X-Total-Count", "5")
|
||||
_, _ = w.Write([]byte("[" + strings.Join(reviews, ",") + "]"))
|
||||
}))
|
||||
window, err := (Reviews{Client: client, Repository: "owner/repo"}).ListPage(context.Background(), 3, 4, 1)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, window.Items, 4)
|
||||
require.EqualValues(t, 4, window.Items[3].ID)
|
||||
require.True(t, window.More)
|
||||
window, err = (Reviews{Client: client, Repository: "owner/repo"}).ListPage(context.Background(), 3, 4, 2)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, window.Items, 1)
|
||||
require.EqualValues(t, 5, window.Items[0].ID)
|
||||
require.False(t, window.More)
|
||||
}
|
||||
|
||||
func TestReviewDismissalReturnsTheUpdatedReview(t *testing.T) {
|
||||
for _, dismiss := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("dismiss=%t", dismiss), func(t *testing.T) {
|
||||
@@ -185,6 +224,17 @@ func TestReviewResolveAndReplyUseCommentEndpoints(t *testing.T) {
|
||||
}, paths)
|
||||
}
|
||||
|
||||
func TestReviewDecisionIgnoresCommentReviews(t *testing.T) {
|
||||
reviews := []Review{
|
||||
{ID: 1, Author: "bob", State: "REQUEST_CHANGES"},
|
||||
{ID: 2, Author: "bob", State: "COMMENT"},
|
||||
{ID: 3, Author: "carol", State: "APPROVED"},
|
||||
}
|
||||
assert.Equal(t, "changes_requested", ReviewDecision(reviews, false))
|
||||
assert.Equal(t, "approved", ReviewDecision([]Review{{ID: 1, Author: "carol", State: "APPROVED"}, {ID: 2, Author: "carol", State: "COMMENT"}}, false))
|
||||
assert.Equal(t, "", ReviewDecision([]Review{{ID: 1, Author: "carol", State: "COMMENT"}}, false))
|
||||
}
|
||||
|
||||
func TestReviewFromMapsServerFields(t *testing.T) {
|
||||
review := decode[gitea.PullReview](t, `{"id":2,"body":"LGTM","state":"APPROVED","user":{"login":"alice"},"html_url":"https://gitea.test/r/2",
|
||||
"commit_id":"abc","submitted_at":"2026-10-01T12:00:00Z","comments_count":3,"dismissed":true}`)
|
||||
@@ -194,6 +244,13 @@ func TestReviewFromMapsServerFields(t *testing.T) {
|
||||
}, reviewFrom(review))
|
||||
}
|
||||
|
||||
func TestReviewFromNamesRequestedTeam(t *testing.T) {
|
||||
review := reviewFrom(decode[gitea.PullReview](t, `{"id":251,"state":"REQUEST_REVIEW","user":null,"team":{"name":"devs"}}`))
|
||||
require.Equal(t, "devs", review.Team)
|
||||
require.Equal(t, "team devs", review.Reviewer())
|
||||
require.Equal(t, "alice", Review{Author: "alice", Team: "devs"}.Reviewer())
|
||||
}
|
||||
|
||||
func TestReviewCommentFromMapsServerFields(t *testing.T) {
|
||||
comment := decode[gitea.PullReviewComment](t, `{"id":5,"pull_request_review_id":1,"body":"Nit","user":{"login":"alice"},
|
||||
"resolver":{"login":"bob"},"html_url":"https://gitea.test/c/5","path":"main.go","position":12,
|
||||
@@ -203,3 +260,11 @@ func TestReviewCommentFromMapsServerFields(t *testing.T) {
|
||||
CreatedAt: "2026-10-01T12:00:00Z", UpdatedAt: "2026-10-02T12:00:00Z",
|
||||
}, reviewCommentFrom(comment))
|
||||
}
|
||||
|
||||
func TestReviewCommentLocationNamesRemovedLines(t *testing.T) {
|
||||
removed := reviewCommentFrom(decode[gitea.PullReviewComment](t, `{"id":6,"path":"main.go","position":0,"original_position":4}`))
|
||||
require.EqualValues(t, 4, removed.OldLine)
|
||||
require.Equal(t, "main.go:4 (old)", removed.Location())
|
||||
require.Equal(t, "main.go:12", ReviewComment{Path: "main.go", Line: 12}.Location())
|
||||
require.Equal(t, "main.go", ReviewComment{Path: "main.go"}.Location())
|
||||
}
|
||||
|
||||
@@ -67,8 +67,8 @@ func (t Team) Access() string {
|
||||
var level string
|
||||
var granted []string
|
||||
for _, unit := range TeamUnits {
|
||||
access := t.Units[unit]
|
||||
if access == "" || access == "none" {
|
||||
access := t.UnitLevel(unit)
|
||||
if access == "none" {
|
||||
continue
|
||||
}
|
||||
if level != "" && access != level {
|
||||
@@ -86,6 +86,22 @@ func (t Team) Access() string {
|
||||
return level + " (" + strings.Join(granted, ", ") + ")"
|
||||
}
|
||||
|
||||
// UnitLevel is the access the team has to unit: the higher of the unit's own level and the team
|
||||
// permission, which Gitea grants on every unit, capped at the levels the unit allows.
|
||||
func (t Team) UnitLevel(unit string) string {
|
||||
levels := UnitAccess(unit)
|
||||
level := "none"
|
||||
for _, candidate := range []string{t.Units[unit], t.Permission} {
|
||||
if candidate == "write" && !slices.Contains(levels, "write") {
|
||||
candidate = "read"
|
||||
}
|
||||
if slices.Index(levels, candidate) > slices.Index(levels, level) {
|
||||
level = candidate
|
||||
}
|
||||
}
|
||||
return level
|
||||
}
|
||||
|
||||
// Slug names the team as ORG/TEAM, or by name alone when its organization is unknown.
|
||||
func (t Team) Slug() string {
|
||||
if t.Organization == "" {
|
||||
@@ -234,6 +250,7 @@ func (s Teams) Create(ctx context.Context, org string, opts TeamOptions) (Team,
|
||||
// permissions when changing access to all repositories. Gitea replaces the whole policy on edit.
|
||||
func (s Teams) Edit(ctx context.Context, id int64, opts TeamOptions) (Team, error) {
|
||||
repositoryPolicy := opts.AllRepositories != nil && opts.Permission == nil
|
||||
changesPermission := opts.Permission != nil
|
||||
if repositoryPolicy || (opts.Units != nil && !opts.ReplaceUnits) {
|
||||
current, err := s.View(ctx, id)
|
||||
if err != nil {
|
||||
@@ -258,6 +275,22 @@ func (s Teams) Edit(ctx context.Context, id int64, opts TeamOptions) (Team, erro
|
||||
opts.Units = units
|
||||
}
|
||||
}
|
||||
// Gitea 28 keeps an admin team admin when one request changes its permission and sets units_map,
|
||||
// so change the permission alone first and then apply the units.
|
||||
if changesPermission && opts.Units != nil {
|
||||
first := TeamOptions{Name: opts.Name, Permission: opts.Permission}
|
||||
if first.Name == nil {
|
||||
current, err := s.View(ctx, id)
|
||||
if err != nil {
|
||||
return Team{}, err
|
||||
}
|
||||
first.Name = ¤t.Name
|
||||
}
|
||||
// TODO(sdk): EditTeamOption requires a name of at most 30 characters and a permission, and EditTeam should return the team.
|
||||
if err := sendJSON(ctx, s.Client, http.MethodPatch, fmt.Sprintf("teams/%d", id), first, nil); err != nil {
|
||||
return Team{}, err
|
||||
}
|
||||
}
|
||||
var team gitea.Team
|
||||
// TODO(sdk): EditTeamOption requires a name of at most 30 characters and a permission, and EditTeam should return the team.
|
||||
if err := sendJSON(ctx, s.Client, http.MethodPatch, fmt.Sprintf("teams/%d", id), opts, &team); err != nil {
|
||||
@@ -273,12 +306,23 @@ func (s Teams) Delete(ctx context.Context, id int64) error {
|
||||
})
|
||||
}
|
||||
|
||||
// TeamMember identifies a team member without exposing private profile fields.
|
||||
type TeamMember struct {
|
||||
ID int64 `json:"id"`
|
||||
Username string `json:"username"`
|
||||
FullName string `json:"full_name"`
|
||||
}
|
||||
|
||||
func teamMemberFrom(user *gitea.User) TeamMember {
|
||||
return TeamMember{ID: user.ID, Username: user.UserName, FullName: user.FullName}
|
||||
}
|
||||
|
||||
// Members lists members of a team.
|
||||
func (s Teams) Members(ctx context.Context, id int64, limit, page int) (Page[OrganizationMember], error) {
|
||||
func (s Teams) Members(ctx context.Context, id int64, limit, page int) (Page[TeamMember], error) {
|
||||
users, err := callPage(ctx, s.Client, limit, page, func(ctx context.Context, c *gitea.Client, list gitea.ListOptions) ([]*gitea.User, *gitea.Response, error) {
|
||||
return c.Organizations.ListTeamMembers(ctx, id, gitea.ListTeamMembersOptions{ListOptions: list})
|
||||
})
|
||||
return convertPage(users, memberFrom), err
|
||||
return convertPage(users, teamMemberFrom), err
|
||||
}
|
||||
|
||||
// SetMember adds or removes one team membership.
|
||||
|
||||
@@ -102,7 +102,7 @@ func TestTeamAccessRequests(t *testing.T) {
|
||||
service := Teams{Client: client}
|
||||
members, err := service.Members(context.Background(), 3, 5, 2)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []OrganizationMember{{ID: 2, Username: "bob"}}, members.Items)
|
||||
require.Equal(t, []TeamMember{{ID: 2, Username: "bob"}}, members.Items)
|
||||
repos, err := service.Repositories(context.Background(), 3, 5, 1)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "https://gitea.test/acme/project", repos.Items[0].URL)
|
||||
@@ -119,6 +119,15 @@ func TestTeamFromKeepsAbsentValuesEmpty(t *testing.T) {
|
||||
require.Equal(t, Team{ID: 1, Name: "Owners", Permission: "owner", Units: map[string]string{}}, item)
|
||||
}
|
||||
|
||||
func TestTeamUnitLevelAppliesThePermissionToEveryUnit(t *testing.T) {
|
||||
team := Team{Permission: "write", Units: map[string]string{"repo.wiki": "none"}}
|
||||
require.Equal(t, "write", team.UnitLevel("repo.code"))
|
||||
require.Equal(t, "write", team.UnitLevel("repo.wiki"))
|
||||
require.Equal(t, "read", team.UnitLevel("repo.ext_wiki"))
|
||||
require.Equal(t, "write", Team{Permission: "none", Units: map[string]string{"repo.code": "write"}}.UnitLevel("repo.code"))
|
||||
require.Equal(t, "none", Team{Permission: "none"}.UnitLevel("repo.code"))
|
||||
}
|
||||
|
||||
func TestTeamAccessSummarizesUnits(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
permission string
|
||||
@@ -132,6 +141,11 @@ func TestTeamAccessSummarizesUnits(t *testing.T) {
|
||||
{"none", map[string]string{"repo.code": "write", "repo.issues": "write", "repo.pulls": "write", "repo.wiki": "none", "repo.ext_wiki": "read"}, "write (code, issues, pulls)"},
|
||||
{"none", map[string]string{"repo.code": "write", "repo.wiki": "read"}, "custom"},
|
||||
{"none", map[string]string{"repo.ext_issues": "read"}, "none"},
|
||||
// Gitea grants the team permission on every unit when the team has no unit rows.
|
||||
{"write", nil, "write"},
|
||||
{"read", map[string]string{}, "read"},
|
||||
{"write", map[string]string{"repo.wiki": "read"}, "write"},
|
||||
{"read", map[string]string{"repo.code": "write"}, "custom"},
|
||||
} {
|
||||
require.Equal(t, tc.want, Team{Permission: tc.permission, Units: tc.units}.Access(), "%v", tc.units)
|
||||
}
|
||||
@@ -165,3 +179,22 @@ func TestTeamFindSearchesTheOrganization(t *testing.T) {
|
||||
require.EqualError(t, err, `organization "nope" not found`)
|
||||
require.Equal(t, []string{"devops", "devops", "", "", "DEV", "DEV"}, queries)
|
||||
}
|
||||
|
||||
func TestTeamEditSendsThePermissionBeforeTheUnits(t *testing.T) {
|
||||
var bodies []map[string]any
|
||||
client := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
require.Equal(t, "/api/v1/teams/5", r.URL.Path)
|
||||
if r.Method == http.MethodGet {
|
||||
_, _ = w.Write([]byte(`{"id":5,"name":"devs","permission":"admin"}`))
|
||||
return
|
||||
}
|
||||
bodies = append(bodies, requestJSON(t, r))
|
||||
_, _ = w.Write([]byte(`{"id":5,"name":"devs","permission":"write"}`))
|
||||
}))
|
||||
permission := "write"
|
||||
_, err := (Teams{Client: client}).Edit(context.Background(), 5, TeamOptions{Permission: &permission, Units: map[string]string{"repo.wiki": "read"}, ReplaceUnits: true})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, bodies, 2)
|
||||
require.Equal(t, map[string]any{"name": "devs", "permission": "write"}, bodies[0], "Gitea 28 keeps an admin team admin when one request sets both")
|
||||
require.Equal(t, map[string]any{"repo.wiki": "read"}, bodies[1]["units_map"])
|
||||
}
|
||||
|
||||
+60
-11
@@ -133,8 +133,34 @@ func (s Wiki) ListPage(ctx context.Context, limit, page int) (Page[WikiPage], er
|
||||
return Page[WikiPage]{Items: items, More: page*limit < len(all), Total: len(all), Counted: true}, err
|
||||
}
|
||||
|
||||
// disabled explains a 404 from the wiki API. Gitea answers a bare 404 when the wiki is disabled or
|
||||
// the repository is missing, which says nothing about the page itself. It returns nil for any other
|
||||
// error, and the repository lookup's error when the repository cannot be read.
|
||||
func (s Wiki) disabled(ctx context.Context, err error) error {
|
||||
if !IsNotFound(err) {
|
||||
return nil
|
||||
}
|
||||
repository, checkErr := (Repositories{Client: s.Client}).get(ctx, s.Repository)
|
||||
if checkErr != nil {
|
||||
return checkErr
|
||||
}
|
||||
if !repository.HasWiki {
|
||||
return fmt.Errorf("the wiki of %s is disabled; turn it on with: gt repo edit --enable-wiki -R %s", s.Repository, s.Repository)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// View retrieves and decodes a wiki page.
|
||||
func (s Wiki) View(ctx context.Context, name string) (WikiPage, error) {
|
||||
item, err := s.lookup(ctx, name)
|
||||
if err := s.disabled(ctx, err); err != nil {
|
||||
return WikiPage{}, err
|
||||
}
|
||||
return item, err
|
||||
}
|
||||
|
||||
// lookup is View without the check for a disabled wiki.
|
||||
func (s Wiki) lookup(ctx context.Context, name string) (WikiPage, error) {
|
||||
item, err := s.page(ctx, func(ctx context.Context, c *gitea.Client, owner, repo string) (*gitea.WikiPage, *gitea.Response, error) {
|
||||
return c.Wiki.GetPage(ctx, owner, repo, name)
|
||||
})
|
||||
@@ -150,22 +176,37 @@ func (s Wiki) Create(ctx context.Context, opts WikiOptions) (WikiPage, error) {
|
||||
item, err := s.page(ctx, func(ctx context.Context, c *gitea.Client, owner, repo string) (*gitea.WikiPage, *gitea.Response, error) {
|
||||
return c.Wiki.CreatePage(ctx, owner, repo, wikiOptions(opts))
|
||||
})
|
||||
if err := s.disabled(ctx, err); err != nil {
|
||||
return WikiPage{}, err
|
||||
}
|
||||
return item, Classify(err, "wiki page", strconv.Quote(opts.Title), s.Repository)
|
||||
}
|
||||
|
||||
// Edit replaces page content and optionally changes its title.
|
||||
func (s Wiki) Edit(ctx context.Context, name string, opts WikiOptions) (WikiPage, error) {
|
||||
// Edit replaces page content and optionally changes its title. It reports whether the title
|
||||
// changed. Gitea's edit creates a page that does not exist and overwrites one the new title
|
||||
// names, so both are checked first.
|
||||
func (s Wiki) Edit(ctx context.Context, name string, opts WikiOptions) (WikiPage, bool, error) {
|
||||
current, err := s.View(ctx, name)
|
||||
if err != nil {
|
||||
return WikiPage{}, false, err
|
||||
}
|
||||
renamed := opts.Title != "" && opts.Title != current.Title
|
||||
if opts.Title == "" {
|
||||
current, err := s.View(ctx, name)
|
||||
if err != nil {
|
||||
return WikiPage{}, err
|
||||
}
|
||||
opts.Title = current.Title
|
||||
}
|
||||
if renamed {
|
||||
existing, err := s.lookup(ctx, opts.Title)
|
||||
if err == nil && existing.Title != current.Title {
|
||||
return WikiPage{}, false, &ConflictError{Reason: ReasonExists, Kind: "wiki page", Key: strconv.Quote(opts.Title), Scope: s.Repository}
|
||||
}
|
||||
if err != nil && !IsNotFound(err) {
|
||||
return WikiPage{}, false, err
|
||||
}
|
||||
}
|
||||
item, err := s.page(ctx, func(ctx context.Context, c *gitea.Client, owner, repo string) (*gitea.WikiPage, *gitea.Response, error) {
|
||||
return c.Wiki.EditPage(ctx, owner, repo, name, wikiOptions(opts))
|
||||
})
|
||||
return item, Classify(err, "wiki page", strconv.Quote(name), s.Repository)
|
||||
return item, renamed, Classify(err, "wiki page", strconv.Quote(name), s.Repository)
|
||||
}
|
||||
|
||||
// Delete removes a named wiki page.
|
||||
@@ -173,16 +214,24 @@ func (s Wiki) Delete(ctx context.Context, name string) error {
|
||||
err := repoDo(ctx, s.Client, s.Repository, func(ctx context.Context, c *gitea.Client, owner, repo string) (*gitea.Response, error) {
|
||||
return c.Wiki.DeletePage(ctx, owner, repo, name)
|
||||
})
|
||||
if err := s.disabled(ctx, err); err != nil {
|
||||
return err
|
||||
}
|
||||
return Classify(err, "wiki page", strconv.Quote(name), s.Repository)
|
||||
}
|
||||
|
||||
// Revisions returns one server-paginated page of wiki commits.
|
||||
func (s Wiki) Revisions(ctx context.Context, name string, page int) ([]WikiRevision, error) {
|
||||
// wikiRevisionPageSize is Gitea's default number of wiki commits per page ([git] COMMITS_RANGE_SIZE).
|
||||
const wikiRevisionPageSize = 50
|
||||
|
||||
// Revisions returns one server-paginated page of wiki commits and the total the server counted.
|
||||
func (s Wiki) Revisions(ctx context.Context, name string, page int) (Page[WikiRevision], error) {
|
||||
revisions, err := repoCall(ctx, s.Client, s.Repository, func(ctx context.Context, c *gitea.Client, owner, repo string) (*gitea.WikiCommitList, *gitea.Response, error) {
|
||||
return c.Wiki.GetPageRevisions(ctx, owner, repo, name, gitea.ListWikiPageRevisionsOptions{Page: page})
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return Page[WikiRevision]{}, err
|
||||
}
|
||||
return convertAll(revisions.WikiCommits, wikiRevisionFrom), nil
|
||||
items := convertAll(revisions.WikiCommits, wikiRevisionFrom)
|
||||
total := int(revisions.Count)
|
||||
return Page[WikiRevision]{Items: items, Total: total, Counted: true, More: (page-1)*wikiRevisionPageSize+len(items) < total}, nil
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user