forked from forgejo/forgejo
Add postgres support, clean code, code review
This commit is contained in:
parent
9d3b003add
commit
e51afe4621
19 changed files with 1124 additions and 303 deletions
|
@ -9,11 +9,13 @@ import (
|
|||
"time"
|
||||
)
|
||||
|
||||
// Access types.
|
||||
const (
|
||||
AU_READABLE = iota + 1
|
||||
AU_WRITABLE
|
||||
)
|
||||
|
||||
// Access represents the accessibility of user and repository.
|
||||
type Access struct {
|
||||
Id int64
|
||||
UserName string `xorm:"unique(s)"`
|
||||
|
@ -22,12 +24,13 @@ type Access struct {
|
|||
Created time.Time `xorm:"created"`
|
||||
}
|
||||
|
||||
// AddAccess adds new access record.
|
||||
func AddAccess(access *Access) error {
|
||||
_, err := orm.Insert(access)
|
||||
return err
|
||||
}
|
||||
|
||||
// if one user can read or write one repository
|
||||
// HasAccess returns true if someone can read or write given repository.
|
||||
func HasAccess(userName, repoName string, mode int) (bool, error) {
|
||||
return orm.Get(&Access{
|
||||
Id: 0,
|
||||
|
|
|
@ -19,7 +19,7 @@ const (
|
|||
OP_PULL_REQUEST
|
||||
)
|
||||
|
||||
// An Action represents
|
||||
// Action represents user operation type and information to the repository.
|
||||
type Action struct {
|
||||
Id int64
|
||||
UserId int64 // Receiver user id.
|
||||
|
|
|
@ -7,10 +7,9 @@ package models
|
|||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/Unknwon/com"
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
_ "github.com/lib/pq"
|
||||
"github.com/lunny/xorm"
|
||||
|
||||
"github.com/gogits/gogs/modules/base"
|
||||
|
@ -47,54 +46,50 @@ func setEngine() {
|
|||
dbName := base.Cfg.MustValue("database", "NAME")
|
||||
dbUser := base.Cfg.MustValue("database", "USER")
|
||||
dbPwd := base.Cfg.MustValue("database", "PASSWD")
|
||||
sslMode := base.Cfg.MustValue("database", "SSL_MODE")
|
||||
|
||||
var err error
|
||||
switch dbType {
|
||||
case "mysql":
|
||||
orm, err = xorm.NewEngine("mysql", fmt.Sprintf("%v:%v@%v/%v?charset=utf8",
|
||||
orm, err = xorm.NewEngine("mysql", fmt.Sprintf("%s:%s@%s/%s?charset=utf8",
|
||||
dbUser, dbPwd, dbHost, dbName))
|
||||
case "postgres":
|
||||
orm, err = xorm.NewEngine("postgres", fmt.Sprintf("user=%s password=%s dbname=%s sslmode=%s",
|
||||
dbUser, dbPwd, dbName, sslMode))
|
||||
default:
|
||||
fmt.Printf("Unknown database type: %s\n", dbType)
|
||||
os.Exit(2)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
fmt.Printf("models.init -> fail to conntect database: %s\n", dbType)
|
||||
fmt.Printf("models.init(fail to conntect database): %v\n", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
|
||||
//TODO: for serv command, MUST remove the output to os.stdout, so
|
||||
// TODO: for serv command, MUST remove the output to os.stdout, so
|
||||
// use log file to instead print to stdout
|
||||
|
||||
//x.ShowDebug = true
|
||||
//orm.ShowErr = true
|
||||
f, _ := os.Create("xorm.log")
|
||||
f, err := os.Create("xorm.log")
|
||||
if err != nil {
|
||||
fmt.Printf("models.init(fail to create xorm.log): %v\n", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
orm.Logger = f
|
||||
orm.ShowSQL = true
|
||||
|
||||
// Determine and create root git reposiroty path.
|
||||
RepoRootPath = base.Cfg.MustValue("repository", "ROOT")
|
||||
if err = os.MkdirAll(RepoRootPath, os.ModePerm); err != nil {
|
||||
fmt.Printf("models.init -> fail to create RepoRootPath(%s): %v\n", RepoRootPath, err)
|
||||
os.Exit(2)
|
||||
}
|
||||
|
||||
homeDir, err := com.HomeDir()
|
||||
if err != nil {
|
||||
fmt.Printf("models.init -> fail to get homeDir: %v\n", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
sshPath := filepath.Join(homeDir, ".ssh")
|
||||
if err = os.MkdirAll(sshPath, os.ModePerm); err != nil {
|
||||
fmt.Printf("models.init -> fail to create sshPath(%s): %v\n", sshPath, err)
|
||||
fmt.Printf("models.init(fail to create RepoRootPath(%s)): %v\n", RepoRootPath, err)
|
||||
os.Exit(2)
|
||||
}
|
||||
}
|
||||
|
||||
func init() {
|
||||
setEngine()
|
||||
err := orm.Sync(new(User), new(PublicKey), new(Repository), new(Access), new(Action))
|
||||
if err != nil {
|
||||
fmt.Printf("sync database struct error: %s\n", err)
|
||||
if err := orm.Sync(new(User), new(PublicKey), new(Repository), new(Access), new(Action)); err != nil {
|
||||
fmt.Printf("sync database struct error: %v\n", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -9,6 +9,7 @@ import (
|
|||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path"
|
||||
|
@ -20,16 +21,19 @@ import (
|
|||
"github.com/Unknwon/com"
|
||||
)
|
||||
|
||||
var (
|
||||
sshOpLocker = sync.Mutex{}
|
||||
//publicKeyRootPath string
|
||||
sshPath string
|
||||
appPath string
|
||||
const (
|
||||
// "### autogenerated by gitgos, DO NOT EDIT\n"
|
||||
tmplPublicKey = "command=\"%s serv key-%d\",no-port-forwarding," +
|
||||
"no-X11-forwarding,no-agent-forwarding,no-pty %s\n"
|
||||
TPL_PUBLICK_KEY = `command="%s serv key-%d",no-port-forwarding, no-X11-forwarding,no-agent-forwarding,no-pty %s`
|
||||
)
|
||||
|
||||
var (
|
||||
sshOpLocker = sync.Mutex{}
|
||||
|
||||
sshPath string
|
||||
appPath string
|
||||
)
|
||||
|
||||
// exePath returns the executable path.
|
||||
func exePath() (string, error) {
|
||||
file, err := exec.LookPath(os.Args[0])
|
||||
if err != nil {
|
||||
|
@ -38,6 +42,7 @@ func exePath() (string, error) {
|
|||
return filepath.Abs(file)
|
||||
}
|
||||
|
||||
// homeDir returns the home directory of current user.
|
||||
func homeDir() string {
|
||||
home, err := com.HomeDir()
|
||||
if err != nil {
|
||||
|
@ -48,15 +53,22 @@ func homeDir() string {
|
|||
|
||||
func init() {
|
||||
var err error
|
||||
|
||||
appPath, err = exePath()
|
||||
if err != nil {
|
||||
println(err.Error())
|
||||
fmt.Printf("publickey.init(fail to get app path): %v\n", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
|
||||
// Determine and create .ssh path.
|
||||
sshPath = filepath.Join(homeDir(), ".ssh")
|
||||
if err = os.MkdirAll(sshPath, os.ModePerm); err != nil {
|
||||
fmt.Printf("publickey.init(fail to create sshPath(%s)): %v\n", sshPath, err)
|
||||
os.Exit(2)
|
||||
}
|
||||
}
|
||||
|
||||
// PublicKey represents a SSH key of user.
|
||||
type PublicKey struct {
|
||||
Id int64
|
||||
OwnerId int64 `xorm:"index"`
|
||||
|
@ -71,10 +83,12 @@ var (
|
|||
ErrKeyAlreadyExist = errors.New("Public key already exist")
|
||||
)
|
||||
|
||||
// GenAuthorizedKey returns formatted public key string.
|
||||
func GenAuthorizedKey(keyId int64, key string) string {
|
||||
return fmt.Sprintf(tmplPublicKey, appPath, keyId, key)
|
||||
return fmt.Sprintf(TPL_PUBLICK_KEY+"\n", appPath, keyId, key)
|
||||
}
|
||||
|
||||
// AddPublicKey adds new public key to database and SSH key file.
|
||||
func AddPublicKey(key *PublicKey) (err error) {
|
||||
// Check if public key name has been used.
|
||||
has, err := orm.Get(key)
|
||||
|
@ -88,14 +102,9 @@ func AddPublicKey(key *PublicKey) (err error) {
|
|||
tmpPath := filepath.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()),
|
||||
"id_rsa.pub")
|
||||
os.MkdirAll(path.Dir(tmpPath), os.ModePerm)
|
||||
f, err := os.Create(tmpPath)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if _, err = f.WriteString(key.Content); err != nil {
|
||||
if err = ioutil.WriteFile(tmpPath, []byte(key.Content), os.ModePerm); err != nil {
|
||||
return err
|
||||
}
|
||||
f.Close()
|
||||
stdout, _, err := com.ExecCmd("ssh-keygen", "-l", "-f", tmpPath)
|
||||
if err != nil {
|
||||
return err
|
||||
|
@ -108,7 +117,6 @@ func AddPublicKey(key *PublicKey) (err error) {
|
|||
if _, err = orm.Insert(key); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = SaveAuthorizedKeyFile(key); err != nil {
|
||||
if _, err2 := orm.Delete(key); err2 != nil {
|
||||
return err2
|
||||
|
@ -121,6 +129,7 @@ func AddPublicKey(key *PublicKey) (err error) {
|
|||
|
||||
// DeletePublicKey deletes SSH key information both in database and authorized_keys file.
|
||||
func DeletePublicKey(key *PublicKey) (err error) {
|
||||
// Delete SSH key in database.
|
||||
has, err := orm.Id(key.Id).Get(key)
|
||||
if err != nil {
|
||||
return err
|
||||
|
@ -131,6 +140,7 @@ func DeletePublicKey(key *PublicKey) (err error) {
|
|||
return err
|
||||
}
|
||||
|
||||
// Delete SSH key in SSH key file.
|
||||
sshOpLocker.Lock()
|
||||
defer sshOpLocker.Unlock()
|
||||
|
||||
|
@ -182,16 +192,17 @@ func DeletePublicKey(key *PublicKey) (err error) {
|
|||
if err = os.Remove(p); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return os.Rename(tmpP, p)
|
||||
}
|
||||
|
||||
// ListPublicKey returns a list of public keys that user has.
|
||||
func ListPublicKey(userId int64) ([]PublicKey, error) {
|
||||
keys := make([]PublicKey, 0)
|
||||
err := orm.Find(&keys, &PublicKey{OwnerId: userId})
|
||||
return keys, err
|
||||
}
|
||||
|
||||
// SaveAuthorizedKeyFile writes SSH key content to SSH key file.
|
||||
func SaveAuthorizedKeyFile(key *PublicKey) error {
|
||||
sshOpLocker.Lock()
|
||||
defer sshOpLocker.Unlock()
|
||||
|
@ -203,7 +214,6 @@ func SaveAuthorizedKeyFile(key *PublicKey) error {
|
|||
}
|
||||
defer f.Close()
|
||||
|
||||
//os.Chmod(p, 0600)
|
||||
_, err = f.WriteString(GenAuthorizedKey(key.Id, key.Content))
|
||||
return err
|
||||
}
|
||||
|
|
241
models/repo.go
241
models/repo.go
|
@ -9,6 +9,7 @@ import (
|
|||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
|
@ -24,6 +25,7 @@ import (
|
|||
"github.com/gogits/gogs/modules/log"
|
||||
)
|
||||
|
||||
// Repository represents a git repository.
|
||||
type Repository struct {
|
||||
Id int64
|
||||
OwnerId int64 `xorm:"unique(s)"`
|
||||
|
@ -63,7 +65,7 @@ func init() {
|
|||
zip.Verbose = false
|
||||
}
|
||||
|
||||
// check if repository is exist
|
||||
// IsRepositoryExist returns true if the repository with given name under user has already existed.
|
||||
func IsRepositoryExist(user *User, repoName string) (bool, error) {
|
||||
repo := Repository{OwnerId: user.Id}
|
||||
has, err := orm.Where("lower_name = ?", strings.ToLower(repoName)).Get(&repo)
|
||||
|
@ -94,8 +96,8 @@ func CreateRepository(user *User, repoName, desc, repoLang, license string, priv
|
|||
Private: private,
|
||||
}
|
||||
|
||||
f := RepoPath(user.Name, repoName)
|
||||
if err = initRepository(f, user, repo, initReadme, repoLang, license); err != nil {
|
||||
repoPath := RepoPath(user.Name, repoName)
|
||||
if err = initRepository(repoPath, user, repo, initReadme, repoLang, license); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
session := orm.NewSession()
|
||||
|
@ -103,9 +105,10 @@ func CreateRepository(user *User, repoName, desc, repoLang, license string, priv
|
|||
session.Begin()
|
||||
|
||||
if _, err = session.Insert(repo); err != nil {
|
||||
if err2 := os.RemoveAll(f); err2 != nil {
|
||||
if err2 := os.RemoveAll(repoPath); err2 != nil {
|
||||
log.Error("repo.CreateRepository(repo): %v", err)
|
||||
return nil, errors.New(fmt.Sprintf(
|
||||
"delete repo directory %s/%s failed", user.Name, repoName))
|
||||
"delete repo directory %s/%s failed(1): %v", user.Name, repoName, err2))
|
||||
}
|
||||
session.Rollback()
|
||||
return nil, err
|
||||
|
@ -118,33 +121,39 @@ func CreateRepository(user *User, repoName, desc, repoLang, license string, priv
|
|||
}
|
||||
if _, err = session.Insert(&access); err != nil {
|
||||
session.Rollback()
|
||||
if err2 := os.RemoveAll(f); err2 != nil {
|
||||
if err2 := os.RemoveAll(repoPath); err2 != nil {
|
||||
log.Error("repo.CreateRepository(access): %v", err)
|
||||
return nil, errors.New(fmt.Sprintf(
|
||||
"delete repo directory %s/%s failed", user.Name, repoName))
|
||||
"delete repo directory %s/%s failed(2): %v", user.Name, repoName, err2))
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if _, err = session.Exec("update user set num_repos = num_repos + 1 where id = ?", user.Id); err != nil {
|
||||
rawSql := "UPDATE user SET num_repos = num_repos + 1 WHERE id = ?"
|
||||
if base.Cfg.MustValue("database", "DB_TYPE") == "postgres" {
|
||||
rawSql = "UPDATE \"user\" SET num_repos = num_repos + 1 WHERE id = ?"
|
||||
}
|
||||
if _, err = session.Exec(rawSql, user.Id); err != nil {
|
||||
session.Rollback()
|
||||
if err2 := os.RemoveAll(f); err2 != nil {
|
||||
if err2 := os.RemoveAll(repoPath); err2 != nil {
|
||||
log.Error("repo.CreateRepository(repo count): %v", err)
|
||||
return nil, errors.New(fmt.Sprintf(
|
||||
"delete repo directory %s/%s failed", user.Name, repoName))
|
||||
"delete repo directory %s/%s failed(3): %v", user.Name, repoName, err2))
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err = session.Commit(); err != nil {
|
||||
session.Rollback()
|
||||
if err2 := os.RemoveAll(f); err2 != nil {
|
||||
if err2 := os.RemoveAll(repoPath); err2 != nil {
|
||||
log.Error("repo.CreateRepository(commit): %v", err)
|
||||
return nil, errors.New(fmt.Sprintf(
|
||||
"delete repo directory %s/%s failed", user.Name, repoName))
|
||||
"delete repo directory %s/%s failed(3): %v", user.Name, repoName, err2))
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return repo, NewRepoAction(user, repo)
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// extractGitBareZip extracts git-bare.zip to repository path.
|
||||
|
@ -255,6 +264,7 @@ func initRepository(f string, user *User, repo *Repository, initReadme bool, rep
|
|||
return nil
|
||||
}
|
||||
|
||||
// GetRepositoryByName returns the repository by given name under user if exists.
|
||||
func GetRepositoryByName(user *User, repoName string) (*Repository, error) {
|
||||
repo := &Repository{
|
||||
OwnerId: user.Id,
|
||||
|
@ -269,6 +279,7 @@ func GetRepositoryByName(user *User, repoName string) (*Repository, error) {
|
|||
return repo, err
|
||||
}
|
||||
|
||||
// GetRepositoryById returns the repository by given id if exists.
|
||||
func GetRepositoryById(id int64) (repo *Repository, err error) {
|
||||
has, err := orm.Id(id).Get(repo)
|
||||
if err != nil {
|
||||
|
@ -336,7 +347,11 @@ func DeleteRepository(userId, repoId int64, userName string) (err error) {
|
|||
session.Rollback()
|
||||
return err
|
||||
}
|
||||
if _, err = session.Exec("update user set num_repos = num_repos - 1 where id = ?", userId); err != nil {
|
||||
rawSql := "UPDATE user SET num_repos = num_repos - 1 WHERE id = ?"
|
||||
if base.Cfg.MustValue("database", "DB_TYPE") == "postgres" {
|
||||
rawSql = "UPDATE \"user\" SET num_repos = num_repos - 1 WHERE id = ?"
|
||||
}
|
||||
if _, err = session.Exec(rawSql, userId); err != nil {
|
||||
session.Rollback()
|
||||
return err
|
||||
}
|
||||
|
@ -346,8 +361,204 @@ func DeleteRepository(userId, repoId int64, userName string) (err error) {
|
|||
}
|
||||
if err = os.RemoveAll(RepoPath(userName, repo.Name)); err != nil {
|
||||
// TODO: log and delete manully
|
||||
log.Error("delete repo %s/%s failed", userName, repo.Name)
|
||||
log.Error("delete repo %s/%s failed: %v", userName, repo.Name, err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Commit represents a git commit.
|
||||
type Commit struct {
|
||||
Author string
|
||||
Email string
|
||||
Date time.Time
|
||||
SHA string
|
||||
Message string
|
||||
}
|
||||
|
||||
var (
|
||||
ErrRepoFileNotLoaded = fmt.Errorf("repo file not loaded")
|
||||
)
|
||||
|
||||
// RepoFile represents a file object in git repository.
|
||||
type RepoFile struct {
|
||||
*git.TreeEntry
|
||||
Path string
|
||||
Message string
|
||||
Created time.Time
|
||||
Size int64
|
||||
Repo *git.Repository
|
||||
LastCommit string
|
||||
}
|
||||
|
||||
// LookupBlob returns the content of an object.
|
||||
func (file *RepoFile) LookupBlob() (*git.Blob, error) {
|
||||
if file.Repo == nil {
|
||||
return nil, ErrRepoFileNotLoaded
|
||||
}
|
||||
|
||||
return file.Repo.LookupBlob(file.Id)
|
||||
}
|
||||
|
||||
// GetBranches returns all branches of given repository.
|
||||
func GetBranches(userName, reposName string) ([]string, error) {
|
||||
repo, err := git.OpenRepository(RepoPath(userName, reposName))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
refs, err := repo.AllReferences()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
brs := make([]string, len(refs))
|
||||
for i, ref := range refs {
|
||||
brs[i] = ref.Name
|
||||
}
|
||||
return brs, nil
|
||||
}
|
||||
|
||||
// GetReposFiles returns a list of file object in given directory of repository.
|
||||
func GetReposFiles(userName, reposName, branchName, rpath string) ([]*RepoFile, error) {
|
||||
repo, err := git.OpenRepository(RepoPath(userName, reposName))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ref, err := repo.LookupReference("refs/heads/" + branchName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
lastCommit, err := repo.LookupCommit(ref.Oid)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var repodirs []*RepoFile
|
||||
var repofiles []*RepoFile
|
||||
lastCommit.Tree.Walk(func(dirname string, entry *git.TreeEntry) int {
|
||||
if dirname == rpath {
|
||||
size, err := repo.ObjectSize(entry.Id)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
|
||||
var cm = lastCommit
|
||||
|
||||
for {
|
||||
if cm.ParentCount() == 0 {
|
||||
break
|
||||
} else if cm.ParentCount() == 1 {
|
||||
pt, _ := repo.SubTree(cm.Parent(0).Tree, dirname)
|
||||
if pt == nil {
|
||||
break
|
||||
}
|
||||
pEntry := pt.EntryByName(entry.Name)
|
||||
if pEntry == nil || !pEntry.Id.Equal(entry.Id) {
|
||||
break
|
||||
} else {
|
||||
cm = cm.Parent(0)
|
||||
}
|
||||
} else {
|
||||
var emptyCnt = 0
|
||||
var sameIdcnt = 0
|
||||
for i := 0; i < cm.ParentCount(); i++ {
|
||||
p := cm.Parent(i)
|
||||
pt, _ := repo.SubTree(p.Tree, dirname)
|
||||
var pEntry *git.TreeEntry
|
||||
if pt != nil {
|
||||
pEntry = pt.EntryByName(entry.Name)
|
||||
}
|
||||
|
||||
if pEntry == nil {
|
||||
if emptyCnt == cm.ParentCount()-1 {
|
||||
goto loop
|
||||
} else {
|
||||
emptyCnt = emptyCnt + 1
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
if !pEntry.Id.Equal(entry.Id) {
|
||||
goto loop
|
||||
} else {
|
||||
if sameIdcnt == cm.ParentCount()-1 {
|
||||
// TODO: now follow the first parent commit?
|
||||
cm = cm.Parent(0)
|
||||
break
|
||||
}
|
||||
sameIdcnt = sameIdcnt + 1
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
loop:
|
||||
|
||||
rp := &RepoFile{
|
||||
entry,
|
||||
path.Join(dirname, entry.Name),
|
||||
cm.Message(),
|
||||
cm.Committer.When,
|
||||
size,
|
||||
repo,
|
||||
cm.Id().String(),
|
||||
}
|
||||
|
||||
if entry.IsFile() {
|
||||
repofiles = append(repofiles, rp)
|
||||
} else if entry.IsDir() {
|
||||
repodirs = append(repodirs, rp)
|
||||
}
|
||||
}
|
||||
return 0
|
||||
})
|
||||
|
||||
return append(repodirs, repofiles...), nil
|
||||
}
|
||||
|
||||
// GetLastestCommit returns the latest commit of given repository.
|
||||
func GetLastestCommit(userName, repoName string) (*Commit, error) {
|
||||
stdout, _, err := com.ExecCmd("git", "--git-dir="+RepoPath(userName, repoName), "log", "-1")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
commit := new(Commit)
|
||||
for _, line := range strings.Split(stdout, "\n") {
|
||||
if len(line) == 0 {
|
||||
continue
|
||||
}
|
||||
switch {
|
||||
case line[0] == 'c':
|
||||
commit.SHA = line[7:]
|
||||
case line[0] == 'A':
|
||||
infos := strings.SplitN(line, " ", 3)
|
||||
commit.Author = infos[1]
|
||||
commit.Email = infos[2][1 : len(infos[2])-1]
|
||||
case line[0] == 'D':
|
||||
commit.Date, err = time.Parse("Mon Jan 02 15:04:05 2006 -0700", line[8:])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case line[:4] == " ":
|
||||
commit.Message = line[4:]
|
||||
}
|
||||
}
|
||||
return commit, nil
|
||||
}
|
||||
|
||||
// GetCommits returns all commits of given branch of repository.
|
||||
func GetCommits(userName, reposName, branchname string) ([]*git.Commit, error) {
|
||||
repo, err := git.OpenRepository(RepoPath(userName, reposName))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r, err := repo.LookupReference(fmt.Sprintf("refs/heads/%s", branchname))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return r.AllCommits()
|
||||
}
|
||||
|
|
205
models/repo2.go
205
models/repo2.go
|
@ -1,205 +0,0 @@
|
|||
// Copyright 2014 The Gogs Authors. All rights reserved.
|
||||
// Use of this source code is governed by a MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package models
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Unknwon/com"
|
||||
|
||||
"github.com/gogits/git"
|
||||
)
|
||||
|
||||
type Commit struct {
|
||||
Author string
|
||||
Email string
|
||||
Date time.Time
|
||||
SHA string
|
||||
Message string
|
||||
}
|
||||
|
||||
var (
|
||||
ErrRepoFileNotLoaded = fmt.Errorf("repo file not loaded")
|
||||
)
|
||||
|
||||
type RepoFile struct {
|
||||
*git.TreeEntry
|
||||
Path string
|
||||
Message string
|
||||
Created time.Time
|
||||
Size int64
|
||||
Repo *git.Repository
|
||||
LastCommit string
|
||||
}
|
||||
|
||||
func (file *RepoFile) LookupBlob() (*git.Blob, error) {
|
||||
if file.Repo == nil {
|
||||
return nil, ErrRepoFileNotLoaded
|
||||
}
|
||||
|
||||
return file.Repo.LookupBlob(file.Id)
|
||||
}
|
||||
|
||||
func GetBranches(userName, reposName string) ([]string, error) {
|
||||
repo, err := git.OpenRepository(RepoPath(userName, reposName))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
refs, err := repo.AllReferences()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
brs := make([]string, len(refs))
|
||||
for i, ref := range refs {
|
||||
brs[i] = ref.Name
|
||||
}
|
||||
return brs, nil
|
||||
}
|
||||
|
||||
func GetReposFiles(userName, reposName, branchName, rpath string) ([]*RepoFile, error) {
|
||||
repo, err := git.OpenRepository(RepoPath(userName, reposName))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ref, err := repo.LookupReference("refs/heads/" + branchName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
lastCommit, err := repo.LookupCommit(ref.Oid)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var repodirs []*RepoFile
|
||||
var repofiles []*RepoFile
|
||||
lastCommit.Tree.Walk(func(dirname string, entry *git.TreeEntry) int {
|
||||
if dirname == rpath {
|
||||
size, err := repo.ObjectSize(entry.Id)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
|
||||
var cm = lastCommit
|
||||
|
||||
for {
|
||||
if cm.ParentCount() == 0 {
|
||||
break
|
||||
} else if cm.ParentCount() == 1 {
|
||||
pt, _ := repo.SubTree(cm.Parent(0).Tree, dirname)
|
||||
if pt == nil {
|
||||
break
|
||||
}
|
||||
pEntry := pt.EntryByName(entry.Name)
|
||||
if pEntry == nil || !pEntry.Id.Equal(entry.Id) {
|
||||
break
|
||||
} else {
|
||||
cm = cm.Parent(0)
|
||||
}
|
||||
} else {
|
||||
var emptyCnt = 0
|
||||
var sameIdcnt = 0
|
||||
for i := 0; i < cm.ParentCount(); i++ {
|
||||
p := cm.Parent(i)
|
||||
pt, _ := repo.SubTree(p.Tree, dirname)
|
||||
var pEntry *git.TreeEntry
|
||||
if pt != nil {
|
||||
pEntry = pt.EntryByName(entry.Name)
|
||||
}
|
||||
|
||||
if pEntry == nil {
|
||||
if emptyCnt == cm.ParentCount()-1 {
|
||||
goto loop
|
||||
} else {
|
||||
emptyCnt = emptyCnt + 1
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
if !pEntry.Id.Equal(entry.Id) {
|
||||
goto loop
|
||||
} else {
|
||||
if sameIdcnt == cm.ParentCount()-1 {
|
||||
// TODO: now follow the first parent commit?
|
||||
cm = cm.Parent(0)
|
||||
break
|
||||
}
|
||||
sameIdcnt = sameIdcnt + 1
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
loop:
|
||||
|
||||
rp := &RepoFile{
|
||||
entry,
|
||||
path.Join(dirname, entry.Name),
|
||||
cm.Message(),
|
||||
cm.Committer.When,
|
||||
size,
|
||||
repo,
|
||||
cm.Id().String(),
|
||||
}
|
||||
|
||||
if entry.IsFile() {
|
||||
repofiles = append(repofiles, rp)
|
||||
} else if entry.IsDir() {
|
||||
repodirs = append(repodirs, rp)
|
||||
}
|
||||
}
|
||||
return 0
|
||||
})
|
||||
|
||||
return append(repodirs, repofiles...), nil
|
||||
}
|
||||
|
||||
func GetLastestCommit(userName, repoName string) (*Commit, error) {
|
||||
stdout, _, err := com.ExecCmd("git", "--git-dir="+RepoPath(userName, repoName), "log", "-1")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
commit := new(Commit)
|
||||
for _, line := range strings.Split(stdout, "\n") {
|
||||
if len(line) == 0 {
|
||||
continue
|
||||
}
|
||||
switch {
|
||||
case line[0] == 'c':
|
||||
commit.SHA = line[7:]
|
||||
case line[0] == 'A':
|
||||
infos := strings.SplitN(line, " ", 3)
|
||||
commit.Author = infos[1]
|
||||
commit.Email = infos[2][1 : len(infos[2])-1]
|
||||
case line[0] == 'D':
|
||||
commit.Date, err = time.Parse("Mon Jan 02 15:04:05 2006 -0700", line[8:])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case line[:4] == " ":
|
||||
commit.Message = line[4:]
|
||||
}
|
||||
}
|
||||
return commit, nil
|
||||
}
|
||||
|
||||
func GetCommits(userName, reposName, branchname string) ([]*git.Commit, error) {
|
||||
repo, err := git.OpenRepository(RepoPath(userName, reposName))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r, err := repo.LookupReference(fmt.Sprintf("refs/heads/%s", branchname))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return r.AllCommits()
|
||||
}
|
|
@ -19,7 +19,9 @@ import (
|
|||
"github.com/gogits/gogs/modules/base"
|
||||
)
|
||||
|
||||
var UserPasswdSalt string
|
||||
var (
|
||||
UserPasswdSalt string
|
||||
)
|
||||
|
||||
func init() {
|
||||
UserPasswdSalt = base.Cfg.MustValue("security", "USER_PASSWD_SALT")
|
||||
|
@ -37,7 +39,7 @@ const (
|
|||
LT_LDAP
|
||||
)
|
||||
|
||||
// A User represents the object of individual and member of organization.
|
||||
// User represents the object of individual and member of organization.
|
||||
type User struct {
|
||||
Id int64
|
||||
LowerName string `xorm:"unique not null"`
|
||||
|
@ -58,15 +60,16 @@ type User struct {
|
|||
Updated time.Time `xorm:"updated"`
|
||||
}
|
||||
|
||||
// HomeLink returns the user home page link.
|
||||
func (user *User) HomeLink() string {
|
||||
return "/user/" + user.LowerName
|
||||
}
|
||||
|
||||
// AvatarLink returns the user gravatar link.
|
||||
func (user *User) AvatarLink() string {
|
||||
return "http://1.gravatar.com/avatar/" + user.Avatar
|
||||
}
|
||||
|
||||
// A Follow represents
|
||||
type Follow struct {
|
||||
Id int64
|
||||
UserId int64 `xorm:"unique(s)"`
|
||||
|
@ -87,6 +90,7 @@ func IsUserExist(name string) (bool, error) {
|
|||
return orm.Get(&User{LowerName: strings.ToLower(name)})
|
||||
}
|
||||
|
||||
// IsEmailUsed returns true if the e-mail has been used.
|
||||
func IsEmailUsed(email string) (bool, error) {
|
||||
return orm.Get(&User{Email: email})
|
||||
}
|
||||
|
@ -121,16 +125,12 @@ func RegisterUser(user *User) (err error) {
|
|||
user.AvatarEmail = user.Email
|
||||
if err = user.EncodePasswd(); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = orm.Insert(user); err != nil {
|
||||
} else if _, err = orm.Insert(user); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = os.MkdirAll(UserPath(user.Name), os.ModePerm); err != nil {
|
||||
|
||||
} else if err = os.MkdirAll(UserPath(user.Name), os.ModePerm); err != nil {
|
||||
if _, err := orm.Id(user.Id).Delete(&User{}); err != nil {
|
||||
return errors.New(fmt.Sprintf(
|
||||
"both create userpath %s and delete table record faild", user.Name))
|
||||
"both create userpath %s and delete table record faild: %v", user.Name, err))
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
@ -188,23 +188,28 @@ func (user *User) EncodePasswd() error {
|
|||
return err
|
||||
}
|
||||
|
||||
// UserPath returns the path absolute path of user repositories.
|
||||
func UserPath(userName string) string {
|
||||
return filepath.Join(RepoRootPath, userName)
|
||||
}
|
||||
|
||||
func GetUserByKeyId(keyId int64) (*User, error) {
|
||||
user := new(User)
|
||||
has, err := orm.Sql("select a.* from user as a, public_key as b where a.id = b.owner_id and b.id=?", keyId).Get(user)
|
||||
rawSql := "SELECT a.* FROM user AS a, public_key AS b WHERE a.id = b.owner_id AND b.id=?"
|
||||
if base.Cfg.MustValue("database", "DB_TYPE") == "postgres" {
|
||||
rawSql = "SELECT a.* FROM \"user\" AS a, public_key AS b WHERE a.id = b.owner_id AND b.id=?"
|
||||
}
|
||||
has, err := orm.Sql(rawSql, keyId).Get(user)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !has {
|
||||
} else if !has {
|
||||
err = errors.New("not exist key owner")
|
||||
return nil, err
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// GetUserById returns the user object by given id if exists.
|
||||
func GetUserById(id int64) (*User, error) {
|
||||
user := new(User)
|
||||
has, err := orm.Id(id).Get(user)
|
||||
|
@ -217,6 +222,7 @@ func GetUserById(id int64) (*User, error) {
|
|||
return user, nil
|
||||
}
|
||||
|
||||
// GetUserByName returns the user object by given name if exists.
|
||||
func GetUserByName(name string) (*User, error) {
|
||||
if len(name) == 0 {
|
||||
return nil, ErrUserNotExist
|
||||
|
@ -227,8 +233,7 @@ func GetUserByName(name string) (*User, error) {
|
|||
has, err := orm.Get(user)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !has {
|
||||
} else if !has {
|
||||
return nil, ErrUserNotExist
|
||||
}
|
||||
return user, nil
|
||||
|
@ -242,32 +247,39 @@ func LoginUserPlain(name, passwd string) (*User, error) {
|
|||
}
|
||||
|
||||
has, err := orm.Get(&user)
|
||||
if !has {
|
||||
err = ErrUserNotExist
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
} else if !has {
|
||||
err = ErrUserNotExist
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// FollowUser marks someone be another's follower.
|
||||
func FollowUser(userId int64, followId int64) error {
|
||||
func FollowUser(userId int64, followId int64) (err error) {
|
||||
session := orm.NewSession()
|
||||
defer session.Close()
|
||||
session.Begin()
|
||||
_, err := session.Insert(&Follow{UserId: userId, FollowId: followId})
|
||||
if err != nil {
|
||||
|
||||
if _, err = session.Insert(&Follow{UserId: userId, FollowId: followId}); err != nil {
|
||||
session.Rollback()
|
||||
return err
|
||||
}
|
||||
_, err = session.Exec("update user set num_followers = num_followers + 1 where id = ?", followId)
|
||||
if err != nil {
|
||||
|
||||
rawSql := "UPDATE user SET num_followers = num_followers + 1 WHERE id = ?"
|
||||
if base.Cfg.MustValue("database", "DB_TYPE") == "postgres" {
|
||||
rawSql = "UPDATE \"user\" SET num_followers = num_followers + 1 WHERE id = ?"
|
||||
}
|
||||
if _, err = session.Exec(rawSql, followId); err != nil {
|
||||
session.Rollback()
|
||||
return err
|
||||
}
|
||||
_, err = session.Exec("update user set num_followings = num_followings + 1 where id = ?", userId)
|
||||
if err != nil {
|
||||
|
||||
rawSql = "UPDATE user SET num_followings = num_followings + 1 WHERE id = ?"
|
||||
if base.Cfg.MustValue("database", "DB_TYPE") == "postgres" {
|
||||
rawSql = "UPDATE \"user\" SET num_followings = num_followings + 1 WHERE id = ?"
|
||||
}
|
||||
if _, err = session.Exec(rawSql, userId); err != nil {
|
||||
session.Rollback()
|
||||
return err
|
||||
}
|
||||
|
@ -275,22 +287,30 @@ func FollowUser(userId int64, followId int64) error {
|
|||
}
|
||||
|
||||
// UnFollowUser unmarks someone be another's follower.
|
||||
func UnFollowUser(userId int64, unFollowId int64) error {
|
||||
func UnFollowUser(userId int64, unFollowId int64) (err error) {
|
||||
session := orm.NewSession()
|
||||
defer session.Close()
|
||||
session.Begin()
|
||||
_, err := session.Delete(&Follow{UserId: userId, FollowId: unFollowId})
|
||||
if err != nil {
|
||||
|
||||
if _, err = session.Delete(&Follow{UserId: userId, FollowId: unFollowId}); err != nil {
|
||||
session.Rollback()
|
||||
return err
|
||||
}
|
||||
_, err = session.Exec("update user set num_followers = num_followers - 1 where id = ?", unFollowId)
|
||||
if err != nil {
|
||||
|
||||
rawSql := "UPDATE user SET num_followers = num_followers - 1 WHERE id = ?"
|
||||
if base.Cfg.MustValue("database", "DB_TYPE") == "postgres" {
|
||||
rawSql = "UPDATE \"user\" SET num_followers = num_followers - 1 WHERE id = ?"
|
||||
}
|
||||
if _, err = session.Exec(rawSql, unFollowId); err != nil {
|
||||
session.Rollback()
|
||||
return err
|
||||
}
|
||||
_, err = session.Exec("update user set num_followings = num_followings - 1 where id = ?", userId)
|
||||
if err != nil {
|
||||
|
||||
rawSql = "UPDATE user SET num_followings = num_followings - 1 WHERE id = ?"
|
||||
if base.Cfg.MustValue("database", "DB_TYPE") == "postgres" {
|
||||
rawSql = "UPDATE \"user\" SET num_followings = num_followings - 1 WHERE id = ?"
|
||||
}
|
||||
if _, err = session.Exec(rawSql, userId); err != nil {
|
||||
session.Rollback()
|
||||
return err
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue