diff options
author | Justin Nuß <nuss.justin@gmail.com> | 2014-07-26 11:23:58 +0200 |
---|---|---|
committer | Justin Nuß <nuss.justin@gmail.com> | 2014-07-26 11:23:58 +0200 |
commit | 91480f3791f266369c343c539f8eeec245fa969a (patch) | |
tree | a03ad6062fe4b546367cdb6f9921399458d97441 /models | |
parent | 835e85b5ce9921ffd4d50b90b706e02685167331 (diff) | |
parent | 35c75f06a0a4f321021984830d760e67ca0ef8e5 (diff) | |
download | gitea-91480f3791f266369c343c539f8eeec245fa969a.tar.gz gitea-91480f3791f266369c343c539f8eeec245fa969a.zip |
Merge branch 'dev' of https://github.com/gogits/Gogs into issue/281
Conflicts:
modules/base/tool.go
Diffstat (limited to 'models')
-rw-r--r-- | models/action.go | 64 | ||||
-rw-r--r-- | models/git_diff.go | 9 | ||||
-rw-r--r-- | models/issue.go | 12 | ||||
-rw-r--r-- | models/login.go | 27 | ||||
-rw-r--r-- | models/publickey.go | 92 | ||||
-rw-r--r-- | models/release.go | 2 | ||||
-rw-r--r-- | models/repo.go | 155 | ||||
-rw-r--r-- | models/update.go | 15 | ||||
-rw-r--r-- | models/user.go | 113 | ||||
-rw-r--r-- | models/webhook.go | 6 |
10 files changed, 296 insertions, 199 deletions
diff --git a/models/action.go b/models/action.go index 0342abf5e3..b9d45ab375 100644 --- a/models/action.go +++ b/models/action.go @@ -8,30 +8,31 @@ import ( "encoding/json" "errors" "fmt" + "path" "regexp" "strings" "time" "unicode" - "github.com/gogits/git" - "github.com/gogits/gogs/modules/base" + "github.com/gogits/gogs/modules/git" "github.com/gogits/gogs/modules/log" "github.com/gogits/gogs/modules/setting" ) -// Operation types of user action. +type ActionType int + const ( - OP_CREATE_REPO = iota + 1 - OP_DELETE_REPO - OP_STAR_REPO - OP_FOLLOW_REPO - OP_COMMIT_REPO - OP_CREATE_ISSUE - OP_PULL_REQUEST - OP_TRANSFER_REPO - OP_PUSH_TAG - OP_COMMENT_ISSUE + CREATE_REPO ActionType = iota + 1 // 1 + DELETE_REPO // 2 + STAR_REPO // 3 + FOLLOW_REPO // 4 + COMMIT_REPO // 5 + CREATE_ISSUE // 6 + PULL_REQUEST // 7 + TRANSFER_REPO // 8 + PUSH_TAG // 9 + COMMENT_ISSUE // 10 ) var ( @@ -53,7 +54,7 @@ func init() { type Action struct { Id int64 UserId int64 // Receiver user id. - OpType int + OpType ActionType ActUserId int64 // Action user id. ActUserName string // Action user name. ActEmail string @@ -67,7 +68,7 @@ type Action struct { } func (a Action) GetOpType() int { - return a.OpType + return int(a.OpType) } func (a Action) GetActUserName() string { @@ -86,6 +87,10 @@ func (a Action) GetRepoName() string { return a.RepoName } +func (a Action) GetRepoLink() string { + return path.Join(a.RepoUserName, a.RepoName) +} + func (a Action) GetBranch() string { return a.RefName } @@ -94,6 +99,14 @@ func (a Action) GetContent() string { return a.Content } +func (a Action) GetCreate() time.Time { + return a.Created +} + +func (a Action) GetIssueInfos() []string { + return strings.SplitN(a.Content, "|", 2) +} + func updateIssuesCommit(userId, repoId int64, repoUserName, repoName string, commits []*base.PushCommit) error { for _, c := range commits { refs := IssueKeywordsPat.FindAllString(c.Message, -1) @@ -160,12 +173,11 @@ func updateIssuesCommit(userId, repoId int64, repoUserName, repoName string, com // CommitRepoAction adds new action for committing repository. func CommitRepoAction(userId, repoUserId int64, userName, actEmail string, repoId int64, repoUserName, repoName string, refFullName string, commit *base.PushCommits) error { - // log.Trace("action.CommitRepoAction(start): %d/%s", userId, repoName) - opType := OP_COMMIT_REPO + opType := COMMIT_REPO // Check it's tag push or branch. if strings.HasPrefix(refFullName, "refs/tags/") { - opType = OP_PUSH_TAG + opType = PUSH_TAG commit = &base.PushCommits{} } @@ -269,26 +281,26 @@ func CommitRepoAction(userId, repoUserId int64, userName, actEmail string, // NewRepoAction adds new action for creating repository. func NewRepoAction(u *User, repo *Repository) (err error) { if err = NotifyWatchers(&Action{ActUserId: u.Id, ActUserName: u.Name, ActEmail: u.Email, - OpType: OP_CREATE_REPO, RepoId: repo.Id, RepoUserName: repo.Owner.Name, RepoName: repo.Name, + OpType: CREATE_REPO, RepoId: repo.Id, RepoUserName: repo.Owner.Name, RepoName: repo.Name, IsPrivate: repo.IsPrivate}); err != nil { - log.Error("action.NewRepoAction(notify watchers): %d/%s", u.Id, repo.Name) + log.Error(4, "NotifyWatchers: %d/%s", u.Id, repo.Name) return err } - log.Trace("action.NewRepoAction: %s/%s", u.LowerName, repo.LowerName) + log.Trace("action.NewRepoAction: %s/%s", u.Name, repo.Name) return err } // TransferRepoAction adds new action for transfering repository. -func TransferRepoAction(user, newUser *User, repo *Repository) (err error) { - if err = NotifyWatchers(&Action{ActUserId: user.Id, ActUserName: user.Name, ActEmail: user.Email, - OpType: OP_TRANSFER_REPO, RepoId: repo.Id, RepoName: repo.Name, Content: newUser.Name, +func TransferRepoAction(u, newUser *User, repo *Repository) (err error) { + if err = NotifyWatchers(&Action{ActUserId: u.Id, ActUserName: u.Name, ActEmail: u.Email, + OpType: TRANSFER_REPO, RepoId: repo.Id, RepoName: repo.Name, Content: newUser.Name, IsPrivate: repo.IsPrivate}); err != nil { - log.Error("action.TransferRepoAction(notify watchers): %d/%s", user.Id, repo.Name) + log.Error(4, "NotifyWatchers: %d/%s", u.Id, repo.Name) return err } - log.Trace("action.TransferRepoAction: %s/%s", user.LowerName, repo.LowerName) + log.Trace("action.TransferRepoAction: %s/%s", u.Name, repo.Name) return err } diff --git a/models/git_diff.go b/models/git_diff.go index 303d61d5de..4b4d1234dd 100644 --- a/models/git_diff.go +++ b/models/git_diff.go @@ -13,9 +13,10 @@ import ( "strings" "time" + "github.com/Unknwon/com" + "github.com/gogits/git" - "github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/log" "github.com/gogits/gogs/modules/process" ) @@ -118,8 +119,8 @@ func ParsePatch(pid int64, cmd *exec.Cmd, reader io.Reader) (*Diff, error) { // Parse line number. ranges := strings.Split(ss[len(ss)-2][1:], " ") - leftLine, _ = base.StrTo(strings.Split(ranges[0], ",")[0][1:]).Int() - rightLine, _ = base.StrTo(strings.Split(ranges[1], ",")[0]).Int() + leftLine, _ = com.StrTo(strings.Split(ranges[0], ",")[0][1:]).Int() + rightLine, _ = com.StrTo(strings.Split(ranges[1], ",")[0]).Int() continue case line[0] == '+': curFile.Addition++ @@ -214,7 +215,7 @@ func GetDiff(repoPath, commitid string) (*Diff, error) { select { case <-time.After(5 * time.Minute): if errKill := process.Kill(pid); errKill != nil { - log.Error("git_diff.ParsePatch(Kill): %v", err) + log.Error(4, "git_diff.ParsePatch(Kill): %v", err) } <-done // return "", ErrExecTimeout.Error(), ErrExecTimeout diff --git a/models/issue.go b/models/issue.go index 05c9525341..307ace816d 100644 --- a/models/issue.go +++ b/models/issue.go @@ -13,9 +13,9 @@ import ( "strings" "time" + "github.com/Unknwon/com" "github.com/go-xorm/xorm" - "github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/log" ) @@ -72,7 +72,7 @@ func (i *Issue) GetLabels() error { strIds := strings.Split(strings.TrimSuffix(i.LabelIds[1:], "|"), "|$") i.Labels = make([]*Label, 0, len(strIds)) for _, strId := range strIds { - id, _ := base.StrTo(strId).Int64() + id, _ := com.StrTo(strId).Int64() if id > 0 { l, err := GetLabelById(id) if err != nil { @@ -337,7 +337,7 @@ func GetIssueUserPairsByRepoIds(rids []int64, isClosed bool, page int) ([]*Issue buf := bytes.NewBufferString("") for _, rid := range rids { buf.WriteString("repo_id=") - buf.WriteString(base.ToStr(rid)) + buf.WriteString(com.ToStr(rid)) buf.WriteString(" OR ") } cond := strings.TrimSuffix(buf.String(), " OR ") @@ -564,7 +564,7 @@ func UpdateLabel(l *Label) error { // DeleteLabel delete a label of given repository. func DeleteLabel(repoId int64, strId string) error { - id, _ := base.StrTo(strId).Int64() + id, _ := com.StrTo(strId).Int64() l, err := GetLabelById(id) if err != nil { if err == ErrLabelNotExist { @@ -768,7 +768,7 @@ func ChangeMilestoneAssign(oldMid, mid int64, issue *Issue) (err error) { m.Completeness = 0 } - if _, err = sess.Id(m.Id).Update(m); err != nil { + if _, err = sess.Id(m.Id).Cols("num_issues,num_completeness,num_closed_issues").Update(m); err != nil { sess.Rollback() return err } @@ -796,7 +796,7 @@ func ChangeMilestoneAssign(oldMid, mid int64, issue *Issue) (err error) { } m.Completeness = m.NumClosedIssues * 100 / m.NumIssues - if _, err = sess.Id(m.Id).Update(m); err != nil { + if _, err = sess.Id(m.Id).Cols("num_issues,num_completeness,num_closed_issues").Update(m); err != nil { sess.Rollback() return err } diff --git a/models/login.go b/models/login.go index e99b61e779..da7722f294 100644 --- a/models/login.go +++ b/models/login.go @@ -164,15 +164,14 @@ func UserSignIn(uname, passwd string) (*User, error) { if u.LoginType == NOTYPE { if has { u.LoginType = PLAIN + } else { + return nil, ErrUserNotExist } } - // for plain login, user must have existed. + // For plain login, user must exist to reach this line. + // Now verify password. if u.LoginType == PLAIN { - if !has { - return nil, ErrUserNotExist - } - newUser := &User{Passwd: passwd, Salt: u.Salt} newUser.EncodePasswd() if u.Passwd != newUser.Passwd { @@ -233,18 +232,18 @@ func UserSignIn(uname, passwd string) (*User, error) { // Query if name/passwd can login against the LDAP direcotry pool // Create a local user if success // Return the same LoginUserPlain semantic -func LoginUserLdapSource(user *User, name, passwd string, sourceId int64, cfg *LDAPConfig, autoRegister bool) (*User, error) { +func LoginUserLdapSource(u *User, name, passwd string, sourceId int64, cfg *LDAPConfig, autoRegister bool) (*User, error) { mail, logged := cfg.Ldapsource.SearchEntry(name, passwd) if !logged { // user not in LDAP, do nothing return nil, ErrUserNotExist } if !autoRegister { - return user, nil + return u, nil } // fake a local user creation - user = &User{ + u = &User{ LowerName: strings.ToLower(name), Name: strings.ToLower(name), LoginType: LDAP, @@ -255,7 +254,8 @@ func LoginUserLdapSource(user *User, name, passwd string, sourceId int64, cfg *L Email: mail, } - return CreateUser(user) + err := CreateUser(u) + return u, err } type loginAuth struct { @@ -322,7 +322,7 @@ func SmtpAuth(host string, port int, a smtp.Auth, useTls bool) error { // Query if name/passwd can login against the LDAP direcotry pool // Create a local user if success // Return the same LoginUserPlain semantic -func LoginUserSMTPSource(user *User, name, passwd string, sourceId int64, cfg *SMTPConfig, autoRegister bool) (*User, error) { +func LoginUserSMTPSource(u *User, name, passwd string, sourceId int64, cfg *SMTPConfig, autoRegister bool) (*User, error) { var auth smtp.Auth if cfg.Auth == SMTP_PLAIN { auth = smtp.PlainAuth("", name, passwd, cfg.Host) @@ -340,7 +340,7 @@ func LoginUserSMTPSource(user *User, name, passwd string, sourceId int64, cfg *S } if !autoRegister { - return user, nil + return u, nil } var loginName = name @@ -349,7 +349,7 @@ func LoginUserSMTPSource(user *User, name, passwd string, sourceId int64, cfg *S loginName = name[:idx] } // fake a local user creation - user = &User{ + u = &User{ LowerName: strings.ToLower(loginName), Name: strings.ToLower(loginName), LoginType: SMTP, @@ -359,5 +359,6 @@ func LoginUserSMTPSource(user *User, name, passwd string, sourceId int64, cfg *S Passwd: passwd, Email: name, } - return CreateUser(user) + err := CreateUser(u) + return u, err } diff --git a/models/publickey.go b/models/publickey.go index 603ff36438..baf381778e 100644 --- a/models/publickey.go +++ b/models/publickey.go @@ -54,7 +54,7 @@ func exePath() (string, error) { func homeDir() string { home, err := com.HomeDir() if err != nil { - log.Fatal("Fail to get home directory: %v", err) + log.Fatal(4, "Fail to get home directory: %v", err) } return home } @@ -63,25 +63,28 @@ func init() { var err error if appPath, err = exePath(); err != nil { - log.Fatal("publickey.init(fail to get app path): %v\n", err) + log.Fatal(4, "fail to get app path: %v\n", err) } + appPath = strings.Replace(appPath, "\\", "/", -1) // Determine and create .ssh path. SshPath = filepath.Join(homeDir(), ".ssh") if err = os.MkdirAll(SshPath, os.ModePerm); err != nil { - log.Fatal("publickey.init(fail to create SshPath(%s)): %v\n", SshPath, err) + log.Fatal(4, "fail to create SshPath(%s): %v\n", SshPath, err) } } // PublicKey represents a SSH key. type PublicKey struct { - Id int64 - OwnerId int64 `xorm:"UNIQUE(s) INDEX NOT NULL"` - Name string `xorm:"UNIQUE(s) NOT NULL"` - Fingerprint string - Content string `xorm:"TEXT NOT NULL"` - Created time.Time `xorm:"CREATED"` - Updated time.Time `xorm:"UPDATED"` + Id int64 + OwnerId int64 `xorm:"UNIQUE(s) INDEX NOT NULL"` + Name string `xorm:"UNIQUE(s) NOT NULL"` + Fingerprint string + Content string `xorm:"TEXT NOT NULL"` + Created time.Time `xorm:"CREATED"` + Updated time.Time + HasRecentActivity bool `xorm:"-"` + HasUsed bool `xorm:"-"` } // GetAuthorizedString generates and returns formatted public key string for authorized_keys file. @@ -89,6 +92,59 @@ func (key *PublicKey) GetAuthorizedString() string { return fmt.Sprintf(_TPL_PUBLICK_KEY, appPath, key.Id, key.Content) } +var ( + MinimumKeySize = map[string]int{ + "(ED25519)": 256, + "(ECDSA)": 256, + "(NTRU)": 1087, + "(MCE)": 1702, + "(McE)": 1702, + "(RSA)": 2048, + } +) + +// CheckPublicKeyString checks if the given public key string is recognized by SSH. +func CheckPublicKeyString(content string) (bool, error) { + if strings.ContainsAny(content, "\n\r") { + return false, errors.New("Only a single line with a single key please") + } + + // write the key to a file… + tmpFile, err := ioutil.TempFile(os.TempDir(), "keytest") + if err != nil { + return false, err + } + tmpPath := tmpFile.Name() + defer os.Remove(tmpPath) + tmpFile.WriteString(content) + tmpFile.Close() + + // … see if ssh-keygen recognizes its contents + stdout, stderr, err := process.Exec("CheckPublicKeyString", "ssh-keygen", "-l", "-f", tmpPath) + if err != nil { + return false, errors.New("ssh-keygen -l -f: " + stderr) + } else if len(stdout) < 2 { + return false, errors.New("ssh-keygen returned not enough output to evaluate the key") + } + sshKeygenOutput := strings.Split(stdout, " ") + if len(sshKeygenOutput) < 4 { + return false, errors.New("Not enough fields returned by ssh-keygen -l -f") + } + keySize, err := com.StrTo(sshKeygenOutput[0]).Int() + if err != nil { + return false, errors.New("Cannot get key size of the given key") + } + keyType := strings.TrimSpace(sshKeygenOutput[len(sshKeygenOutput)-1]) + + if minimumKeySize := MinimumKeySize[keyType]; minimumKeySize == 0 { + return false, errors.New("Sorry, unrecognized public key type") + } else if keySize < minimumKeySize { + return false, fmt.Errorf("The minimum accepted size of a public key %s is %d", keyType, minimumKeySize) + } + + return true, nil +} + // saveAuthorizedKeyFile writes SSH key content to authorized_keys file. func saveAuthorizedKeyFile(key *PublicKey) error { sshOpLocker.Lock() @@ -144,10 +200,18 @@ func AddPublicKey(key *PublicKey) (err error) { } // ListPublicKey returns a list of all public keys that user has. -func ListPublicKey(uid int64) ([]PublicKey, error) { - keys := make([]PublicKey, 0, 5) +func ListPublicKey(uid int64) ([]*PublicKey, error) { + keys := make([]*PublicKey, 0, 5) err := x.Find(&keys, &PublicKey{OwnerId: uid}) - return keys, err + if err != nil { + return nil, err + } + + for _, key := range keys { + key.HasUsed = key.Updated.After(key.Created) + key.HasRecentActivity = key.Updated.Add(7 * 24 * time.Hour).After(time.Now()) + } + return keys, nil } // rewriteAuthorizedKeys finds and deletes corresponding line in authorized_keys file. @@ -218,8 +282,6 @@ func DeletePublicKey(key *PublicKey) error { fpath := filepath.Join(SshPath, "authorized_keys") tmpPath := filepath.Join(SshPath, "authorized_keys.tmp") - log.Trace("publickey.DeletePublicKey(authorized_keys): %s", fpath) - if err = rewriteAuthorizedKeys(key, fpath, tmpPath); err != nil { return err } else if err = os.Remove(fpath); err != nil { diff --git a/models/release.go b/models/release.go index 3e1a78118c..012b6cc5c4 100644 --- a/models/release.go +++ b/models/release.go @@ -10,7 +10,7 @@ import ( "strings" "time" - "github.com/gogits/git" + "github.com/gogits/gogs/modules/git" ) var ( diff --git a/models/repo.go b/models/repo.go index 8dda6f0d03..da0813e3b4 100644 --- a/models/repo.go +++ b/models/repo.go @@ -14,7 +14,6 @@ import ( "path" "path/filepath" "regexp" - "runtime" "sort" "strings" "time" @@ -23,10 +22,7 @@ import ( "github.com/Unknwon/cae/zip" "github.com/Unknwon/com" - "github.com/gogits/git" - - "github.com/gogits/gogs/modules/base" - "github.com/gogits/gogs/modules/bin" + "github.com/gogits/gogs/modules/git" "github.com/gogits/gogs/modules/log" "github.com/gogits/gogs/modules/process" "github.com/gogits/gogs/modules/setting" @@ -47,35 +43,27 @@ var ( ) var ( - LanguageIgns, Licenses []string + Gitignores, Licenses []string ) var ( DescriptionPattern = regexp.MustCompile(`https?://\S+`) ) -// getAssetList returns corresponding asset list in 'conf'. -func getAssetList(prefix string) []string { - assets := make([]string, 0, 15) - for _, name := range bin.AssetNames() { - if strings.HasPrefix(name, prefix) { - assets = append(assets, strings.TrimPrefix(name, prefix+"/")) - } - } - return assets -} - func LoadRepoConfig() { // Load .gitignore and license files. types := []string{"gitignore", "license"} typeFiles := make([][]string, 2) for i, t := range types { - files := getAssetList(path.Join("conf", t)) + files, err := com.StatDir(path.Join("conf", t)) + if err != nil { + log.Fatal(4, "Fail to get %s files: %v", t, err) + } customPath := path.Join(setting.CustomPath, "conf", t) if com.IsDir(customPath) { customFiles, err := com.StatDir(customPath) if err != nil { - log.Fatal("Fail to get custom %s files: %v", t, err) + log.Fatal(4, "Fail to get custom %s files: %v", t, err) } for _, f := range customFiles { @@ -87,34 +75,33 @@ func LoadRepoConfig() { typeFiles[i] = files } - LanguageIgns = typeFiles[0] + Gitignores = typeFiles[0] Licenses = typeFiles[1] - sort.Strings(LanguageIgns) + sort.Strings(Gitignores) sort.Strings(Licenses) } func NewRepoContext() { zip.Verbose = false + // Check Git version. + ver, err := git.GetVersion() + if err != nil { + log.Fatal(4, "Fail to get Git version: %v", err) + } + if ver.Major < 2 && ver.Minor < 8 { + log.Fatal(4, "Gogs requires Git version greater or equal to 1.8.0") + } + // Check if server has basic git setting. stdout, stderr, err := process.Exec("NewRepoContext(get setting)", "git", "config", "--get", "user.name") if err != nil { - log.Fatal("repo.NewRepoContext(fail to get git user.name): %s", stderr) + log.Fatal(4, "Fail to get git user.name: %s", stderr) } else if err != nil || len(strings.TrimSpace(stdout)) == 0 { if _, stderr, err = process.Exec("NewRepoContext(set email)", "git", "config", "--global", "user.email", "gogitservice@gmail.com"); err != nil { - log.Fatal("repo.NewRepoContext(fail to set git user.email): %s", stderr) + log.Fatal(4, "Fail to set git user.email: %s", stderr) } else if _, stderr, err = process.Exec("NewRepoContext(set name)", "git", "config", "--global", "user.name", "Gogs"); err != nil { - log.Fatal("repo.NewRepoContext(fail to set git user.name): %s", stderr) - } - } - - barePath := path.Join(setting.RepoRootPath, "git-bare.zip") - if !com.IsExist(barePath) { - data, err := bin.Asset("conf/content/git-bare.zip") - if err != nil { - log.Fatal("Fail to get asset 'git-bare.zip': %v", err) - } else if err := ioutil.WriteFile(barePath, data, os.ModePerm); err != nil { - log.Fatal("Fail to write asset 'git-bare.zip': %v", err) + log.Fatal(4, "Fail to set git user.name: %s", stderr) } } } @@ -135,12 +122,16 @@ type Repository struct { NumIssues int NumClosedIssues int NumOpenIssues int `xorm:"-"` + NumPulls int + NumClosedPulls int + NumOpenPulls int `xorm:"-"` NumMilestones int `xorm:"NOT NULL DEFAULT 0"` NumClosedMilestones int `xorm:"NOT NULL DEFAULT 0"` NumOpenMilestones int `xorm:"-"` NumTags int `xorm:"-"` IsPrivate bool IsMirror bool + IsFork bool `xorm:"NOT NULL DEFAULT false"` IsBare bool IsGoget bool DefaultBranch string @@ -153,11 +144,11 @@ func (repo *Repository) GetOwner() (err error) { return err } +// DescriptionHtml does special handles to description and return HTML string. func (repo *Repository) DescriptionHtml() template.HTML { sanitize := func(s string) string { // TODO(nuss-justin): Improve sanitization. Strip all tags? ss := html.EscapeString(s) - return fmt.Sprintf(`<a href="%s" target="_blank">%s</a>`, ss, ss) } return template.HTML(DescriptionPattern.ReplaceAllStringFunc(repo.Description, sanitize)) @@ -225,7 +216,8 @@ func MirrorRepository(repoId int64, userName, repoName, repoPath, url string) er return err } - return git.UnpackRefs(repoPath) + // return git.UnpackRefs(repoPath) + return nil } func GetMirror(repoId int64) (*Mirror, error) { @@ -257,14 +249,14 @@ func MirrorUpdate() { repoPath, fmt.Sprintf("MirrorUpdate: %s", repoPath), "git", "remote", "update"); err != nil { return errors.New("git remote update: " + stderr) - } else if err = git.UnpackRefs(repoPath); err != nil { - return errors.New("UnpackRefs: " + err.Error()) - } + } // else if err = git.UnpackRefs(repoPath); err != nil { + // return errors.New("UnpackRefs: " + err.Error()) + // } m.NextUpdate = time.Now().Add(time.Duration(m.Interval) * time.Hour) return UpdateMirror(m) }); err != nil { - log.Error("repo.MirrorUpdate: %v", err) + log.Error(4, "repo.MirrorUpdate: %v", err) } } @@ -317,7 +309,7 @@ func MigrateRepository(u *User, name, desc string, private, mirror bool, url str // extractGitBareZip extracts git-bare.zip to repository path. func extractGitBareZip(repoPath string) error { - z, err := zip.Open(filepath.Join(setting.RepoRootPath, "git-bare.zip")) + z, err := zip.Open(path.Join(setting.ConfRootPath, "content/git-bare.zip")) if err != nil { return err } @@ -361,34 +353,18 @@ func createHookUpdate(hookPath, content string) error { return err } -// SetRepoEnvs sets environment variables for command update. -func SetRepoEnvs(userId int64, userName, repoName, repoUserName string) { - os.Setenv("userId", base.ToStr(userId)) - os.Setenv("userName", userName) - os.Setenv("repoName", repoName) - os.Setenv("repoUserName", repoUserName) -} - // InitRepository initializes README and .gitignore if needed. -func initRepository(f string, user *User, repo *Repository, initReadme bool, repoLang, license string) error { - repoPath := RepoPath(user.Name, repo.Name) +func initRepository(f string, u *User, repo *Repository, initReadme bool, repoLang, license string) error { + repoPath := RepoPath(u.Name, repo.Name) // Create bare new repository. if err := extractGitBareZip(repoPath); err != nil { return err } - if runtime.GOOS == "windows" { - rp := strings.NewReplacer("\\", "/") - appPath = "\"" + rp.Replace(appPath) + "\"" - } else { - rp := strings.NewReplacer("\\", "/", " ", "\\ ") - appPath = rp.Replace(appPath) - } - // hook/post-update if err := createHookUpdate(filepath.Join(repoPath, "hooks", "update"), - fmt.Sprintf(TPL_UPDATE_HOOK, setting.ScriptType, appPath)); err != nil { + fmt.Sprintf(TPL_UPDATE_HOOK, setting.ScriptType, "\""+appPath+"\"")); err != nil { return err } @@ -405,7 +381,7 @@ func initRepository(f string, user *User, repo *Repository, initReadme bool, rep } // Clone to temprory path and do the init commit. - tmpDir := filepath.Join(os.TempDir(), base.ToStr(time.Now().Nanosecond())) + tmpDir := filepath.Join(os.TempDir(), com.ToStr(time.Now().Nanosecond())) os.MkdirAll(tmpDir, os.ModePerm) _, stderr, err := process.Exec( @@ -426,12 +402,11 @@ func initRepository(f string, user *User, repo *Repository, initReadme bool, rep } // .gitignore - if repoLang != "" { - filePath := "conf/gitignore/" + repoLang + filePath := "conf/gitignore/" + repoLang + if com.IsFile(filePath) { targetPath := path.Join(tmpDir, fileName["gitign"]) - data, err := bin.Asset(filePath) - if err == nil { - if err = ioutil.WriteFile(targetPath, data, os.ModePerm); err != nil { + if com.IsFile(filePath) { + if err = com.Copy(filePath, targetPath); err != nil { return err } } else { @@ -443,15 +418,16 @@ func initRepository(f string, user *User, repo *Repository, initReadme bool, rep } } } + } else { + delete(fileName, "gitign") } // LICENSE - if license != "" { - filePath := "conf/license/" + license + filePath = "conf/license/" + license + if com.IsFile(filePath) { targetPath := path.Join(tmpDir, fileName["license"]) - data, err := bin.Asset(filePath) - if err == nil { - if err = ioutil.WriteFile(targetPath, data, os.ModePerm); err != nil { + if com.IsFile(filePath) { + if err = com.Copy(filePath, targetPath); err != nil { return err } } else { @@ -463,16 +439,16 @@ func initRepository(f string, user *User, repo *Repository, initReadme bool, rep } } } + } else { + delete(fileName, "license") } if len(fileName) == 0 { return nil } - SetRepoEnvs(user.Id, user.Name, repo.Name, user.Name) - // Apply changes and commit. - return initRepoCommit(tmpDir, user.NewGitSig()) + return initRepoCommit(tmpDir, u.NewGitSig()) } // CreateRepository creates a repository for given user or organization. @@ -549,15 +525,15 @@ func CreateRepository(u *User, name, desc, lang, license string, private, mirror } } - rawSql := "UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?" - if _, err = sess.Exec(rawSql, u.Id); err != nil { + if _, err = sess.Exec( + "UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?", u.Id); err != nil { sess.Rollback() return nil, err } // Update owner team info and count. if u.IsOrganization() { - t.RepoIds += "$" + base.ToStr(repo.Id) + "|" + t.RepoIds += "$" + com.ToStr(repo.Id) + "|" t.NumRepos++ if _, err = sess.Id(t.Id).AllCols().Update(t); err != nil { sess.Rollback() @@ -572,24 +548,24 @@ func CreateRepository(u *User, name, desc, lang, license string, private, mirror if u.IsOrganization() { ous, err := GetOrgUsersByOrgId(u.Id) if err != nil { - log.Error("repo.CreateRepository(GetOrgUsersByOrgId): %v", err) + log.Error(4, "repo.CreateRepository(GetOrgUsersByOrgId): %v", err) } else { for _, ou := range ous { if err = WatchRepo(ou.Uid, repo.Id, true); err != nil { - log.Error("repo.CreateRepository(WatchRepo): %v", err) + log.Error(4, "repo.CreateRepository(WatchRepo): %v", err) } } } } if err = WatchRepo(u.Id, repo.Id, true); err != nil { - log.Error("repo.CreateRepository(WatchRepo2): %v", err) + log.Error(4, "WatchRepo2: %v", err) } if err = NewRepoAction(u, repo); err != nil { - log.Error("repo.CreateRepository(NewRepoAction): %v", err) + log.Error(4, "NewRepoAction: %v", err) } - // No need for init for mirror. + // No need for init mirror. if mirror { return repo, nil } @@ -597,11 +573,11 @@ func CreateRepository(u *User, name, desc, lang, license string, private, mirror repoPath := RepoPath(u.Name, repo.Name) if err = initRepository(repoPath, u, repo, initReadme, lang, license); err != nil { if err2 := os.RemoveAll(repoPath); err2 != nil { - log.Error("repo.CreateRepository(initRepository): %v", err) - return nil, errors.New(fmt.Sprintf( - "delete repo directory %s/%s failed(2): %v", u.Name, repo.Name, err2)) + log.Error(4, "initRepository: %v", err) + return nil, fmt.Errorf( + "delete repo directory %s/%s failed(2): %v", u.Name, repo.Name, err2) } - return nil, err + return nil, fmt.Errorf("initRepository: %v", err) } _, stderr, err := process.ExecDir(-1, @@ -982,15 +958,12 @@ func WatchRepo(uid, rid int64, watch bool) (err error) { if _, err = x.Insert(&Watch{RepoId: rid, UserId: uid}); err != nil { return err } - - rawSql := "UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?" - _, err = x.Exec(rawSql, rid) + _, err = x.Exec("UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?", rid) } else { if _, err = x.Delete(&Watch{0, uid, rid}); err != nil { return err } - rawSql := "UPDATE `repository` SET num_watches = num_watches - 1 WHERE id = ?" - _, err = x.Exec(rawSql, rid) + _, err = x.Exec("UPDATE `repository` SET num_watches = num_watches - 1 WHERE id = ?", rid) } return err } diff --git a/models/update.go b/models/update.go index cf7f5d2a79..68a92ada1d 100644 --- a/models/update.go +++ b/models/update.go @@ -10,9 +10,8 @@ import ( "os/exec" "strings" - "github.com/gogits/git" - "github.com/gogits/gogs/modules/base" + "github.com/gogits/gogs/modules/git" "github.com/gogits/gogs/modules/log" ) @@ -47,8 +46,6 @@ func DelUpdateTasksByUuid(uuid string) error { } func Update(refName, oldCommitId, newCommitId, userName, repoUserName, repoName string, userId int64) error { - //fmt.Println(refName, oldCommitId, newCommitId) - //fmt.Println(userName, repoUserName, repoName) isNew := strings.HasPrefix(oldCommitId, "0000000") if isNew && strings.HasPrefix(newCommitId, "0000000") { @@ -82,12 +79,12 @@ func Update(refName, oldCommitId, newCommitId, userName, repoUserName, repoName return fmt.Errorf("runUpdate.GetRepositoryByName userId: %v", err) } - // if tags push + // Push tags. if strings.HasPrefix(refName, "refs/tags/") { tagName := git.RefEndName(refName) tag, err := repo.GetTag(tagName) if err != nil { - log.GitLogger.Fatal("runUpdate.GetTag: %v", err) + log.GitLogger.Fatal(4, "runUpdate.GetTag: %v", err) } var actEmail string @@ -96,7 +93,7 @@ func Update(refName, oldCommitId, newCommitId, userName, repoUserName, repoName } else { cmt, err := tag.Commit() if err != nil { - log.GitLogger.Fatal("runUpdate.GetTag Commit: %v", err) + log.GitLogger.Fatal(4, "runUpdate.GetTag Commit: %v", err) } actEmail = cmt.Committer.Email } @@ -105,7 +102,7 @@ func Update(refName, oldCommitId, newCommitId, userName, repoUserName, repoName if err = CommitRepoAction(userId, ru.Id, userName, actEmail, repos.Id, repoUserName, repoName, refName, commit); err != nil { - log.GitLogger.Fatal("runUpdate.models.CommitRepoAction: %s/%s:%v", repoUserName, repoName, err) + log.GitLogger.Fatal(4, "runUpdate.models.CommitRepoAction: %s/%s:%v", repoUserName, repoName, err) } return err } @@ -135,7 +132,7 @@ func Update(refName, oldCommitId, newCommitId, userName, repoUserName, repoName // if commits push commits := make([]*base.PushCommit, 0) - var maxCommits = 3 + var maxCommits = 2 var actEmail string for e := l.Front(); e != nil; e = e.Next() { commit := e.Value.(*git.Commit) diff --git a/models/user.go b/models/user.go index a46232427e..540f4b6af4 100644 --- a/models/user.go +++ b/models/user.go @@ -14,9 +14,10 @@ import ( "strings" "time" - "github.com/gogits/git" + "github.com/Unknwon/com" "github.com/gogits/gogs/modules/base" + "github.com/gogits/gogs/modules/git" "github.com/gogits/gogs/modules/log" "github.com/gogits/gogs/modules/setting" ) @@ -77,6 +78,14 @@ type User struct { Members []*User `xorm:"-"` } +// DashboardLink returns the user dashboard page link. +func (u *User) DashboardLink() string { + if u.IsOrganization() { + return "/org/" + u.Name + "/dashboard" + } + return "/" +} + // HomeLink returns the user home page link. func (u *User) HomeLink() string { return "/user/" + u.Name @@ -157,23 +166,23 @@ func GetUserSalt() string { } // CreateUser creates record of a new user. -func CreateUser(u *User) (*User, error) { +func CreateUser(u *User) error { if !IsLegalName(u.Name) { - return nil, ErrUserNameIllegal + return ErrUserNameIllegal } isExist, err := IsUserExist(u.Name) if err != nil { - return nil, err + return err } else if isExist { - return nil, ErrUserAlreadyExist + return ErrUserAlreadyExist } isExist, err = IsEmailUsed(u.Email) if err != nil { - return nil, err + return err } else if isExist { - return nil, ErrEmailAlreadyUsed + return ErrEmailAlreadyUsed } u.LowerName = strings.ToLower(u.Name) @@ -186,21 +195,17 @@ func CreateUser(u *User) (*User, error) { sess := x.NewSession() defer sess.Close() if err = sess.Begin(); err != nil { - return nil, err + return err } if _, err = sess.Insert(u); err != nil { sess.Rollback() - return nil, err - } - - if err = os.MkdirAll(UserPath(u.Name), os.ModePerm); err != nil { + return err + } else if err = os.MkdirAll(UserPath(u.Name), os.ModePerm); err != nil { sess.Rollback() - return nil, err - } - - if err = sess.Commit(); err != nil { - return nil, err + return err + } else if err = sess.Commit(); err != nil { + return err } // Auto-set admin for user whose ID is 1. @@ -209,7 +214,7 @@ func CreateUser(u *User) (*User, error) { u.IsActive = true _, err = x.Id(u.Id).UseBool().Update(u) } - return u, err + return err } // CountUsers returns number of users. @@ -237,7 +242,7 @@ func getVerifyUser(code string) (user *User) { if user, err = GetUserByName(string(b)); user != nil { return user } - log.Error("user.getVerifyUser: %v", err) + log.Error(4, "user.getVerifyUser: %v", err) } return nil @@ -250,7 +255,7 @@ func VerifyUserActiveCode(code string) (user *User) { if user = getVerifyUser(code); user != nil { // time limit code prefix := code[:base.TimeLimitCodeLength] - data := base.ToStr(user.Id) + user.Email + user.LowerName + user.Passwd + user.Rands + data := com.ToStr(user.Id) + user.Email + user.LowerName + user.Passwd + user.Rands if base.VerifyTimeLimitCode(data, minutes, prefix) { return user @@ -260,12 +265,16 @@ func VerifyUserActiveCode(code string) (user *User) { } // ChangeUserName changes all corresponding setting from old user name to new one. -func ChangeUserName(user *User, newUserName string) (err error) { +func ChangeUserName(u *User, newUserName string) (err error) { + if !IsLegalName(newUserName) { + return ErrUserNameIllegal + } + newUserName = strings.ToLower(newUserName) // Update accesses of user. accesses := make([]Access, 0, 10) - if err = x.Find(&accesses, &Access{UserName: user.LowerName}); err != nil { + if err = x.Find(&accesses, &Access{UserName: u.LowerName}); err != nil { return err } @@ -277,28 +286,28 @@ func ChangeUserName(user *User, newUserName string) (err error) { for i := range accesses { accesses[i].UserName = newUserName - if strings.HasPrefix(accesses[i].RepoName, user.LowerName+"/") { - accesses[i].RepoName = strings.Replace(accesses[i].RepoName, user.LowerName, newUserName, 1) + if strings.HasPrefix(accesses[i].RepoName, u.LowerName+"/") { + accesses[i].RepoName = strings.Replace(accesses[i].RepoName, u.LowerName, newUserName, 1) } if err = UpdateAccessWithSession(sess, &accesses[i]); err != nil { return err } } - repos, err := GetRepositories(user.Id, true) + repos, err := GetRepositories(u.Id, true) if err != nil { return err } for i := range repos { accesses = make([]Access, 0, 10) // Update accesses of user repository. - if err = x.Find(&accesses, &Access{RepoName: user.LowerName + "/" + repos[i].LowerName}); err != nil { + if err = x.Find(&accesses, &Access{RepoName: u.LowerName + "/" + repos[i].LowerName}); err != nil { return err } for j := range accesses { // if the access is not the user's access (already updated above) - if accesses[j].UserName != user.LowerName { + if accesses[j].UserName != u.LowerName { accesses[j].RepoName = newUserName + "/" + repos[i].LowerName if err = UpdateAccessWithSession(sess, &accesses[j]); err != nil { return err @@ -308,7 +317,7 @@ func ChangeUserName(user *User, newUserName string) (err error) { } // Change user directory name. - if err = os.Rename(UserPath(user.LowerName), UserPath(newUserName)); err != nil { + if err = os.Rename(UserPath(u.LowerName), UserPath(newUserName)); err != nil { sess.Rollback() return err } @@ -317,7 +326,7 @@ func ChangeUserName(user *User, newUserName string) (err error) { } // UpdateUser updates user's information. -func UpdateUser(u *User) (err error) { +func UpdateUser(u *User) error { u.LowerName = strings.ToLower(u.Name) if len(u.Location) > 255 { @@ -330,7 +339,7 @@ func UpdateUser(u *User) (err error) { u.Description = u.Description[:255] } - _, err = x.Id(u.Id).AllCols().Update(u) + _, err := x.Id(u.Id).AllCols().Update(u) return err } @@ -340,7 +349,7 @@ func DeleteUser(u *User) error { // Check ownership of repository. count, err := GetRepositoryCount(u) if err != nil { - return errors.New("modesl.GetRepositories(GetRepositoryCount): " + err.Error()) + return errors.New("GetRepositoryCount: " + err.Error()) } else if count > 0 { return ErrUserOwnRepos } @@ -562,3 +571,45 @@ func UnFollowUser(userId int64, unFollowId int64) (err error) { } return session.Commit() } + +func UpdateMentions(userNames []string, issueId int64) error { + users := make([]*User, 0, len(userNames)) + + if err := x.Where("name IN (?)", strings.Join(userNames, "\",\"")).OrderBy("name ASC").Find(&users); err != nil { + return err + } + + ids := make([]int64, 0, len(userNames)) + + for _, user := range users { + ids = append(ids, user.Id) + + if user.Type == INDIVIDUAL { + continue + } + + if user.NumMembers == 0 { + continue + } + + tempIds := make([]int64, 0, user.NumMembers) + + orgUsers, err := GetOrgUsersByOrgId(user.Id) + + if err != nil { + return err + } + + for _, orgUser := range orgUsers { + tempIds = append(tempIds, orgUser.Id) + } + + ids = append(ids, tempIds...) + } + + if err := UpdateIssueUserPairsByMentions(ids, issueId); err != nil { + return err + } + + return nil +} diff --git a/models/webhook.go b/models/webhook.go index 9044befba2..925ec1a7de 100644 --- a/models/webhook.go +++ b/models/webhook.go @@ -47,7 +47,7 @@ type Webhook struct { func (w *Webhook) GetEvent() { w.HookEvent = &HookEvent{} if err := json.Unmarshal([]byte(w.Events), w.HookEvent); err != nil { - log.Error("webhook.GetEvent(%d): %v", w.Id, err) + log.Error(4, "webhook.GetEvent(%d): %v", w.Id, err) } } @@ -193,13 +193,13 @@ func DeliverHooks() { // Only support JSON now. if _, err := httplib.Post(t.Url).SetTimeout(timeout, timeout). Body([]byte(t.PayloadContent)).Response(); err != nil { - log.Error("webhook.DeliverHooks(Delivery): %v", err) + log.Error(4, "webhook.DeliverHooks(Delivery): %v", err) return nil } t.IsDeliveried = true if err := UpdateHookTask(t); err != nil { - log.Error("webhook.DeliverHooks(UpdateHookTask): %v", err) + log.Error(4, "webhook.DeliverHooks(UpdateHookTask): %v", err) return nil } |