Skip to content

Commit 2b52f77

Browse files
thehowlbkcsoft
authored andcommitted
General refactor of the cmd package (#3328)
* General refactor of the cmd package * Address breakage in runCreateUser * Place "common" functions into cmd.go
1 parent 079273e commit 2b52f77

File tree

6 files changed

+92
-79
lines changed

6 files changed

+92
-79
lines changed

cmd/admin.go

+27-51
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,7 @@ var (
2020
// CmdAdmin represents the available admin sub-command.
2121
CmdAdmin = cli.Command{
2222
Name: "admin",
23-
Usage: "Perform admin operations on command line",
24-
Description: `Allow using internal logic of Gitea without hacking into the source code
25-
to make automatic initialization process more smoothly`,
23+
Usage: "Command line interface to perform common administrative operations",
2624
Subcommands: []cli.Command{
2725
subcmdCreateUser,
2826
subcmdChangePassword,
@@ -37,17 +35,14 @@ to make automatic initialization process more smoothly`,
3735
Flags: []cli.Flag{
3836
cli.StringFlag{
3937
Name: "name",
40-
Value: "",
4138
Usage: "Username",
4239
},
4340
cli.StringFlag{
4441
Name: "password",
45-
Value: "",
4642
Usage: "User password",
4743
},
4844
cli.StringFlag{
4945
Name: "email",
50-
Value: "",
5146
Usage: "User email address",
5247
},
5348
cli.BoolFlag{
@@ -88,56 +83,42 @@ to make automatic initialization process more smoothly`,
8883
)
8984

9085
func runChangePassword(c *cli.Context) error {
91-
if !c.IsSet("password") {
92-
return fmt.Errorf("Password is not specified")
93-
} else if !c.IsSet("username") {
94-
return fmt.Errorf("Username is not specified")
86+
if err := argsSet(c, "username", "password"); err != nil {
87+
return err
9588
}
9689

97-
setting.NewContext()
98-
models.LoadConfigs()
99-
100-
setting.NewXORMLogService(false)
101-
if err := models.SetEngine(); err != nil {
102-
return fmt.Errorf("models.SetEngine: %v", err)
90+
if err := initDB(); err != nil {
91+
return err
10392
}
10493

10594
uname := c.String("username")
10695
user, err := models.GetUserByName(uname)
10796
if err != nil {
108-
return fmt.Errorf("%v", err)
97+
return err
10998
}
11099
if user.Salt, err = models.GetUserSalt(); err != nil {
111-
return fmt.Errorf("%v", err)
100+
return err
112101
}
113102
user.HashPassword(c.String("password"))
114103
if err := models.UpdateUserCols(user, "passwd", "salt"); err != nil {
115-
return fmt.Errorf("%v", err)
104+
return err
116105
}
117106

118-
fmt.Printf("User '%s' password has been successfully updated!\n", uname)
107+
fmt.Printf("%s's password has been successfully updated!\n", user.Name)
119108
return nil
120109
}
121110

122111
func runCreateUser(c *cli.Context) error {
123-
if !c.IsSet("name") {
124-
return fmt.Errorf("Username is not specified")
125-
} else if !c.IsSet("password") {
126-
return fmt.Errorf("Password is not specified")
127-
} else if !c.IsSet("email") {
128-
return fmt.Errorf("Email is not specified")
112+
if err := argsSet(c, "name", "password", "email"); err != nil {
113+
return err
129114
}
130115

131116
if c.IsSet("config") {
132117
setting.CustomConf = c.String("config")
133118
}
134119

135-
setting.NewContext()
136-
models.LoadConfigs()
137-
138-
setting.NewXORMLogService(false)
139-
if err := models.SetEngine(); err != nil {
140-
return fmt.Errorf("models.SetEngine: %v", err)
120+
if err := initDB(); err != nil {
121+
return err
141122
}
142123

143124
if err := models.CreateUser(&models.User{
@@ -155,13 +136,8 @@ func runCreateUser(c *cli.Context) error {
155136
}
156137

157138
func runRepoSyncReleases(c *cli.Context) error {
158-
159-
setting.NewContext()
160-
models.LoadConfigs()
161-
162-
setting.NewXORMLogService(false)
163-
if err := models.SetEngine(); err != nil {
164-
return fmt.Errorf("models.SetEngine: %v", err)
139+
if err := initDB(); err != nil {
140+
return err
165141
}
166142

167143
log.Trace("Synchronizing repository releases (this may take a while)")
@@ -172,8 +148,7 @@ func runRepoSyncReleases(c *cli.Context) error {
172148
Private: true,
173149
})
174150
if err != nil {
175-
log.Fatal(4, "SearchRepositoryByName: %v", err)
176-
return err
151+
return fmt.Errorf("SearchRepositoryByName: %v", err)
177152
}
178153
if len(repos) == 0 {
179154
break
@@ -187,11 +162,7 @@ func runRepoSyncReleases(c *cli.Context) error {
187162
continue
188163
}
189164

190-
oldnum, err := models.GetReleaseCountByRepoID(repo.ID,
191-
models.FindReleasesOptions{
192-
IncludeDrafts: false,
193-
IncludeTags: true,
194-
})
165+
oldnum, err := getReleaseCount(repo.ID)
195166
if err != nil {
196167
log.Warn(" GetReleaseCountByRepoID: %v", err)
197168
}
@@ -202,11 +173,7 @@ func runRepoSyncReleases(c *cli.Context) error {
202173
continue
203174
}
204175

205-
count, err = models.GetReleaseCountByRepoID(repo.ID,
206-
models.FindReleasesOptions{
207-
IncludeDrafts: false,
208-
IncludeTags: true,
209-
})
176+
count, err = getReleaseCount(repo.ID)
210177
if err != nil {
211178
log.Warn(" GetReleaseCountByRepoID: %v", err)
212179
continue
@@ -219,3 +186,12 @@ func runRepoSyncReleases(c *cli.Context) error {
219186

220187
return nil
221188
}
189+
190+
func getReleaseCount(id int64) (int64, error) {
191+
return models.GetReleaseCountByRepoID(
192+
id,
193+
models.FindReleasesOptions{
194+
IncludeTags: true,
195+
},
196+
)
197+
}

cmd/cert.go

+13-13
Original file line numberDiff line numberDiff line change
@@ -90,16 +90,16 @@ func pemBlockForKey(priv interface{}) *pem.Block {
9090
}
9191
}
9292

93-
func runCert(ctx *cli.Context) error {
94-
if len(ctx.String("host")) == 0 {
95-
log.Fatal("Missing required --host parameter")
93+
func runCert(c *cli.Context) error {
94+
if err := argsSet(c, "host"); err != nil {
95+
return err
9696
}
9797

9898
var priv interface{}
9999
var err error
100-
switch ctx.String("ecdsa-curve") {
100+
switch c.String("ecdsa-curve") {
101101
case "":
102-
priv, err = rsa.GenerateKey(rand.Reader, ctx.Int("rsa-bits"))
102+
priv, err = rsa.GenerateKey(rand.Reader, c.Int("rsa-bits"))
103103
case "P224":
104104
priv, err = ecdsa.GenerateKey(elliptic.P224(), rand.Reader)
105105
case "P256":
@@ -109,23 +109,23 @@ func runCert(ctx *cli.Context) error {
109109
case "P521":
110110
priv, err = ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
111111
default:
112-
log.Fatalf("Unrecognized elliptic curve: %q", ctx.String("ecdsa-curve"))
112+
log.Fatalf("Unrecognized elliptic curve: %q", c.String("ecdsa-curve"))
113113
}
114114
if err != nil {
115115
log.Fatalf("Failed to generate private key: %v", err)
116116
}
117117

118118
var notBefore time.Time
119-
if len(ctx.String("start-date")) == 0 {
120-
notBefore = time.Now()
121-
} else {
122-
notBefore, err = time.Parse("Jan 2 15:04:05 2006", ctx.String("start-date"))
119+
if startDate := c.String("start-date"); startDate != "" {
120+
notBefore, err = time.Parse("Jan 2 15:04:05 2006", startDate)
123121
if err != nil {
124122
log.Fatalf("Failed to parse creation date: %v", err)
125123
}
124+
} else {
125+
notBefore = time.Now()
126126
}
127127

128-
notAfter := notBefore.Add(ctx.Duration("duration"))
128+
notAfter := notBefore.Add(c.Duration("duration"))
129129

130130
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
131131
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
@@ -147,7 +147,7 @@ func runCert(ctx *cli.Context) error {
147147
BasicConstraintsValid: true,
148148
}
149149

150-
hosts := strings.Split(ctx.String("host"), ",")
150+
hosts := strings.Split(c.String("host"), ",")
151151
for _, h := range hosts {
152152
if ip := net.ParseIP(h); ip != nil {
153153
template.IPAddresses = append(template.IPAddresses, ip)
@@ -156,7 +156,7 @@ func runCert(ctx *cli.Context) error {
156156
}
157157
}
158158

159-
if ctx.Bool("ca") {
159+
if c.Bool("ca") {
160160
template.IsCA = true
161161
template.KeyUsage |= x509.KeyUsageCertSign
162162
}

cmd/cmd.go

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// Copyright 2018 The Gitea Authors. All rights reserved.
2+
// Use of this source code is governed by a MIT-style
3+
// license that can be found in the LICENSE file.
4+
5+
// Package cmd provides subcommands to the gitea binary - such as "web" or
6+
// "admin".
7+
package cmd
8+
9+
import (
10+
"errors"
11+
"fmt"
12+
13+
"code.gitea.io/gitea/models"
14+
"code.gitea.io/gitea/modules/setting"
15+
"github.com/urfave/cli"
16+
)
17+
18+
// argsSet checks that all the required arguments are set. args is a list of
19+
// arguments that must be set in the passed Context.
20+
func argsSet(c *cli.Context, args ...string) error {
21+
for _, a := range args {
22+
if !c.IsSet(a) {
23+
return errors.New(a + " is not set")
24+
}
25+
}
26+
return nil
27+
}
28+
29+
func initDB() error {
30+
setting.NewContext()
31+
models.LoadConfigs()
32+
33+
setting.NewXORMLogService(false)
34+
if err := models.SetEngine(); err != nil {
35+
return fmt.Errorf("models.SetEngine: %v", err)
36+
}
37+
return nil
38+
}

cmd/dump.go

+8-8
Original file line numberDiff line numberDiff line change
@@ -68,19 +68,19 @@ func runDump(ctx *cli.Context) error {
6868
if _, err := os.Stat(tmpDir); os.IsNotExist(err) {
6969
log.Fatalf("Path does not exist: %s", tmpDir)
7070
}
71-
TmpWorkDir, err := ioutil.TempDir(tmpDir, "gitea-dump-")
71+
tmpWorkDir, err := ioutil.TempDir(tmpDir, "gitea-dump-")
7272
if err != nil {
7373
log.Fatalf("Failed to create tmp work directory: %v", err)
7474
}
75-
log.Printf("Creating tmp work dir: %s", TmpWorkDir)
75+
log.Printf("Creating tmp work dir: %s", tmpWorkDir)
7676

7777
// work-around #1103
7878
if os.Getenv("TMPDIR") == "" {
79-
os.Setenv("TMPDIR", TmpWorkDir)
79+
os.Setenv("TMPDIR", tmpWorkDir)
8080
}
8181

82-
reposDump := path.Join(TmpWorkDir, "gitea-repo.zip")
83-
dbDump := path.Join(TmpWorkDir, "gitea-db.sql")
82+
reposDump := path.Join(tmpWorkDir, "gitea-repo.zip")
83+
dbDump := path.Join(tmpWorkDir, "gitea-db.sql")
8484

8585
log.Printf("Dumping local repositories...%s", setting.RepoRootPath)
8686
zip.Verbose = ctx.Bool("verbose")
@@ -146,10 +146,10 @@ func runDump(ctx *cli.Context) error {
146146
log.Printf("Can't change file access permissions mask to 0600: %v", err)
147147
}
148148

149-
log.Printf("Removing tmp work dir: %s", TmpWorkDir)
149+
log.Printf("Removing tmp work dir: %s", tmpWorkDir)
150150

151-
if err := os.RemoveAll(TmpWorkDir); err != nil {
152-
log.Fatalf("Failed to remove %s: %v", TmpWorkDir, err)
151+
if err := os.RemoveAll(tmpWorkDir); err != nil {
152+
log.Fatalf("Failed to remove %s: %v", tmpWorkDir, err)
153153
}
154154
log.Printf("Finish dumping in file %s", fileName)
155155

cmd/hook.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ var (
3737
},
3838
Subcommands: []cli.Command{
3939
subcmdHookPreReceive,
40-
subcmdHookUpadte,
40+
subcmdHookUpdate,
4141
subcmdHookPostReceive,
4242
},
4343
}
@@ -48,7 +48,7 @@ var (
4848
Description: "This command should only be called by Git",
4949
Action: runHookPreReceive,
5050
}
51-
subcmdHookUpadte = cli.Command{
51+
subcmdHookUpdate = cli.Command{
5252
Name: "update",
5353
Usage: "Delegate update Git hook",
5454
Description: "This command should only be called by Git",

cmd/web.go

+4-5
Original file line numberDiff line numberDiff line change
@@ -121,11 +121,9 @@ func runWeb(ctx *cli.Context) error {
121121
}
122122
}
123123

124-
var listenAddr string
125-
if setting.Protocol == setting.UnixSocket {
126-
listenAddr = fmt.Sprintf("%s", setting.HTTPAddr)
127-
} else {
128-
listenAddr = fmt.Sprintf("%s:%s", setting.HTTPAddr, setting.HTTPPort)
124+
listenAddr := setting.HTTPAddr
125+
if setting.Protocol != setting.UnixSocket {
126+
listenAddr += ":" + setting.HTTPPort
129127
}
130128
log.Info("Listen: %v://%s%s", setting.Protocol, listenAddr, setting.AppSubURL)
131129

@@ -135,6 +133,7 @@ func runWeb(ctx *cli.Context) error {
135133

136134
if setting.EnablePprof {
137135
go func() {
136+
log.Info("Starting pprof server on localhost:6060")
138137
log.Info("%v", http.ListenAndServe("localhost:6060", nil))
139138
}()
140139
}

0 commit comments

Comments
 (0)