Refactoring: rename and simplify pkg/tool functions

master
Unknwon 2017-04-06 17:13:53 -04:00
parent 3c0de17133
commit 0e271799f2
No known key found for this signature in database
GPG Key ID: 25B575AE3213B2B3
20 changed files with 50 additions and 44 deletions

View File

@ -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 {

View File

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

View File

@ -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,

View File

@ -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) {

View File

@ -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(` <code><a href="%s">%s</a></code>`, m, tool.ShortSha(string(m[i+7:j]))))
out.WriteString(fmt.Sprintf(` <code><a href="%s">%s</a></code>`, m, tool.ShortSHA1(string(m[i+7:j]))))
return
}

View File

@ -140,7 +140,7 @@ func RenderSha1CurrentPattern(rawBytes []byte, urlPrefix string) []byte {
if com.StrTo(m).MustInt() > 0 {
return m
}
return fmt.Sprintf(`<a href="%s/commit/%s"><code>%s</code></a>`, urlPrefix, m, tool.ShortSha(string(m)))
return fmt.Sprintf(`<a href="%s/commit/%s"><code>%s</code></a>`, urlPrefix, m, tool.ShortSHA1(string(m)))
}))
}

View File

@ -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) {

View File

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

View File

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

View File

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

View File

@ -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"),

View File

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

View File

@ -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)

View File

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

View File

@ -4,7 +4,7 @@
<span class="text">
<i class="octicon octicon-git-branch"></i>
{{if .IsViewBranch}}{{.i18n.Tr "repo.branch"}}{{else}}{{.i18n.Tr "repo.tree"}}{{end}}:
<strong>{{if .IsViewBranch}}{{.BranchName}}{{else}}{{ShortSha .BranchName}}{{end}}</strong>
<strong>{{if .IsViewBranch}}{{.BranchName}}{{else}}{{ShortSHA1 .BranchName}}{{end}}</strong>
</span>
<i class="dropdown icon"></i>
</div>

View File

@ -14,7 +14,7 @@
</form>
</div>
{{else if .IsDiffCompare}}
<a href="{{$.CommitRepoLink}}/commit/{{.BeforeCommitID}}" class="ui green sha label">{{ShortSha .BeforeCommitID}}</a> ... <a href="{{$.CommitRepoLink}}/commit/{{.AfterCommitID}}" class="ui green sha label">{{ShortSha .AfterCommitID}}</a>
<a href="{{$.CommitRepoLink}}/commit/{{.BeforeCommitID}}" class="ui green sha label">{{ShortSHA1 .BeforeCommitID}}</a> ... <a href="{{$.CommitRepoLink}}/commit/{{.AfterCommitID}}" class="ui green sha label">{{ShortSHA1 .AfterCommitID}}</a>
{{end}}
</h4>
@ -43,9 +43,9 @@
<td class="message collapsing has-emoji">
{{/* Username or Reponame doesn't present we assume the source repository no longer exists */}}
{{if not (and $.Username $.Reponame)}}
<span class="ui sha label">{{ShortSha .ID.String}}</span>
<span class="ui sha label">{{ShortSHA1 .ID.String}}</span>
{{else}}
<a rel="nofollow" class="ui sha label" href="{{AppSubUrl}}/{{$.Username}}/{{$.Reponame}}/commit/{{.ID}}">{{ShortSha .ID.String}}</a>
<a rel="nofollow" class="ui sha label" href="{{AppSubUrl}}/{{$.Username}}/{{$.Reponame}}/commit/{{.ID}}">{{ShortSHA1 .ID.String}}</a>
{{end}}
<span {{if gt .ParentCount 1}}class="grey text"{{end}}>{{RenderCommitMessage false .Summary $.RepoLink $.Repository.ComposeMetas}}</span>
</td>

View File

@ -28,12 +28,12 @@
</div>
<div class="item">
{{range .Parents}}
<a class="ui blue sha label" href="{{$.RepoLink}}/commit/{{.}}">{{ShortSha .}}</a>
<a class="ui blue sha label" href="{{$.RepoLink}}/commit/{{.}}">{{ShortSHA1 .}}</a>
{{end}}
</div>
{{end}}
<div class="item">{{.i18n.Tr "repo.diff.commit"}}</div>
<div class="item"><span class="ui blue sha label">{{ShortSha .CommitID}}</span></div>
<div class="item"><span class="ui blue sha label">{{ShortSHA1 .CommitID}}</span></div>
</div>
</div>
</div>

View File

@ -28,7 +28,7 @@
</span>
{{end}}
<span class="commit">
<a href="{{$.RepoLink}}/src/{{.Sha1}}" rel="nofollow"><i class="code icon"></i> {{ShortSha .Sha1}}</a>
<a href="{{$.RepoLink}}/src/{{.Sha1}}" rel="nofollow"><i class="code icon"></i> {{ShortSHA1 .Sha1}}</a>
</span>
</div>
<div class="ui twelve wide column detail">

View File

@ -9,7 +9,7 @@
<img class="ui avatar image img-12" src="{{AvatarLink .LatestCommit.Author.Email}}" />
<strong>{{.LatestCommit.Author.Name}}</strong>
{{end}}
<a rel="nofollow" class="ui sha label" href="{{.RepoLink}}/commit/{{.LatestCommit.ID}}" rel="nofollow">{{ShortSha .LatestCommit.ID.String}}</a>
<a rel="nofollow" class="ui sha label" href="{{.RepoLink}}/commit/{{.LatestCommit.ID}}" rel="nofollow">{{ShortSHA1 .LatestCommit.ID.String}}</a>
<span class="grey has-emoji">{{RenderCommitMessage false .LatestCommit.Summary .RepoLink $.Repository.ComposeMetas}}</span>
</th>
<th class="nine wide">
@ -32,9 +32,9 @@
<span class="octicon octicon-file-submodule"></span>
{{$refURL := $commit.RefURL AppUrl $.BranchLink}}
{{if $refURL}}
<a href="{{$refURL}}">{{$entry.Name}}</a> @ <a href="{{$refURL}}/commit/{{$commit.RefID}}">{{ShortSha $commit.RefID}}</a>
<a href="{{$refURL}}">{{$entry.Name}}</a> @ <a href="{{$refURL}}/commit/{{$commit.RefID}}">{{ShortSHA1 $commit.RefID}}</a>
{{else}}
{{$entry.Name}} @ {{ShortSha $commit.RefID}}
{{$entry.Name}} @ {{ShortSHA1 $commit.RefID}}
{{end}}
</td>
{{else}}
@ -44,7 +44,7 @@
</td>
{{end}}
<td class="message collapsing has-emoji">
<a rel="nofollow" class="ui sha label" href="{{$.RepoLink}}/commit/{{$commit.ID}}">{{ShortSha $commit.ID.String}}</a>
<a rel="nofollow" class="ui sha label" href="{{$.RepoLink}}/commit/{{$commit.ID}}">{{ShortSHA1 $commit.ID.String}}</a>
{{RenderCommitMessage false $commit.Summary $.RepoLink $.Repository.ComposeMetas}}
</td>
<td class="text grey right age">{{TimeSince $commit.Committer.When $.Lang}}</td>

View File

@ -62,7 +62,7 @@
{{ $repoLink := .GetRepoLink}}
{{if $push.Commits}}
{{range $push.Commits}}
<li><img class="img-8" src="{{$push.AvatarLink .AuthorEmail}}"> <a class="commit-id" href="{{$repoLink}}/commit/{{.Sha1}}">{{ShortSha .Sha1}}</a> <span class="text truncate light grey has-emoji">{{.Message}}</span></li>
<li><img class="img-8" src="{{$push.AvatarLink .AuthorEmail}}"> <a class="commit-id" href="{{$repoLink}}/commit/{{.Sha1}}">{{ShortSHA1 .Sha1}}</a> <span class="text truncate light grey has-emoji">{{.Message}}</span></li>
{{end}}
{{end}}
{{if and (gt $push.Len 1) $push.CompareURL}}<li><a href="{{AppSubUrl}}/{{$push.CompareURL}}">{{$.i18n.Tr "action.compare_commits" $push.Len}} »</a></li>{{end}}