THIS IS A TEST INSTANCE ONLY! REPOSITORIES CAN BE DELETED AT ANY TIME!

Browse Source

General refactor of the cmd package (#3328)

* General refactor of the cmd package

* Address breakage in runCreateUser

* Place "common" functions into cmd.go
tags/v1.4.0-rc1
Morgan Bazalgette 1 year ago
parent
commit
2b52f77e1b
6 changed files with 92 additions and 79 deletions
  1. 27
    51
      cmd/admin.go
  2. 13
    13
      cmd/cert.go
  3. 38
    0
      cmd/cmd.go
  4. 8
    8
      cmd/dump.go
  5. 2
    2
      cmd/hook.go
  6. 4
    5
      cmd/web.go

+ 27
- 51
cmd/admin.go View File

@@ -20,9 +20,7 @@ var (
20 20
 	// CmdAdmin represents the available admin sub-command.
21 21
 	CmdAdmin = cli.Command{
22 22
 		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",
26 24
 		Subcommands: []cli.Command{
27 25
 			subcmdCreateUser,
28 26
 			subcmdChangePassword,
@@ -37,17 +35,14 @@ to make automatic initialization process more smoothly`,
37 35
 		Flags: []cli.Flag{
38 36
 			cli.StringFlag{
39 37
 				Name:  "name",
40
-				Value: "",
41 38
 				Usage: "Username",
42 39
 			},
43 40
 			cli.StringFlag{
44 41
 				Name:  "password",
45
-				Value: "",
46 42
 				Usage: "User password",
47 43
 			},
48 44
 			cli.StringFlag{
49 45
 				Name:  "email",
50
-				Value: "",
51 46
 				Usage: "User email address",
52 47
 			},
53 48
 			cli.BoolFlag{
@@ -88,56 +83,42 @@ to make automatic initialization process more smoothly`,
88 83
 )
89 84
 
90 85
 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
95 88
 	}
96 89
 
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
103 92
 	}
104 93
 
105 94
 	uname := c.String("username")
106 95
 	user, err := models.GetUserByName(uname)
107 96
 	if err != nil {
108
-		return fmt.Errorf("%v", err)
97
+		return err
109 98
 	}
110 99
 	if user.Salt, err = models.GetUserSalt(); err != nil {
111
-		return fmt.Errorf("%v", err)
100
+		return err
112 101
 	}
113 102
 	user.HashPassword(c.String("password"))
114 103
 	if err := models.UpdateUserCols(user, "passwd", "salt"); err != nil {
115
-		return fmt.Errorf("%v", err)
104
+		return err
116 105
 	}
117 106
 
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)
119 108
 	return nil
120 109
 }
121 110
 
122 111
 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
129 114
 	}
130 115
 
131 116
 	if c.IsSet("config") {
132 117
 		setting.CustomConf = c.String("config")
133 118
 	}
134 119
 
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
141 122
 	}
142 123
 
143 124
 	if err := models.CreateUser(&models.User{
@@ -155,13 +136,8 @@ func runCreateUser(c *cli.Context) error {
155 136
 }
156 137
 
157 138
 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
165 141
 	}
166 142
 
167 143
 	log.Trace("Synchronizing repository releases (this may take a while)")
@@ -172,8 +148,7 @@ func runRepoSyncReleases(c *cli.Context) error {
172 148
 			Private:  true,
173 149
 		})
174 150
 		if err != nil {
175
-			log.Fatal(4, "SearchRepositoryByName: %v", err)
176
-			return err
151
+			return fmt.Errorf("SearchRepositoryByName: %v", err)
177 152
 		}
178 153
 		if len(repos) == 0 {
179 154
 			break
@@ -187,11 +162,7 @@ func runRepoSyncReleases(c *cli.Context) error {
187 162
 				continue
188 163
 			}
189 164
 
190
-			oldnum, err := models.GetReleaseCountByRepoID(repo.ID,
191
-				models.FindReleasesOptions{
192
-					IncludeDrafts: false,
193
-					IncludeTags:   true,
194
-				})
165
+			oldnum, err := getReleaseCount(repo.ID)
195 166
 			if err != nil {
196 167
 				log.Warn(" GetReleaseCountByRepoID: %v", err)
197 168
 			}
@@ -202,11 +173,7 @@ func runRepoSyncReleases(c *cli.Context) error {
202 173
 				continue
203 174
 			}
204 175
 
205
-			count, err = models.GetReleaseCountByRepoID(repo.ID,
206
-				models.FindReleasesOptions{
207
-					IncludeDrafts: false,
208
-					IncludeTags:   true,
209
-				})
176
+			count, err = getReleaseCount(repo.ID)
210 177
 			if err != nil {
211 178
 				log.Warn(" GetReleaseCountByRepoID: %v", err)
212 179
 				continue
@@ -219,3 +186,12 @@ func runRepoSyncReleases(c *cli.Context) error {
219 186
 
220 187
 	return nil
221 188
 }
189
+
190
+func getReleaseCount(id int64) (int64, error) {
191
+	return models.GetReleaseCountByRepoID(
192
+		id,
193
+		models.FindReleasesOptions{
194
+			IncludeTags: true,
195
+		},
196
+	)
197
+}

+ 13
- 13
cmd/cert.go View File

@@ -90,16 +90,16 @@ func pemBlockForKey(priv interface{}) *pem.Block {
90 90
 	}
91 91
 }
92 92
 
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
96 96
 	}
97 97
 
98 98
 	var priv interface{}
99 99
 	var err error
