Skip to content

Commit

Permalink
Merge remote-tracking branch 'upstream/main'
Browse files Browse the repository at this point in the history
* upstream/main: (25 commits)
  [docs] Add missing backtick in quickstart.zh-cn.md (go-gitea#26349)
  Fix incorrect CLI exit code and duplicate error message (go-gitea#26346)
  Improve CLI and messages (go-gitea#26341)
  Remove backslashed newlines on markdown (go-gitea#26344)
  Hide `last indexed SHA` when a repo could not be indexed yet (go-gitea#26340)
  Fix log typo in task.go (go-gitea#26337)
  Prevent newline errors with Debian packages (go-gitea#26332)
  Fix the bug when getting files changed for `pull_request_target` event (go-gitea#26320)
  Refactor backend SVG package and add tests (go-gitea#26335)
  Fix bug with sqlite load read (go-gitea#26305)
  Remove commit load branches and tags in wiki repo (go-gitea#26304)
  Add highlight to selected repos in milestone dashboard (go-gitea#26300)
  Do not show Profile README when repository is private (go-gitea#26295)
  Fix incorrect color of selected assignees when create issue (go-gitea#26324)
  Delete `issue_service.CreateComment` (go-gitea#26298)
  Make git batch operations use parent context timeout instead of default timeout (go-gitea#26325)
  Fix typos and grammer problems for actions documentation (go-gitea#26328)
  Update documentation for 1.21 actions (go-gitea#26317)
  Fix the wrong derive path (go-gitea#26271)
  Support getting changed files when commit ID is `EmptySHA` (go-gitea#26290)
  ...
  • Loading branch information
zjjhot committed Aug 6, 2023
2 parents 9c39987 + c1c83db commit 24e253a
Show file tree
Hide file tree
Showing 50 changed files with 794 additions and 236 deletions.
57 changes: 21 additions & 36 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ package cmd
import (
"fmt"
"os"
"reflect"
"strings"

"code.gitea.io/gitea/modules/log"
Expand Down Expand Up @@ -58,7 +57,6 @@ func appGlobalFlags() []cli.Flag {
return []cli.Flag{
// make the builtin flags at the top
helpFlag,
cli.VersionFlag,

// shared configuration flags, they are for global and for each sub-command at the same time
// eg: such command is valid: "./gitea --config /tmp/app.ini web --config /tmp/app.ini", while it's discouraged indeed
Expand Down Expand Up @@ -120,38 +118,12 @@ func prepareWorkPathAndCustomConf(action cli.ActionFunc) func(ctx *cli.Context)
}
}

func reflectGet(v any, fieldName string) any {
e := reflect.ValueOf(v).Elem()
return e.FieldByName(fieldName).Interface()
}

// https://cli.urfave.org/migrate-v1-to-v2/#flag-aliases-are-done-differently
// Sadly v2 doesn't warn you if a comma is in the name. (https://github.com/urfave/cli/issues/1103)
func checkCommandFlags(c any) bool {
var cmds []*cli.Command
if app, ok := c.(*cli.App); ok {
cmds = app.Commands
} else {
cmds = c.(*cli.Command).Subcommands
}
ok := true
for _, cmd := range cmds {
for _, flag := range cmd.Flags {
flagName := reflectGet(flag, "Name").(string)
if strings.Contains(flagName, ",") {
ok = false
log.Error("cli.Flag can't have comma in its Name: %q, use Aliases instead", flagName)
}
}
if !checkCommandFlags(cmd) {
ok = false
}
}
return ok
}

func NewMainApp() *cli.App {
func NewMainApp(version, versionExtra string) *cli.App {
app := cli.NewApp()
app.Name = "Gitea"
app.Usage = "A painless self-hosted Git service"
app.Description = `By default, Gitea will start serving using the web-server with no argument, which can alternatively be run by running the subcommand "web".`
app.Version = version + versionExtra
app.EnableBashCompletion = true

// these sub-commands need to use config file
Expand Down Expand Up @@ -187,6 +159,7 @@ func NewMainApp() *cli.App {
app.DefaultCommand = CmdWeb.Name

globalFlags := appGlobalFlags()
app.Flags = append(app.Flags, cli.VersionFlag)
app.Flags = append(app.Flags, globalFlags...)
app.HideHelp = true // use our own help action to show helps (with more information like default config)
app.Before = PrepareConsoleLoggerLevel(log.INFO)
Expand All @@ -196,8 +169,20 @@ func NewMainApp() *cli.App {
app.Commands = append(app.Commands, subCmdWithConfig...)
app.Commands = append(app.Commands, subCmdStandalone...)

if !checkCommandFlags(app) {
panic("some flags are incorrect") // this is a runtime check to help developers
}
return app
}

func RunMainApp(app *cli.App, args ...string) error {
err := app.Run(args)
if err == nil {
return nil
}
if strings.HasPrefix(err.Error(), "flag provided but not defined:") {
// the cli package should already have output the error message, so just exit
cli.OsExiter(1)
return err
}
_, _ = fmt.Fprintf(app.ErrWriter, "Command error: %v\n", err)
cli.OsExiter(1)
return err
}
79 changes: 64 additions & 15 deletions cmd/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@ package cmd

import (
"fmt"
"io"
"os"
"path/filepath"
"strings"
"testing"

"code.gitea.io/gitea/models/unittest"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/test"

"github.com/stretchr/testify/assert"
"github.com/urfave/cli/v2"
Expand All @@ -27,21 +29,38 @@ func makePathOutput(workPath, customPath, customConf string) string {
return fmt.Sprintf("WorkPath=%s\nCustomPath=%s\nCustomConf=%s", workPath, customPath, customConf)
}

func newTestApp() *cli.App {
app := NewMainApp()
testCmd := &cli.Command{
Name: "test-cmd",
Action: func(ctx *cli.Context) error {
_, _ = fmt.Fprint(app.Writer, makePathOutput(setting.AppWorkPath, setting.CustomPath, setting.CustomConf))
return nil
},
}
func newTestApp(testCmdAction func(ctx *cli.Context) error) *cli.App {
app := NewMainApp("version", "version-extra")
testCmd := &cli.Command{Name: "test-cmd", Action: testCmdAction}
prepareSubcommandWithConfig(testCmd, appGlobalFlags())
app.Commands = append(app.Commands, testCmd)
app.DefaultCommand = testCmd.Name
return app
}

type runResult struct {
Stdout string
Stderr string
ExitCode int
}

func runTestApp(app *cli.App, args ...string) (runResult, error) {
outBuf := new(strings.Builder)
errBuf := new(strings.Builder)
app.Writer = outBuf
app.ErrWriter = errBuf
exitCode := -1
defer test.MockVariableValue(&cli.ErrWriter, app.ErrWriter)()
defer test.MockVariableValue(&cli.OsExiter, func(code int) {
if exitCode == -1 {
exitCode = code // save the exit code once and then reset the writer (to simulate the exit)
app.Writer, app.ErrWriter, cli.ErrWriter = io.Discard, io.Discard, io.Discard
}
})()
err := RunMainApp(app, args...)
return runResult{outBuf.String(), errBuf.String(), exitCode}, err
}

func TestCliCmd(t *testing.T) {
defaultWorkPath := filepath.Dir(setting.AppPath)
defaultCustomPath := filepath.Join(defaultWorkPath, "custom")
Expand Down Expand Up @@ -92,7 +111,10 @@ func TestCliCmd(t *testing.T) {
},
}

app := newTestApp()
app := newTestApp(func(ctx *cli.Context) error {
_, _ = fmt.Fprint(ctx.App.Writer, makePathOutput(setting.AppWorkPath, setting.CustomPath, setting.CustomConf))
return nil
})
var envBackup []string
for _, s := range os.Environ() {
if strings.HasPrefix(s, "GITEA_") && strings.Contains(s, "=") {
Expand Down Expand Up @@ -120,12 +142,39 @@ func TestCliCmd(t *testing.T) {
_ = os.Setenv(k, v)
}
args := strings.Split(c.cmd, " ") // for test only, "split" is good enough
out := new(strings.Builder)
app.Writer = out
err := app.Run(args)
r, err := runTestApp(app, args...)
assert.NoError(t, err, c.cmd)
assert.NotEmpty(t, c.exp, c.cmd)
outStr := out.String()
assert.Contains(t, outStr, c.exp, c.cmd)
assert.Contains(t, r.Stdout, c.exp, c.cmd)
}
}

func TestCliCmdError(t *testing.T) {
app := newTestApp(func(ctx *cli.Context) error { return fmt.Errorf("normal error") })
r, err := runTestApp(app, "./gitea", "test-cmd")
assert.Error(t, err)
assert.Equal(t, 1, r.ExitCode)
assert.Equal(t, "", r.Stdout)
assert.Equal(t, "Command error: normal error\n", r.Stderr)

app = newTestApp(func(ctx *cli.Context) error { return cli.Exit("exit error", 2) })
r, err = runTestApp(app, "./gitea", "test-cmd")
assert.Error(t, err)
assert.Equal(t, 2, r.ExitCode)
assert.Equal(t, "", r.Stdout)
assert.Equal(t, "exit error\n", r.Stderr)

app = newTestApp(func(ctx *cli.Context) error { return nil })
r, err = runTestApp(app, "./gitea", "test-cmd", "--no-such")
assert.Error(t, err)
assert.Equal(t, 1, r.ExitCode)
assert.Equal(t, "Incorrect Usage: flag provided but not defined: -no-such\n\n", r.Stdout)
assert.Equal(t, "", r.Stderr) // the cli package's strange behavior, the error message is not in stderr ....

app = newTestApp(func(ctx *cli.Context) error { return nil })
r, err = runTestApp(app, "./gitea", "test-cmd")
assert.NoError(t, err)
assert.Equal(t, -1, r.ExitCode) // the cli.OsExiter is not called
assert.Equal(t, "", r.Stdout)
assert.Equal(t, "", r.Stderr)
}
32 changes: 16 additions & 16 deletions cmd/web.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,13 +107,18 @@ func createPIDFile(pidPath string) {
}
}

func serveInstall(ctx *cli.Context) error {
func showWebStartupMessage(msg string) {
log.Info("Gitea version: %s%s", setting.AppVer, setting.AppBuiltWith)
log.Info("App path: %s", setting.AppPath)
log.Info("Work path: %s", setting.AppWorkPath)
log.Info("Custom path: %s", setting.CustomPath)
log.Info("Config file: %s", setting.CustomConf)
log.Info("Prepare to run install page")
log.Info("* RunMode: %s", setting.RunMode)
log.Info("* AppPath: %s", setting.AppPath)
log.Info("* WorkPath: %s", setting.AppWorkPath)
log.Info("* CustomPath: %s", setting.CustomPath)
log.Info("* ConfigFile: %s", setting.CustomConf)
log.Info("%s", msg)
}

func serveInstall(ctx *cli.Context) error {
showWebStartupMessage("Prepare to run install page")

routers.InitWebInstallPage(graceful.GetManager().HammerContext())

Expand Down Expand Up @@ -150,29 +155,24 @@ func serveInstalled(ctx *cli.Context) error {
setting.LoadCommonSettings()
setting.MustInstalled()

log.Info("Gitea version: %s%s", setting.AppVer, setting.AppBuiltWith)
log.Info("App path: %s", setting.AppPath)
log.Info("Work path: %s", setting.AppWorkPath)
log.Info("Custom path: %s", setting.CustomPath)
log.Info("Config file: %s", setting.CustomConf)
log.Info("Run mode: %s", setting.RunMode)
log.Info("Prepare to run web server")
showWebStartupMessage("Prepare to run web server")

if setting.AppWorkPathMismatch {
log.Error("WORK_PATH from config %q doesn't match other paths from environment variables or command arguments. "+
"Only WORK_PATH in config should be set and used. Please remove the other outdated work paths from environment variables and command arguments", setting.CustomConf)
"Only WORK_PATH in config should be set and used. Please make sure the path in config file is correct, "+
"remove the other outdated work paths from environment variables and command arguments", setting.CustomConf)
}

rootCfg := setting.CfgProvider
if rootCfg.Section("").Key("WORK_PATH").String() == "" {
saveCfg, err := rootCfg.PrepareSaving()
if err != nil {
log.Error("Unable to prepare saving WORK_PATH=%s to config %q: %v\nYou must set it manually, otherwise there might be bugs when accessing the git repositories.", setting.AppWorkPath, setting.CustomConf, err)
log.Error("Unable to prepare saving WORK_PATH=%s to config %q: %v\nYou should set it manually, otherwise there might be bugs when accessing the git repositories.", setting.AppWorkPath, setting.CustomConf, err)
} else {
rootCfg.Section("").Key("WORK_PATH").SetValue(setting.AppWorkPath)
saveCfg.Section("").Key("WORK_PATH").SetValue(setting.AppWorkPath)
if err = saveCfg.Save(); err != nil {
log.Error("Unable to update WORK_PATH=%s to config %q: %v\nYou must set it manually, otherwise there might be bugs when accessing the git repositories.", setting.AppWorkPath, setting.CustomConf, err)
log.Error("Unable to update WORK_PATH=%s to config %q: %v\nYou should set it manually, otherwise there might be bugs when accessing the git repositories.", setting.AppWorkPath, setting.CustomConf, err)
}
}
}
Expand Down
35 changes: 33 additions & 2 deletions docs/content/usage/actions/act-runner.en-us.md
Original file line number Diff line number Diff line change
Expand Up @@ -245,8 +245,8 @@ You can find more useful images on [act images](https://github.com/nektos/act/bl
If you want to run jobs in the host directly, you can change it to `ubuntu-22.04:host` or just `ubuntu-22.04`, the `:host` is optional.
However, we suggest you to use a special name like `linux_amd64:host` or `windows:host` to avoid misusing it.

One more thing is that it is recommended to register the runner if you want to change the labels.
It may be annoying to do this, so we may provide a better way to do it in the future.
Starting with Gitea 1.21, you can change labels by modifying `container.labels` in the runner configuration file (if you don't have a configuration file, please refer to [configuration tutorials](#configuration)).
The runner will use these new labels as soon as you restart it, i.e., by calling `./act_runner daemon --config config.yaml`.

## Running

Expand All @@ -261,3 +261,34 @@ After you have registered the runner, you can run it by running the following co
The runner will fetch jobs from the Gitea instance and run them automatically.

Since act runner is still in development, it is recommended to check the latest version and upgrade it regularly.

## Configuration variable

You can create configuration variables on the user, organization and repository level.
The level of the variable depends on where you created it.

### Naming conventions

The following rules apply to variable names:

- Variable names can only contain alphanumeric characters (`[a-z]`, `[A-Z]`, `[0-9]`) or underscores (`_`). Spaces are not allowed.

- Variable names must not start with the `GITHUB_` and `GITEA_` prefix.

- Variable names must not start with a number.

- Variable names are case-insensitive.

- Variable names must be unique at the level they are created at.

- Variable names must not be `CI`.

### Using variable

After creating configuration variables, they will be automatically filled in the `vars` context.
They can be accessed through expressions like `{{ vars.VARIABLE_NAME }}` in the workflow.

### Precedence

If a variable with the same name exists at multiple levels, the variable at the lowest level takes precedence:
A repository variable will always be chosen over an organization/user variable.
32 changes: 30 additions & 2 deletions docs/content/usage/actions/act-runner.zh-cn.md
Original file line number Diff line number Diff line change
Expand Up @@ -241,8 +241,7 @@ Runner的标签用于确定Runner可以运行哪些Job以及如何运行它们
如果您想直接在主机上运行Job,您可以将其更改为`ubuntu-22.04:host`或仅`ubuntu-22.04`,`:host`是可选的。
然而,我们建议您使用类似`linux_amd64:host`或`windows:host`的特殊名称,以避免误用。

还有一点需要注意的是,建议在更改标签时注册Runner。
这可能会有些麻烦,所以我们可能会在将来提供更好的方法来处理。
从 Gitea 1.21 开始,您可以通过修改 runner 的配置文件中的 `container.labels` 来更改标签(如果没有配置文件,请参考 [配置教程](#配置)),通过执行 `./act_runner daemon --config config.yaml` 命令重启 runner 之后,这些新定义的标签就会生效。

## 运行

Expand All @@ -257,3 +256,32 @@ Runner的标签用于确定Runner可以运行哪些Job以及如何运行它们
Runner将从Gitea实例获取Job并自动运行它们。

由于Act Runner仍处于开发中,建议定期检查最新版本并进行升级。

## 变量

您可以创建用户、组织和仓库级别的变量。变量的级别取决于创建它的位置。

### 命名规则

以下规则适用于变量名:

- 变量名称只能包含字母数字字符 (`[a-z]`, `[A-Z]`, `[0-9]`) 或下划线 (`_`)。不允许使用空格。

- 变量名称不能以 `GITHUB_` 和 `GITEA_` 前缀开头。

- 变量名称不能以数字开头。

- 变量名称不区分大小写。

- 变量名称在创建它们的级别上必须是唯一的。

- 变量名称不能为 “CI”。

### 使用

创建配置变量后,它们将自动填充到 `vars` 上下文中。您可以在工作流中使用类似 `{{ vars.VARIABLE_NAME }}` 这样的表达式来使用它们。

### 优先级

如果同名变量存在于多个级别,则级别最低的变量优先。
仓库级别的变量总是比组织或者用户级别的变量优先被选中。
2 changes: 1 addition & 1 deletion docs/content/usage/actions/quickstart.zh-cn.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ jobs:

请注意,演示文件中包含一些表情符号。
请确保您的数据库支持它们,特别是在使用MySQL时。
如果字符集不是`utf8mb4,将出现错误,例如`Error 1366 (HY000): Incorrect string value: '\\xF0\\x9F\\x8E\\x89 T...' for column 'name' at row 1`。
如果字符集不是`utf8mb4`,将出现错误,例如`Error 1366 (HY000): Incorrect string value: '\\xF0\\x9F\\x8E\\x89 T...' for column 'name' at row 1`。
有关更多信息,请参阅[数据库准备工作](installation/database-preparation.md#mysql)。

或者,您可以从演示文件中删除所有表情符号,然后再尝试一次。
Expand Down
4 changes: 2 additions & 2 deletions docs/content/usage/agit-support.en-us.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ In Gitea `1.13`, support for [agit](https://git-repo.info/en/2020/03/agit-flow-a

## Creating PRs with Agit

Agit allows to create PRs while pushing code to the remote repo. \
This can be done by pushing to the branch followed by a specific refspec (a location identifier known to git). \
Agit allows to create PRs while pushing code to the remote repo.
This can be done by pushing to the branch followed by a specific refspec (a location identifier known to git).
The following example illustrates this:

```shell
Expand Down
Loading

0 comments on commit 24e253a

Please sign in to comment.