From 0e271799f2ec744332761cd87fe0d96f4d9653e0 Mon Sep 17 00:00:00 2001 From: Unknwon Date: Thu, 6 Apr 2017 17:13:53 -0400 Subject: [PATCH] Refactoring: rename and simplify pkg/tool functions --- models/migrations/migrations.go | 4 ++-- models/token.go | 2 +- models/two_factor.go | 4 ++-- models/user.go | 10 +++++----- pkg/markup/markdown.go | 2 +- pkg/markup/markup.go | 2 +- pkg/template/template.go | 6 +++--- pkg/tool/tool.go | 26 ++++++++++++++++---------- routers/install.go | 2 +- routers/repo/commit.go | 4 ++-- routers/repo/http.go | 2 +- routers/repo/pull.go | 2 +- routers/repo/repo.go | 2 +- routers/user/setting.go | 2 +- templates/repo/branch_dropdown.tmpl | 2 +- templates/repo/commits_table.tmpl | 6 +++--- templates/repo/diff/page.tmpl | 4 ++-- templates/repo/release/list.tmpl | 2 +- templates/repo/view_list.tmpl | 8 ++++---- templates/user/dashboard/feeds.tmpl | 2 +- 20 files changed, 50 insertions(+), 44 deletions(-) diff --git a/models/migrations/migrations.go b/models/migrations/migrations.go index 30733423..29cb288a 100644 --- a/models/migrations/migrations.go +++ b/models/migrations/migrations.go @@ -159,10 +159,10 @@ func generateOrgRandsAndSalt(x *xorm.Engine) (err error) { } for _, org := range orgs { - if org.Rands, err = tool.GetRandomString(10); err != nil { + if org.Rands, err = tool.RandomString(10); err != nil { return err } - if org.Salt, err = tool.GetRandomString(10); err != nil { + if org.Salt, err = tool.RandomString(10); err != nil { return err } if _, err = sess.Id(org.ID).Update(org); err != nil { diff --git a/models/token.go b/models/token.go index 6824e43c..9a69a601 100644 --- a/models/token.go +++ b/models/token.go @@ -49,7 +49,7 @@ func (t *AccessToken) AfterSet(colName string, _ xorm.Cell) { // NewAccessToken creates new access token. func NewAccessToken(t *AccessToken) error { - t.Sha1 = tool.EncodeSha1(gouuid.NewV4().String()) + t.Sha1 = tool.SHA1(gouuid.NewV4().String()) _, err := x.Insert(t) return err } diff --git a/models/two_factor.go b/models/two_factor.go index 2f6e7991..60d26147 100644 --- a/models/two_factor.go +++ b/models/two_factor.go @@ -66,9 +66,9 @@ func IsUserEnabledTwoFactor(userID int64) bool { func generateRecoveryCodes(userID int64) ([]*TwoFactorRecoveryCode, error) { recoveryCodes := make([]*TwoFactorRecoveryCode, 10) for i := 0; i < 10; i++ { - code, err := tool.GetRandomString(10) + code, err := tool.RandomString(10) if err != nil { - return nil, fmt.Errorf("GetRandomString: %v", err) + return nil, fmt.Errorf("RandomString: %v", err) } recoveryCodes[i] = &TwoFactorRecoveryCode{ UserID: userID, diff --git a/models/user.go b/models/user.go index d9a1e2a0..9f7b602a 100644 --- a/models/user.go +++ b/models/user.go @@ -489,7 +489,7 @@ func IsUserExist(uid int64, name string) (bool, error) { // GetUserSalt returns a ramdom user salt token. func GetUserSalt() (string, error) { - return tool.GetRandomString(10) + return tool.RandomString(10) } // NewGhostUser creates and returns a fake user for someone has deleted his/her account. @@ -601,12 +601,12 @@ func Users(page, pageSize int) ([]*User, error) { // get user by erify code func getVerifyUser(code string) (user *User) { - if len(code) <= tool.TimeLimitCodeLength { + if len(code) <= tool.TIME_LIMIT_CODE_LENGTH { return nil } // use tail hex username query user - hexStr := code[tool.TimeLimitCodeLength:] + hexStr := code[tool.TIME_LIMIT_CODE_LENGTH:] if b, err := hex.DecodeString(hexStr); err == nil { if user, err = GetUserByName(string(b)); user != nil { return user @@ -623,7 +623,7 @@ func VerifyUserActiveCode(code string) (user *User) { if user = getVerifyUser(code); user != nil { // time limit code - prefix := code[:tool.TimeLimitCodeLength] + prefix := code[:tool.TIME_LIMIT_CODE_LENGTH] data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Passwd + user.Rands if tool.VerifyTimeLimitCode(data, minutes, prefix) { @@ -639,7 +639,7 @@ func VerifyActiveEmailCode(code, email string) *EmailAddress { if user := getVerifyUser(code); user != nil { // time limit code - prefix := code[:tool.TimeLimitCodeLength] + prefix := code[:tool.TIME_LIMIT_CODE_LENGTH] data := com.ToStr(user.ID) + email + user.LowerName + user.Passwd + user.Rands if tool.VerifyTimeLimitCode(data, minutes, prefix) { diff --git a/pkg/markup/markdown.go b/pkg/markup/markdown.go index fc2f54c6..43f58806 100644 --- a/pkg/markup/markdown.go +++ b/pkg/markup/markdown.go @@ -72,7 +72,7 @@ func (r *MarkdownRenderer) AutoLink(out *bytes.Buffer, link []byte, kind int) { if j == -1 { j = len(m) } - out.WriteString(fmt.Sprintf(` %s`, m, tool.ShortSha(string(m[i+7:j])))) + out.WriteString(fmt.Sprintf(` %s`, m, tool.ShortSHA1(string(m[i+7:j])))) return } diff --git a/pkg/markup/markup.go b/pkg/markup/markup.go index 98742540..c5549b6c 100644 --- a/pkg/markup/markup.go +++ b/pkg/markup/markup.go @@ -140,7 +140,7 @@ func RenderSha1CurrentPattern(rawBytes []byte, urlPrefix string) []byte { if com.StrTo(m).MustInt() > 0 { return m } - return fmt.Sprintf(`%s`, urlPrefix, m, tool.ShortSha(string(m))) + return fmt.Sprintf(`%s`, urlPrefix, m, tool.ShortSHA1(string(m))) })) } diff --git a/pkg/template/template.go b/pkg/template/template.go index 55bc8764..dd29ccc4 100644 --- a/pkg/template/template.go +++ b/pkg/template/template.go @@ -96,8 +96,8 @@ func NewFuncMap() []template.FuncMap { "DiffTypeToStr": DiffTypeToStr, "DiffLineTypeToStr": DiffLineTypeToStr, "Sha1": Sha1, - "ShortSha": tool.ShortSha, - "MD5": tool.EncodeMD5, + "ShortSHA1": tool.ShortSHA1, + "MD5": tool.MD5, "ActionContent2Commits": ActionContent2Commits, "EscapePound": EscapePound, "RenderCommitMessage": RenderCommitMessage, @@ -142,7 +142,7 @@ func List(l *list.List) chan interface{} { } func Sha1(str string) string { - return tool.EncodeSha1(str) + return tool.SHA1(str) } func ToUTF8WithErr(content []byte) (error, string) { diff --git a/pkg/tool/tool.go b/pkg/tool/tool.go index 167edbb6..4a5532a3 100644 --- a/pkg/tool/tool.go +++ b/pkg/tool/tool.go @@ -34,28 +34,30 @@ func MD5Bytes(str string) []byte { return m.Sum(nil) } -// EncodeMD5 encodes string to MD5 hex value. -func EncodeMD5(str string) string { +// MD5 encodes string to MD5 hex value. +func MD5(str string) string { return hex.EncodeToString(MD5Bytes(str)) } -// Encode string to sha1 hex value. -func EncodeSha1(str string) string { +// SHA1 encodes string to SHA1 hex value. +func SHA1(str string) string { h := sha1.New() h.Write([]byte(str)) return hex.EncodeToString(h.Sum(nil)) } -func ShortSha(sha1 string) string { +// ShortSHA1 truncates SHA1 string length to at most 10. +func ShortSHA1(sha1 string) string { if len(sha1) > 10 { return sha1[:10] } return sha1 } +// DetectEncoding returns best guess of encoding of given content. func DetectEncoding(content []byte) (string, error) { if utf8.Valid(content) { - log.Trace("Detected encoding: utf-8 (fast)") + log.Trace("Detected encoding: UTF-8 (fast)") return "UTF-8", nil } @@ -69,6 +71,8 @@ func DetectEncoding(content []byte) (string, error) { return result.Charset, err } +// BasicAuthDecode decodes username and password portions of HTTP Basic Authentication +// from encoded content. func BasicAuthDecode(encoded string) (string, string, error) { s, err := base64.StdEncoding.DecodeString(encoded) if err != nil { @@ -79,14 +83,16 @@ func BasicAuthDecode(encoded string) (string, string, error) { return auth[0], auth[1], nil } +// BasicAuthEncode encodes username and password in HTTP Basic Authentication format. func BasicAuthEncode(username, password string) string { return base64.StdEncoding.EncodeToString([]byte(username + ":" + password)) } -// GetRandomString generate random string by specify chars. -func GetRandomString(n int) (string, error) { - const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" +const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" +// RandomString returns generated random string in given length of characters. +// It also returns possible error during generation. +func RandomString(n int) (string, error) { buffer := make([]byte, n) max := big.NewInt(int64(len(alphanum))) @@ -138,7 +144,7 @@ func VerifyTimeLimitCode(data string, minutes int, code string) bool { return false } -const TimeLimitCodeLength = 12 + 6 + 40 +const TIME_LIMIT_CODE_LENGTH = 12 + 6 + 40 // create a time limit code // code format: 12 length date time string + 6 minutes string + 40 sha1 encoded string diff --git a/routers/install.go b/routers/install.go index 2f482e45..2f94dc09 100644 --- a/routers/install.go +++ b/routers/install.go @@ -344,7 +344,7 @@ func InstallPost(ctx *context.Context, f form.Install) { cfg.Section("log").Key("ROOT_PATH").SetValue(f.LogRootPath) cfg.Section("security").Key("INSTALL_LOCK").SetValue("true") - secretKey, err := tool.GetRandomString(15) + secretKey, err := tool.RandomString(15) if err != nil { ctx.RenderWithErr(ctx.Tr("install.secret_key_failed", err), INSTALL, &f) return diff --git a/routers/repo/commit.go b/routers/repo/commit.go index 19803dc6..9723b7f1 100644 --- a/routers/repo/commit.go +++ b/routers/repo/commit.go @@ -165,7 +165,7 @@ func Diff(ctx *context.Context) { ctx.Data["Username"] = userName ctx.Data["Reponame"] = repoName ctx.Data["IsImageFile"] = commit.IsImageFile - ctx.Data["Title"] = commit.Summary() + " · " + tool.ShortSha(commitID) + ctx.Data["Title"] = commit.Summary() + " · " + tool.ShortSHA1(commitID) ctx.Data["Commit"] = commit ctx.Data["Author"] = models.ValidateCommitWithEmail(commit) ctx.Data["Diff"] = diff @@ -228,7 +228,7 @@ func CompareDiff(ctx *context.Context) { ctx.Data["Username"] = userName ctx.Data["Reponame"] = repoName ctx.Data["IsImageFile"] = commit.IsImageFile - ctx.Data["Title"] = "Comparing " + tool.ShortSha(beforeCommitID) + "..." + tool.ShortSha(afterCommitID) + " · " + userName + "/" + repoName + ctx.Data["Title"] = "Comparing " + tool.ShortSHA1(beforeCommitID) + "..." + tool.ShortSHA1(afterCommitID) + " · " + userName + "/" + repoName ctx.Data["Commit"] = commit ctx.Data["Diff"] = diff ctx.Data["DiffNotAvailable"] = diff.NumFiles() == 0 diff --git a/routers/repo/http.go b/routers/repo/http.go index 256ca16f..786fa542 100644 --- a/routers/repo/http.go +++ b/routers/repo/http.go @@ -232,7 +232,7 @@ func ComposeHookEnvs(opts ComposeHookEnvsOptions) []string { ENV_AUTH_USER_NAME + "=" + opts.AuthUser.Name, ENV_AUTH_USER_EMAIL + "=" + opts.AuthUser.Email, ENV_REPO_OWNER_NAME + "=" + opts.OwnerName, - ENV_REPO_OWNER_SALT_MD5 + "=" + tool.EncodeMD5(opts.OwnerSalt), + ENV_REPO_OWNER_SALT_MD5 + "=" + tool.MD5(opts.OwnerSalt), ENV_REPO_ID + "=" + com.ToStr(opts.RepoID), ENV_REPO_NAME + "=" + opts.RepoName, ENV_REPO_CUSTOM_HOOKS_PATH + "=" + path.Join(opts.RepoPath, "custom_hooks"), diff --git a/routers/repo/pull.go b/routers/repo/pull.go index 6d420121..6ff313b7 100644 --- a/routers/repo/pull.go +++ b/routers/repo/pull.go @@ -738,7 +738,7 @@ func TriggerTask(ctx *context.Context) { if ctx.Written() { return } - if secret != tool.EncodeMD5(owner.Salt) { + if secret != tool.MD5(owner.Salt) { ctx.Error(404) log.Trace("TriggerTask [%s/%s]: invalid secret", owner.Name, repo.Name) return diff --git a/routers/repo/repo.go b/routers/repo/repo.go index 2781da9a..bdc471fe 100644 --- a/routers/repo/repo.go +++ b/routers/repo/repo.go @@ -323,7 +323,7 @@ func Download(ctx *context.Context) { return } - archivePath = path.Join(archivePath, tool.ShortSha(commit.ID.String())+ext) + archivePath = path.Join(archivePath, tool.ShortSHA1(commit.ID.String())+ext) if !com.IsFile(archivePath) { if err := commit.CreateArchive(archivePath, archiveType); err != nil { ctx.Handle(500, "Download -> CreateArchive "+archivePath, err) diff --git a/routers/user/setting.go b/routers/user/setting.go index 9083454a..b9c70d64 100644 --- a/routers/user/setting.go +++ b/routers/user/setting.go @@ -123,7 +123,7 @@ func SettingsPost(ctx *context.Context, f form.UpdateProfile) { func UpdateAvatarSetting(ctx *context.Context, f form.Avatar, ctxUser *models.User) error { ctxUser.UseCustomAvatar = f.Source == form.AVATAR_LOCAL if len(f.Gravatar) > 0 { - ctxUser.Avatar = tool.EncodeMD5(f.Gravatar) + ctxUser.Avatar = tool.MD5(f.Gravatar) ctxUser.AvatarEmail = f.Gravatar } diff --git a/templates/repo/branch_dropdown.tmpl b/templates/repo/branch_dropdown.tmpl index 1a8c7aa8..26409707 100644 --- a/templates/repo/branch_dropdown.tmpl +++ b/templates/repo/branch_dropdown.tmpl @@ -4,7 +4,7 @@ {{if .IsViewBranch}}{{.i18n.Tr "repo.branch"}}{{else}}{{.i18n.Tr "repo.tree"}}{{end}}: - {{if .IsViewBranch}}{{.BranchName}}{{else}}{{ShortSha .BranchName}}{{end}} + {{if .IsViewBranch}}{{.BranchName}}{{else}}{{ShortSHA1 .BranchName}}{{end}} diff --git a/templates/repo/commits_table.tmpl b/templates/repo/commits_table.tmpl index a95cb824..e68dd76f 100644 --- a/templates/repo/commits_table.tmpl +++ b/templates/repo/commits_table.tmpl @@ -14,7 +14,7 @@ {{else if .IsDiffCompare}} - {{ShortSha .BeforeCommitID}} ... {{ShortSha .AfterCommitID}} + {{ShortSHA1 .BeforeCommitID}} ... {{ShortSHA1 .AfterCommitID}} {{end}} @@ -43,9 +43,9 @@ {{/* Username or Reponame doesn't present we assume the source repository no longer exists */}} {{if not (and $.Username $.Reponame)}} - {{ShortSha .ID.String}} + {{ShortSHA1 .ID.String}} {{else}} - {{ShortSha .ID.String}} + {{ShortSHA1 .ID.String}} {{end}} {{RenderCommitMessage false .Summary $.RepoLink $.Repository.ComposeMetas}} diff --git a/templates/repo/diff/page.tmpl b/templates/repo/diff/page.tmpl index 0a35a804..4d2f6bc1 100644 --- a/templates/repo/diff/page.tmpl +++ b/templates/repo/diff/page.tmpl @@ -28,12 +28,12 @@
{{range .Parents}} - {{ShortSha .}} + {{ShortSHA1 .}} {{end}}
{{end}}
{{.i18n.Tr "repo.diff.commit"}}
-
{{ShortSha .CommitID}}
+
{{ShortSHA1 .CommitID}}
diff --git a/templates/repo/release/list.tmpl b/templates/repo/release/list.tmpl index ccb611fb..c4414534 100644 --- a/templates/repo/release/list.tmpl +++ b/templates/repo/release/list.tmpl @@ -28,7 +28,7 @@ {{end}} - {{ShortSha .Sha1}} + {{ShortSHA1 .Sha1}}
diff --git a/templates/repo/view_list.tmpl b/templates/repo/view_list.tmpl index f532dd74..1b7ae9e0 100644 --- a/templates/repo/view_list.tmpl +++ b/templates/repo/view_list.tmpl @@ -9,7 +9,7 @@ {{.LatestCommit.Author.Name}} {{end}} - {{ShortSha .LatestCommit.ID.String}} + {{ShortSHA1 .LatestCommit.ID.String}} {{RenderCommitMessage false .LatestCommit.Summary .RepoLink $.Repository.ComposeMetas}} @@ -32,9 +32,9 @@ {{$refURL := $commit.RefURL AppUrl $.BranchLink}} {{if $refURL}} - {{$entry.Name}} @ {{ShortSha $commit.RefID}} + {{$entry.Name}} @ {{ShortSHA1 $commit.RefID}} {{else}} - {{$entry.Name}} @ {{ShortSha $commit.RefID}} + {{$entry.Name}} @ {{ShortSHA1 $commit.RefID}} {{end}} {{else}} @@ -44,7 +44,7 @@ {{end}} - {{ShortSha $commit.ID.String}} + {{ShortSHA1 $commit.ID.String}} {{RenderCommitMessage false $commit.Summary $.RepoLink $.Repository.ComposeMetas}} {{TimeSince $commit.Committer.When $.Lang}} diff --git a/templates/user/dashboard/feeds.tmpl b/templates/user/dashboard/feeds.tmpl index a110c04a..17f3d6c0 100644 --- a/templates/user/dashboard/feeds.tmpl +++ b/templates/user/dashboard/feeds.tmpl @@ -62,7 +62,7 @@ {{ $repoLink := .GetRepoLink}} {{if $push.Commits}} {{range $push.Commits}} -
  • {{ShortSha .Sha1}} {{.Message}}
  • +
  • {{ShortSHA1 .Sha1}} {{.Message}}
  • {{end}} {{end}} {{if and (gt $push.Len 1) $push.CompareURL}}
  • {{$.i18n.Tr "action.compare_commits" $push.Len}} »
  • {{end}}