mirror of
https://github.com/go-gitea/gitea.git
synced 2025-07-14 00:01:44 -04:00
Compare commits
8 Commits
82728a7cec
...
c2774d9e80
Author | SHA1 | Date | |
---|---|---|---|
|
c2774d9e80 | ||
|
6bc3079c00 | ||
|
3c5655ce18 | ||
|
01f082287d | ||
|
ce4fd95233 | ||
|
cfb1cb1168 | ||
|
1410e13dc5 | ||
|
891391689a |
32
.drone.yml
32
.drone.yml
@ -25,7 +25,7 @@ steps:
|
|||||||
- make deps-frontend
|
- make deps-frontend
|
||||||
|
|
||||||
- name: deps-backend
|
- name: deps-backend
|
||||||
image: golang:1.19
|
image: golang:1.20
|
||||||
pull: always
|
pull: always
|
||||||
commands:
|
commands:
|
||||||
- make deps-backend
|
- make deps-backend
|
||||||
@ -88,7 +88,7 @@ steps:
|
|||||||
depends_on: [deps-frontend]
|
depends_on: [deps-frontend]
|
||||||
|
|
||||||
- name: checks-backend
|
- name: checks-backend
|
||||||
image: golang:1.19
|
image: golang:1.20
|
||||||
commands:
|
commands:
|
||||||
- make --always-make checks-backend # ensure the 'go-licenses' make target runs
|
- make --always-make checks-backend # ensure the 'go-licenses' make target runs
|
||||||
depends_on: [deps-backend]
|
depends_on: [deps-backend]
|
||||||
@ -109,7 +109,7 @@ steps:
|
|||||||
depends_on: [deps-frontend]
|
depends_on: [deps-frontend]
|
||||||
|
|
||||||
- name: build-backend-no-gcc
|
- name: build-backend-no-gcc
|
||||||
image: golang:1.18 # this step is kept as the lowest version of golang that we support
|
image: golang:1.19 # this step is kept as the lowest version of golang that we support
|
||||||
pull: always
|
pull: always
|
||||||
environment:
|
environment:
|
||||||
GO111MODULE: on
|
GO111MODULE: on
|
||||||
@ -122,7 +122,7 @@ steps:
|
|||||||
path: /go
|
path: /go
|
||||||
|
|
||||||
- name: build-backend-arm64
|
- name: build-backend-arm64
|
||||||
image: golang:1.19
|
image: golang:1.20
|
||||||
environment:
|
environment:
|
||||||
GO111MODULE: on
|
GO111MODULE: on
|
||||||
GOPROXY: https://goproxy.io
|
GOPROXY: https://goproxy.io
|
||||||
@ -138,7 +138,7 @@ steps:
|
|||||||
path: /go
|
path: /go
|
||||||
|
|
||||||
- name: build-backend-windows
|
- name: build-backend-windows
|
||||||
image: golang:1.19
|
image: golang:1.20
|
||||||
environment:
|
environment:
|
||||||
GO111MODULE: on
|
GO111MODULE: on
|
||||||
GOPROXY: https://goproxy.io
|
GOPROXY: https://goproxy.io
|
||||||
@ -153,7 +153,7 @@ steps:
|
|||||||
path: /go
|
path: /go
|
||||||
|
|
||||||
- name: build-backend-386
|
- name: build-backend-386
|
||||||
image: golang:1.19
|
image: golang:1.20
|
||||||
environment:
|
environment:
|
||||||
GO111MODULE: on
|
GO111MODULE: on
|
||||||
GOPROXY: https://goproxy.io
|
GOPROXY: https://goproxy.io
|
||||||
@ -247,7 +247,7 @@ steps:
|
|||||||
- pull_request
|
- pull_request
|
||||||
|
|
||||||
- name: deps-backend
|
- name: deps-backend
|
||||||
image: golang:1.19
|
image: golang:1.20
|
||||||
pull: always
|
pull: always
|
||||||
commands:
|
commands:
|
||||||
- make deps-backend
|
- make deps-backend
|
||||||
@ -364,7 +364,7 @@ steps:
|
|||||||
path: /go
|
path: /go
|
||||||
|
|
||||||
- name: generate-coverage
|
- name: generate-coverage
|
||||||
image: golang:1.19
|
image: golang:1.20
|
||||||
commands:
|
commands:
|
||||||
- make coverage
|
- make coverage
|
||||||
environment:
|
environment:
|
||||||
@ -440,7 +440,7 @@ steps:
|
|||||||
- pull_request
|
- pull_request
|
||||||
|
|
||||||
- name: deps-backend
|
- name: deps-backend
|
||||||
image: golang:1.19
|
image: golang:1.20
|
||||||
pull: always
|
pull: always
|
||||||
commands:
|
commands:
|
||||||
- make deps-backend
|
- make deps-backend
|
||||||
@ -557,7 +557,7 @@ steps:
|
|||||||
- name: test-e2e
|
- name: test-e2e
|
||||||
image: mcr.microsoft.com/playwright:v1.29.2-focal
|
image: mcr.microsoft.com/playwright:v1.29.2-focal
|
||||||
commands:
|
commands:
|
||||||
- curl -sLO https://go.dev/dl/go1.19.linux-amd64.tar.gz && tar -C /usr/local -xzf go1.19.linux-amd64.tar.gz
|
- curl -sLO https://go.dev/dl/go1.20.linux-amd64.tar.gz && tar -C /usr/local -xzf go1.20.linux-amd64.tar.gz
|
||||||
- groupadd --gid 1001 gitea && useradd -m --gid 1001 --uid 1001 gitea
|
- groupadd --gid 1001 gitea && useradd -m --gid 1001 --uid 1001 gitea
|
||||||
- apt-get -qq update && apt-get -qqy install build-essential
|
- apt-get -qq update && apt-get -qqy install build-essential
|
||||||
- export TEST_PGSQL_SCHEMA=''
|
- export TEST_PGSQL_SCHEMA=''
|
||||||
@ -656,7 +656,7 @@ trigger:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: download
|
- name: download
|
||||||
image: golang:1.19
|
image: golang:1.20
|
||||||
pull: always
|
pull: always
|
||||||
commands:
|
commands:
|
||||||
- timeout -s ABRT 40m make generate-license generate-gitignore
|
- timeout -s ABRT 40m make generate-license generate-gitignore
|
||||||
@ -720,7 +720,7 @@ steps:
|
|||||||
- make deps-frontend
|
- make deps-frontend
|
||||||
|
|
||||||
- name: deps-backend
|
- name: deps-backend
|
||||||
image: golang:1.19
|
image: golang:1.20
|
||||||
pull: always
|
pull: always
|
||||||
commands:
|
commands:
|
||||||
- make deps-backend
|
- make deps-backend
|
||||||
@ -729,7 +729,7 @@ steps:
|
|||||||
path: /go
|
path: /go
|
||||||
|
|
||||||
- name: static
|
- name: static
|
||||||
image: techknowlogick/xgo:go-1.19.x
|
image: techknowlogick/xgo:go-1.20.x
|
||||||
pull: always
|
pull: always
|
||||||
commands:
|
commands:
|
||||||
# Upgrade to node 18 once https://github.com/techknowlogick/xgo/issues/163 is resolved
|
# Upgrade to node 18 once https://github.com/techknowlogick/xgo/issues/163 is resolved
|
||||||
@ -841,7 +841,7 @@ steps:
|
|||||||
- make deps-frontend
|
- make deps-frontend
|
||||||
|
|
||||||
- name: deps-backend
|
- name: deps-backend
|
||||||
image: golang:1.19
|
image: golang:1.20
|
||||||
pull: always
|
pull: always
|
||||||
commands:
|
commands:
|
||||||
- make deps-backend
|
- make deps-backend
|
||||||
@ -850,7 +850,7 @@ steps:
|
|||||||
path: /go
|
path: /go
|
||||||
|
|
||||||
- name: static
|
- name: static
|
||||||
image: techknowlogick/xgo:go-1.19.x
|
image: techknowlogick/xgo:go-1.20.x
|
||||||
pull: always
|
pull: always
|
||||||
commands:
|
commands:
|
||||||
# Upgrade to node 18 once https://github.com/techknowlogick/xgo/issues/163 is resolved
|
# Upgrade to node 18 once https://github.com/techknowlogick/xgo/issues/163 is resolved
|
||||||
@ -932,7 +932,7 @@ trigger:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: build-docs
|
- name: build-docs
|
||||||
image: golang:1.19
|
image: golang:1.20
|
||||||
commands:
|
commands:
|
||||||
- cd docs
|
- cd docs
|
||||||
- make trans-copy clean build
|
- make trans-copy clean build
|
||||||
|
@ -28,7 +28,7 @@ linters:
|
|||||||
fast: false
|
fast: false
|
||||||
|
|
||||||
run:
|
run:
|
||||||
go: 1.19
|
go: 1.20
|
||||||
timeout: 10m
|
timeout: 10m
|
||||||
skip-dirs:
|
skip-dirs:
|
||||||
- node_modules
|
- node_modules
|
||||||
@ -74,7 +74,7 @@ linters-settings:
|
|||||||
- name: modifies-value-receiver
|
- name: modifies-value-receiver
|
||||||
gofumpt:
|
gofumpt:
|
||||||
extra-rules: true
|
extra-rules: true
|
||||||
lang-version: "1.19"
|
lang-version: "1.20"
|
||||||
depguard:
|
depguard:
|
||||||
list-type: denylist
|
list-type: denylist
|
||||||
# Check the list against standard lib.
|
# Check the list against standard lib.
|
||||||
@ -84,6 +84,7 @@ linters-settings:
|
|||||||
- github.com/unknwon/com: "use gitea's util and replacements"
|
- github.com/unknwon/com: "use gitea's util and replacements"
|
||||||
- io/ioutil: "use os or io instead"
|
- io/ioutil: "use os or io instead"
|
||||||
- golang.org/x/exp: "it's experimental and unreliable."
|
- golang.org/x/exp: "it's experimental and unreliable."
|
||||||
|
- code.gitea.io/gitea/modules/git/internal: "do not use the internal package, use AddXxx function instead"
|
||||||
|
|
||||||
issues:
|
issues:
|
||||||
max-issues-per-linter: 0
|
max-issues-per-linter: 0
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
#Build stage
|
#Build stage
|
||||||
FROM golang:1.19-alpine3.17 AS build-env
|
FROM golang:1.20-alpine3.17 AS build-env
|
||||||
|
|
||||||
ARG GOPROXY
|
ARG GOPROXY
|
||||||
ENV GOPROXY ${GOPROXY:-direct}
|
ENV GOPROXY ${GOPROXY:-direct}
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
#Build stage
|
#Build stage
|
||||||
FROM golang:1.19-alpine3.17 AS build-env
|
FROM golang:1.20-alpine3.17 AS build-env
|
||||||
|
|
||||||
ARG GOPROXY
|
ARG GOPROXY
|
||||||
ENV GOPROXY ${GOPROXY:-direct}
|
ENV GOPROXY ${GOPROXY:-direct}
|
||||||
|
4
Makefile
4
Makefile
@ -23,13 +23,13 @@ SHASUM ?= shasum -a 256
|
|||||||
HAS_GO = $(shell hash $(GO) > /dev/null 2>&1 && echo "GO" || echo "NOGO" )
|
HAS_GO = $(shell hash $(GO) > /dev/null 2>&1 && echo "GO" || echo "NOGO" )
|
||||||
COMMA := ,
|
COMMA := ,
|
||||||
|
|
||||||
XGO_VERSION := go-1.19.x
|
XGO_VERSION := go-1.20.x
|
||||||
|
|
||||||
AIR_PACKAGE ?= github.com/cosmtrek/air@v1.40.4
|
AIR_PACKAGE ?= github.com/cosmtrek/air@v1.40.4
|
||||||
EDITORCONFIG_CHECKER_PACKAGE ?= github.com/editorconfig-checker/editorconfig-checker/cmd/editorconfig-checker@2.6.0
|
EDITORCONFIG_CHECKER_PACKAGE ?= github.com/editorconfig-checker/editorconfig-checker/cmd/editorconfig-checker@2.6.0
|
||||||
ERRCHECK_PACKAGE ?= github.com/kisielk/errcheck@v1.6.2
|
ERRCHECK_PACKAGE ?= github.com/kisielk/errcheck@v1.6.2
|
||||||
GOFUMPT_PACKAGE ?= mvdan.cc/gofumpt@v0.4.0
|
GOFUMPT_PACKAGE ?= mvdan.cc/gofumpt@v0.4.0
|
||||||
GOLANGCI_LINT_PACKAGE ?= github.com/golangci/golangci-lint/cmd/golangci-lint@v1.50.1
|
GOLANGCI_LINT_PACKAGE ?= github.com/golangci/golangci-lint/cmd/golangci-lint@v1.51.0
|
||||||
GXZ_PAGAGE ?= github.com/ulikunitz/xz/cmd/gxz@v0.5.10
|
GXZ_PAGAGE ?= github.com/ulikunitz/xz/cmd/gxz@v0.5.10
|
||||||
MISSPELL_PACKAGE ?= github.com/client9/misspell/cmd/misspell@v0.3.4
|
MISSPELL_PACKAGE ?= github.com/client9/misspell/cmd/misspell@v0.3.4
|
||||||
SWAGGER_PACKAGE ?= github.com/go-swagger/go-swagger/cmd/swagger@v0.30.3
|
SWAGGER_PACKAGE ?= github.com/go-swagger/go-swagger/cmd/swagger@v0.30.3
|
||||||
|
@ -19,8 +19,8 @@ params:
|
|||||||
author: The Gitea Authors
|
author: The Gitea Authors
|
||||||
website: https://docs.gitea.io
|
website: https://docs.gitea.io
|
||||||
version: 1.18.1
|
version: 1.18.1
|
||||||
minGoVersion: 1.18
|
minGoVersion: 1.19
|
||||||
goVersion: 1.19
|
goVersion: 1.20
|
||||||
minNodeVersion: 16
|
minNodeVersion: 16
|
||||||
search: nav
|
search: nav
|
||||||
repo: "https://github.com/go-gitea/gitea"
|
repo: "https://github.com/go-gitea/gitea"
|
||||||
|
@ -329,3 +329,22 @@ Before activating SSPI single sign-on authentication (SSO) you have to prepare y
|
|||||||
- You have added the URL of the web app to the `Local intranet zone`
|
- You have added the URL of the web app to the `Local intranet zone`
|
||||||
- The clocks of the server and client should not differ with more than 5 minutes (depends on group policy)
|
- The clocks of the server and client should not differ with more than 5 minutes (depends on group policy)
|
||||||
- `Integrated Windows Authentication` should be enabled in Internet Explorer (under `Advanced settings`)
|
- `Integrated Windows Authentication` should be enabled in Internet Explorer (under `Advanced settings`)
|
||||||
|
|
||||||
|
## Reverse Proxy
|
||||||
|
|
||||||
|
Gitea supports Reverse Proxy Header authentication, it will read headers as a trusted login user name or user email address. This hasn't been enabled by default, you can enable it with
|
||||||
|
|
||||||
|
```ini
|
||||||
|
[service]
|
||||||
|
ENABLE_REVERSE_PROXY_AUTHENTICATION = true
|
||||||
|
```
|
||||||
|
|
||||||
|
The default login user name is in the `X-WEBAUTH-USER` header, you can change it via changing `REVERSE_PROXY_AUTHENTICATION_USER` in app.ini. If the user doesn't exist, you can enable automatic registration with `ENABLE_REVERSE_PROXY_AUTO_REGISTRATION=true`.
|
||||||
|
|
||||||
|
The default login user email is `X-WEBAUTH-EMAIL`, you can change it via changing `REVERSE_PROXY_AUTHENTICATION_EMAIL` in app.ini, this could also be disabled with `ENABLE_REVERSE_PROXY_EMAIL`
|
||||||
|
|
||||||
|
If set `ENABLE_REVERSE_PROXY_FULL_NAME=true`, a user full name expected in `X-WEBAUTH-FULLNAME` will be assigned to the user when auto creating the user. You can also change the header name with `REVERSE_PROXY_AUTHENTICATION_FULL_NAME`.
|
||||||
|
|
||||||
|
You can also limit the reverse proxy's IP address range with `REVERSE_PROXY_TRUSTED_PROXIES` which default value is `127.0.0.0/8,::1/128`. By `REVERSE_PROXY_LIMIT`, you can limit trusted proxies level.
|
||||||
|
|
||||||
|
Notice: Reverse Proxy Auth doesn't support the API. You still need an access token or basic auth to make API requests.
|
||||||
|
@ -15,4 +15,21 @@ menu:
|
|||||||
|
|
||||||
# 认证
|
# 认证
|
||||||
|
|
||||||
## TBD
|
## 反向代理认证
|
||||||
|
|
||||||
|
Gitea 支持通过读取反向代理传递的 HTTP 头中的登录名或者 email 地址来支持反向代理来认证。默认是不启用的,你可以用以下配置启用。
|
||||||
|
|
||||||
|
```ini
|
||||||
|
[service]
|
||||||
|
ENABLE_REVERSE_PROXY_AUTHENTICATION = true
|
||||||
|
```
|
||||||
|
|
||||||
|
默认的登录用户名的 HTTP 头是 `X-WEBAUTH-USER`,你可以通过修改 `REVERSE_PROXY_AUTHENTICATION_USER` 来变更它。如果用户不存在,可以自动创建用户,当然你需要修改 `ENABLE_REVERSE_PROXY_AUTO_REGISTRATION=true` 来启用它。
|
||||||
|
|
||||||
|
默认的登录用户 Email 的 HTTP 头是 `X-WEBAUTH-EMAIL`,你可以通过修改 `REVERSE_PROXY_AUTHENTICATION_EMAIL` 来变更它。如果用户不存在,可以自动创建用户,当然你需要修改 `ENABLE_REVERSE_PROXY_AUTO_REGISTRATION=true` 来启用它。你也可以通过修改 `ENABLE_REVERSE_PROXY_EMAIL` 来启用或停用这个 HTTP 头。
|
||||||
|
|
||||||
|
如果设置了 `ENABLE_REVERSE_PROXY_FULL_NAME=true`,则用户的全名会从 `X-WEBAUTH-FULLNAME` 读取,这样在自动创建用户时将使用这个字段作为用户全名,你也可以通过修改 `REVERSE_PROXY_AUTHENTICATION_FULL_NAME` 来变更 HTTP 头。
|
||||||
|
|
||||||
|
你也可以通过修改 `REVERSE_PROXY_TRUSTED_PROXIES` 来设置反向代理的IP地址范围,加强安全性,默认值是 `127.0.0.0/8,::1/128`。 通过 `REVERSE_PROXY_LIMIT`, 可以设置最多信任几级反向代理。
|
||||||
|
|
||||||
|
注意:反向代理认证不支持认证 API,API 仍旧需要用 access token 来进行认证。
|
||||||
|
2
go.mod
2
go.mod
@ -1,6 +1,6 @@
|
|||||||
module code.gitea.io/gitea
|
module code.gitea.io/gitea
|
||||||
|
|
||||||
go 1.18
|
go 1.19
|
||||||
|
|
||||||
require (
|
require (
|
||||||
code.gitea.io/actions-proto-go v0.2.0
|
code.gitea.io/actions-proto-go v0.2.0
|
||||||
|
@ -37,9 +37,7 @@ func (d *postgresSchemaDriver) Open(name string) (driver.Conn, error) {
|
|||||||
}
|
}
|
||||||
schemaValue, _ := driver.String.ConvertValue(setting.Database.Schema)
|
schemaValue, _ := driver.String.ConvertValue(setting.Database.Schema)
|
||||||
|
|
||||||
// golangci lint is incorrect here - there is no benefit to using driver.ExecerContext here
|
if execer, ok := conn.(driver.Execer); ok {
|
||||||
// and in any case pq does not implement it
|
|
||||||
if execer, ok := conn.(driver.Execer); ok { //nolint
|
|
||||||
_, err := execer.Exec(`SELECT set_config(
|
_, err := execer.Exec(`SELECT set_config(
|
||||||
'search_path',
|
'search_path',
|
||||||
$1 || ',' || current_setting('search_path'),
|
$1 || ',' || current_setting('search_path'),
|
||||||
@ -63,8 +61,7 @@ func (d *postgresSchemaDriver) Open(name string) (driver.Conn, error) {
|
|||||||
|
|
||||||
// driver.String.ConvertValue will never return err for string
|
// driver.String.ConvertValue will never return err for string
|
||||||
|
|
||||||
// golangci lint is incorrect here - there is no benefit to using stmt.ExecWithContext here
|
_, err = stmt.Exec([]driver.Value{schemaValue})
|
||||||
_, err = stmt.Exec([]driver.Value{schemaValue}) //nolint
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
_ = conn.Close()
|
_ = conn.Close()
|
||||||
return nil, err
|
return nil, err
|
||||||
|
@ -8,6 +8,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"code.gitea.io/gitea/models/db"
|
"code.gitea.io/gitea/models/db"
|
||||||
@ -132,6 +133,27 @@ const (
|
|||||||
PullRequestStatusAncestor
|
PullRequestStatusAncestor
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func (status PullRequestStatus) String() string {
|
||||||
|
switch status {
|
||||||
|
case PullRequestStatusConflict:
|
||||||
|
return "CONFLICT"
|
||||||
|
case PullRequestStatusChecking:
|
||||||
|
return "CHECKING"
|
||||||
|
case PullRequestStatusMergeable:
|
||||||
|
return "MERGEABLE"
|
||||||
|
case PullRequestStatusManuallyMerged:
|
||||||
|
return "MANUALLY_MERGED"
|
||||||
|
case PullRequestStatusError:
|
||||||
|
return "ERROR"
|
||||||
|
case PullRequestStatusEmpty:
|
||||||
|
return "EMPTY"
|
||||||
|
case PullRequestStatusAncestor:
|
||||||
|
return "ANCESTOR"
|
||||||
|
default:
|
||||||
|
return strconv.Itoa(int(status))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// PullRequestFlow the flow of pull request
|
// PullRequestFlow the flow of pull request
|
||||||
type PullRequestFlow int
|
type PullRequestFlow int
|
||||||
|
|
||||||
@ -202,6 +224,42 @@ func DeletePullsByBaseRepoID(ctx context.Context, repoID int64) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ColorFormat writes a colored string to identify this struct
|
||||||
|
func (pr *PullRequest) ColorFormat(s fmt.State) {
|
||||||
|
if pr == nil {
|
||||||
|
log.ColorFprintf(s, "PR[%d]%s#%d[%s...%s:%s]",
|
||||||
|
log.NewColoredIDValue(0),
|
||||||
|
log.NewColoredValue("<nil>/<nil>"),
|
||||||
|
log.NewColoredIDValue(0),
|
||||||
|
log.NewColoredValue("<nil>"),
|
||||||
|
log.NewColoredValue("<nil>/<nil>"),
|
||||||
|
log.NewColoredValue("<nil>"),
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.ColorFprintf(s, "PR[%d]", log.NewColoredIDValue(pr.ID))
|
||||||
|
if pr.BaseRepo != nil {
|
||||||
|
log.ColorFprintf(s, "%s#%d[%s...", log.NewColoredValue(pr.BaseRepo.FullName()),
|
||||||
|
log.NewColoredIDValue(pr.Index), log.NewColoredValue(pr.BaseBranch))
|
||||||
|
} else {
|
||||||
|
log.ColorFprintf(s, "Repo[%d]#%d[%s...", log.NewColoredIDValue(pr.BaseRepoID),
|
||||||
|
log.NewColoredIDValue(pr.Index), log.NewColoredValue(pr.BaseBranch))
|
||||||
|
}
|
||||||
|
if pr.HeadRepoID == pr.BaseRepoID {
|
||||||
|
log.ColorFprintf(s, "%s]", log.NewColoredValue(pr.HeadBranch))
|
||||||
|
} else if pr.HeadRepo != nil {
|
||||||
|
log.ColorFprintf(s, "%s:%s]", log.NewColoredValue(pr.HeadRepo.FullName()), log.NewColoredValue(pr.HeadBranch))
|
||||||
|
} else {
|
||||||
|
log.ColorFprintf(s, "Repo[%d]:%s]", log.NewColoredIDValue(pr.HeadRepoID), log.NewColoredValue(pr.HeadBranch))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// String represents the pr as a simple string
|
||||||
|
func (pr *PullRequest) String() string {
|
||||||
|
return log.ColorFormatAsString(pr)
|
||||||
|
}
|
||||||
|
|
||||||
// MustHeadUserName returns the HeadRepo's username if failed return blank
|
// MustHeadUserName returns the HeadRepo's username if failed return blank
|
||||||
func (pr *PullRequest) MustHeadUserName(ctx context.Context) string {
|
func (pr *PullRequest) MustHeadUserName(ctx context.Context) string {
|
||||||
if err := pr.LoadHeadRepo(ctx); err != nil {
|
if err := pr.LoadHeadRepo(ctx); err != nil {
|
||||||
@ -234,7 +292,8 @@ func (pr *PullRequest) LoadAttributes(ctx context.Context) (err error) {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// LoadHeadRepo loads the head repository
|
// LoadHeadRepo loads the head repository, pr.HeadRepo will remain nil if it does not exist
|
||||||
|
// and thus ErrRepoNotExist will never be returned
|
||||||
func (pr *PullRequest) LoadHeadRepo(ctx context.Context) (err error) {
|
func (pr *PullRequest) LoadHeadRepo(ctx context.Context) (err error) {
|
||||||
if !pr.isHeadRepoLoaded && pr.HeadRepo == nil && pr.HeadRepoID > 0 {
|
if !pr.isHeadRepoLoaded && pr.HeadRepo == nil && pr.HeadRepoID > 0 {
|
||||||
if pr.HeadRepoID == pr.BaseRepoID {
|
if pr.HeadRepoID == pr.BaseRepoID {
|
||||||
@ -249,14 +308,14 @@ func (pr *PullRequest) LoadHeadRepo(ctx context.Context) (err error) {
|
|||||||
|
|
||||||
pr.HeadRepo, err = repo_model.GetRepositoryByID(ctx, pr.HeadRepoID)
|
pr.HeadRepo, err = repo_model.GetRepositoryByID(ctx, pr.HeadRepoID)
|
||||||
if err != nil && !repo_model.IsErrRepoNotExist(err) { // Head repo maybe deleted, but it should still work
|
if err != nil && !repo_model.IsErrRepoNotExist(err) { // Head repo maybe deleted, but it should still work
|
||||||
return fmt.Errorf("GetRepositoryByID(head): %w", err)
|
return fmt.Errorf("pr[%d].LoadHeadRepo[%d]: %w", pr.ID, pr.HeadRepoID, err)
|
||||||
}
|
}
|
||||||
pr.isHeadRepoLoaded = true
|
pr.isHeadRepoLoaded = true
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// LoadBaseRepo loads the target repository
|
// LoadBaseRepo loads the target repository. ErrRepoNotExist may be returned.
|
||||||
func (pr *PullRequest) LoadBaseRepo(ctx context.Context) (err error) {
|
func (pr *PullRequest) LoadBaseRepo(ctx context.Context) (err error) {
|
||||||
if pr.BaseRepo != nil {
|
if pr.BaseRepo != nil {
|
||||||
return nil
|
return nil
|
||||||
@ -274,7 +333,7 @@ func (pr *PullRequest) LoadBaseRepo(ctx context.Context) (err error) {
|
|||||||
|
|
||||||
pr.BaseRepo, err = repo_model.GetRepositoryByID(ctx, pr.BaseRepoID)
|
pr.BaseRepo, err = repo_model.GetRepositoryByID(ctx, pr.BaseRepoID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("repo_model.GetRepositoryByID(base): %w", err)
|
return fmt.Errorf("pr[%d].LoadBaseRepo[%d]: %w", pr.ID, pr.BaseRepoID, err)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
@ -16,14 +16,20 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
"unsafe"
|
"unsafe"
|
||||||
|
|
||||||
|
"code.gitea.io/gitea/modules/git/internal" //nolint:depguard // only this file can use the internal type CmdArg, other files and packages should use AddXxx functions
|
||||||
"code.gitea.io/gitea/modules/log"
|
"code.gitea.io/gitea/modules/log"
|
||||||
"code.gitea.io/gitea/modules/process"
|
"code.gitea.io/gitea/modules/process"
|
||||||
"code.gitea.io/gitea/modules/util"
|
"code.gitea.io/gitea/modules/util"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// TrustedCmdArgs returns the trusted arguments for git command.
|
||||||
|
// It's mainly for passing user-provided and trusted arguments to git command
|
||||||
|
// In most cases, it shouldn't be used. Use AddXxx function instead
|
||||||
|
type TrustedCmdArgs []internal.CmdArg
|
||||||
|
|
||||||
var (
|
var (
|
||||||
// globalCommandArgs global command args for external package setting
|
// globalCommandArgs global command args for external package setting
|
||||||
globalCommandArgs []CmdArg
|
globalCommandArgs TrustedCmdArgs
|
||||||
|
|
||||||
// defaultCommandExecutionTimeout default command execution timeout duration
|
// defaultCommandExecutionTimeout default command execution timeout duration
|
||||||
defaultCommandExecutionTimeout = 360 * time.Second
|
defaultCommandExecutionTimeout = 360 * time.Second
|
||||||
@ -42,8 +48,6 @@ type Command struct {
|
|||||||
brokenArgs []string
|
brokenArgs []string
|
||||||
}
|
}
|
||||||
|
|
||||||
type CmdArg string
|
|
||||||
|
|
||||||
func (c *Command) String() string {
|
func (c *Command) String() string {
|
||||||
if len(c.args) == 0 {
|
if len(c.args) == 0 {
|
||||||
return c.name
|
return c.name
|
||||||
@ -53,7 +57,7 @@ func (c *Command) String() string {
|
|||||||
|
|
||||||
// NewCommand creates and returns a new Git Command based on given command and arguments.
|
// NewCommand creates and returns a new Git Command based on given command and arguments.
|
||||||
// Each argument should be safe to be trusted. User-provided arguments should be passed to AddDynamicArguments instead.
|
// Each argument should be safe to be trusted. User-provided arguments should be passed to AddDynamicArguments instead.
|
||||||
func NewCommand(ctx context.Context, args ...CmdArg) *Command {
|
func NewCommand(ctx context.Context, args ...internal.CmdArg) *Command {
|
||||||
// Make an explicit copy of globalCommandArgs, otherwise append might overwrite it
|
// Make an explicit copy of globalCommandArgs, otherwise append might overwrite it
|
||||||
cargs := make([]string, 0, len(globalCommandArgs)+len(args))
|
cargs := make([]string, 0, len(globalCommandArgs)+len(args))
|
||||||
for _, arg := range globalCommandArgs {
|
for _, arg := range globalCommandArgs {
|
||||||
@ -70,15 +74,9 @@ func NewCommand(ctx context.Context, args ...CmdArg) *Command {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewCommandNoGlobals creates and returns a new Git Command based on given command and arguments only with the specify args and don't care global command args
|
|
||||||
// Each argument should be safe to be trusted. User-provided arguments should be passed to AddDynamicArguments instead.
|
|
||||||
func NewCommandNoGlobals(args ...CmdArg) *Command {
|
|
||||||
return NewCommandContextNoGlobals(DefaultContext, args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewCommandContextNoGlobals creates and returns a new Git Command based on given command and arguments only with the specify args and don't care global command args
|
// NewCommandContextNoGlobals creates and returns a new Git Command based on given command and arguments only with the specify args and don't care global command args
|
||||||
// Each argument should be safe to be trusted. User-provided arguments should be passed to AddDynamicArguments instead.
|
// Each argument should be safe to be trusted. User-provided arguments should be passed to AddDynamicArguments instead.
|
||||||
func NewCommandContextNoGlobals(ctx context.Context, args ...CmdArg) *Command {
|
func NewCommandContextNoGlobals(ctx context.Context, args ...internal.CmdArg) *Command {
|
||||||
cargs := make([]string, 0, len(args))
|
cargs := make([]string, 0, len(args))
|
||||||
for _, arg := range args {
|
for _, arg := range args {
|
||||||
cargs = append(cargs, string(arg))
|
cargs = append(cargs, string(arg))
|
||||||
@ -96,27 +94,70 @@ func (c *Command) SetParentContext(ctx context.Context) *Command {
|
|||||||
return c
|
return c
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetDescription sets the description for this command which be returned on
|
// SetDescription sets the description for this command which be returned on c.String()
|
||||||
// c.String()
|
|
||||||
func (c *Command) SetDescription(desc string) *Command {
|
func (c *Command) SetDescription(desc string) *Command {
|
||||||
c.desc = desc
|
c.desc = desc
|
||||||
return c
|
return c
|
||||||
}
|
}
|
||||||
|
|
||||||
// AddArguments adds new git argument(s) to the command. Each argument must be safe to be trusted.
|
// isSafeArgumentValue checks if the argument is safe to be used as a value (not an option)
|
||||||
// User-provided arguments should be passed to AddDynamicArguments instead.
|
func isSafeArgumentValue(s string) bool {
|
||||||
func (c *Command) AddArguments(args ...CmdArg) *Command {
|
return s == "" || s[0] != '-'
|
||||||
|
}
|
||||||
|
|
||||||
|
// isValidArgumentOption checks if the argument is a valid option (starting with '-').
|
||||||
|
// It doesn't check whether the option is supported or not
|
||||||
|
func isValidArgumentOption(s string) bool {
|
||||||
|
return s != "" && s[0] == '-'
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddArguments adds new git arguments (option/value) to the command. It only accepts string literals, or trusted CmdArg.
|
||||||
|
// Type CmdArg is in the internal package, so it can not be used outside of this package directly,
|
||||||
|
// it makes sure that user-provided arguments won't cause RCE risks.
|
||||||
|
// User-provided arguments should be passed by other AddXxx functions
|
||||||
|
func (c *Command) AddArguments(args ...internal.CmdArg) *Command {
|
||||||
for _, arg := range args {
|
for _, arg := range args {
|
||||||
c.args = append(c.args, string(arg))
|
c.args = append(c.args, string(arg))
|
||||||
}
|
}
|
||||||
return c
|
return c
|
||||||
}
|
}
|
||||||
|
|
||||||
// AddDynamicArguments adds new dynamic argument(s) to the command.
|
// AddOptionValues adds a new option with a list of non-option values
|
||||||
// The arguments may come from user input and can not be trusted, so no leading '-' is allowed to avoid passing options
|
// For example: AddOptionValues("--opt", val) means 2 arguments: {"--opt", val}.
|
||||||
|
// The values are treated as dynamic argument values. It equals to: AddArguments("--opt") then AddDynamicArguments(val).
|
||||||
|
func (c *Command) AddOptionValues(opt internal.CmdArg, args ...string) *Command {
|
||||||
|
if !isValidArgumentOption(string(opt)) {
|
||||||
|
c.brokenArgs = append(c.brokenArgs, string(opt))
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
c.args = append(c.args, string(opt))
|
||||||
|
c.AddDynamicArguments(args...)
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddOptionFormat adds a new option with a format string and arguments
|
||||||
|
// For example: AddOptionFormat("--opt=%s %s", val1, val2) means 1 argument: {"--opt=val1 val2"}.
|
||||||
|
func (c *Command) AddOptionFormat(opt string, args ...any) *Command {
|
||||||
|
if !isValidArgumentOption(opt) {
|
||||||
|
c.brokenArgs = append(c.brokenArgs, opt)
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
// a quick check to make sure the format string matches the number of arguments, to find low-level mistakes ASAP
|
||||||
|
if strings.Count(strings.ReplaceAll(opt, "%%", ""), "%") != len(args) {
|
||||||
|
c.brokenArgs = append(c.brokenArgs, opt)
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
s := fmt.Sprintf(opt, args...)
|
||||||
|
c.args = append(c.args, s)
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddDynamicArguments adds new dynamic argument values to the command.
|
||||||
|
// The arguments may come from user input and can not be trusted, so no leading '-' is allowed to avoid passing options.
|
||||||
|
// TODO: in the future, this function can be renamed to AddArgumentValues
|
||||||
func (c *Command) AddDynamicArguments(args ...string) *Command {
|
func (c *Command) AddDynamicArguments(args ...string) *Command {
|
||||||
for _, arg := range args {
|
for _, arg := range args {
|
||||||
if arg != "" && arg[0] == '-' {
|
if !isSafeArgumentValue(arg) {
|
||||||
c.brokenArgs = append(c.brokenArgs, arg)
|
c.brokenArgs = append(c.brokenArgs, arg)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -137,14 +178,14 @@ func (c *Command) AddDashesAndList(list ...string) *Command {
|
|||||||
return c
|
return c
|
||||||
}
|
}
|
||||||
|
|
||||||
// CmdArgCheck checks whether the string is safe to be used as a dynamic argument.
|
// ToTrustedCmdArgs converts a list of strings (trusted as argument) to TrustedCmdArgs
|
||||||
// It panics if the check fails. Usually it should not be used, it's just for refactoring purpose
|
// In most cases, it shouldn't be used. Use AddXxx function instead
|
||||||
// deprecated
|
func ToTrustedCmdArgs(args []string) TrustedCmdArgs {
|
||||||
func CmdArgCheck(s string) CmdArg {
|
ret := make(TrustedCmdArgs, len(args))
|
||||||
if s != "" && s[0] == '-' {
|
for i, arg := range args {
|
||||||
panic("invalid git cmd argument: " + s)
|
ret[i] = internal.CmdArg(arg)
|
||||||
}
|
}
|
||||||
return CmdArg(s)
|
return ret
|
||||||
}
|
}
|
||||||
|
|
||||||
// RunOpts represents parameters to run the command. If UseContextTimeout is specified, then Timeout is ignored.
|
// RunOpts represents parameters to run the command. If UseContextTimeout is specified, then Timeout is ignored.
|
||||||
@ -364,9 +405,9 @@ func (c *Command) RunStdBytes(opts *RunOpts) (stdout, stderr []byte, runErr RunS
|
|||||||
}
|
}
|
||||||
|
|
||||||
// AllowLFSFiltersArgs return globalCommandArgs with lfs filter, it should only be used for tests
|
// AllowLFSFiltersArgs return globalCommandArgs with lfs filter, it should only be used for tests
|
||||||
func AllowLFSFiltersArgs() []CmdArg {
|
func AllowLFSFiltersArgs() TrustedCmdArgs {
|
||||||
// Now here we should explicitly allow lfs filters to run
|
// Now here we should explicitly allow lfs filters to run
|
||||||
filteredLFSGlobalArgs := make([]CmdArg, len(globalCommandArgs))
|
filteredLFSGlobalArgs := make(TrustedCmdArgs, len(globalCommandArgs))
|
||||||
j := 0
|
j := 0
|
||||||
for _, arg := range globalCommandArgs {
|
for _, arg := range globalCommandArgs {
|
||||||
if strings.Contains(string(arg), "lfs") {
|
if strings.Contains(string(arg), "lfs") {
|
||||||
|
@ -41,3 +41,14 @@ func TestRunWithContextStd(t *testing.T) {
|
|||||||
assert.Empty(t, stderr)
|
assert.Empty(t, stderr)
|
||||||
assert.Contains(t, stdout, "git version")
|
assert.Contains(t, stdout, "git version")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestGitArgument(t *testing.T) {
|
||||||
|
assert.True(t, isValidArgumentOption("-x"))
|
||||||
|
assert.True(t, isValidArgumentOption("--xx"))
|
||||||
|
assert.False(t, isValidArgumentOption(""))
|
||||||
|
assert.False(t, isValidArgumentOption("x"))
|
||||||
|
|
||||||
|
assert.True(t, isSafeArgumentValue(""))
|
||||||
|
assert.True(t, isSafeArgumentValue("x"))
|
||||||
|
assert.False(t, isSafeArgumentValue("-x"))
|
||||||
|
}
|
||||||
|
@ -9,7 +9,6 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
|
||||||
"io"
|
"io"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
"strconv"
|
"strconv"
|
||||||
@ -91,8 +90,8 @@ func AddChanges(repoPath string, all bool, files ...string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// AddChangesWithArgs marks local changes to be ready for commit.
|
// AddChangesWithArgs marks local changes to be ready for commit.
|
||||||
func AddChangesWithArgs(repoPath string, globalArgs []CmdArg, all bool, files ...string) error {
|
func AddChangesWithArgs(repoPath string, globalArgs TrustedCmdArgs, all bool, files ...string) error {
|
||||||
cmd := NewCommandNoGlobals(append(globalArgs, "add")...)
|
cmd := NewCommandContextNoGlobals(DefaultContext, globalArgs...).AddArguments("add")
|
||||||
if all {
|
if all {
|
||||||
cmd.AddArguments("--all")
|
cmd.AddArguments("--all")
|
||||||
}
|
}
|
||||||
@ -111,17 +110,18 @@ type CommitChangesOptions struct {
|
|||||||
// CommitChanges commits local changes with given committer, author and message.
|
// CommitChanges commits local changes with given committer, author and message.
|
||||||
// If author is nil, it will be the same as committer.
|
// If author is nil, it will be the same as committer.
|
||||||
func CommitChanges(repoPath string, opts CommitChangesOptions) error {
|
func CommitChanges(repoPath string, opts CommitChangesOptions) error {
|
||||||
cargs := make([]CmdArg, len(globalCommandArgs))
|
cargs := make(TrustedCmdArgs, len(globalCommandArgs))
|
||||||
copy(cargs, globalCommandArgs)
|
copy(cargs, globalCommandArgs)
|
||||||
return CommitChangesWithArgs(repoPath, cargs, opts)
|
return CommitChangesWithArgs(repoPath, cargs, opts)
|
||||||
}
|
}
|
||||||
|
|
||||||
// CommitChangesWithArgs commits local changes with given committer, author and message.
|
// CommitChangesWithArgs commits local changes with given committer, author and message.
|
||||||
// If author is nil, it will be the same as committer.
|
// If author is nil, it will be the same as committer.
|
||||||
func CommitChangesWithArgs(repoPath string, args []CmdArg, opts CommitChangesOptions) error {
|
func CommitChangesWithArgs(repoPath string, args TrustedCmdArgs, opts CommitChangesOptions) error {
|
||||||
cmd := NewCommandNoGlobals(args...)
|
cmd := NewCommandContextNoGlobals(DefaultContext, args...)
|
||||||
if opts.Committer != nil {
|
if opts.Committer != nil {
|
||||||
cmd.AddArguments("-c", CmdArg("user.name="+opts.Committer.Name), "-c", CmdArg("user.email="+opts.Committer.Email))
|
cmd.AddOptionValues("-c", "user.name="+opts.Committer.Name)
|
||||||
|
cmd.AddOptionValues("-c", "user.email="+opts.Committer.Email)
|
||||||
}
|
}
|
||||||
cmd.AddArguments("commit")
|
cmd.AddArguments("commit")
|
||||||
|
|
||||||
@ -129,9 +129,9 @@ func CommitChangesWithArgs(repoPath string, args []CmdArg, opts CommitChangesOpt
|
|||||||
opts.Author = opts.Committer
|
opts.Author = opts.Committer
|
||||||
}
|
}
|
||||||
if opts.Author != nil {
|
if opts.Author != nil {
|
||||||
cmd.AddArguments(CmdArg(fmt.Sprintf("--author='%s <%s>'", opts.Author.Name, opts.Author.Email)))
|
cmd.AddOptionFormat("--author='%s <%s>'", opts.Author.Name, opts.Author.Email)
|
||||||
}
|
}
|
||||||
cmd.AddArguments("-m").AddDynamicArguments(opts.Message)
|
cmd.AddOptionValues("-m", opts.Message)
|
||||||
|
|
||||||
_, _, err := cmd.RunStdString(&RunOpts{Dir: repoPath})
|
_, _, err := cmd.RunStdString(&RunOpts{Dir: repoPath})
|
||||||
// No stderr but exit status 1 means nothing to commit.
|
// No stderr but exit status 1 means nothing to commit.
|
||||||
|
@ -383,6 +383,6 @@ func configUnsetAll(key, value string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Fsck verifies the connectivity and validity of the objects in the database
|
// Fsck verifies the connectivity and validity of the objects in the database
|
||||||
func Fsck(ctx context.Context, repoPath string, timeout time.Duration, args ...CmdArg) error {
|
func Fsck(ctx context.Context, repoPath string, timeout time.Duration, args TrustedCmdArgs) error {
|
||||||
return NewCommand(ctx, "fsck").AddArguments(args...).Run(&RunOpts{Timeout: timeout, Dir: repoPath})
|
return NewCommand(ctx, "fsck").AddArguments(args...).Run(&RunOpts{Timeout: timeout, Dir: repoPath})
|
||||||
}
|
}
|
||||||
|
9
modules/git/internal/cmdarg.go
Normal file
9
modules/git/internal/cmdarg.go
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
// Copyright 2023 The Gitea Authors. All rights reserved.
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
package internal
|
||||||
|
|
||||||
|
// CmdArg represents a command argument for git command, and it will be used for the git command directly without any further processing.
|
||||||
|
// In most cases, you should use the "AddXxx" functions to add arguments, but not use this type directly.
|
||||||
|
// Casting a risky (user-provided) string to CmdArg would cause security issues if it's injected with a "--xxx" argument.
|
||||||
|
type CmdArg string
|
@ -115,7 +115,7 @@ func Clone(ctx context.Context, from, to string, opts CloneRepoOptions) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// CloneWithArgs original repository to target path.
|
// CloneWithArgs original repository to target path.
|
||||||
func CloneWithArgs(ctx context.Context, args []CmdArg, from, to string, opts CloneRepoOptions) (err error) {
|
func CloneWithArgs(ctx context.Context, args TrustedCmdArgs, from, to string, opts CloneRepoOptions) (err error) {
|
||||||
toDir := path.Dir(to)
|
toDir := path.Dir(to)
|
||||||
if err = os.MkdirAll(toDir, os.ModePerm); err != nil {
|
if err = os.MkdirAll(toDir, os.ModePerm); err != nil {
|
||||||
return err
|
return err
|
||||||
|
@ -57,9 +57,9 @@ func (repo *Repository) CreateArchive(ctx context.Context, format ArchiveType, t
|
|||||||
|
|
||||||
cmd := NewCommand(ctx, "archive")
|
cmd := NewCommand(ctx, "archive")
|
||||||
if usePrefix {
|
if usePrefix {
|
||||||
cmd.AddArguments(CmdArg("--prefix=" + filepath.Base(strings.TrimSuffix(repo.Path, ".git")) + "/"))
|
cmd.AddOptionFormat("--prefix=%s", filepath.Base(strings.TrimSuffix(repo.Path, ".git"))+"/")
|
||||||
}
|
}
|
||||||
cmd.AddArguments(CmdArg("--format=" + format.String()))
|
cmd.AddOptionFormat("--format=%s", format.String())
|
||||||
cmd.AddDynamicArguments(commitID)
|
cmd.AddDynamicArguments(commitID)
|
||||||
|
|
||||||
var stderr strings.Builder
|
var stderr strings.Builder
|
||||||
|
@ -17,7 +17,7 @@ import (
|
|||||||
type CheckAttributeOpts struct {
|
type CheckAttributeOpts struct {
|
||||||
CachedOnly bool
|
CachedOnly bool
|
||||||
AllAttributes bool
|
AllAttributes bool
|
||||||
Attributes []CmdArg
|
Attributes []string
|
||||||
Filenames []string
|
Filenames []string
|
||||||
IndexFile string
|
IndexFile string
|
||||||
WorkTree string
|
WorkTree string
|
||||||
@ -48,7 +48,7 @@ func (repo *Repository) CheckAttribute(opts CheckAttributeOpts) (map[string]map[
|
|||||||
} else {
|
} else {
|
||||||
for _, attribute := range opts.Attributes {
|
for _, attribute := range opts.Attributes {
|
||||||
if attribute != "" {
|
if attribute != "" {
|
||||||
cmd.AddArguments(attribute)
|
cmd.AddDynamicArguments(attribute)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -95,7 +95,7 @@ func (repo *Repository) CheckAttribute(opts CheckAttributeOpts) (map[string]map[
|
|||||||
// CheckAttributeReader provides a reader for check-attribute content that can be long running
|
// CheckAttributeReader provides a reader for check-attribute content that can be long running
|
||||||
type CheckAttributeReader struct {
|
type CheckAttributeReader struct {
|
||||||
// params
|
// params
|
||||||
Attributes []CmdArg
|
Attributes []string
|
||||||
Repo *Repository
|
Repo *Repository
|
||||||
IndexFile string
|
IndexFile string
|
||||||
WorkTree string
|
WorkTree string
|
||||||
@ -111,19 +111,6 @@ type CheckAttributeReader struct {
|
|||||||
|
|
||||||
// Init initializes the CheckAttributeReader
|
// Init initializes the CheckAttributeReader
|
||||||
func (c *CheckAttributeReader) Init(ctx context.Context) error {
|
func (c *CheckAttributeReader) Init(ctx context.Context) error {
|
||||||
cmdArgs := []CmdArg{"check-attr", "--stdin", "-z"}
|
|
||||||
|
|
||||||
if len(c.IndexFile) > 0 {
|
|
||||||
cmdArgs = append(cmdArgs, "--cached")
|
|
||||||
c.env = append(c.env, "GIT_INDEX_FILE="+c.IndexFile)
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(c.WorkTree) > 0 {
|
|
||||||
c.env = append(c.env, "GIT_WORK_TREE="+c.WorkTree)
|
|
||||||
}
|
|
||||||
|
|
||||||
c.env = append(c.env, "GIT_FLUSH=1")
|
|
||||||
|
|
||||||
if len(c.Attributes) == 0 {
|
if len(c.Attributes) == 0 {
|
||||||
lw := new(nulSeparatedAttributeWriter)
|
lw := new(nulSeparatedAttributeWriter)
|
||||||
lw.attributes = make(chan attributeTriple)
|
lw.attributes = make(chan attributeTriple)
|
||||||
@ -134,11 +121,22 @@ func (c *CheckAttributeReader) Init(ctx context.Context) error {
|
|||||||
return fmt.Errorf("no provided Attributes to check")
|
return fmt.Errorf("no provided Attributes to check")
|
||||||
}
|
}
|
||||||
|
|
||||||
cmdArgs = append(cmdArgs, c.Attributes...)
|
|
||||||
cmdArgs = append(cmdArgs, "--")
|
|
||||||
|
|
||||||
c.ctx, c.cancel = context.WithCancel(ctx)
|
c.ctx, c.cancel = context.WithCancel(ctx)
|
||||||
c.cmd = NewCommand(c.ctx, cmdArgs...)
|
c.cmd = NewCommand(c.ctx, "check-attr", "--stdin", "-z")
|
||||||
|
|
||||||
|
if len(c.IndexFile) > 0 {
|
||||||
|
c.cmd.AddArguments("--cached")
|
||||||
|
c.env = append(c.env, "GIT_INDEX_FILE="+c.IndexFile)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(c.WorkTree) > 0 {
|
||||||
|
c.env = append(c.env, "GIT_WORK_TREE="+c.WorkTree)
|
||||||
|
}
|
||||||
|
|
||||||
|
c.env = append(c.env, "GIT_FLUSH=1")
|
||||||
|
|
||||||
|
// The empty "--" comes from #16773 , and it seems unnecessary because nothing else would be added later.
|
||||||
|
c.cmd.AddDynamicArguments(c.Attributes...).AddArguments("--")
|
||||||
|
|
||||||
var err error
|
var err error
|
||||||
|
|
||||||
@ -294,7 +292,7 @@ func (repo *Repository) CheckAttributeReader(commitID string) (*CheckAttributeRe
|
|||||||
}
|
}
|
||||||
|
|
||||||
checker := &CheckAttributeReader{
|
checker := &CheckAttributeReader{
|
||||||
Attributes: []CmdArg{"linguist-vendored", "linguist-generated", "linguist-language", "gitlab-language"},
|
Attributes: []string{"linguist-vendored", "linguist-generated", "linguist-language", "gitlab-language"},
|
||||||
Repo: repo,
|
Repo: repo,
|
||||||
IndexFile: indexFilename,
|
IndexFile: indexFilename,
|
||||||
WorkTree: worktree,
|
WorkTree: worktree,
|
||||||
|
@ -3,7 +3,9 @@
|
|||||||
|
|
||||||
package git
|
package git
|
||||||
|
|
||||||
import "fmt"
|
import (
|
||||||
|
"fmt"
|
||||||
|
)
|
||||||
|
|
||||||
// FileBlame return the Blame object of file
|
// FileBlame return the Blame object of file
|
||||||
func (repo *Repository) FileBlame(revision, path, file string) ([]byte, error) {
|
func (repo *Repository) FileBlame(revision, path, file string) ([]byte, error) {
|
||||||
@ -14,8 +16,8 @@ func (repo *Repository) FileBlame(revision, path, file string) ([]byte, error) {
|
|||||||
// LineBlame returns the latest commit at the given line
|
// LineBlame returns the latest commit at the given line
|
||||||
func (repo *Repository) LineBlame(revision, path, file string, line uint) (*Commit, error) {
|
func (repo *Repository) LineBlame(revision, path, file string, line uint) (*Commit, error) {
|
||||||
res, _, err := NewCommand(repo.Ctx, "blame").
|
res, _, err := NewCommand(repo.Ctx, "blame").
|
||||||
AddArguments(CmdArg(fmt.Sprintf("-L %d,%d", line, line))).
|
AddOptionFormat("-L %d,%d", line, line).
|
||||||
AddArguments("-p").AddDynamicArguments(revision).
|
AddOptionValues("-p", revision).
|
||||||
AddDashesAndList(file).RunStdString(&RunOpts{Dir: path})
|
AddDashesAndList(file).RunStdString(&RunOpts{Dir: path})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
@ -50,8 +50,8 @@ func (repo *Repository) IsBranchExist(name string) bool {
|
|||||||
return reference.Type() != plumbing.InvalidReference
|
return reference.Type() != plumbing.InvalidReference
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetBranches returns branches from the repository, skipping skip initial branches and
|
// GetBranches returns branches from the repository, skipping "skip" initial branches and
|
||||||
// returning at most limit branches, or all branches if limit is 0.
|
// returning at most "limit" branches, or all branches if "limit" is 0.
|
||||||
func (repo *Repository) GetBranchNames(skip, limit int) ([]string, int, error) {
|
func (repo *Repository) GetBranchNames(skip, limit int) ([]string, int, error) {
|
||||||
var branchNames []string
|
var branchNames []string
|
||||||
|
|
||||||
|
@ -59,10 +59,10 @@ func (repo *Repository) IsBranchExist(name string) bool {
|
|||||||
return repo.IsReferenceExist(BranchPrefix + name)
|
return repo.IsReferenceExist(BranchPrefix + name)
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetBranchNames returns branches from the repository, skipping skip initial branches and
|
// GetBranchNames returns branches from the repository, skipping "skip" initial branches and
|
||||||
// returning at most limit branches, or all branches if limit is 0.
|
// returning at most "limit" branches, or all branches if "limit" is 0.
|
||||||
func (repo *Repository) GetBranchNames(skip, limit int) ([]string, int, error) {
|
func (repo *Repository) GetBranchNames(skip, limit int) ([]string, int, error) {
|
||||||
return callShowRef(repo.Ctx, repo.Path, BranchPrefix, []CmdArg{BranchPrefix, "--sort=-committerdate"}, skip, limit)
|
return callShowRef(repo.Ctx, repo.Path, BranchPrefix, TrustedCmdArgs{BranchPrefix, "--sort=-committerdate"}, skip, limit)
|
||||||
}
|
}
|
||||||
|
|
||||||
// WalkReferences walks all the references from the repository
|
// WalkReferences walks all the references from the repository
|
||||||
@ -73,19 +73,19 @@ func WalkReferences(ctx context.Context, repoPath string, walkfn func(sha1, refn
|
|||||||
// WalkReferences walks all the references from the repository
|
// WalkReferences walks all the references from the repository
|
||||||
// refType should be empty, ObjectTag or ObjectBranch. All other values are equivalent to empty.
|
// refType should be empty, ObjectTag or ObjectBranch. All other values are equivalent to empty.
|
||||||
func (repo *Repository) WalkReferences(refType ObjectType, skip, limit int, walkfn func(sha1, refname string) error) (int, error) {
|
func (repo *Repository) WalkReferences(refType ObjectType, skip, limit int, walkfn func(sha1, refname string) error) (int, error) {
|
||||||
var args []CmdArg
|
var args TrustedCmdArgs
|
||||||
switch refType {
|
switch refType {
|
||||||
case ObjectTag:
|
case ObjectTag:
|
||||||
args = []CmdArg{TagPrefix, "--sort=-taggerdate"}
|
args = TrustedCmdArgs{TagPrefix, "--sort=-taggerdate"}
|
||||||
case ObjectBranch:
|
case ObjectBranch:
|
||||||
args = []CmdArg{BranchPrefix, "--sort=-committerdate"}
|
args = TrustedCmdArgs{BranchPrefix, "--sort=-committerdate"}
|
||||||
}
|
}
|
||||||
|
|
||||||
return walkShowRef(repo.Ctx, repo.Path, args, skip, limit, walkfn)
|
return walkShowRef(repo.Ctx, repo.Path, args, skip, limit, walkfn)
|
||||||
}
|
}
|
||||||
|
|
||||||
// callShowRef return refs, if limit = 0 it will not limit
|
// callShowRef return refs, if limit = 0 it will not limit
|
||||||
func callShowRef(ctx context.Context, repoPath, trimPrefix string, extraArgs []CmdArg, skip, limit int) (branchNames []string, countAll int, err error) {
|
func callShowRef(ctx context.Context, repoPath, trimPrefix string, extraArgs TrustedCmdArgs, skip, limit int) (branchNames []string, countAll int, err error) {
|
||||||
countAll, err = walkShowRef(ctx, repoPath, extraArgs, skip, limit, func(_, branchName string) error {
|
countAll, err = walkShowRef(ctx, repoPath, extraArgs, skip, limit, func(_, branchName string) error {
|
||||||
branchName = strings.TrimPrefix(branchName, trimPrefix)
|
branchName = strings.TrimPrefix(branchName, trimPrefix)
|
||||||
branchNames = append(branchNames, branchName)
|
branchNames = append(branchNames, branchName)
|
||||||
@ -95,7 +95,7 @@ func callShowRef(ctx context.Context, repoPath, trimPrefix string, extraArgs []C
|
|||||||
return branchNames, countAll, err
|
return branchNames, countAll, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func walkShowRef(ctx context.Context, repoPath string, extraArgs []CmdArg, skip, limit int, walkfn func(sha1, refname string) error) (countAll int, err error) {
|
func walkShowRef(ctx context.Context, repoPath string, extraArgs TrustedCmdArgs, skip, limit int, walkfn func(sha1, refname string) error) (countAll int, err error) {
|
||||||
stdoutReader, stdoutWriter := io.Pipe()
|
stdoutReader, stdoutWriter := io.Pipe()
|
||||||
defer func() {
|
defer func() {
|
||||||
_ = stdoutReader.Close()
|
_ = stdoutReader.Close()
|
||||||
@ -104,7 +104,7 @@ func walkShowRef(ctx context.Context, repoPath string, extraArgs []CmdArg, skip,
|
|||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
stderrBuilder := &strings.Builder{}
|
stderrBuilder := &strings.Builder{}
|
||||||
args := []CmdArg{"for-each-ref", "--format=%(objectname) %(refname)"}
|
args := TrustedCmdArgs{"for-each-ref", "--format=%(objectname) %(refname)"}
|
||||||
args = append(args, extraArgs...)
|
args = append(args, extraArgs...)
|
||||||
err := NewCommand(ctx, args...).Run(&RunOpts{
|
err := NewCommand(ctx, args...).Run(&RunOpts{
|
||||||
Dir: repoPath,
|
Dir: repoPath,
|
||||||
|
@ -89,7 +89,7 @@ func (repo *Repository) GetCommitByPath(relpath string) (*Commit, error) {
|
|||||||
|
|
||||||
func (repo *Repository) commitsByRange(id SHA1, page, pageSize int) ([]*Commit, error) {
|
func (repo *Repository) commitsByRange(id SHA1, page, pageSize int) ([]*Commit, error) {
|
||||||
stdout, _, err := NewCommand(repo.Ctx, "log").
|
stdout, _, err := NewCommand(repo.Ctx, "log").
|
||||||
AddArguments(CmdArg("--skip="+strconv.Itoa((page-1)*pageSize)), CmdArg("--max-count="+strconv.Itoa(pageSize)), prettyLogFormat).
|
AddOptionFormat("--skip=%d", (page-1)*pageSize).AddOptionFormat("--max-count=%d", pageSize).AddArguments(prettyLogFormat).
|
||||||
AddDynamicArguments(id.String()).
|
AddDynamicArguments(id.String()).
|
||||||
RunStdBytes(&RunOpts{Dir: repo.Path})
|
RunStdBytes(&RunOpts{Dir: repo.Path})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -99,32 +99,36 @@ func (repo *Repository) commitsByRange(id SHA1, page, pageSize int) ([]*Commit,
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (repo *Repository) searchCommits(id SHA1, opts SearchCommitsOptions) ([]*Commit, error) {
|
func (repo *Repository) searchCommits(id SHA1, opts SearchCommitsOptions) ([]*Commit, error) {
|
||||||
// create new git log command with limit of 100 commis
|
// add common arguments to git command
|
||||||
|
addCommonSearchArgs := func(c *Command) {
|
||||||
|
// ignore case
|
||||||
|
c.AddArguments("-i")
|
||||||
|
|
||||||
|
// add authors if present in search query
|
||||||
|
if len(opts.Authors) > 0 {
|
||||||
|
for _, v := range opts.Authors {
|
||||||
|
c.AddOptionFormat("--author=%s", v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// add committers if present in search query
|
||||||
|
if len(opts.Committers) > 0 {
|
||||||
|
for _, v := range opts.Committers {
|
||||||
|
c.AddOptionFormat("--committer=%s", v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// add time constraints if present in search query
|
||||||
|
if len(opts.After) > 0 {
|
||||||
|
c.AddOptionFormat("--after=%s", opts.After)
|
||||||
|
}
|
||||||
|
if len(opts.Before) > 0 {
|
||||||
|
c.AddOptionFormat("--before=%s", opts.Before)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// create new git log command with limit of 100 commits
|
||||||
cmd := NewCommand(repo.Ctx, "log", "-100", prettyLogFormat).AddDynamicArguments(id.String())
|
cmd := NewCommand(repo.Ctx, "log", "-100", prettyLogFormat).AddDynamicArguments(id.String())
|
||||||
// ignore case
|
|
||||||
args := []CmdArg{"-i"}
|
|
||||||
|
|
||||||
// add authors if present in search query
|
|
||||||
if len(opts.Authors) > 0 {
|
|
||||||
for _, v := range opts.Authors {
|
|
||||||
args = append(args, CmdArg("--author="+v))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// add committers if present in search query
|
|
||||||
if len(opts.Committers) > 0 {
|
|
||||||
for _, v := range opts.Committers {
|
|
||||||
args = append(args, CmdArg("--committer="+v))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// add time constraints if present in search query
|
|
||||||
if len(opts.After) > 0 {
|
|
||||||
args = append(args, CmdArg("--after="+opts.After))
|
|
||||||
}
|
|
||||||
if len(opts.Before) > 0 {
|
|
||||||
args = append(args, CmdArg("--before="+opts.Before))
|
|
||||||
}
|
|
||||||
|
|
||||||
// pretend that all refs along with HEAD were listed on command line as <commis>
|
// pretend that all refs along with HEAD were listed on command line as <commis>
|
||||||
// https://git-scm.com/docs/git-log#Documentation/git-log.txt---all
|
// https://git-scm.com/docs/git-log#Documentation/git-log.txt---all
|
||||||
@ -137,12 +141,12 @@ func (repo *Repository) searchCommits(id SHA1, opts SearchCommitsOptions) ([]*Co
|
|||||||
// note this is done only for command created above
|
// note this is done only for command created above
|
||||||
if len(opts.Keywords) > 0 {
|
if len(opts.Keywords) > 0 {
|
||||||
for _, v := range opts.Keywords {
|
for _, v := range opts.Keywords {
|
||||||
cmd.AddArguments(CmdArg("--grep=" + v))
|
cmd.AddOptionFormat("--grep=%s", v)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// search for commits matching given constraints and keywords in commit msg
|
// search for commits matching given constraints and keywords in commit msg
|
||||||
cmd.AddArguments(args...)
|
addCommonSearchArgs(cmd)
|
||||||
stdout, _, err := cmd.RunStdBytes(&RunOpts{Dir: repo.Path})
|
stdout, _, err := cmd.RunStdBytes(&RunOpts{Dir: repo.Path})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -160,7 +164,7 @@ func (repo *Repository) searchCommits(id SHA1, opts SearchCommitsOptions) ([]*Co
|
|||||||
// create new git log command with 1 commit limit
|
// create new git log command with 1 commit limit
|
||||||
hashCmd := NewCommand(repo.Ctx, "log", "-1", prettyLogFormat)
|
hashCmd := NewCommand(repo.Ctx, "log", "-1", prettyLogFormat)
|
||||||
// add previous arguments except for --grep and --all
|
// add previous arguments except for --grep and --all
|
||||||
hashCmd.AddArguments(args...)
|
addCommonSearchArgs(hashCmd)
|
||||||
// add keyword as <commit>
|
// add keyword as <commit>
|
||||||
hashCmd.AddDynamicArguments(v)
|
hashCmd.AddDynamicArguments(v)
|
||||||
|
|
||||||
@ -213,8 +217,8 @@ func (repo *Repository) CommitsByFileAndRange(revision, file string, page int) (
|
|||||||
go func() {
|
go func() {
|
||||||
stderr := strings.Builder{}
|
stderr := strings.Builder{}
|
||||||
gitCmd := NewCommand(repo.Ctx, "rev-list").
|
gitCmd := NewCommand(repo.Ctx, "rev-list").
|
||||||
AddArguments(CmdArg("--max-count=" + strconv.Itoa(setting.Git.CommitsRangeSize*page))).
|
AddOptionFormat("--max-count=%d", setting.Git.CommitsRangeSize*page).
|
||||||
AddArguments(CmdArg("--skip=" + strconv.Itoa(skip)))
|
AddOptionFormat("--skip=%d", skip)
|
||||||
gitCmd.AddDynamicArguments(revision)
|
gitCmd.AddDynamicArguments(revision)
|
||||||
gitCmd.AddDashesAndList(file)
|
gitCmd.AddDashesAndList(file)
|
||||||
err := gitCmd.Run(&RunOpts{
|
err := gitCmd.Run(&RunOpts{
|
||||||
@ -295,21 +299,21 @@ func (repo *Repository) CommitsBetweenLimit(last, before *Commit, limit, skip in
|
|||||||
var stdout []byte
|
var stdout []byte
|
||||||
var err error
|
var err error
|
||||||
if before == nil {
|
if before == nil {
|
||||||
stdout, _, err = NewCommand(repo.Ctx, "rev-list",
|
stdout, _, err = NewCommand(repo.Ctx, "rev-list").
|
||||||
"--max-count", CmdArg(strconv.Itoa(limit)),
|
AddOptionValues("--max-count", strconv.Itoa(limit)).
|
||||||
"--skip", CmdArg(strconv.Itoa(skip))).
|
AddOptionValues("--skip", strconv.Itoa(skip)).
|
||||||
AddDynamicArguments(last.ID.String()).RunStdBytes(&RunOpts{Dir: repo.Path})
|
AddDynamicArguments(last.ID.String()).RunStdBytes(&RunOpts{Dir: repo.Path})
|
||||||
} else {
|
} else {
|
||||||
stdout, _, err = NewCommand(repo.Ctx, "rev-list",
|
stdout, _, err = NewCommand(repo.Ctx, "rev-list").
|
||||||
"--max-count", CmdArg(strconv.Itoa(limit)),
|
AddOptionValues("--max-count", strconv.Itoa(limit)).
|
||||||
"--skip", CmdArg(strconv.Itoa(skip))).
|
AddOptionValues("--skip", strconv.Itoa(skip)).
|
||||||
AddDynamicArguments(before.ID.String() + ".." + last.ID.String()).RunStdBytes(&RunOpts{Dir: repo.Path})
|
AddDynamicArguments(before.ID.String() + ".." + last.ID.String()).RunStdBytes(&RunOpts{Dir: repo.Path})
|
||||||
if err != nil && strings.Contains(err.Error(), "no merge base") {
|
if err != nil && strings.Contains(err.Error(), "no merge base") {
|
||||||
// future versions of git >= 2.28 are likely to return an error if before and last have become unrelated.
|
// future versions of git >= 2.28 are likely to return an error if before and last have become unrelated.
|
||||||
// previously it would return the results of git rev-list --max-count n before last so let's try that...
|
// previously it would return the results of git rev-list --max-count n before last so let's try that...
|
||||||
stdout, _, err = NewCommand(repo.Ctx, "rev-list",
|
stdout, _, err = NewCommand(repo.Ctx, "rev-list").
|
||||||
"--max-count", CmdArg(strconv.Itoa(limit)),
|
AddOptionValues("--max-count", strconv.Itoa(limit)).
|
||||||
"--skip", CmdArg(strconv.Itoa(skip))).
|
AddOptionValues("--skip", strconv.Itoa(skip)).
|
||||||
AddDynamicArguments(before.ID.String(), last.ID.String()).RunStdBytes(&RunOpts{Dir: repo.Path})
|
AddDynamicArguments(before.ID.String(), last.ID.String()).RunStdBytes(&RunOpts{Dir: repo.Path})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -349,12 +353,11 @@ func (repo *Repository) CommitsCountBetween(start, end string) (int64, error) {
|
|||||||
|
|
||||||
// commitsBefore the limit is depth, not total number of returned commits.
|
// commitsBefore the limit is depth, not total number of returned commits.
|
||||||
func (repo *Repository) commitsBefore(id SHA1, limit int) ([]*Commit, error) {
|
func (repo *Repository) commitsBefore(id SHA1, limit int) ([]*Commit, error) {
|
||||||
cmd := NewCommand(repo.Ctx, "log")
|
cmd := NewCommand(repo.Ctx, "log", prettyLogFormat)
|
||||||
if limit > 0 {
|
if limit > 0 {
|
||||||
cmd.AddArguments(CmdArg("-"+strconv.Itoa(limit)), prettyLogFormat).AddDynamicArguments(id.String())
|
cmd.AddOptionFormat("-%d", limit)
|
||||||
} else {
|
|
||||||
cmd.AddArguments(prettyLogFormat).AddDynamicArguments(id.String())
|
|
||||||
}
|
}
|
||||||
|
cmd.AddDynamicArguments(id.String())
|
||||||
|
|
||||||
stdout, _, runErr := cmd.RunStdBytes(&RunOpts{Dir: repo.Path})
|
stdout, _, runErr := cmd.RunStdBytes(&RunOpts{Dir: repo.Path})
|
||||||
if runErr != nil {
|
if runErr != nil {
|
||||||
@ -393,10 +396,9 @@ func (repo *Repository) getCommitsBeforeLimit(id SHA1, num int) ([]*Commit, erro
|
|||||||
|
|
||||||
func (repo *Repository) getBranches(commit *Commit, limit int) ([]string, error) {
|
func (repo *Repository) getBranches(commit *Commit, limit int) ([]string, error) {
|
||||||
if CheckGitVersionAtLeast("2.7.0") == nil {
|
if CheckGitVersionAtLeast("2.7.0") == nil {
|
||||||
stdout, _, err := NewCommand(repo.Ctx, "for-each-ref",
|
stdout, _, err := NewCommand(repo.Ctx, "for-each-ref", "--format=%(refname:strip=2)").
|
||||||
CmdArg("--count="+strconv.Itoa(limit)),
|
AddOptionFormat("--count=%d", limit).
|
||||||
"--format=%(refname:strip=2)", "--contains").
|
AddOptionValues("--contains", commit.ID.String(), BranchPrefix).
|
||||||
AddDynamicArguments(commit.ID.String(), BranchPrefix).
|
|
||||||
RunStdString(&RunOpts{Dir: repo.Path})
|
RunStdString(&RunOpts{Dir: repo.Path})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -406,7 +408,7 @@ func (repo *Repository) getBranches(commit *Commit, limit int) ([]string, error)
|
|||||||
return branches, nil
|
return branches, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
stdout, _, err := NewCommand(repo.Ctx, "branch", "--contains").AddDynamicArguments(commit.ID.String()).RunStdString(&RunOpts{Dir: repo.Path})
|
stdout, _, err := NewCommand(repo.Ctx, "branch").AddOptionValues("--contains", commit.ID.String()).RunStdString(&RunOpts{Dir: repo.Path})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
@ -172,25 +172,21 @@ func (repo *Repository) GetDiffNumChangedFiles(base, head string, directComparis
|
|||||||
|
|
||||||
// GetDiffShortStat counts number of changed files, number of additions and deletions
|
// GetDiffShortStat counts number of changed files, number of additions and deletions
|
||||||
func (repo *Repository) GetDiffShortStat(base, head string) (numFiles, totalAdditions, totalDeletions int, err error) {
|
func (repo *Repository) GetDiffShortStat(base, head string) (numFiles, totalAdditions, totalDeletions int, err error) {
|
||||||
numFiles, totalAdditions, totalDeletions, err = GetDiffShortStat(repo.Ctx, repo.Path, CmdArgCheck(base+"..."+head))
|
numFiles, totalAdditions, totalDeletions, err = GetDiffShortStat(repo.Ctx, repo.Path, nil, base+"..."+head)
|
||||||
if err != nil && strings.Contains(err.Error(), "no merge base") {
|
if err != nil && strings.Contains(err.Error(), "no merge base") {
|
||||||
return GetDiffShortStat(repo.Ctx, repo.Path, CmdArgCheck(base), CmdArgCheck(head))
|
return GetDiffShortStat(repo.Ctx, repo.Path, nil, base, head)
|
||||||
}
|
}
|
||||||
return numFiles, totalAdditions, totalDeletions, err
|
return numFiles, totalAdditions, totalDeletions, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetDiffShortStat counts number of changed files, number of additions and deletions
|
// GetDiffShortStat counts number of changed files, number of additions and deletions
|
||||||
func GetDiffShortStat(ctx context.Context, repoPath string, args ...CmdArg) (numFiles, totalAdditions, totalDeletions int, err error) {
|
func GetDiffShortStat(ctx context.Context, repoPath string, trustedArgs TrustedCmdArgs, dynamicArgs ...string) (numFiles, totalAdditions, totalDeletions int, err error) {
|
||||||
// Now if we call:
|
// Now if we call:
|
||||||
// $ git diff --shortstat 1ebb35b98889ff77299f24d82da426b434b0cca0...788b8b1440462d477f45b0088875
|
// $ git diff --shortstat 1ebb35b98889ff77299f24d82da426b434b0cca0...788b8b1440462d477f45b0088875
|
||||||
// we get:
|
// we get:
|
||||||
// " 9902 files changed, 2034198 insertions(+), 298800 deletions(-)\n"
|
// " 9902 files changed, 2034198 insertions(+), 298800 deletions(-)\n"
|
||||||
args = append([]CmdArg{
|
cmd := NewCommand(ctx, "diff", "--shortstat").AddArguments(trustedArgs...).AddDynamicArguments(dynamicArgs...)
|
||||||
"diff",
|
stdout, _, err := cmd.RunStdString(&RunOpts{Dir: repoPath})
|
||||||
"--shortstat",
|
|
||||||
}, args...)
|
|
||||||
|
|
||||||
stdout, _, err := NewCommand(ctx, args...).RunStdString(&RunOpts{Dir: repoPath})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, 0, 0, err
|
return 0, 0, 0, err
|
||||||
}
|
}
|
||||||
|
@ -40,7 +40,7 @@ func (repo *Repository) GetCodeActivityStats(fromTime time.Time, branch string)
|
|||||||
|
|
||||||
since := fromTime.Format(time.RFC3339)
|
since := fromTime.Format(time.RFC3339)
|
||||||
|
|
||||||
stdout, _, runErr := NewCommand(repo.Ctx, "rev-list", "--count", "--no-merges", "--branches=*", "--date=iso", CmdArg(fmt.Sprintf("--since='%s'", since))).RunStdString(&RunOpts{Dir: repo.Path})
|
stdout, _, runErr := NewCommand(repo.Ctx, "rev-list", "--count", "--no-merges", "--branches=*", "--date=iso").AddOptionFormat("--since='%s'", since).RunStdString(&RunOpts{Dir: repo.Path})
|
||||||
if runErr != nil {
|
if runErr != nil {
|
||||||
return nil, runErr
|
return nil, runErr
|
||||||
}
|
}
|
||||||
@ -60,7 +60,7 @@ func (repo *Repository) GetCodeActivityStats(fromTime time.Time, branch string)
|
|||||||
_ = stdoutWriter.Close()
|
_ = stdoutWriter.Close()
|
||||||
}()
|
}()
|
||||||
|
|
||||||
gitCmd := NewCommand(repo.Ctx, "log", "--numstat", "--no-merges", "--pretty=format:---%n%h%n%aN%n%aE%n", "--date=iso", CmdArg(fmt.Sprintf("--since='%s'", since)))
|
gitCmd := NewCommand(repo.Ctx, "log", "--numstat", "--no-merges", "--pretty=format:---%n%h%n%aN%n%aE%n", "--date=iso").AddOptionFormat("--since='%s'", since)
|
||||||
if len(branch) == 0 {
|
if len(branch) == 0 {
|
||||||
gitCmd.AddArguments("--branches=*")
|
gitCmd.AddArguments("--branches=*")
|
||||||
} else {
|
} else {
|
||||||
|
@ -121,7 +121,9 @@ func (repo *Repository) GetTagInfos(page, pageSize int) ([]*Tag, int, error) {
|
|||||||
rc := &RunOpts{Dir: repo.Path, Stdout: stdoutWriter, Stderr: &stderr}
|
rc := &RunOpts{Dir: repo.Path, Stdout: stdoutWriter, Stderr: &stderr}
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
err := NewCommand(repo.Ctx, "for-each-ref", CmdArg("--format="+forEachRefFmt.Flag()), "--sort", "-*creatordate", "refs/tags").Run(rc)
|
err := NewCommand(repo.Ctx, "for-each-ref").
|
||||||
|
AddOptionFormat("--format=%s", forEachRefFmt.Flag()).
|
||||||
|
AddArguments("--sort", "-*creatordate", "refs/tags").Run(rc)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
_ = stdoutWriter.CloseWithError(ConcatenateError(err, stderr.String()))
|
_ = stdoutWriter.CloseWithError(ConcatenateError(err, stderr.String()))
|
||||||
} else {
|
} else {
|
||||||
|
@ -25,7 +25,7 @@ func (repo *Repository) IsTagExist(name string) bool {
|
|||||||
// GetTags returns all tags of the repository.
|
// GetTags returns all tags of the repository.
|
||||||
// returning at most limit tags, or all if limit is 0.
|
// returning at most limit tags, or all if limit is 0.
|
||||||
func (repo *Repository) GetTags(skip, limit int) (tags []string, err error) {
|
func (repo *Repository) GetTags(skip, limit int) (tags []string, err error) {
|
||||||
tags, _, err = callShowRef(repo.Ctx, repo.Path, TagPrefix, []CmdArg{TagPrefix, "--sort=-taggerdate"}, skip, limit)
|
tags, _, err = callShowRef(repo.Ctx, repo.Path, TagPrefix, TrustedCmdArgs{TagPrefix, "--sort=-taggerdate"}, skip, limit)
|
||||||
return tags, err
|
return tags, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -6,7 +6,6 @@ package git
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"fmt"
|
|
||||||
"os"
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
@ -45,7 +44,7 @@ func (repo *Repository) CommitTree(author, committer *Signature, tree *Tree, opt
|
|||||||
_, _ = messageBytes.WriteString("\n")
|
_, _ = messageBytes.WriteString("\n")
|
||||||
|
|
||||||
if opts.KeyID != "" || opts.AlwaysSign {
|
if opts.KeyID != "" || opts.AlwaysSign {
|
||||||
cmd.AddArguments(CmdArg(fmt.Sprintf("-S%s", opts.KeyID)))
|
cmd.AddOptionFormat("-S%s", opts.KeyID)
|
||||||
}
|
}
|
||||||
|
|
||||||
if opts.NoGPGSign {
|
if opts.NoGPGSign {
|
||||||
|
@ -100,14 +100,15 @@ func (t *Tree) ListEntries() (Entries, error) {
|
|||||||
|
|
||||||
// listEntriesRecursive returns all entries of current tree recursively including all subtrees
|
// listEntriesRecursive returns all entries of current tree recursively including all subtrees
|
||||||
// extraArgs could be "-l" to get the size, which is slower
|
// extraArgs could be "-l" to get the size, which is slower
|
||||||
func (t *Tree) listEntriesRecursive(extraArgs ...CmdArg) (Entries, error) {
|
func (t *Tree) listEntriesRecursive(extraArgs TrustedCmdArgs) (Entries, error) {
|
||||||
if t.entriesRecursiveParsed {
|
if t.entriesRecursiveParsed {
|
||||||
return t.entriesRecursive, nil
|
return t.entriesRecursive, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
args := append([]CmdArg{"ls-tree", "-t", "-r"}, extraArgs...)
|
stdout, _, runErr := NewCommand(t.repo.Ctx, "ls-tree", "-t", "-r").
|
||||||
args = append(args, CmdArg(t.ID.String()))
|
AddArguments(extraArgs...).
|
||||||
stdout, _, runErr := NewCommand(t.repo.Ctx, args...).RunStdBytes(&RunOpts{Dir: t.repo.Path})
|
AddDynamicArguments(t.ID.String()).
|
||||||
|
RunStdBytes(&RunOpts{Dir: t.repo.Path})
|
||||||
if runErr != nil {
|
if runErr != nil {
|
||||||
return nil, runErr
|
return nil, runErr
|
||||||
}
|
}
|
||||||
@ -123,10 +124,10 @@ func (t *Tree) listEntriesRecursive(extraArgs ...CmdArg) (Entries, error) {
|
|||||||
|
|
||||||
// ListEntriesRecursiveFast returns all entries of current tree recursively including all subtrees, no size
|
// ListEntriesRecursiveFast returns all entries of current tree recursively including all subtrees, no size
|
||||||
func (t *Tree) ListEntriesRecursiveFast() (Entries, error) {
|
func (t *Tree) ListEntriesRecursiveFast() (Entries, error) {
|
||||||
return t.listEntriesRecursive()
|
return t.listEntriesRecursive(nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListEntriesRecursiveWithSize returns all entries of current tree recursively including all subtrees, with size
|
// ListEntriesRecursiveWithSize returns all entries of current tree recursively including all subtrees, with size
|
||||||
func (t *Tree) ListEntriesRecursiveWithSize() (Entries, error) {
|
func (t *Tree) ListEntriesRecursiveWithSize() (Entries, error) {
|
||||||
return t.listEntriesRecursive("--long")
|
return t.listEntriesRecursive(TrustedCmdArgs{"--long"})
|
||||||
}
|
}
|
||||||
|
@ -7,7 +7,6 @@ import (
|
|||||||
"bufio"
|
"bufio"
|
||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
|
||||||
"os"
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
@ -33,12 +32,9 @@ func GetCommitGraph(r *git.Repository, page, maxAllowedColors int, hidePRRefs bo
|
|||||||
graphCmd.AddArguments("--all")
|
graphCmd.AddArguments("--all")
|
||||||
}
|
}
|
||||||
|
|
||||||
graphCmd.AddArguments(
|
graphCmd.AddArguments("-C", "-M", "--date=iso").
|
||||||
"-C",
|
AddOptionFormat("-n %d", setting.UI.GraphMaxCommitNum*page).
|
||||||
"-M",
|
AddOptionFormat("--pretty=format:%s", format)
|
||||||
git.CmdArg(fmt.Sprintf("-n %d", setting.UI.GraphMaxCommitNum*page)),
|
|
||||||
"--date=iso",
|
|
||||||
git.CmdArg(fmt.Sprintf("--pretty=format:%s", format)))
|
|
||||||
|
|
||||||
if len(branches) > 0 {
|
if len(branches) > 0 {
|
||||||
graphCmd.AddDynamicArguments(branches...)
|
graphCmd.AddDynamicArguments(branches...)
|
||||||
|
@ -383,6 +383,13 @@ func (cv *ColoredValue) Format(s fmt.State, c rune) {
|
|||||||
s.Write(*cv.resetBytes)
|
s.Write(*cv.resetBytes)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ColorFormatAsString returns the result of the ColorFormat without the color
|
||||||
|
func ColorFormatAsString(colorVal ColorFormatted) string {
|
||||||
|
s := new(strings.Builder)
|
||||||
|
_, _ = ColorFprintf(&protectedANSIWriter{w: s, mode: removeColor}, "%-v", colorVal)
|
||||||
|
return s.String()
|
||||||
|
}
|
||||||
|
|
||||||
// SetColorBytes will allow a user to set the colorBytes of a colored value
|
// SetColorBytes will allow a user to set the colorBytes of a colored value
|
||||||
func (cv *ColoredValue) SetColorBytes(colorBytes []byte) {
|
func (cv *ColoredValue) SetColorBytes(colorBytes []byte) {
|
||||||
cv.colorBytes = &colorBytes
|
cv.colorBytes = &colorBytes
|
||||||
|
@ -9,6 +9,8 @@ import (
|
|||||||
"runtime"
|
"runtime"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
|
"code.gitea.io/gitea/modules/process"
|
||||||
)
|
)
|
||||||
|
|
||||||
type loggerMap struct {
|
type loggerMap struct {
|
||||||
@ -285,6 +287,15 @@ func (l *LoggerAsWriter) Log(msg string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
|
process.Trace = func(start bool, pid process.IDType, description string, parentPID process.IDType, typ string) {
|
||||||
|
if start && parentPID != "" {
|
||||||
|
Log(1, TRACE, "Start %s: %s (from %s) (%s)", NewColoredValue(pid, FgHiYellow), description, NewColoredValue(parentPID, FgYellow), NewColoredValue(typ, Reset))
|
||||||
|
} else if start {
|
||||||
|
Log(1, TRACE, "Start %s: %s (%s)", NewColoredValue(pid, FgHiYellow), description, NewColoredValue(typ, Reset))
|
||||||
|
} else {
|
||||||
|
Log(1, TRACE, "Done %s: %s", NewColoredValue(pid, FgHiYellow), NewColoredValue(description, Reset))
|
||||||
|
}
|
||||||
|
}
|
||||||
_, filename, _, _ := runtime.Caller(0)
|
_, filename, _, _ := runtime.Caller(0)
|
||||||
prefix = strings.TrimSuffix(filename, "modules/log/log.go")
|
prefix = strings.TrimSuffix(filename, "modules/log/log.go")
|
||||||
if prefix == filename {
|
if prefix == filename {
|
||||||
|
@ -6,6 +6,7 @@ package process
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"log"
|
||||||
"runtime/pprof"
|
"runtime/pprof"
|
||||||
"strconv"
|
"strconv"
|
||||||
"sync"
|
"sync"
|
||||||
@ -43,6 +44,18 @@ type IDType string
|
|||||||
// - it is simply an alias for context.CancelFunc and is only for documentary purposes
|
// - it is simply an alias for context.CancelFunc and is only for documentary purposes
|
||||||
type FinishedFunc = context.CancelFunc
|
type FinishedFunc = context.CancelFunc
|
||||||
|
|
||||||
|
var Trace = defaultTrace // this global can be overridden by particular logging packages - thus avoiding import cycles
|
||||||
|
|
||||||
|
func defaultTrace(start bool, pid IDType, description string, parentPID IDType, typ string) {
|
||||||
|
if start && parentPID != "" {
|
||||||
|
log.Printf("start process %s: %s (from %s) (%s)", pid, description, parentPID, typ)
|
||||||
|
} else if start {
|
||||||
|
log.Printf("start process %s: %s (%s)", pid, description, typ)
|
||||||
|
} else {
|
||||||
|
log.Printf("end process %s: %s", pid, description)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Manager manages all processes and counts PIDs.
|
// Manager manages all processes and counts PIDs.
|
||||||
type Manager struct {
|
type Manager struct {
|
||||||
mutex sync.Mutex
|
mutex sync.Mutex
|
||||||
@ -154,6 +167,7 @@ func (pm *Manager) Add(ctx context.Context, description string, cancel context.C
|
|||||||
|
|
||||||
pm.processMap[pid] = process
|
pm.processMap[pid] = process
|
||||||
pm.mutex.Unlock()
|
pm.mutex.Unlock()
|
||||||
|
Trace(true, pid, description, parentPID, processType)
|
||||||
|
|
||||||
pprofCtx := pprof.WithLabels(ctx, pprof.Labels(DescriptionPProfLabel, description, PPIDPProfLabel, string(parentPID), PIDPProfLabel, string(pid), ProcessTypePProfLabel, processType))
|
pprofCtx := pprof.WithLabels(ctx, pprof.Labels(DescriptionPProfLabel, description, PPIDPProfLabel, string(parentPID), PIDPProfLabel, string(pid), ProcessTypePProfLabel, processType))
|
||||||
if currentlyRunning {
|
if currentlyRunning {
|
||||||
@ -185,18 +199,12 @@ func (pm *Manager) nextPID() (start time.Time, pid IDType) {
|
|||||||
return start, pid
|
return start, pid
|
||||||
}
|
}
|
||||||
|
|
||||||
// Remove a process from the ProcessManager.
|
|
||||||
func (pm *Manager) Remove(pid IDType) {
|
|
||||||
pm.mutex.Lock()
|
|
||||||
delete(pm.processMap, pid)
|
|
||||||
pm.mutex.Unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pm *Manager) remove(process *process) {
|
func (pm *Manager) remove(process *process) {
|
||||||
pm.mutex.Lock()
|
pm.mutex.Lock()
|
||||||
defer pm.mutex.Unlock()
|
defer pm.mutex.Unlock()
|
||||||
if p := pm.processMap[process.PID]; p == process {
|
if p := pm.processMap[process.PID]; p == process {
|
||||||
delete(pm.processMap, process.PID)
|
delete(pm.processMap, process.PID)
|
||||||
|
Trace(false, process.PID, process.Description, process.ParentPID, process.Type)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -82,7 +82,7 @@ func TestManager_Remove(t *testing.T) {
|
|||||||
|
|
||||||
assert.NotEqual(t, GetContext(p1Ctx).GetPID(), GetContext(p2Ctx).GetPID(), "expected to get different pids got %s == %s", GetContext(p2Ctx).GetPID(), GetContext(p1Ctx).GetPID())
|
assert.NotEqual(t, GetContext(p1Ctx).GetPID(), GetContext(p2Ctx).GetPID(), "expected to get different pids got %s == %s", GetContext(p2Ctx).GetPID(), GetContext(p1Ctx).GetPID())
|
||||||
|
|
||||||
pm.Remove(GetPID(p2Ctx))
|
finished()
|
||||||
|
|
||||||
_, exists := pm.processMap[GetPID(p2Ctx)]
|
_, exists := pm.processMap[GetPID(p2Ctx)]
|
||||||
assert.False(t, exists, "PID %d is in the list but shouldn't", GetPID(p2Ctx))
|
assert.False(t, exists, "PID %d is in the list but shouldn't", GetPID(p2Ctx))
|
||||||
|
@ -316,14 +316,13 @@ func initRepoCommit(ctx context.Context, tmpPath string, repo *repo_model.Reposi
|
|||||||
return fmt.Errorf("git add --all: %w", err)
|
return fmt.Errorf("git add --all: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
cmd := git.NewCommand(ctx,
|
cmd := git.NewCommand(ctx, "commit").
|
||||||
"commit", git.CmdArg(fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email)),
|
AddOptionFormat("--author='%s <%s>'", sig.Name, sig.Email).
|
||||||
"-m", "Initial commit",
|
AddOptionValues("-m", "Initial commit")
|
||||||
)
|
|
||||||
|
|
||||||
sign, keyID, signer, _ := asymkey_service.SignInitialCommit(ctx, tmpPath, u)
|
sign, keyID, signer, _ := asymkey_service.SignInitialCommit(ctx, tmpPath, u)
|
||||||
if sign {
|
if sign {
|
||||||
cmd.AddArguments(git.CmdArg("-S" + keyID))
|
cmd.AddOptionFormat("-S%s", keyID)
|
||||||
|
|
||||||
if repo.GetTrustModel() == repo_model.CommitterTrustModel || repo.GetTrustModel() == repo_model.CollaboratorCommitterTrustModel {
|
if repo.GetTrustModel() == repo_model.CommitterTrustModel || repo.GetTrustModel() == repo_model.CollaboratorCommitterTrustModel {
|
||||||
// need to set the committer to the KeyID owner
|
// need to set the committer to the KeyID owner
|
||||||
|
@ -6,6 +6,7 @@ package setting
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"math"
|
"math"
|
||||||
"net"
|
"net"
|
||||||
@ -466,8 +467,7 @@ func getAppPath() (string, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// FIXME: Once we switch to go 1.19 use !errors.Is(err, exec.ErrDot)
|
if !errors.Is(err, exec.ErrDot) {
|
||||||
if !strings.Contains(err.Error(), "cannot run executable found relative to current directory") {
|
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
appPath, err = filepath.Abs(os.Args[0])
|
appPath, err = filepath.Abs(os.Args[0])
|
||||||
|
@ -217,7 +217,7 @@ func renderBlame(ctx *context.Context, blameParts []git.BlamePart, commitNames m
|
|||||||
|
|
||||||
filename2attribute2info, err := ctx.Repo.GitRepo.CheckAttribute(git.CheckAttributeOpts{
|
filename2attribute2info, err := ctx.Repo.GitRepo.CheckAttribute(git.CheckAttributeOpts{
|
||||||
CachedOnly: true,
|
CachedOnly: true,
|
||||||
Attributes: []git.CmdArg{"linguist-language", "gitlab-language"},
|
Attributes: []string{"linguist-language", "gitlab-language"},
|
||||||
Filenames: []string{ctx.Repo.TreePath},
|
Filenames: []string{ctx.Repo.TreePath},
|
||||||
IndexFile: indexFilename,
|
IndexFile: indexFilename,
|
||||||
WorkTree: worktree,
|
WorkTree: worktree,
|
||||||
|
@ -560,7 +560,7 @@ func ParseCompareInfo(ctx *context.Context) *CompareInfo {
|
|||||||
func PrepareCompareDiff(
|
func PrepareCompareDiff(
|
||||||
ctx *context.Context,
|
ctx *context.Context,
|
||||||
ci *CompareInfo,
|
ci *CompareInfo,
|
||||||
whitespaceBehavior git.CmdArg,
|
whitespaceBehavior git.TrustedCmdArgs,
|
||||||
) bool {
|
) bool {
|
||||||
var (
|
var (
|
||||||
repo = ctx.Repo.Repository
|
repo = ctx.Repo.Repository
|
||||||
|
@ -498,7 +498,8 @@ func serviceRPC(ctx gocontext.Context, h serviceHandler, service string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var stderr bytes.Buffer
|
var stderr bytes.Buffer
|
||||||
cmd := git.NewCommand(h.r.Context(), git.CmdArgCheck(service), "--stateless-rpc").AddDynamicArguments(h.dir)
|
// the service is generated by ourselves, so it's safe to trust it
|
||||||
|
cmd := git.NewCommand(h.r.Context(), git.ToTrustedCmdArgs([]string{service})...).AddArguments("--stateless-rpc").AddDynamicArguments(h.dir)
|
||||||
cmd.SetDescription(fmt.Sprintf("%s %s %s [repo_path: %s]", git.GitExecutable, service, "--stateless-rpc", h.dir))
|
cmd.SetDescription(fmt.Sprintf("%s %s %s [repo_path: %s]", git.GitExecutable, service, "--stateless-rpc", h.dir))
|
||||||
if err := cmd.Run(&git.RunOpts{
|
if err := cmd.Run(&git.RunOpts{
|
||||||
Dir: h.dir,
|
Dir: h.dir,
|
||||||
@ -570,7 +571,8 @@ func GetInfoRefs(ctx *context.Context) {
|
|||||||
}
|
}
|
||||||
h.environ = append(os.Environ(), h.environ...)
|
h.environ = append(os.Environ(), h.environ...)
|
||||||
|
|
||||||
refs, _, err := git.NewCommand(ctx, git.CmdArgCheck(service), "--stateless-rpc", "--advertise-refs", ".").RunStdBytes(&git.RunOpts{Env: h.environ, Dir: h.dir})
|
// the service is generated by ourselves, so we can trust it
|
||||||
|
refs, _, err := git.NewCommand(ctx, git.ToTrustedCmdArgs([]string{service})...).AddArguments("--stateless-rpc", "--advertise-refs", ".").RunStdBytes(&git.RunOpts{Env: h.environ, Dir: h.dir})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error(fmt.Sprintf("%v - %s", err, string(refs)))
|
log.Error(fmt.Sprintf("%v - %s", err, string(refs)))
|
||||||
}
|
}
|
||||||
|
@ -146,7 +146,7 @@ func LFSLocks(ctx *context.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
name2attribute2info, err := gitRepo.CheckAttribute(git.CheckAttributeOpts{
|
name2attribute2info, err := gitRepo.CheckAttribute(git.CheckAttributeOpts{
|
||||||
Attributes: []git.CmdArg{"lockable"},
|
Attributes: []string{"lockable"},
|
||||||
Filenames: filenames,
|
Filenames: filenames,
|
||||||
CachedOnly: true,
|
CachedOnly: true,
|
||||||
})
|
})
|
||||||
|
@ -926,59 +926,54 @@ func MergePullRequest(ctx *context.Context) {
|
|||||||
pr := issue.PullRequest
|
pr := issue.PullRequest
|
||||||
pr.Issue = issue
|
pr.Issue = issue
|
||||||
pr.Issue.Repo = ctx.Repo.Repository
|
pr.Issue.Repo = ctx.Repo.Repository
|
||||||
manuallMerge := repo_model.MergeStyle(form.Do) == repo_model.MergeStyleManuallyMerged
|
manualMerge := repo_model.MergeStyle(form.Do) == repo_model.MergeStyleManuallyMerged
|
||||||
forceMerge := form.ForceMerge != nil && *form.ForceMerge
|
forceMerge := form.ForceMerge != nil && *form.ForceMerge
|
||||||
|
|
||||||
// start with merging by checking
|
// start with merging by checking
|
||||||
if err := pull_service.CheckPullMergable(ctx, ctx.Doer, &ctx.Repo.Permission, pr, manuallMerge, forceMerge); err != nil {
|
if err := pull_service.CheckPullMergable(ctx, ctx.Doer, &ctx.Repo.Permission, pr, manualMerge, forceMerge); err != nil {
|
||||||
if errors.Is(err, pull_service.ErrIsClosed) {
|
switch {
|
||||||
|
case errors.Is(err, pull_service.ErrIsClosed):
|
||||||
if issue.IsPull {
|
if issue.IsPull {
|
||||||
ctx.Flash.Error(ctx.Tr("repo.pulls.is_closed"))
|
ctx.Flash.Error(ctx.Tr("repo.pulls.is_closed"))
|
||||||
ctx.Redirect(issue.Link())
|
|
||||||
} else {
|
} else {
|
||||||
ctx.Flash.Error(ctx.Tr("repo.issues.closed_title"))
|
ctx.Flash.Error(ctx.Tr("repo.issues.closed_title"))
|
||||||
ctx.Redirect(issue.Link())
|
|
||||||
}
|
}
|
||||||
} else if errors.Is(err, pull_service.ErrUserNotAllowedToMerge) {
|
case errors.Is(err, pull_service.ErrUserNotAllowedToMerge):
|
||||||
ctx.Flash.Error(ctx.Tr("repo.pulls.update_not_allowed"))
|
ctx.Flash.Error(ctx.Tr("repo.pulls.update_not_allowed"))
|
||||||
ctx.Redirect(issue.Link())
|
case errors.Is(err, pull_service.ErrHasMerged):
|
||||||
} else if errors.Is(err, pull_service.ErrHasMerged) {
|
|
||||||
ctx.Flash.Error(ctx.Tr("repo.pulls.has_merged"))
|
ctx.Flash.Error(ctx.Tr("repo.pulls.has_merged"))
|
||||||
ctx.Redirect(issue.Link())
|
case errors.Is(err, pull_service.ErrIsWorkInProgress):
|
||||||
} else if errors.Is(err, pull_service.ErrIsWorkInProgress) {
|
|
||||||
ctx.Flash.Error(ctx.Tr("repo.pulls.no_merge_wip"))
|
ctx.Flash.Error(ctx.Tr("repo.pulls.no_merge_wip"))
|
||||||
ctx.Redirect(issue.Link())
|
case errors.Is(err, pull_service.ErrNotMergableState):
|
||||||
} else if errors.Is(err, pull_service.ErrNotMergableState) {
|
|
||||||
ctx.Flash.Error(ctx.Tr("repo.pulls.no_merge_not_ready"))
|
ctx.Flash.Error(ctx.Tr("repo.pulls.no_merge_not_ready"))
|
||||||
ctx.Redirect(issue.Link())
|
case models.IsErrDisallowedToMerge(err):
|
||||||
} else if models.IsErrDisallowedToMerge(err) {
|
|
||||||
ctx.Flash.Error(ctx.Tr("repo.pulls.no_merge_not_ready"))
|
ctx.Flash.Error(ctx.Tr("repo.pulls.no_merge_not_ready"))
|
||||||
ctx.Redirect(issue.Link())
|
case asymkey_service.IsErrWontSign(err):
|
||||||
} else if asymkey_service.IsErrWontSign(err) {
|
ctx.Flash.Error(err.Error()) // has no translation ...
|
||||||
ctx.Flash.Error(err.Error()) // has not translation ...
|
case errors.Is(err, pull_service.ErrDependenciesLeft):
|
||||||
ctx.Redirect(issue.Link())
|
|
||||||
} else if errors.Is(err, pull_service.ErrDependenciesLeft) {
|
|
||||||
ctx.Flash.Error(ctx.Tr("repo.issues.dependency.pr_close_blocked"))
|
ctx.Flash.Error(ctx.Tr("repo.issues.dependency.pr_close_blocked"))
|
||||||
ctx.Redirect(issue.Link())
|
default:
|
||||||
} else {
|
|
||||||
ctx.ServerError("WebCheck", err)
|
ctx.ServerError("WebCheck", err)
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
ctx.Redirect(issue.Link())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// handle manually-merged mark
|
// handle manually-merged mark
|
||||||
if manuallMerge {
|
if manualMerge {
|
||||||
if err := pull_service.MergedManually(pr, ctx.Doer, ctx.Repo.GitRepo, form.MergeCommitID); err != nil {
|
if err := pull_service.MergedManually(pr, ctx.Doer, ctx.Repo.GitRepo, form.MergeCommitID); err != nil {
|
||||||
if models.IsErrInvalidMergeStyle(err) {
|
switch {
|
||||||
|
|
||||||
|
case models.IsErrInvalidMergeStyle(err):
|
||||||
ctx.Flash.Error(ctx.Tr("repo.pulls.invalid_merge_option"))
|
ctx.Flash.Error(ctx.Tr("repo.pulls.invalid_merge_option"))
|
||||||
ctx.Redirect(issue.Link())
|
case strings.Contains(err.Error(), "Wrong commit ID"):
|
||||||
} else if strings.Contains(err.Error(), "Wrong commit ID") {
|
|
||||||
ctx.Flash.Error(ctx.Tr("repo.pulls.wrong_commit_id"))
|
ctx.Flash.Error(ctx.Tr("repo.pulls.wrong_commit_id"))
|
||||||
ctx.Redirect(issue.Link())
|
default:
|
||||||
} else {
|
|
||||||
ctx.ServerError("MergedManually", err)
|
ctx.ServerError("MergedManually", err)
|
||||||
|
return
|
||||||
}
|
}
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx.Redirect(issue.Link())
|
ctx.Redirect(issue.Link())
|
||||||
|
@ -509,7 +509,7 @@ func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink st
|
|||||||
|
|
||||||
filename2attribute2info, err := ctx.Repo.GitRepo.CheckAttribute(git.CheckAttributeOpts{
|
filename2attribute2info, err := ctx.Repo.GitRepo.CheckAttribute(git.CheckAttributeOpts{
|
||||||
CachedOnly: true,
|
CachedOnly: true,
|
||||||
Attributes: []git.CmdArg{"linguist-language", "gitlab-language"},
|
Attributes: []string{"linguist-language", "gitlab-language"},
|
||||||
Filenames: []string{ctx.Repo.TreePath},
|
Filenames: []string{ctx.Repo.TreePath},
|
||||||
IndexFile: indexFilename,
|
IndexFile: indexFilename,
|
||||||
WorkTree: worktree,
|
WorkTree: worktree,
|
||||||
|
@ -164,7 +164,7 @@ func getPullRequestsByHeadSHA(ctx context.Context, sha string, repo *repo_model.
|
|||||||
|
|
||||||
func handlePull(pullID int64, sha string) {
|
func handlePull(pullID int64, sha string) {
|
||||||
ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(),
|
ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(),
|
||||||
fmt.Sprintf("Handle AutoMerge of pull[%d] with sha[%s]", pullID, sha))
|
fmt.Sprintf("Handle AutoMerge of PR[%d] with sha[%s]", pullID, sha))
|
||||||
defer finished()
|
defer finished()
|
||||||
|
|
||||||
pr, err := issues_model.GetPullRequestByID(ctx, pullID)
|
pr, err := issues_model.GetPullRequestByID(ctx, pullID)
|
||||||
@ -176,7 +176,7 @@ func handlePull(pullID int64, sha string) {
|
|||||||
// Check if there is a scheduled pr in the db
|
// Check if there is a scheduled pr in the db
|
||||||
exists, scheduledPRM, err := pull_model.GetScheduledMergeByPullID(ctx, pr.ID)
|
exists, scheduledPRM, err := pull_model.GetScheduledMergeByPullID(ctx, pr.ID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("pull[%d] GetScheduledMergeByPullID: %v", pr.ID, err)
|
log.Error("%-v GetScheduledMergeByPullID: %v", pr, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if !exists {
|
if !exists {
|
||||||
@ -188,13 +188,13 @@ func handlePull(pullID int64, sha string) {
|
|||||||
// did not succeed or was not finished yet.
|
// did not succeed or was not finished yet.
|
||||||
|
|
||||||
if err = pr.LoadHeadRepo(ctx); err != nil {
|
if err = pr.LoadHeadRepo(ctx); err != nil {
|
||||||
log.Error("pull[%d] LoadHeadRepo: %v", pr.ID, err)
|
log.Error("%-v LoadHeadRepo: %v", pr, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
headGitRepo, err := git.OpenRepository(ctx, pr.HeadRepo.RepoPath())
|
headGitRepo, err := git.OpenRepository(ctx, pr.HeadRepo.RepoPath())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("OpenRepository: %v", err)
|
log.Error("OpenRepository %-v: %v", pr.HeadRepo, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
defer headGitRepo.Close()
|
defer headGitRepo.Close()
|
||||||
@ -202,40 +202,40 @@ func handlePull(pullID int64, sha string) {
|
|||||||
headBranchExist := headGitRepo.IsBranchExist(pr.HeadBranch)
|
headBranchExist := headGitRepo.IsBranchExist(pr.HeadBranch)
|
||||||
|
|
||||||
if pr.HeadRepo == nil || !headBranchExist {
|
if pr.HeadRepo == nil || !headBranchExist {
|
||||||
log.Warn("Head branch of auto merge pr does not exist [HeadRepoID: %d, Branch: %s, PR ID: %d]", pr.HeadRepoID, pr.HeadBranch, pr.ID)
|
log.Warn("Head branch of auto merge %-v does not exist [HeadRepoID: %d, Branch: %s]", pr, pr.HeadRepoID, pr.HeadBranch)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if all checks succeeded
|
// Check if all checks succeeded
|
||||||
pass, err := pull_service.IsPullCommitStatusPass(ctx, pr)
|
pass, err := pull_service.IsPullCommitStatusPass(ctx, pr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("IsPullCommitStatusPass: %v", err)
|
log.Error("%-v IsPullCommitStatusPass: %v", pr, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if !pass {
|
if !pass {
|
||||||
log.Info("Scheduled auto merge pr has unsuccessful status checks [PullID: %d]", pr.ID)
|
log.Info("Scheduled auto merge %-v has unsuccessful status checks", pr)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Merge if all checks succeeded
|
// Merge if all checks succeeded
|
||||||
doer, err := user_model.GetUserByID(ctx, scheduledPRM.DoerID)
|
doer, err := user_model.GetUserByID(ctx, scheduledPRM.DoerID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("GetUserByIDCtx: %v", err)
|
log.Error("Unable to get scheduled User[%d]: %v", scheduledPRM.DoerID, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
perm, err := access_model.GetUserRepoPermission(ctx, pr.HeadRepo, doer)
|
perm, err := access_model.GetUserRepoPermission(ctx, pr.HeadRepo, doer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("GetUserRepoPermission: %v", err)
|
log.Error("GetUserRepoPermission %-v: %v", pr.HeadRepo, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := pull_service.CheckPullMergable(ctx, doer, &perm, pr, false, false); err != nil {
|
if err := pull_service.CheckPullMergable(ctx, doer, &perm, pr, false, false); err != nil {
|
||||||
if errors.Is(pull_service.ErrUserNotAllowedToMerge, err) {
|
if errors.Is(pull_service.ErrUserNotAllowedToMerge, err) {
|
||||||
log.Info("PR %d was scheduled to automerge by an unauthorized user", pr.ID)
|
log.Info("%-v was scheduled to automerge by an unauthorized user", pr)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
log.Error("pull[%d] CheckPullMergable: %v", pr.ID, err)
|
log.Error("%-v CheckPullMergable: %v", pr, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -244,13 +244,13 @@ func handlePull(pullID int64, sha string) {
|
|||||||
baseGitRepo = headGitRepo
|
baseGitRepo = headGitRepo
|
||||||
} else {
|
} else {
|
||||||
if err = pr.LoadBaseRepo(ctx); err != nil {
|
if err = pr.LoadBaseRepo(ctx); err != nil {
|
||||||
log.Error("LoadBaseRepo: %v", err)
|
log.Error("%-v LoadBaseRepo: %v", pr, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
baseGitRepo, err = git.OpenRepository(ctx, pr.BaseRepo.RepoPath())
|
baseGitRepo, err = git.OpenRepository(ctx, pr.BaseRepo.RepoPath())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("OpenRepository: %v", err)
|
log.Error("OpenRepository %-v: %v", pr.BaseRepo, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
defer baseGitRepo.Close()
|
defer baseGitRepo.Close()
|
||||||
|
@ -59,11 +59,7 @@ func registerRepoHealthCheck() {
|
|||||||
}, func(ctx context.Context, _ *user_model.User, config Config) error {
|
}, func(ctx context.Context, _ *user_model.User, config Config) error {
|
||||||
rhcConfig := config.(*RepoHealthCheckConfig)
|
rhcConfig := config.(*RepoHealthCheckConfig)
|
||||||
// the git args are set by config, they can be safe to be trusted
|
// the git args are set by config, they can be safe to be trusted
|
||||||
args := make([]git.CmdArg, 0, len(rhcConfig.Args))
|
return repo_service.GitFsckRepos(ctx, rhcConfig.Timeout, git.ToTrustedCmdArgs(rhcConfig.Args))
|
||||||
for _, arg := range rhcConfig.Args {
|
|
||||||
args = append(args, git.CmdArg(arg))
|
|
||||||
}
|
|
||||||
return repo_service.GitFsckRepos(ctx, rhcConfig.Timeout, args)
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -61,11 +61,7 @@ func registerGarbageCollectRepositories() {
|
|||||||
}, func(ctx context.Context, _ *user_model.User, config Config) error {
|
}, func(ctx context.Context, _ *user_model.User, config Config) error {
|
||||||
rhcConfig := config.(*RepoHealthCheckConfig)
|
rhcConfig := config.(*RepoHealthCheckConfig)
|
||||||
// the git args are set by config, they can be safe to be trusted
|
// the git args are set by config, they can be safe to be trusted
|
||||||
args := make([]git.CmdArg, 0, len(rhcConfig.Args))
|
return repo_service.GitGcRepos(ctx, rhcConfig.Timeout, git.ToTrustedCmdArgs(rhcConfig.Args))
|
||||||
for _, arg := range rhcConfig.Args {
|
|
||||||
args = append(args, git.CmdArg(arg))
|
|
||||||
}
|
|
||||||
return repo_service.GitGcRepos(ctx, rhcConfig.Timeout, args...)
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1056,7 +1056,7 @@ type DiffOptions struct {
|
|||||||
MaxLines int
|
MaxLines int
|
||||||
MaxLineCharacters int
|
MaxLineCharacters int
|
||||||
MaxFiles int
|
MaxFiles int
|
||||||
WhitespaceBehavior git.CmdArg
|
WhitespaceBehavior git.TrustedCmdArgs
|
||||||
DirectComparison bool
|
DirectComparison bool
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1071,38 +1071,22 @@ func GetDiff(gitRepo *git.Repository, opts *DiffOptions, files ...string) (*Diff
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
argsLength := 6
|
cmdDiff := git.NewCommand(gitRepo.Ctx)
|
||||||
if len(opts.WhitespaceBehavior) > 0 {
|
|
||||||
argsLength++
|
|
||||||
}
|
|
||||||
if len(opts.SkipTo) > 0 {
|
|
||||||
argsLength++
|
|
||||||
}
|
|
||||||
if len(files) > 0 {
|
|
||||||
argsLength += len(files) + 1
|
|
||||||
}
|
|
||||||
|
|
||||||
diffArgs := make([]git.CmdArg, 0, argsLength)
|
|
||||||
if (len(opts.BeforeCommitID) == 0 || opts.BeforeCommitID == git.EmptySHA) && commit.ParentCount() == 0 {
|
if (len(opts.BeforeCommitID) == 0 || opts.BeforeCommitID == git.EmptySHA) && commit.ParentCount() == 0 {
|
||||||
diffArgs = append(diffArgs, "diff", "--src-prefix=\\a/", "--dst-prefix=\\b/", "-M")
|
cmdDiff.AddArguments("diff", "--src-prefix=\\a/", "--dst-prefix=\\b/", "-M").
|
||||||
if len(opts.WhitespaceBehavior) != 0 {
|
AddArguments(opts.WhitespaceBehavior...).
|
||||||
diffArgs = append(diffArgs, opts.WhitespaceBehavior)
|
AddArguments("4b825dc642cb6eb9a060e54bf8d69288fbee4904"). // append empty tree ref
|
||||||
}
|
AddDynamicArguments(opts.AfterCommitID)
|
||||||
// append empty tree ref
|
|
||||||
diffArgs = append(diffArgs, "4b825dc642cb6eb9a060e54bf8d69288fbee4904")
|
|
||||||
diffArgs = append(diffArgs, git.CmdArgCheck(opts.AfterCommitID))
|
|
||||||
} else {
|
} else {
|
||||||
actualBeforeCommitID := opts.BeforeCommitID
|
actualBeforeCommitID := opts.BeforeCommitID
|
||||||
if len(actualBeforeCommitID) == 0 {
|
if len(actualBeforeCommitID) == 0 {
|
||||||
parentCommit, _ := commit.Parent(0)
|
parentCommit, _ := commit.Parent(0)
|
||||||
actualBeforeCommitID = parentCommit.ID.String()
|
actualBeforeCommitID = parentCommit.ID.String()
|
||||||
}
|
}
|
||||||
diffArgs = append(diffArgs, "diff", "--src-prefix=\\a/", "--dst-prefix=\\b/", "-M")
|
|
||||||
if len(opts.WhitespaceBehavior) != 0 {
|
cmdDiff.AddArguments("diff", "--src-prefix=\\a/", "--dst-prefix=\\b/", "-M").
|
||||||
diffArgs = append(diffArgs, opts.WhitespaceBehavior)
|
AddArguments(opts.WhitespaceBehavior...).
|
||||||
}
|
AddDynamicArguments(actualBeforeCommitID, opts.AfterCommitID)
|
||||||
diffArgs = append(diffArgs, git.CmdArgCheck(actualBeforeCommitID))
|
|
||||||
diffArgs = append(diffArgs, git.CmdArgCheck(opts.AfterCommitID))
|
|
||||||
opts.BeforeCommitID = actualBeforeCommitID
|
opts.BeforeCommitID = actualBeforeCommitID
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1111,16 +1095,11 @@ func GetDiff(gitRepo *git.Repository, opts *DiffOptions, files ...string) (*Diff
|
|||||||
// the skipping for us
|
// the skipping for us
|
||||||
parsePatchSkipToFile := opts.SkipTo
|
parsePatchSkipToFile := opts.SkipTo
|
||||||
if opts.SkipTo != "" && git.CheckGitVersionAtLeast("2.31") == nil {
|
if opts.SkipTo != "" && git.CheckGitVersionAtLeast("2.31") == nil {
|
||||||
diffArgs = append(diffArgs, git.CmdArg("--skip-to="+opts.SkipTo))
|
cmdDiff.AddOptionFormat("--skip-to=%s", opts.SkipTo)
|
||||||
parsePatchSkipToFile = ""
|
parsePatchSkipToFile = ""
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(files) > 0 {
|
cmdDiff.AddDashesAndList(files...)
|
||||||
diffArgs = append(diffArgs, "--")
|
|
||||||
for _, file := range files {
|
|
||||||
diffArgs = append(diffArgs, git.CmdArg(file)) // it's safe to cast it to CmdArg because there is a "--" before
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
reader, writer := io.Pipe()
|
reader, writer := io.Pipe()
|
||||||
defer func() {
|
defer func() {
|
||||||
@ -1128,10 +1107,9 @@ func GetDiff(gitRepo *git.Repository, opts *DiffOptions, files ...string) (*Diff
|
|||||||
_ = writer.Close()
|
_ = writer.Close()
|
||||||
}()
|
}()
|
||||||
|
|
||||||
go func(ctx context.Context, diffArgs []git.CmdArg, repoPath string, writer *io.PipeWriter) {
|
go func() {
|
||||||
cmd := git.NewCommand(ctx, diffArgs...)
|
cmdDiff.SetDescription(fmt.Sprintf("GetDiffRange [repo_path: %s]", repoPath))
|
||||||
cmd.SetDescription(fmt.Sprintf("GetDiffRange [repo_path: %s]", repoPath))
|
if err := cmdDiff.Run(&git.RunOpts{
|
||||||
if err := cmd.Run(&git.RunOpts{
|
|
||||||
Timeout: time.Duration(setting.Git.Timeout.Default) * time.Second,
|
Timeout: time.Duration(setting.Git.Timeout.Default) * time.Second,
|
||||||
Dir: repoPath,
|
Dir: repoPath,
|
||||||
Stderr: os.Stderr,
|
Stderr: os.Stderr,
|
||||||
@ -1141,7 +1119,7 @@ func GetDiff(gitRepo *git.Repository, opts *DiffOptions, files ...string) (*Diff
|
|||||||
}
|
}
|
||||||
|
|
||||||
_ = writer.Close()
|
_ = writer.Close()
|
||||||
}(gitRepo.Ctx, diffArgs, repoPath, writer)
|
}()
|
||||||
|
|
||||||
diff, err := ParsePatch(opts.MaxLines, opts.MaxLineCharacters, opts.MaxFiles, reader, parsePatchSkipToFile)
|
diff, err := ParsePatch(opts.MaxLines, opts.MaxLineCharacters, opts.MaxFiles, reader, parsePatchSkipToFile)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -1201,16 +1179,16 @@ func GetDiff(gitRepo *git.Repository, opts *DiffOptions, files ...string) (*Diff
|
|||||||
separator = ".."
|
separator = ".."
|
||||||
}
|
}
|
||||||
|
|
||||||
shortstatArgs := []git.CmdArg{git.CmdArgCheck(opts.BeforeCommitID + separator + opts.AfterCommitID)}
|
diffPaths := []string{opts.BeforeCommitID + separator + opts.AfterCommitID}
|
||||||
if len(opts.BeforeCommitID) == 0 || opts.BeforeCommitID == git.EmptySHA {
|
if len(opts.BeforeCommitID) == 0 || opts.BeforeCommitID == git.EmptySHA {
|
||||||
shortstatArgs = []git.CmdArg{git.EmptyTreeSHA, git.CmdArgCheck(opts.AfterCommitID)}
|
diffPaths = []string{git.EmptyTreeSHA, opts.AfterCommitID}
|
||||||
}
|
}
|
||||||
diff.NumFiles, diff.TotalAddition, diff.TotalDeletion, err = git.GetDiffShortStat(gitRepo.Ctx, repoPath, shortstatArgs...)
|
diff.NumFiles, diff.TotalAddition, diff.TotalDeletion, err = git.GetDiffShortStat(gitRepo.Ctx, repoPath, nil, diffPaths...)
|
||||||
if err != nil && strings.Contains(err.Error(), "no merge base") {
|
if err != nil && strings.Contains(err.Error(), "no merge base") {
|
||||||
// git >= 2.28 now returns an error if base and head have become unrelated.
|
// git >= 2.28 now returns an error if base and head have become unrelated.
|
||||||
// previously it would return the results of git diff --shortstat base head so let's try that...
|
// previously it would return the results of git diff --shortstat base head so let's try that...
|
||||||
shortstatArgs = []git.CmdArg{git.CmdArgCheck(opts.BeforeCommitID), git.CmdArgCheck(opts.AfterCommitID)}
|
diffPaths = []string{opts.BeforeCommitID, opts.AfterCommitID}
|
||||||
diff.NumFiles, diff.TotalAddition, diff.TotalDeletion, err = git.GetDiffShortStat(gitRepo.Ctx, repoPath, shortstatArgs...)
|
diff.NumFiles, diff.TotalAddition, diff.TotalDeletion, err = git.GetDiffShortStat(gitRepo.Ctx, repoPath, nil, diffPaths...)
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -1324,17 +1302,17 @@ func CommentMustAsDiff(c *issues_model.Comment) *Diff {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// GetWhitespaceFlag returns git diff flag for treating whitespaces
|
// GetWhitespaceFlag returns git diff flag for treating whitespaces
|
||||||
func GetWhitespaceFlag(whitespaceBehavior string) git.CmdArg {
|
func GetWhitespaceFlag(whitespaceBehavior string) git.TrustedCmdArgs {
|
||||||
whitespaceFlags := map[string]string{
|
whitespaceFlags := map[string]git.TrustedCmdArgs{
|
||||||
"ignore-all": "-w",
|
"ignore-all": {"-w"},
|
||||||
"ignore-change": "-b",
|
"ignore-change": {"-b"},
|
||||||
"ignore-eol": "--ignore-space-at-eol",
|
"ignore-eol": {"--ignore-space-at-eol"},
|
||||||
"show-all": "",
|
"show-all": nil,
|
||||||
}
|
}
|
||||||
|
|
||||||
if flag, ok := whitespaceFlags[whitespaceBehavior]; ok {
|
if flag, ok := whitespaceFlags[whitespaceBehavior]; ok {
|
||||||
return git.CmdArg(flag)
|
return flag
|
||||||
}
|
}
|
||||||
log.Warn("unknown whitespace behavior: %q, default to 'show-all'", whitespaceBehavior)
|
log.Warn("unknown whitespace behavior: %q, default to 'show-all'", whitespaceBehavior)
|
||||||
return ""
|
return nil
|
||||||
}
|
}
|
||||||
|
@ -626,7 +626,7 @@ func TestGetDiffRangeWithWhitespaceBehavior(t *testing.T) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
defer gitRepo.Close()
|
defer gitRepo.Close()
|
||||||
for _, behavior := range []git.CmdArg{"-w", "--ignore-space-at-eol", "-b", ""} {
|
for _, behavior := range []git.TrustedCmdArgs{{"-w"}, {"--ignore-space-at-eol"}, {"-b"}, nil} {
|
||||||
diffs, err := GetDiff(gitRepo,
|
diffs, err := GetDiff(gitRepo,
|
||||||
&DiffOptions{
|
&DiffOptions{
|
||||||
AfterCommitID: "bd7063cc7c04689c4d082183d32a604ed27a24f9",
|
AfterCommitID: "bd7063cc7c04689c4d082183d32a604ed27a24f9",
|
||||||
|
@ -203,11 +203,11 @@ func runSync(ctx context.Context, m *repo_model.Mirror) ([]*mirrorSyncResult, bo
|
|||||||
|
|
||||||
log.Trace("SyncMirrors [repo: %-v]: running git remote update...", m.Repo)
|
log.Trace("SyncMirrors [repo: %-v]: running git remote update...", m.Repo)
|
||||||
|
|
||||||
gitArgs := []git.CmdArg{"remote", "update"}
|
cmd := git.NewCommand(ctx, "remote", "update")
|
||||||
if m.EnablePrune {
|
if m.EnablePrune {
|
||||||
gitArgs = append(gitArgs, "--prune")
|
cmd.AddArguments("--prune")
|
||||||
}
|
}
|
||||||
gitArgs = append(gitArgs, git.CmdArgCheck(m.GetRemoteName()))
|
cmd.AddDynamicArguments(m.GetRemoteName())
|
||||||
|
|
||||||
remoteURL, remoteErr := git.GetRemoteURL(ctx, repoPath, m.GetRemoteName())
|
remoteURL, remoteErr := git.GetRemoteURL(ctx, repoPath, m.GetRemoteName())
|
||||||
if remoteErr != nil {
|
if remoteErr != nil {
|
||||||
@ -217,7 +217,7 @@ func runSync(ctx context.Context, m *repo_model.Mirror) ([]*mirrorSyncResult, bo
|
|||||||
|
|
||||||
stdoutBuilder := strings.Builder{}
|
stdoutBuilder := strings.Builder{}
|
||||||
stderrBuilder := strings.Builder{}
|
stderrBuilder := strings.Builder{}
|
||||||
if err := git.NewCommand(ctx, gitArgs...).
|
if err := cmd.
|
||||||
SetDescription(fmt.Sprintf("Mirror.runSync: %s", m.Repo.FullName())).
|
SetDescription(fmt.Sprintf("Mirror.runSync: %s", m.Repo.FullName())).
|
||||||
Run(&git.RunOpts{
|
Run(&git.RunOpts{
|
||||||
Timeout: timeout,
|
Timeout: timeout,
|
||||||
@ -243,7 +243,7 @@ func runSync(ctx context.Context, m *repo_model.Mirror) ([]*mirrorSyncResult, bo
|
|||||||
// Successful prune - reattempt mirror
|
// Successful prune - reattempt mirror
|
||||||
stderrBuilder.Reset()
|
stderrBuilder.Reset()
|
||||||
stdoutBuilder.Reset()
|
stdoutBuilder.Reset()
|
||||||
if err = git.NewCommand(ctx, gitArgs...).
|
if err = cmd.
|
||||||
SetDescription(fmt.Sprintf("Mirror.runSync: %s", m.Repo.FullName())).
|
SetDescription(fmt.Sprintf("Mirror.runSync: %s", m.Repo.FullName())).
|
||||||
Run(&git.RunOpts{
|
Run(&git.RunOpts{
|
||||||
Timeout: timeout,
|
Timeout: timeout,
|
||||||
|
@ -37,10 +37,10 @@ func AddPushMirrorRemote(ctx context.Context, m *repo_model.PushMirror, addr str
|
|||||||
if _, _, err := cmd.RunStdString(&git.RunOpts{Dir: path}); err != nil {
|
if _, _, err := cmd.RunStdString(&git.RunOpts{Dir: path}); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if _, _, err := git.NewCommand(ctx, "config", "--add", git.CmdArg("remote."+m.RemoteName+".push"), "+refs/heads/*:refs/heads/*").RunStdString(&git.RunOpts{Dir: path}); err != nil {
|
if _, _, err := git.NewCommand(ctx, "config", "--add").AddDynamicArguments("remote."+m.RemoteName+".push", "+refs/heads/*:refs/heads/*").RunStdString(&git.RunOpts{Dir: path}); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if _, _, err := git.NewCommand(ctx, "config", "--add", git.CmdArg("remote."+m.RemoteName+".push"), "+refs/tags/*:refs/tags/*").RunStdString(&git.RunOpts{Dir: path}); err != nil {
|
if _, _, err := git.NewCommand(ctx, "config", "--add").AddDynamicArguments("remote."+m.RemoteName+".push", "+refs/tags/*:refs/tags/*").RunStdString(&git.RunOpts{Dir: path}); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
|
@ -8,7 +8,6 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
@ -27,7 +26,6 @@ import (
|
|||||||
"code.gitea.io/gitea/modules/process"
|
"code.gitea.io/gitea/modules/process"
|
||||||
"code.gitea.io/gitea/modules/queue"
|
"code.gitea.io/gitea/modules/queue"
|
||||||
"code.gitea.io/gitea/modules/timeutil"
|
"code.gitea.io/gitea/modules/timeutil"
|
||||||
"code.gitea.io/gitea/modules/util"
|
|
||||||
asymkey_service "code.gitea.io/gitea/services/asymkey"
|
asymkey_service "code.gitea.io/gitea/services/asymkey"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -50,14 +48,14 @@ func AddToTaskQueue(pr *issues_model.PullRequest) {
|
|||||||
pr.Status = issues_model.PullRequestStatusChecking
|
pr.Status = issues_model.PullRequestStatusChecking
|
||||||
err := pr.UpdateColsIfNotMerged(db.DefaultContext, "status")
|
err := pr.UpdateColsIfNotMerged(db.DefaultContext, "status")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err)
|
log.Error("AddToTaskQueue(%-v).UpdateCols.(add to queue): %v", pr, err)
|
||||||
} else {
|
} else {
|
||||||
log.Trace("Adding PR ID: %d to the test pull requests queue", pr.ID)
|
log.Trace("Adding %-v to the test pull requests queue", pr)
|
||||||
}
|
}
|
||||||
return err
|
return err
|
||||||
})
|
})
|
||||||
if err != nil && err != queue.ErrAlreadyInQueue {
|
if err != nil && err != queue.ErrAlreadyInQueue {
|
||||||
log.Error("Error adding prID %d to the test pull requests queue: %v", pr.ID, err)
|
log.Error("Error adding %-v to the test pull requests queue: %v", pr, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -69,12 +67,14 @@ func CheckPullMergable(stdCtx context.Context, doer *user_model.User, perm *acce
|
|||||||
}
|
}
|
||||||
|
|
||||||
if err := pr.LoadIssue(ctx); err != nil {
|
if err := pr.LoadIssue(ctx); err != nil {
|
||||||
|
log.Error("Unable to load issue[%d] for %-v: %v", pr.IssueID, pr, err)
|
||||||
return err
|
return err
|
||||||
} else if pr.Issue.IsClosed {
|
} else if pr.Issue.IsClosed {
|
||||||
return ErrIsClosed
|
return ErrIsClosed
|
||||||
}
|
}
|
||||||
|
|
||||||
if allowedMerge, err := IsUserAllowedToMerge(ctx, pr, *perm, doer); err != nil {
|
if allowedMerge, err := IsUserAllowedToMerge(ctx, pr, *perm, doer); err != nil {
|
||||||
|
log.Error("Error whilst checking if %-v is allowed to merge %-v: %v", doer, pr, err)
|
||||||
return err
|
return err
|
||||||
} else if !allowedMerge {
|
} else if !allowedMerge {
|
||||||
return ErrUserNotAllowedToMerge
|
return ErrUserNotAllowedToMerge
|
||||||
@ -98,15 +98,19 @@ func CheckPullMergable(stdCtx context.Context, doer *user_model.User, perm *acce
|
|||||||
}
|
}
|
||||||
|
|
||||||
if err := CheckPullBranchProtections(ctx, pr, false); err != nil {
|
if err := CheckPullBranchProtections(ctx, pr, false); err != nil {
|
||||||
if models.IsErrDisallowedToMerge(err) {
|
if !models.IsErrDisallowedToMerge(err) {
|
||||||
if force {
|
log.Error("Error whilst checking pull branch protection for %-v: %v", pr, err)
|
||||||
if isRepoAdmin, err2 := access_model.IsUserRepoAdmin(ctx, pr.BaseRepo, doer); err2 != nil {
|
return err
|
||||||
return err2
|
}
|
||||||
} else if !isRepoAdmin {
|
|
||||||
return err
|
if !force {
|
||||||
}
|
return err
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
|
if isRepoAdmin, err2 := access_model.IsUserRepoAdmin(ctx, pr.BaseRepo, doer); err2 != nil {
|
||||||
|
log.Error("Unable to check if %-v is a repo admin in %-v: %v", doer, pr.BaseRepo, err2)
|
||||||
|
return err2
|
||||||
|
} else if !isRepoAdmin {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -144,7 +148,7 @@ func isSignedIfRequired(ctx context.Context, pr *issues_model.PullRequest, doer
|
|||||||
// checkAndUpdateStatus checks if pull request is possible to leaving checking status,
|
// checkAndUpdateStatus checks if pull request is possible to leaving checking status,
|
||||||
// and set to be either conflict or mergeable.
|
// and set to be either conflict or mergeable.
|
||||||
func checkAndUpdateStatus(ctx context.Context, pr *issues_model.PullRequest) {
|
func checkAndUpdateStatus(ctx context.Context, pr *issues_model.PullRequest) {
|
||||||
// Status is not changed to conflict means mergeable.
|
// If status has not been changed to conflict by testPatch then we are mergeable
|
||||||
if pr.Status == issues_model.PullRequestStatusChecking {
|
if pr.Status == issues_model.PullRequestStatusChecking {
|
||||||
pr.Status = issues_model.PullRequestStatusMergeable
|
pr.Status = issues_model.PullRequestStatusMergeable
|
||||||
}
|
}
|
||||||
@ -152,79 +156,69 @@ func checkAndUpdateStatus(ctx context.Context, pr *issues_model.PullRequest) {
|
|||||||
// Make sure there is no waiting test to process before leaving the checking status.
|
// Make sure there is no waiting test to process before leaving the checking status.
|
||||||
has, err := prPatchCheckerQueue.Has(strconv.FormatInt(pr.ID, 10))
|
has, err := prPatchCheckerQueue.Has(strconv.FormatInt(pr.ID, 10))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("Unable to check if the queue is waiting to reprocess pr.ID %d. Error: %v", pr.ID, err)
|
log.Error("Unable to check if the queue is waiting to reprocess %-v. Error: %v", pr, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if !has {
|
if has {
|
||||||
if err := pr.UpdateColsIfNotMerged(ctx, "merge_base", "status", "conflicted_files", "changed_protected_files"); err != nil {
|
log.Trace("Not updating status for %-v as it is due to be rechecked", pr)
|
||||||
log.Error("Update[%d]: %v", pr.ID, err)
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if err := pr.UpdateColsIfNotMerged(ctx, "merge_base", "status", "conflicted_files", "changed_protected_files"); err != nil {
|
||||||
|
log.Error("Update[%-v]: %v", pr, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// getMergeCommit checks if a pull request got merged
|
// getMergeCommit checks if a pull request has been merged
|
||||||
// Returns the git.Commit of the pull request if merged
|
// Returns the git.Commit of the pull request if merged
|
||||||
func getMergeCommit(ctx context.Context, pr *issues_model.PullRequest) (*git.Commit, error) {
|
func getMergeCommit(ctx context.Context, pr *issues_model.PullRequest) (*git.Commit, error) {
|
||||||
if pr.BaseRepo == nil {
|
if err := pr.LoadBaseRepo(ctx); err != nil {
|
||||||
var err error
|
return nil, fmt.Errorf("unable to load base repo for %s: %w", pr, err)
|
||||||
pr.BaseRepo, err = repo_model.GetRepositoryByID(ctx, pr.BaseRepoID)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("GetRepositoryByID: %w", err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
indexTmpPath, err := os.MkdirTemp(os.TempDir(), "gitea-"+pr.BaseRepo.Name)
|
prHeadRef := pr.GetGitRefName()
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("Failed to create temp dir for repository %s: %w", pr.BaseRepo.RepoPath(), err)
|
|
||||||
}
|
|
||||||
defer func() {
|
|
||||||
if err := util.RemoveAll(indexTmpPath); err != nil {
|
|
||||||
log.Warn("Unable to remove temporary index path: %s: Error: %v", indexTmpPath, err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
headFile := pr.GetGitRefName()
|
// Check if the pull request is merged into BaseBranch
|
||||||
|
if _, _, err := git.NewCommand(ctx, "merge-base", "--is-ancestor").
|
||||||
// Check if a pull request is merged into BaseBranch
|
AddDynamicArguments(prHeadRef, pr.BaseBranch).
|
||||||
_, _, err = git.NewCommand(ctx, "merge-base", "--is-ancestor").AddDynamicArguments(headFile, pr.BaseBranch).
|
RunStdString(&git.RunOpts{Dir: pr.BaseRepo.RepoPath()}); err != nil {
|
||||||
RunStdString(&git.RunOpts{Dir: pr.BaseRepo.RepoPath(), Env: []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()}})
|
|
||||||
if err != nil {
|
|
||||||
// Errors are signaled by a non-zero status that is not 1
|
|
||||||
if strings.Contains(err.Error(), "exit status 1") {
|
if strings.Contains(err.Error(), "exit status 1") {
|
||||||
|
// prHeadRef is not an ancestor of the base branch
|
||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
return nil, fmt.Errorf("git merge-base --is-ancestor: %w", err)
|
// Errors are signaled by a non-zero status that is not 1
|
||||||
|
return nil, fmt.Errorf("%-v git merge-base --is-ancestor: %w", pr, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
commitIDBytes, err := os.ReadFile(pr.BaseRepo.RepoPath() + "/" + headFile)
|
// If merge-base successfully exits then prHeadRef is an ancestor of pr.BaseBranch
|
||||||
|
|
||||||
|
// Find the head commit id
|
||||||
|
prHeadCommitID, err := git.GetFullCommitID(ctx, pr.BaseRepo.RepoPath(), prHeadRef)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("ReadFile(%s): %w", headFile, err)
|
return nil, fmt.Errorf("GetFullCommitID(%s) in %s: %w", prHeadRef, pr.BaseRepo.FullName(), err)
|
||||||
}
|
}
|
||||||
commitID := string(commitIDBytes)
|
|
||||||
if len(commitID) < git.SHAFullLength {
|
|
||||||
return nil, fmt.Errorf(`ReadFile(%s): invalid commit-ID "%s"`, headFile, commitID)
|
|
||||||
}
|
|
||||||
cmd := commitID[:git.SHAFullLength] + ".." + pr.BaseBranch
|
|
||||||
|
|
||||||
// Get the commit from BaseBranch where the pull request got merged
|
// Get the commit from BaseBranch where the pull request got merged
|
||||||
mergeCommit, _, err := git.NewCommand(ctx, "rev-list", "--ancestry-path", "--merges", "--reverse").AddDynamicArguments(cmd).
|
mergeCommit, _, err := git.NewCommand(ctx, "rev-list", "--ancestry-path", "--merges", "--reverse").
|
||||||
RunStdString(&git.RunOpts{Dir: "", Env: []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()}})
|
AddDynamicArguments(prHeadCommitID + ".." + pr.BaseBranch).
|
||||||
|
RunStdString(&git.RunOpts{Dir: pr.BaseRepo.RepoPath()})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("git rev-list --ancestry-path --merges --reverse: %w", err)
|
return nil, fmt.Errorf("git rev-list --ancestry-path --merges --reverse: %w", err)
|
||||||
} else if len(mergeCommit) < git.SHAFullLength {
|
} else if len(mergeCommit) < git.SHAFullLength {
|
||||||
// PR was maybe fast-forwarded, so just use last commit of PR
|
// PR was maybe fast-forwarded, so just use last commit of PR
|
||||||
mergeCommit = commitID[:git.SHAFullLength]
|
mergeCommit = prHeadCommitID
|
||||||
}
|
}
|
||||||
|
mergeCommit = strings.TrimSpace(mergeCommit)
|
||||||
|
|
||||||
gitRepo, err := git.OpenRepository(ctx, pr.BaseRepo.RepoPath())
|
gitRepo, err := git.OpenRepository(ctx, pr.BaseRepo.RepoPath())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("OpenRepository: %w", err)
|
return nil, fmt.Errorf("%-v OpenRepository: %w", pr.BaseRepo, err)
|
||||||
}
|
}
|
||||||
defer gitRepo.Close()
|
defer gitRepo.Close()
|
||||||
|
|
||||||
commit, err := gitRepo.GetCommit(mergeCommit[:git.SHAFullLength])
|
commit, err := gitRepo.GetCommit(mergeCommit)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("GetMergeCommit[%v]: %w", mergeCommit[:git.SHAFullLength], err)
|
return nil, fmt.Errorf("GetMergeCommit[%s]: %w", mergeCommit, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return commit, nil
|
return commit, nil
|
||||||
@ -234,7 +228,7 @@ func getMergeCommit(ctx context.Context, pr *issues_model.PullRequest) (*git.Com
|
|||||||
// When a pull request got manually merged mark the pull request as merged
|
// When a pull request got manually merged mark the pull request as merged
|
||||||
func manuallyMerged(ctx context.Context, pr *issues_model.PullRequest) bool {
|
func manuallyMerged(ctx context.Context, pr *issues_model.PullRequest) bool {
|
||||||
if err := pr.LoadBaseRepo(ctx); err != nil {
|
if err := pr.LoadBaseRepo(ctx); err != nil {
|
||||||
log.Error("PullRequest[%d].LoadBaseRepo: %v", pr.ID, err)
|
log.Error("%-v LoadBaseRepo: %v", pr, err)
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -244,47 +238,50 @@ func manuallyMerged(ctx context.Context, pr *issues_model.PullRequest) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
log.Error("PullRequest[%d].BaseRepo.GetUnit(unit.TypePullRequests): %v", pr.ID, err)
|
log.Error("%-v BaseRepo.GetUnit(unit.TypePullRequests): %v", pr, err)
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
commit, err := getMergeCommit(ctx, pr)
|
commit, err := getMergeCommit(ctx, pr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("PullRequest[%d].getMergeCommit: %v", pr.ID, err)
|
log.Error("%-v getMergeCommit: %v", pr, err)
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
if commit != nil {
|
|
||||||
pr.MergedCommitID = commit.ID.String()
|
|
||||||
pr.MergedUnix = timeutil.TimeStamp(commit.Author.When.Unix())
|
|
||||||
pr.Status = issues_model.PullRequestStatusManuallyMerged
|
|
||||||
merger, _ := user_model.GetUserByEmail(commit.Author.Email)
|
|
||||||
|
|
||||||
// When the commit author is unknown set the BaseRepo owner as merger
|
if commit == nil {
|
||||||
if merger == nil {
|
// no merge commit found
|
||||||
if pr.BaseRepo.Owner == nil {
|
return false
|
||||||
if err = pr.BaseRepo.GetOwner(ctx); err != nil {
|
|
||||||
log.Error("BaseRepo.GetOwner[%d]: %v", pr.ID, err)
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
merger = pr.BaseRepo.Owner
|
|
||||||
}
|
|
||||||
pr.Merger = merger
|
|
||||||
pr.MergerID = merger.ID
|
|
||||||
|
|
||||||
if merged, err := pr.SetMerged(ctx); err != nil {
|
|
||||||
log.Error("PullRequest[%d].setMerged : %v", pr.ID, err)
|
|
||||||
return false
|
|
||||||
} else if !merged {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
notification.NotifyMergePullRequest(ctx, merger, pr)
|
|
||||||
|
|
||||||
log.Info("manuallyMerged[%d]: Marked as manually merged into %s/%s by commit id: %s", pr.ID, pr.BaseRepo.Name, pr.BaseBranch, commit.ID.String())
|
|
||||||
return true
|
|
||||||
}
|
}
|
||||||
return false
|
|
||||||
|
pr.MergedCommitID = commit.ID.String()
|
||||||
|
pr.MergedUnix = timeutil.TimeStamp(commit.Author.When.Unix())
|
||||||
|
pr.Status = issues_model.PullRequestStatusManuallyMerged
|
||||||
|
merger, _ := user_model.GetUserByEmail(commit.Author.Email)
|
||||||
|
|
||||||
|
// When the commit author is unknown set the BaseRepo owner as merger
|
||||||
|
if merger == nil {
|
||||||
|
if pr.BaseRepo.Owner == nil {
|
||||||
|
if err = pr.BaseRepo.GetOwner(ctx); err != nil {
|
||||||
|
log.Error("%-v BaseRepo.GetOwner: %v", pr, err)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
merger = pr.BaseRepo.Owner
|
||||||
|
}
|
||||||
|
pr.Merger = merger
|
||||||
|
pr.MergerID = merger.ID
|
||||||
|
|
||||||
|
if merged, err := pr.SetMerged(ctx); err != nil {
|
||||||
|
log.Error("%-v setMerged : %v", pr, err)
|
||||||
|
return false
|
||||||
|
} else if !merged {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
notification.NotifyMergePullRequest(ctx, merger, pr)
|
||||||
|
|
||||||
|
log.Info("manuallyMerged[%-v]: Marked as manually merged into %s/%s by commit id: %s", pr, pr.BaseRepo.Name, pr.BaseBranch, commit.ID.String())
|
||||||
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
// InitializePullRequests checks and tests untested patches of pull requests.
|
// InitializePullRequests checks and tests untested patches of pull requests.
|
||||||
@ -300,10 +297,10 @@ func InitializePullRequests(ctx context.Context) {
|
|||||||
return
|
return
|
||||||
default:
|
default:
|
||||||
if err := prPatchCheckerQueue.PushFunc(strconv.FormatInt(prID, 10), func() error {
|
if err := prPatchCheckerQueue.PushFunc(strconv.FormatInt(prID, 10), func() error {
|
||||||
log.Trace("Adding PR ID: %d to the pull requests patch checking queue", prID)
|
log.Trace("Adding PR[%d] to the pull requests patch checking queue", prID)
|
||||||
return nil
|
return nil
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
log.Error("Error adding prID: %s to the pull requests patch checking queue %v", prID, err)
|
log.Error("Error adding PR[%d] to the pull requests patch checking queue %v", prID, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -327,23 +324,30 @@ func testPR(id int64) {
|
|||||||
|
|
||||||
pr, err := issues_model.GetPullRequestByID(ctx, id)
|
pr, err := issues_model.GetPullRequestByID(ctx, id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("GetPullRequestByID[%d]: %v", id, err)
|
log.Error("Unable to GetPullRequestByID[%d] for testPR: %v", id, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
log.Trace("Testing %-v", pr)
|
||||||
|
defer func() {
|
||||||
|
log.Trace("Done testing %-v (status: %s)", pr, pr.Status)
|
||||||
|
}()
|
||||||
|
|
||||||
if pr.HasMerged {
|
if pr.HasMerged {
|
||||||
|
log.Trace("%-v is already merged (status: %s, merge commit: %s)", pr, pr.Status, pr.MergedCommitID)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if manuallyMerged(ctx, pr) {
|
if manuallyMerged(ctx, pr) {
|
||||||
|
log.Trace("%-v is manually merged (status: %s, merge commit: %s)", pr, pr.Status, pr.MergedCommitID)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := TestPatch(pr); err != nil {
|
if err := TestPatch(pr); err != nil {
|
||||||
log.Error("testPatch[%d]: %v", pr.ID, err)
|
log.Error("testPatch[%-v]: %v", pr, err)
|
||||||
pr.Status = issues_model.PullRequestStatusError
|
pr.Status = issues_model.PullRequestStatusError
|
||||||
if err := pr.UpdateCols("status"); err != nil {
|
if err := pr.UpdateCols("status"); err != nil {
|
||||||
log.Error("update pr [%d] status to PullRequestStatusError failed: %v", pr.ID, err)
|
log.Error("update pr [%-v] status to PullRequestStatusError failed: %v", pr, err)
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
@ -370,16 +370,16 @@ func rawMerge(ctx context.Context, pr *issues_model.PullRequest, doer *user_mode
|
|||||||
sig := doer.NewGitSig()
|
sig := doer.NewGitSig()
|
||||||
committer := sig
|
committer := sig
|
||||||
|
|
||||||
// Determine if we should sign
|
// Determine if we should sign. If no signKeyID, use --no-gpg-sign to countermand the sign config (from gitconfig)
|
||||||
var signArg git.CmdArg
|
var signArgs git.TrustedCmdArgs
|
||||||
sign, keyID, signer, _ := asymkey_service.SignMerge(ctx, pr, doer, tmpBasePath, "HEAD", trackingBranch)
|
sign, signKeyID, signer, _ := asymkey_service.SignMerge(ctx, pr, doer, tmpBasePath, "HEAD", trackingBranch)
|
||||||
if sign {
|
if sign {
|
||||||
signArg = git.CmdArg("-S" + keyID)
|
|
||||||
if pr.BaseRepo.GetTrustModel() == repo_model.CommitterTrustModel || pr.BaseRepo.GetTrustModel() == repo_model.CollaboratorCommitterTrustModel {
|
if pr.BaseRepo.GetTrustModel() == repo_model.CommitterTrustModel || pr.BaseRepo.GetTrustModel() == repo_model.CollaboratorCommitterTrustModel {
|
||||||
committer = signer
|
committer = signer
|
||||||
}
|
}
|
||||||
|
signArgs = git.ToTrustedCmdArgs([]string{"-S" + signKeyID})
|
||||||
} else {
|
} else {
|
||||||
signArg = git.CmdArg("--no-gpg-sign")
|
signArgs = append(signArgs, "--no-gpg-sign")
|
||||||
}
|
}
|
||||||
|
|
||||||
commitTimeStr := time.Now().Format(time.RFC3339)
|
commitTimeStr := time.Now().Format(time.RFC3339)
|
||||||
@ -403,7 +403,7 @@ func rawMerge(ctx context.Context, pr *issues_model.PullRequest, doer *user_mode
|
|||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := commitAndSignNoAuthor(ctx, pr, message, signArg, tmpBasePath, env); err != nil {
|
if err := commitAndSignNoAuthor(ctx, pr, message, signArgs, tmpBasePath, env); err != nil {
|
||||||
log.Error("Unable to make final commit: %v", err)
|
log.Error("Unable to make final commit: %v", err)
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
@ -505,7 +505,7 @@ func rawMerge(ctx context.Context, pr *issues_model.PullRequest, doer *user_mode
|
|||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
if mergeStyle == repo_model.MergeStyleRebaseMerge {
|
if mergeStyle == repo_model.MergeStyleRebaseMerge {
|
||||||
if err := commitAndSignNoAuthor(ctx, pr, message, signArg, tmpBasePath, env); err != nil {
|
if err := commitAndSignNoAuthor(ctx, pr, message, signArgs, tmpBasePath, env); err != nil {
|
||||||
log.Error("Unable to make final commit: %v", err)
|
log.Error("Unable to make final commit: %v", err)
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
@ -523,35 +523,22 @@ func rawMerge(ctx context.Context, pr *issues_model.PullRequest, doer *user_mode
|
|||||||
return "", fmt.Errorf("LoadPoster: %w", err)
|
return "", fmt.Errorf("LoadPoster: %w", err)
|
||||||
}
|
}
|
||||||
sig := pr.Issue.Poster.NewGitSig()
|
sig := pr.Issue.Poster.NewGitSig()
|
||||||
if signArg == "" {
|
if setting.Repository.PullRequest.AddCoCommitterTrailers && committer.String() != sig.String() {
|
||||||
if err := git.NewCommand(ctx, "commit", git.CmdArg(fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email)), "-m").AddDynamicArguments(message).
|
// add trailer
|
||||||
Run(&git.RunOpts{
|
message += fmt.Sprintf("\nCo-authored-by: %s\nCo-committed-by: %s\n", sig.String(), sig.String())
|
||||||
Env: env,
|
}
|
||||||
Dir: tmpBasePath,
|
if err := git.NewCommand(ctx, "commit").
|
||||||
Stdout: &outbuf,
|
AddArguments(signArgs...).
|
||||||
Stderr: &errbuf,
|
AddOptionFormat("--author='%s <%s>'", sig.Name, sig.Email).
|
||||||
}); err != nil {
|
AddOptionValues("-m", message).
|
||||||
log.Error("git commit [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
|
Run(&git.RunOpts{
|
||||||
return "", fmt.Errorf("git commit [%s:%s -> %s:%s]: %w\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
|
Env: env,
|
||||||
}
|
Dir: tmpBasePath,
|
||||||
} else {
|
Stdout: &outbuf,
|
||||||
if setting.Repository.PullRequest.AddCoCommitterTrailers && committer.String() != sig.String() {
|
Stderr: &errbuf,
|
||||||
// add trailer
|
}); err != nil {
|
||||||
message += fmt.Sprintf("\nCo-authored-by: %s\nCo-committed-by: %s\n", sig.String(), sig.String())
|
log.Error("git commit [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
|
||||||
}
|
return "", fmt.Errorf("git commit [%s:%s -> %s:%s]: %w\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
|
||||||
if err := git.NewCommand(ctx, "commit").
|
|
||||||
AddArguments(signArg).
|
|
||||||
AddArguments(git.CmdArg(fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email))).
|
|
||||||
AddArguments("-m").AddDynamicArguments(message).
|
|
||||||
Run(&git.RunOpts{
|
|
||||||
Env: env,
|
|
||||||
Dir: tmpBasePath,
|
|
||||||
Stdout: &outbuf,
|
|
||||||
Stderr: &errbuf,
|
|
||||||
}); err != nil {
|
|
||||||
log.Error("git commit [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
|
|
||||||
return "", fmt.Errorf("git commit [%s:%s -> %s:%s]: %w\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
outbuf.Reset()
|
outbuf.Reset()
|
||||||
errbuf.Reset()
|
errbuf.Reset()
|
||||||
@ -649,30 +636,17 @@ func rawMerge(ctx context.Context, pr *issues_model.PullRequest, doer *user_mode
|
|||||||
return mergeCommitID, nil
|
return mergeCommitID, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func commitAndSignNoAuthor(ctx context.Context, pr *issues_model.PullRequest, message string, signArg git.CmdArg, tmpBasePath string, env []string) error {
|
func commitAndSignNoAuthor(ctx context.Context, pr *issues_model.PullRequest, message string, signArgs git.TrustedCmdArgs, tmpBasePath string, env []string) error {
|
||||||
var outbuf, errbuf strings.Builder
|
var outbuf, errbuf strings.Builder
|
||||||
if signArg == "" {
|
if err := git.NewCommand(ctx, "commit").AddArguments(signArgs...).AddOptionValues("-m", message).
|
||||||
if err := git.NewCommand(ctx, "commit", "-m").AddDynamicArguments(message).
|
Run(&git.RunOpts{
|
||||||
Run(&git.RunOpts{
|
Env: env,
|
||||||
Env: env,
|
Dir: tmpBasePath,
|
||||||
Dir: tmpBasePath,
|
Stdout: &outbuf,
|
||||||
Stdout: &outbuf,
|
Stderr: &errbuf,
|
||||||
Stderr: &errbuf,
|
}); err != nil {
|
||||||
}); err != nil {
|
log.Error("git commit [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
|
||||||
log.Error("git commit [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
|
return fmt.Errorf("git commit [%s:%s -> %s:%s]: %w\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
|
||||||
return fmt.Errorf("git commit [%s:%s -> %s:%s]: %w\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if err := git.NewCommand(ctx, "commit").AddArguments(signArg).AddArguments("-m").AddDynamicArguments(message).
|
|
||||||
Run(&git.RunOpts{
|
|
||||||
Env: env,
|
|
||||||
Dir: tmpBasePath,
|
|
||||||
Stdout: &outbuf,
|
|
||||||
Stderr: &errbuf,
|
|
||||||
}); err != nil {
|
|
||||||
log.Error("git commit [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
|
|
||||||
return fmt.Errorf("git commit [%s:%s -> %s:%s]: %w\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
@ -60,7 +60,7 @@ var patchErrorSuffices = []string{
|
|||||||
|
|
||||||
// TestPatch will test whether a simple patch will apply
|
// TestPatch will test whether a simple patch will apply
|
||||||
func TestPatch(pr *issues_model.PullRequest) error {
|
func TestPatch(pr *issues_model.PullRequest) error {
|
||||||
ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("TestPatch: Repo[%d]#%d", pr.BaseRepoID, pr.Index))
|
ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("TestPatch: %s", pr))
|
||||||
defer finished()
|
defer finished()
|
||||||
|
|
||||||
// Clone base repo.
|
// Clone base repo.
|
||||||
@ -376,16 +376,16 @@ func checkConflicts(ctx context.Context, pr *issues_model.PullRequest, gitRepo *
|
|||||||
prConfig := prUnit.PullRequestsConfig()
|
prConfig := prUnit.PullRequestsConfig()
|
||||||
|
|
||||||
// 6. Prepare the arguments to apply the patch against the index
|
// 6. Prepare the arguments to apply the patch against the index
|
||||||
args := []git.CmdArg{"apply", "--check", "--cached"}
|
cmdApply := git.NewCommand(gitRepo.Ctx, "apply", "--check", "--cached")
|
||||||
if prConfig.IgnoreWhitespaceConflicts {
|
if prConfig.IgnoreWhitespaceConflicts {
|
||||||
args = append(args, "--ignore-whitespace")
|
cmdApply.AddArguments("--ignore-whitespace")
|
||||||
}
|
}
|
||||||
is3way := false
|
is3way := false
|
||||||
if git.CheckGitVersionAtLeast("2.32.0") == nil {
|
if git.CheckGitVersionAtLeast("2.32.0") == nil {
|
||||||
args = append(args, "--3way")
|
cmdApply.AddArguments("--3way")
|
||||||
is3way = true
|
is3way = true
|
||||||
}
|
}
|
||||||
args = append(args, git.CmdArgCheck(patchPath))
|
cmdApply.AddDynamicArguments(patchPath)
|
||||||
|
|
||||||
// 7. Prep the pipe:
|
// 7. Prep the pipe:
|
||||||
// - Here we could do the equivalent of:
|
// - Here we could do the equivalent of:
|
||||||
@ -407,71 +407,70 @@ func checkConflicts(ctx context.Context, pr *issues_model.PullRequest, gitRepo *
|
|||||||
|
|
||||||
// 8. Run the check command
|
// 8. Run the check command
|
||||||
conflict = false
|
conflict = false
|
||||||
err = git.NewCommand(gitRepo.Ctx, args...).
|
err = cmdApply.Run(&git.RunOpts{
|
||||||
Run(&git.RunOpts{
|
Dir: tmpBasePath,
|
||||||
Dir: tmpBasePath,
|
Stderr: stderrWriter,
|
||||||
Stderr: stderrWriter,
|
PipelineFunc: func(ctx context.Context, cancel context.CancelFunc) error {
|
||||||
PipelineFunc: func(ctx context.Context, cancel context.CancelFunc) error {
|
// Close the writer end of the pipe to begin processing
|
||||||
// Close the writer end of the pipe to begin processing
|
_ = stderrWriter.Close()
|
||||||
_ = stderrWriter.Close()
|
defer func() {
|
||||||
defer func() {
|
// Close the reader on return to terminate the git command if necessary
|
||||||
// Close the reader on return to terminate the git command if necessary
|
_ = stderrReader.Close()
|
||||||
_ = stderrReader.Close()
|
}()
|
||||||
}()
|
|
||||||
|
|
||||||
const prefix = "error: patch failed:"
|
const prefix = "error: patch failed:"
|
||||||
const errorPrefix = "error: "
|
const errorPrefix = "error: "
|
||||||
const threewayFailed = "Failed to perform three-way merge..."
|
const threewayFailed = "Failed to perform three-way merge..."
|
||||||
const appliedPatchPrefix = "Applied patch to '"
|
const appliedPatchPrefix = "Applied patch to '"
|
||||||
const withConflicts = "' with conflicts."
|
const withConflicts = "' with conflicts."
|
||||||
|
|
||||||
conflicts := make(container.Set[string])
|
conflicts := make(container.Set[string])
|
||||||
|
|
||||||
// Now scan the output from the command
|
// Now scan the output from the command
|
||||||
scanner := bufio.NewScanner(stderrReader)
|
scanner := bufio.NewScanner(stderrReader)
|
||||||
for scanner.Scan() {
|
for scanner.Scan() {
|
||||||
line := scanner.Text()
|
line := scanner.Text()
|
||||||
log.Trace("PullRequest[%d].testPatch: stderr: %s", pr.ID, line)
|
log.Trace("PullRequest[%d].testPatch: stderr: %s", pr.ID, line)
|
||||||
if strings.HasPrefix(line, prefix) {
|
if strings.HasPrefix(line, prefix) {
|
||||||
conflict = true
|
conflict = true
|
||||||
filepath := strings.TrimSpace(strings.Split(line[len(prefix):], ":")[0])
|
filepath := strings.TrimSpace(strings.Split(line[len(prefix):], ":")[0])
|
||||||
conflicts.Add(filepath)
|
conflicts.Add(filepath)
|
||||||
} else if is3way && line == threewayFailed {
|
} else if is3way && line == threewayFailed {
|
||||||
conflict = true
|
conflict = true
|
||||||
} else if strings.HasPrefix(line, errorPrefix) {
|
} else if strings.HasPrefix(line, errorPrefix) {
|
||||||
conflict = true
|
conflict = true
|
||||||
for _, suffix := range patchErrorSuffices {
|
for _, suffix := range patchErrorSuffices {
|
||||||
if strings.HasSuffix(line, suffix) {
|
if strings.HasSuffix(line, suffix) {
|
||||||
filepath := strings.TrimSpace(strings.TrimSuffix(line[len(errorPrefix):], suffix))
|
filepath := strings.TrimSpace(strings.TrimSuffix(line[len(errorPrefix):], suffix))
|
||||||
if filepath != "" {
|
if filepath != "" {
|
||||||
conflicts.Add(filepath)
|
conflicts.Add(filepath)
|
||||||
}
|
|
||||||
break
|
|
||||||
}
|
}
|
||||||
}
|
break
|
||||||
} else if is3way && strings.HasPrefix(line, appliedPatchPrefix) && strings.HasSuffix(line, withConflicts) {
|
|
||||||
conflict = true
|
|
||||||
filepath := strings.TrimPrefix(strings.TrimSuffix(line, withConflicts), appliedPatchPrefix)
|
|
||||||
if filepath != "" {
|
|
||||||
conflicts.Add(filepath)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// only list 10 conflicted files
|
} else if is3way && strings.HasPrefix(line, appliedPatchPrefix) && strings.HasSuffix(line, withConflicts) {
|
||||||
if len(conflicts) >= 10 {
|
conflict = true
|
||||||
break
|
filepath := strings.TrimPrefix(strings.TrimSuffix(line, withConflicts), appliedPatchPrefix)
|
||||||
|
if filepath != "" {
|
||||||
|
conflicts.Add(filepath)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// only list 10 conflicted files
|
||||||
if len(conflicts) > 0 {
|
if len(conflicts) >= 10 {
|
||||||
pr.ConflictedFiles = make([]string, 0, len(conflicts))
|
break
|
||||||
for key := range conflicts {
|
|
||||||
pr.ConflictedFiles = append(pr.ConflictedFiles, key)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return nil
|
if len(conflicts) > 0 {
|
||||||
},
|
pr.ConflictedFiles = make([]string, 0, len(conflicts))
|
||||||
})
|
for key := range conflicts {
|
||||||
|
pr.ConflictedFiles = append(pr.ConflictedFiles, key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
// 9. Check if the found conflictedfiles is non-zero, "err" could be non-nil, so we should ignore it if we found conflicts.
|
// 9. Check if the found conflictedfiles is non-zero, "err" could be non-nil, so we should ignore it if we found conflicts.
|
||||||
// Note: `"err" could be non-nil` is due that if enable 3-way merge, it doesn't return any error on found conflicts.
|
// Note: `"err" could be non-nil` is due that if enable 3-way merge, it doesn't return any error on found conflicts.
|
||||||
|
@ -23,7 +23,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// GitFsckRepos calls 'git fsck' to check repository health.
|
// GitFsckRepos calls 'git fsck' to check repository health.
|
||||||
func GitFsckRepos(ctx context.Context, timeout time.Duration, args []git.CmdArg) error {
|
func GitFsckRepos(ctx context.Context, timeout time.Duration, args git.TrustedCmdArgs) error {
|
||||||
log.Trace("Doing: GitFsck")
|
log.Trace("Doing: GitFsck")
|
||||||
|
|
||||||
if err := db.Iterate(
|
if err := db.Iterate(
|
||||||
@ -47,10 +47,10 @@ func GitFsckRepos(ctx context.Context, timeout time.Duration, args []git.CmdArg)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// GitFsckRepo calls 'git fsck' to check an individual repository's health.
|
// GitFsckRepo calls 'git fsck' to check an individual repository's health.
|
||||||
func GitFsckRepo(ctx context.Context, repo *repo_model.Repository, timeout time.Duration, args []git.CmdArg) error {
|
func GitFsckRepo(ctx context.Context, repo *repo_model.Repository, timeout time.Duration, args git.TrustedCmdArgs) error {
|
||||||
log.Trace("Running health check on repository %-v", repo)
|
log.Trace("Running health check on repository %-v", repo)
|
||||||
repoPath := repo.RepoPath()
|
repoPath := repo.RepoPath()
|
||||||
if err := git.Fsck(ctx, repoPath, timeout, args...); err != nil {
|
if err := git.Fsck(ctx, repoPath, timeout, args); err != nil {
|
||||||
log.Warn("Failed to health check repository (%-v): %v", repo, err)
|
log.Warn("Failed to health check repository (%-v): %v", repo, err)
|
||||||
if err = system_model.CreateRepositoryNotice("Failed to health check repository (%s): %v", repo.FullName(), err); err != nil {
|
if err = system_model.CreateRepositoryNotice("Failed to health check repository (%s): %v", repo.FullName(), err); err != nil {
|
||||||
log.Error("CreateRepositoryNotice: %v", err)
|
log.Error("CreateRepositoryNotice: %v", err)
|
||||||
@ -60,9 +60,8 @@ func GitFsckRepo(ctx context.Context, repo *repo_model.Repository, timeout time.
|
|||||||
}
|
}
|
||||||
|
|
||||||
// GitGcRepos calls 'git gc' to remove unnecessary files and optimize the local repository
|
// GitGcRepos calls 'git gc' to remove unnecessary files and optimize the local repository
|
||||||
func GitGcRepos(ctx context.Context, timeout time.Duration, args ...git.CmdArg) error {
|
func GitGcRepos(ctx context.Context, timeout time.Duration, args git.TrustedCmdArgs) error {
|
||||||
log.Trace("Doing: GitGcRepos")
|
log.Trace("Doing: GitGcRepos")
|
||||||
args = append([]git.CmdArg{"gc"}, args...)
|
|
||||||
|
|
||||||
if err := db.Iterate(
|
if err := db.Iterate(
|
||||||
ctx,
|
ctx,
|
||||||
@ -86,9 +85,9 @@ func GitGcRepos(ctx context.Context, timeout time.Duration, args ...git.CmdArg)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// GitGcRepo calls 'git gc' to remove unnecessary files and optimize the local repository
|
// GitGcRepo calls 'git gc' to remove unnecessary files and optimize the local repository
|
||||||
func GitGcRepo(ctx context.Context, repo *repo_model.Repository, timeout time.Duration, args []git.CmdArg) error {
|
func GitGcRepo(ctx context.Context, repo *repo_model.Repository, timeout time.Duration, args git.TrustedCmdArgs) error {
|
||||||
log.Trace("Running git gc on %-v", repo)
|
log.Trace("Running git gc on %-v", repo)
|
||||||
command := git.NewCommand(ctx, args...).
|
command := git.NewCommand(ctx, "gc").AddArguments(args...).
|
||||||
SetDescription(fmt.Sprintf("Repository Garbage Collection: %s", repo.FullName()))
|
SetDescription(fmt.Sprintf("Repository Garbage Collection: %s", repo.FullName()))
|
||||||
var stdout string
|
var stdout string
|
||||||
var err error
|
var err error
|
||||||
|
@ -141,14 +141,12 @@ func ApplyDiffPatch(ctx context.Context, repo *repo_model.Repository, doer *user
|
|||||||
stdout := &strings.Builder{}
|
stdout := &strings.Builder{}
|
||||||
stderr := &strings.Builder{}
|
stderr := &strings.Builder{}
|
||||||
|
|
||||||
args := []git.CmdArg{"apply", "--index", "--recount", "--cached", "--ignore-whitespace", "--whitespace=fix", "--binary"}
|
cmdApply := git.NewCommand(ctx, "apply", "--index", "--recount", "--cached", "--ignore-whitespace", "--whitespace=fix", "--binary")
|
||||||
|
|
||||||
if git.CheckGitVersionAtLeast("2.32") == nil {
|
if git.CheckGitVersionAtLeast("2.32") == nil {
|
||||||
args = append(args, "-3")
|
cmdApply.AddArguments("-3")
|
||||||
}
|
}
|
||||||
|
|
||||||
cmd := git.NewCommand(ctx, args...)
|
if err := cmdApply.Run(&git.RunOpts{
|
||||||
if err := cmd.Run(&git.RunOpts{
|
|
||||||
Dir: t.basePath,
|
Dir: t.basePath,
|
||||||
Stdout: stdout,
|
Stdout: stdout,
|
||||||
Stderr: stderr,
|
Stderr: stderr,
|
||||||
|
@ -233,11 +233,9 @@ func (t *TemporaryUploadRepository) CommitTreeWithDate(parent string, author, co
|
|||||||
_, _ = messageBytes.WriteString(message)
|
_, _ = messageBytes.WriteString(message)
|
||||||
_, _ = messageBytes.WriteString("\n")
|
_, _ = messageBytes.WriteString("\n")
|
||||||
|
|
||||||
var args []git.CmdArg
|
cmdCommitTree := git.NewCommand(t.ctx, "commit-tree").AddDynamicArguments(treeHash)
|
||||||
if parent != "" {
|
if parent != "" {
|
||||||
args = []git.CmdArg{"commit-tree", git.CmdArgCheck(treeHash), "-p", git.CmdArgCheck(parent)}
|
cmdCommitTree.AddOptionValues("-p", parent)
|
||||||
} else {
|
|
||||||
args = []git.CmdArg{"commit-tree", git.CmdArgCheck(treeHash)}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var sign bool
|
var sign bool
|
||||||
@ -249,7 +247,7 @@ func (t *TemporaryUploadRepository) CommitTreeWithDate(parent string, author, co
|
|||||||
sign, keyID, signer, _ = asymkey_service.SignInitialCommit(t.ctx, t.repo.RepoPath(), author)
|
sign, keyID, signer, _ = asymkey_service.SignInitialCommit(t.ctx, t.repo.RepoPath(), author)
|
||||||
}
|
}
|
||||||
if sign {
|
if sign {
|
||||||
args = append(args, git.CmdArg("-S"+keyID))
|
cmdCommitTree.AddOptionFormat("-S%s", keyID)
|
||||||
if t.repo.GetTrustModel() == repo_model.CommitterTrustModel || t.repo.GetTrustModel() == repo_model.CollaboratorCommitterTrustModel {
|
if t.repo.GetTrustModel() == repo_model.CommitterTrustModel || t.repo.GetTrustModel() == repo_model.CollaboratorCommitterTrustModel {
|
||||||
if committerSig.Name != authorSig.Name || committerSig.Email != authorSig.Email {
|
if committerSig.Name != authorSig.Name || committerSig.Email != authorSig.Email {
|
||||||
// Add trailers
|
// Add trailers
|
||||||
@ -264,7 +262,7 @@ func (t *TemporaryUploadRepository) CommitTreeWithDate(parent string, author, co
|
|||||||
committerSig = signer
|
committerSig = signer
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
args = append(args, "--no-gpg-sign")
|
cmdCommitTree.AddArguments("--no-gpg-sign")
|
||||||
}
|
}
|
||||||
|
|
||||||
if signoff {
|
if signoff {
|
||||||
@ -281,7 +279,7 @@ func (t *TemporaryUploadRepository) CommitTreeWithDate(parent string, author, co
|
|||||||
|
|
||||||
stdout := new(bytes.Buffer)
|
stdout := new(bytes.Buffer)
|
||||||
stderr := new(bytes.Buffer)
|
stderr := new(bytes.Buffer)
|
||||||
if err := git.NewCommand(t.ctx, args...).
|
if err := cmdCommitTree.
|
||||||
Run(&git.RunOpts{
|
Run(&git.RunOpts{
|
||||||
Env: env,
|
Env: env,
|
||||||
Dir: t.basePath,
|
Dir: t.basePath,
|
||||||
@ -364,7 +362,7 @@ func (t *TemporaryUploadRepository) DiffIndex() (*gitdiff.Diff, error) {
|
|||||||
t.repo.FullName(), err, stderr)
|
t.repo.FullName(), err, stderr)
|
||||||
}
|
}
|
||||||
|
|
||||||
diff.NumFiles, diff.TotalAddition, diff.TotalDeletion, err = git.GetDiffShortStat(t.ctx, t.basePath, "--cached", "HEAD")
|
diff.NumFiles, diff.TotalAddition, diff.TotalDeletion, err = git.GetDiffShortStat(t.ctx, t.basePath, git.TrustedCmdArgs{"--cached"}, "HEAD")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
@ -370,7 +370,7 @@ func CreateOrUpdateRepoFile(ctx context.Context, repo *repo_model.Repository, do
|
|||||||
if setting.LFS.StartServer && hasOldBranch {
|
if setting.LFS.StartServer && hasOldBranch {
|
||||||
// Check there is no way this can return multiple infos
|
// Check there is no way this can return multiple infos
|
||||||
filename2attribute2info, err := t.gitRepo.CheckAttribute(git.CheckAttributeOpts{
|
filename2attribute2info, err := t.gitRepo.CheckAttribute(git.CheckAttributeOpts{
|
||||||
Attributes: []git.CmdArg{"filter"},
|
Attributes: []string{"filter"},
|
||||||
Filenames: []string{treePath},
|
Filenames: []string{treePath},
|
||||||
CachedOnly: true,
|
CachedOnly: true,
|
||||||
})
|
})
|
||||||
|
@ -96,7 +96,7 @@ func UploadRepoFiles(ctx context.Context, repo *repo_model.Repository, doer *use
|
|||||||
var filename2attribute2info map[string]map[string]string
|
var filename2attribute2info map[string]map[string]string
|
||||||
if setting.LFS.StartServer {
|
if setting.LFS.StartServer {
|
||||||
filename2attribute2info, err = t.gitRepo.CheckAttribute(git.CheckAttributeOpts{
|
filename2attribute2info, err = t.gitRepo.CheckAttribute(git.CheckAttributeOpts{
|
||||||
Attributes: []git.CmdArg{"filter"},
|
Attributes: []string{"filter"},
|
||||||
Filenames: names,
|
Filenames: names,
|
||||||
CachedOnly: true,
|
CachedOnly: true,
|
||||||
})
|
})
|
||||||
|
@ -163,7 +163,7 @@
|
|||||||
<a class="{{if .PageIsIssueList}}active {{end}}item" href="{{.RepoLink}}/issues">
|
<a class="{{if .PageIsIssueList}}active {{end}}item" href="{{.RepoLink}}/issues">
|
||||||
{{svg "octicon-issue-opened"}} {{.locale.Tr "repo.issues"}}
|
{{svg "octicon-issue-opened"}} {{.locale.Tr "repo.issues"}}
|
||||||
{{if .Repository.NumOpenIssues}}
|
{{if .Repository.NumOpenIssues}}
|
||||||
<span class="ui primary small label">{{CountFmt .Repository.NumOpenIssues}}</span>
|
<span class="ui small label">{{CountFmt .Repository.NumOpenIssues}}</span>
|
||||||
{{end}}
|
{{end}}
|
||||||
</a>
|
</a>
|
||||||
{{end}}
|
{{end}}
|
||||||
@ -178,7 +178,7 @@
|
|||||||
<a class="{{if .PageIsPullList}}active {{end}}item" href="{{.RepoLink}}/pulls">
|
<a class="{{if .PageIsPullList}}active {{end}}item" href="{{.RepoLink}}/pulls">
|
||||||
{{svg "octicon-git-pull-request"}} {{.locale.Tr "repo.pulls"}}
|
{{svg "octicon-git-pull-request"}} {{.locale.Tr "repo.pulls"}}
|
||||||
{{if .Repository.NumOpenPulls}}
|
{{if .Repository.NumOpenPulls}}
|
||||||
<span class="ui primary small label">{{CountFmt .Repository.NumOpenPulls}}</span>
|
<span class="ui small label">{{CountFmt .Repository.NumOpenPulls}}</span>
|
||||||
{{end}}
|
{{end}}
|
||||||
</a>
|
</a>
|
||||||
{{end}}
|
{{end}}
|
||||||
@ -187,7 +187,7 @@
|
|||||||
<a class="{{if .PageIsActions}}active {{end}}item" href="{{.RepoLink}}/actions">
|
<a class="{{if .PageIsActions}}active {{end}}item" href="{{.RepoLink}}/actions">
|
||||||
{{svg "octicon-play"}} {{.locale.Tr "actions.actions"}}
|
{{svg "octicon-play"}} {{.locale.Tr "actions.actions"}}
|
||||||
{{if .Repository.NumOpenActionRuns}}
|
{{if .Repository.NumOpenActionRuns}}
|
||||||
<span class="ui primary small label">{{CountFmt .Repository.NumOpenActionRuns}}</span>
|
<span class="ui small label">{{CountFmt .Repository.NumOpenActionRuns}}</span>
|
||||||
{{end}}
|
{{end}}
|
||||||
</a>
|
</a>
|
||||||
{{end}}
|
{{end}}
|
||||||
@ -202,7 +202,7 @@
|
|||||||
<a href="{{.RepoLink}}/projects" class="{{if .IsProjectsPage}}active {{end}}item">
|
<a href="{{.RepoLink}}/projects" class="{{if .IsProjectsPage}}active {{end}}item">
|
||||||
{{svg "octicon-project"}} {{.locale.Tr "repo.project_board"}}
|
{{svg "octicon-project"}} {{.locale.Tr "repo.project_board"}}
|
||||||
{{if .Repository.NumOpenProjects}}
|
{{if .Repository.NumOpenProjects}}
|
||||||
<span class="ui primary small label">{{CountFmt .Repository.NumOpenProjects}}</span>
|
<span class="ui small label">{{CountFmt .Repository.NumOpenProjects}}</span>
|
||||||
{{end}}
|
{{end}}
|
||||||
</a>
|
</a>
|
||||||
{{end}}
|
{{end}}
|
||||||
@ -211,7 +211,7 @@
|
|||||||
<a class="{{if .PageIsReleaseList}}active {{end}}item" href="{{.RepoLink}}/releases">
|
<a class="{{if .PageIsReleaseList}}active {{end}}item" href="{{.RepoLink}}/releases">
|
||||||
{{svg "octicon-tag"}} {{.locale.Tr "repo.releases"}}
|
{{svg "octicon-tag"}} {{.locale.Tr "repo.releases"}}
|
||||||
{{if .NumReleases}}
|
{{if .NumReleases}}
|
||||||
<span class="ui primary small label">{{CountFmt .NumReleases}}</span>
|
<span class="ui small label">{{CountFmt .NumReleases}}</span>
|
||||||
{{end}}
|
{{end}}
|
||||||
</a>
|
</a>
|
||||||
{{end}}
|
{{end}}
|
||||||
|
@ -190,6 +190,7 @@
|
|||||||
{{end}}
|
{{end}}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
{{template "repo/issue/view_content/update_branch_by_merge" (dict "locale" .locale "Issue" .Issue "UpdateAllowed" .UpdateAllowed "UpdateByRebaseAllowed" .UpdateByRebaseAllowed "Link" .Link)}}
|
||||||
{{else if .Issue.PullRequest.IsChecking}}
|
{{else if .Issue.PullRequest.IsChecking}}
|
||||||
<div class="item">
|
<div class="item">
|
||||||
<i class="icon icon-octicon">{{svg "octicon-sync"}}</i>
|
<i class="icon icon-octicon">{{svg "octicon-sync"}}</i>
|
||||||
@ -282,44 +283,7 @@
|
|||||||
</div>
|
</div>
|
||||||
{{end}}
|
{{end}}
|
||||||
{{end}}
|
{{end}}
|
||||||
{{if and (gt .Issue.PullRequest.CommitsBehind 0) (not .Issue.IsClosed) (not .Issue.PullRequest.IsChecking) (not .IsPullFilesConflicted) (not .IsPullRequestBroken) (not $canAutoMerge)}}
|
{{template "repo/issue/view_content/update_branch_by_merge" (dict "locale" .locale "Issue" .Issue "UpdateAllowed" .UpdateAllowed "UpdateByRebaseAllowed" .UpdateByRebaseAllowed "Link" .Link)}}
|
||||||
<div class="ui divider"></div>
|
|
||||||
<div class="item item-section">
|
|
||||||
<div class="item-section-left">
|
|
||||||
<i class="icon icon-octicon">{{svg "octicon-alert"}}</i>
|
|
||||||
{{$.locale.Tr "repo.pulls.outdated_with_base_branch"}}
|
|
||||||
</div>
|
|
||||||
<div class="item-section-right">
|
|
||||||
{{if and .UpdateAllowed .UpdateByRebaseAllowed}}
|
|
||||||
<div class="dib">
|
|
||||||
<div class="ui buttons update-button">
|
|
||||||
<button class="ui button" data-do="{{.Link}}/update" data-redirect="{{.Link}}">
|
|
||||||
<span class="button-text">
|
|
||||||
{{$.locale.Tr "repo.pulls.update_branch"}}
|
|
||||||
</span>
|
|
||||||
</button>
|
|
||||||
|
|
||||||
<div class="ui dropdown icon button no-text">
|
|
||||||
{{svg "octicon-triangle-down" 14 "dropdown icon"}}
|
|
||||||
<div class="menu">
|
|
||||||
<div class="item active selected" data-do="{{.Link}}/update">{{$.locale.Tr "repo.pulls.update_branch"}}</div>
|
|
||||||
<div class="item" data-do="{{.Link}}/update?style=rebase">{{$.locale.Tr "repo.pulls.update_branch_rebase"}}</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{{end}}
|
|
||||||
{{if and .UpdateAllowed (not .UpdateByRebaseAllowed)}}
|
|
||||||
<form action="{{.Link}}/update" method="post" class="ui update-branch-form">
|
|
||||||
{{.CsrfTokenHtml}}
|
|
||||||
<button class="ui compact button" data-do="update">
|
|
||||||
<span class="ui text">{{$.locale.Tr "repo.pulls.update_branch"}}</span>
|
|
||||||
</button>
|
|
||||||
</form>
|
|
||||||
{{end}}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{{end}}
|
|
||||||
{{if .Issue.PullRequest.IsEmpty}}
|
{{if .Issue.PullRequest.IsEmpty}}
|
||||||
<div class="ui divider"></div>
|
<div class="ui divider"></div>
|
||||||
|
|
||||||
|
@ -0,0 +1,39 @@
|
|||||||
|
{{$canAutoMerge := false}}
|
||||||
|
{{if and (gt .Issue.PullRequest.CommitsBehind 0) (not .Issue.IsClosed) (not .Issue.PullRequest.IsChecking) (not .IsPullFilesConflicted) (not .IsPullRequestBroken) (not $canAutoMerge)}}
|
||||||
|
<div class="ui divider"></div>
|
||||||
|
<div class="item item-section">
|
||||||
|
<div class="item-section-left">
|
||||||
|
<i class="icon icon-octicon">{{svg "octicon-alert"}}</i>
|
||||||
|
{{$.locale.Tr "repo.pulls.outdated_with_base_branch"}}
|
||||||
|
</div>
|
||||||
|
<div class="item-section-right">
|
||||||
|
{{if and .UpdateAllowed .UpdateByRebaseAllowed}}
|
||||||
|
<div class="dib">
|
||||||
|
<div class="ui buttons update-button">
|
||||||
|
<button class="ui button" data-do="{{.Link}}/update" data-redirect="{{.Link}}">
|
||||||
|
<span class="button-text">
|
||||||
|
{{$.locale.Tr "repo.pulls.update_branch"}}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<div class="ui dropdown icon button no-text">
|
||||||
|
{{svg "octicon-triangle-down" 14 "dropdown icon"}}
|
||||||
|
<div class="menu">
|
||||||
|
<div class="item active selected" data-do="{{.Link}}/update">{{$.locale.Tr "repo.pulls.update_branch"}}</div>
|
||||||
|
<div class="item" data-do="{{.Link}}/update?style=rebase">{{$.locale.Tr "repo.pulls.update_branch_rebase"}}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{{end}}
|
||||||
|
{{if and .UpdateAllowed (not .UpdateByRebaseAllowed)}}
|
||||||
|
<form action="{{.Link}}/update" method="post" class="ui update-branch-form">
|
||||||
|
{{.CsrfTokenHtml}}
|
||||||
|
<button class="ui compact button" data-do="update">
|
||||||
|
<span class="ui text">{{$.locale.Tr "repo.pulls.update_branch"}}</span>
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
{{end}}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{{end}}
|
@ -154,16 +154,16 @@ func doGitAddRemote(dstPath, remoteName string, u *url.URL) func(*testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func doGitPushTestRepository(dstPath string, args ...git.CmdArg) func(*testing.T) {
|
func doGitPushTestRepository(dstPath string, args ...string) func(*testing.T) {
|
||||||
return func(t *testing.T) {
|
return func(t *testing.T) {
|
||||||
_, _, err := git.NewCommand(git.DefaultContext, append([]git.CmdArg{"push", "-u"}, args...)...).RunStdString(&git.RunOpts{Dir: dstPath})
|
_, _, err := git.NewCommand(git.DefaultContext, "push", "-u").AddArguments(git.ToTrustedCmdArgs(args)...).RunStdString(&git.RunOpts{Dir: dstPath})
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func doGitPushTestRepositoryFail(dstPath string, args ...git.CmdArg) func(*testing.T) {
|
func doGitPushTestRepositoryFail(dstPath string, args ...string) func(*testing.T) {
|
||||||
return func(t *testing.T) {
|
return func(t *testing.T) {
|
||||||
_, _, err := git.NewCommand(git.DefaultContext, append([]git.CmdArg{"push"}, args...)...).RunStdString(&git.RunOpts{Dir: dstPath})
|
_, _, err := git.NewCommand(git.DefaultContext, "push").AddArguments(git.ToTrustedCmdArgs(args)...).RunStdString(&git.RunOpts{Dir: dstPath})
|
||||||
assert.Error(t, err)
|
assert.Error(t, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -175,23 +175,23 @@ func doGitCreateBranch(dstPath, branch string) func(*testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func doGitCheckoutBranch(dstPath string, args ...git.CmdArg) func(*testing.T) {
|
func doGitCheckoutBranch(dstPath string, args ...string) func(*testing.T) {
|
||||||
return func(t *testing.T) {
|
return func(t *testing.T) {
|
||||||
_, _, err := git.NewCommandNoGlobals(append(append(git.AllowLFSFiltersArgs(), "checkout"), args...)...).RunStdString(&git.RunOpts{Dir: dstPath})
|
_, _, err := git.NewCommandContextNoGlobals(git.DefaultContext, git.AllowLFSFiltersArgs()...).AddArguments("checkout").AddArguments(git.ToTrustedCmdArgs(args)...).RunStdString(&git.RunOpts{Dir: dstPath})
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func doGitMerge(dstPath string, args ...git.CmdArg) func(*testing.T) {
|
func doGitMerge(dstPath string, args ...string) func(*testing.T) {
|
||||||
return func(t *testing.T) {
|
return func(t *testing.T) {
|
||||||
_, _, err := git.NewCommand(git.DefaultContext, append([]git.CmdArg{"merge"}, args...)...).RunStdString(&git.RunOpts{Dir: dstPath})
|
_, _, err := git.NewCommand(git.DefaultContext, "merge").AddArguments(git.ToTrustedCmdArgs(args)...).RunStdString(&git.RunOpts{Dir: dstPath})
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func doGitPull(dstPath string, args ...git.CmdArg) func(*testing.T) {
|
func doGitPull(dstPath string, args ...string) func(*testing.T) {
|
||||||
return func(t *testing.T) {
|
return func(t *testing.T) {
|
||||||
_, _, err := git.NewCommandNoGlobals(append(append(git.AllowLFSFiltersArgs(), "pull"), args...)...).RunStdString(&git.RunOpts{Dir: dstPath})
|
_, _, err := git.NewCommandContextNoGlobals(git.DefaultContext, git.AllowLFSFiltersArgs()...).AddArguments("pull").AddArguments(git.ToTrustedCmdArgs(args)...).RunStdString(&git.RunOpts{Dir: dstPath})
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -509,7 +509,7 @@ func doCreatePRAndSetManuallyMerged(ctx, baseCtx APITestContext, dstPath, baseBr
|
|||||||
}))
|
}))
|
||||||
|
|
||||||
t.Run("CreateHeadBranch", doGitCreateBranch(dstPath, headBranch))
|
t.Run("CreateHeadBranch", doGitCreateBranch(dstPath, headBranch))
|
||||||
t.Run("PushToHeadBranch", doGitPushTestRepository(dstPath, "origin", git.CmdArgCheck(headBranch)))
|
t.Run("PushToHeadBranch", doGitPushTestRepository(dstPath, "origin", headBranch))
|
||||||
t.Run("CreateEmptyPullRequest", func(t *testing.T) {
|
t.Run("CreateEmptyPullRequest", func(t *testing.T) {
|
||||||
pr, err = doAPICreatePullRequest(ctx, baseCtx.Username, baseCtx.Reponame, baseBranch, headBranch)(t)
|
pr, err = doAPICreatePullRequest(ctx, baseCtx.Username, baseCtx.Reponame, baseBranch, headBranch)(t)
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
|
@ -287,7 +287,7 @@ func TestCantMergeUnrelated(t *testing.T) {
|
|||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
sha := strings.TrimSpace(stdout.String())
|
sha := strings.TrimSpace(stdout.String())
|
||||||
|
|
||||||
_, _, err = git.NewCommand(git.DefaultContext, "update-index", "--add", "--replace", "--cacheinfo", "100644", git.CmdArgCheck(sha), "somewher-over-the-rainbow").RunStdString(&git.RunOpts{Dir: path})
|
_, _, err = git.NewCommand(git.DefaultContext, "update-index", "--add", "--replace", "--cacheinfo").AddDynamicArguments("100644", sha, "somewher-over-the-rainbow").RunStdString(&git.RunOpts{Dir: path})
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
|
|
||||||
treeSha, _, err := git.NewCommand(git.DefaultContext, "write-tree").RunStdString(&git.RunOpts{Dir: path})
|
treeSha, _, err := git.NewCommand(git.DefaultContext, "write-tree").RunStdString(&git.RunOpts{Dir: path})
|
||||||
|
@ -2200,9 +2200,7 @@ a.ui.label:hover {
|
|||||||
border: 1px solid var(--color-light-border);
|
border: 1px solid var(--color-light-border);
|
||||||
color: var(--color-text);
|
color: var(--color-text);
|
||||||
}
|
}
|
||||||
.ui.tertiary.button {
|
|
||||||
border: none;
|
|
||||||
}
|
|
||||||
.page-content .ui.button {
|
.page-content .ui.button {
|
||||||
box-shadow: none !important;
|
box-shadow: none !important;
|
||||||
}
|
}
|
||||||
@ -2319,6 +2317,15 @@ a.ui.label:hover {
|
|||||||
color: var(--color-secondary-dark-8) !important;
|
color: var(--color-secondary-dark-8) !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.ui.tertiary.button {
|
||||||
|
color: var(--color-text-light);
|
||||||
|
border: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ui.tertiary.button:hover {
|
||||||
|
color: var(--color-text);
|
||||||
|
}
|
||||||
|
|
||||||
.ui.primary.label,
|
.ui.primary.label,
|
||||||
.ui.primary.labels .label {
|
.ui.primary.labels .label {
|
||||||
background-color: var(--color-primary) !important;
|
background-color: var(--color-primary) !important;
|
||||||
|
Loading…
x
Reference in New Issue
Block a user