100
-	switch ctx.String("ecdsa-curve") {
100
+	switch c.String("ecdsa-curve") {
101 101
 	case "":
102
-		priv, err = rsa.GenerateKey(rand.Reader, ctx.Int("rsa-bits"))
102
+		priv, err = rsa.GenerateKey(rand.Reader, c.Int("rsa-bits"))
103 103
 	case "P224":
104 104
 		priv, err = ecdsa.GenerateKey(elliptic.P224(), rand.Reader)
105 105
 	case "P256":
@@ -109,23 +109,23 @@ func runCert(ctx *cli.Context) error {
109 109
 	case "P521":
110 110
 		priv, err = ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
111 111
 	default:
112
-		log.Fatalf("Unrecognized elliptic curve: %q", ctx.String("ecdsa-curve"))
112
+		log.Fatalf("Unrecognized elliptic curve: %q", c.String("ecdsa-curve"))
113 113
 	}
114 114
 	if err != nil {
115 115
 		log.Fatalf("Failed to generate private key: %v", err)
116 116
 	}
117 117
 
118 118
 	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)
123 121
 		if err != nil {
124 122
 			log.Fatalf("Failed to parse creation date: %v", err)
125 123
 		}
124
+	} else {
125
+		notBefore = time.Now()
126 126
 	}
127 127
 
128
-	notAfter := notBefore.Add(ctx.Duration("duration"))
128
+	notAfter := notBefore.Add(c.Duration("duration"))
129 129
 
130 130
 	serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
131 131
 	serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
@@ -147,7 +147,7 @@ func runCert(ctx *cli.Context) error {
147 147
 		BasicConstraintsValid: true,
148 148
 	}
149 149
 
150
-	hosts := strings.Split(ctx.String("host"), ",")
150
+	hosts := strings.Split(c.String("host"), ",")
151 151
 	for _, h := range hosts {
152 152
 		if ip := net.ParseIP(h); ip != nil {
153 153
 			template.IPAddresses = append(template.IPAddresses, ip)
@@ -156,7 +156,7 @@ func runCert(ctx *cli.Context) error {
156 156
 		}
157 157
 	}
158 158
 
159
-	if ctx.Bool("ca") {
159
+	if c.Bool("ca") {
160 160
 		template.IsCA = true
161 161
 		template.KeyUsage |= x509.KeyUsageCertSign
162 162
 	}

+ 38
- 0
cmd/cmd.go View File

@@ -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
+}

+ 8
- 8
cmd/dump.go View File

@@ -68,19 +68,19 @@ func runDump(ctx *cli.Context) error {
68 68
 	if _, err := os.Stat(tmpDir); os.IsNotExist(err) {
69 69
 		log.Fatalf("Path does not exist: %s", tmpDir)
70 70
 	}
71
-	TmpWorkDir, err := ioutil.TempDir(tmpDir, "gitea-dump-")
71
+	tmpWorkDir, err := ioutil.TempDir(tmpDir, "gitea-dump-")
72 72
 	if err != nil {
73 73
 		log.Fatalf("Failed to create tmp work directory: %v", err)
74 74
 	}
75
-	log.Printf("Creating tmp work dir: %s", TmpWorkDir)
75
+	log.Printf("Creating tmp work dir: %s", tmpWorkDir)
76 76
 
77 77
 	// work-around #1103
78 78
 	if os.Getenv("TMPDIR") == "" {
79
-		os.Setenv("TMPDIR", TmpWorkDir)
79
+		os.Setenv("TMPDIR", tmpWorkDir)
80 80
 	}
81 81
 
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")
84 84
 
85 85
 	log.Printf("Dumping local repositories...%s", setting.RepoRootPath)
86 86
 	zip.Verbose = ctx.Bool("verbose")
@@ -146,10 +146,10 @@ func runDump(ctx *cli.Context) error {
146 146
 		log.Printf("Can't change file access permissions mask to 0600: %v", err)
147 147
 	}
148 148
 
149
-	log.Printf("Removing tmp work dir: %s", TmpWorkDir)
149
+	log.Printf("Removing tmp work dir: %s", tmpWorkDir)
150 150
 
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)
153 153
 	}
154 154
 	log.Printf("Finish dumping in file %s", fileName)
155 155
 

+ 2
- 2
cmd/hook.go View File

@@ -37,7 +37,7 @@ var (
37 37
 		},
38 38
 		Subcommands: []cli.Command{
39 39
 			subcmdHookPreReceive,
40
-			subcmdHookUpadte,
40
+			subcmdHookUpdate,
41 41
 			subcmdHookPostReceive,
42 42
 		},
43 43
 	}
@@ -48,7 +48,7 @@ var (
48 48
 		Description: "This command should only be called by Git",
49 49
 		Action:      runHookPreReceive,
50 50
 	}
51
-	subcmdHookUpadte = cli.Command{
51
+	subcmdHookUpdate = cli.Command{
52 52
 		Name:        "update",
53 53
 		Usage:       "Delegate update Git hook",
54 54
 		Description: "This command should only be called by Git",

+ 4
- 5
cmd/web.go View File

@@ -121,11 +121,9 @@ func runWeb(ctx *cli.Context) error {
121 121
 		}
122 122
 	}
123 123
 
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
129 127
 	}
130 128
 	log.Info("Listen: %v://%s%s", setting.Protocol, listenAddr, setting.AppSubURL)
131 129
 
@@ -135,6 +133,7 @@ func runWeb(ctx *cli.Context) error {
135 133
 
136 134
 	if setting.EnablePprof {
137 135
 		go func() {
136
+			log.Info("Starting pprof server on localhost:6060")
138 137
 			log.Info("%v", http.ListenAndServe("localhost:6060", nil))
139 138
 		}()
140 139
 	}

Loading…
Cancel
Save