Esempio n. 1
0
// updateHistory updates browser history.
func updateHistory(ctx *middleware.Context, id int64) {
	pairs := make([]string, 1, 10)
	pairs[0] = com.ToStr(id) + ":" + com.ToStr(time.Now().UTC().Unix())

	count := 0
	for _, pair := range strings.Split(ctx.GetCookie("user_history"), "|") {
		infos := strings.Split(pair, ":")
		if len(infos) != 2 {
			continue
		}

		pid := com.StrTo(infos[0]).MustInt64()
		if pid == 0 || pid == id {
			continue
		}

		pairs = append(pairs, pair)

		count++
		if count == 9 {
			break
		}
	}
	ctx.SetCookie("user_history", strings.Join(pairs, "|"), 9999999)
}
Esempio n. 2
0
// GetUserIssueStats returns issue statistic information for dashboard by given conditions.
func GetUserIssueStats(repoID, uid int64, repoIDs []int64, filterMode int) *IssueStats {
	stats := &IssueStats{}
	issue := new(Issue)
	stats.AssignCount, _ = x.Where("assignee_id=?", uid).And("is_closed=?", false).Count(issue)
	stats.CreateCount, _ = x.Where("poster_id=?", uid).And("is_closed=?", false).Count(issue)

	queryStr := "SELECT COUNT(*) FROM `issue` "
	baseCond := " WHERE issue.is_closed=?"
	if repoID > 0 {
		baseCond += " AND issue.repo_id=" + com.ToStr(repoID)
	} else {
		baseCond += " AND issue.repo_id IN (" + strings.Join(base.Int64sToStrings(repoIDs), ",") + ")"
	}
	switch filterMode {
	case FM_ASSIGN:
		baseCond += " AND assignee_id=" + com.ToStr(uid)

	case FM_CREATE:
		baseCond += " AND poster_id=" + com.ToStr(uid)
	}

	results, _ := x.Query(queryStr+baseCond, false)
	stats.OpenCount = parseCountResult(results)
	results, _ = x.Query(queryStr+baseCond, true)
	stats.ClosedCount = parseCountResult(results)
	return stats
}
Esempio n. 3
0
File: wiki.go Progetto: CarloQ/gogs
func (repo *Repository) DeleteWikiPage(doer *User, title string) (err error) {
	wikiWorkingPool.CheckIn(com.ToStr(repo.ID))
	defer wikiWorkingPool.CheckOut(com.ToStr(repo.ID))

	localPath := repo.LocalWikiPath()
	if err = discardLocalWikiChanges(localPath); err != nil {
		return fmt.Errorf("discardLocalWikiChanges: %v", err)
	} else if err = repo.UpdateLocalWiki(); err != nil {
		return fmt.Errorf("UpdateLocalWiki: %v", err)
	}

	title = ToWikiPageName(title)
	filename := path.Join(localPath, title+".md")
	os.Remove(filename)

	message := "Delete page '" + title + "'"

	if err = git.AddChanges(localPath, true); err != nil {
		return fmt.Errorf("AddChanges: %v", err)
	} else if err = git.CommitChanges(localPath, message, doer.NewGitSig()); err != nil {
		return fmt.Errorf("CommitChanges: %v", err)
	} else if err = git.Push(localPath, "origin", "master"); err != nil {
		return fmt.Errorf("Push: %v", err)
	}

	return nil
}
Esempio n. 4
0
File: user.go Progetto: GoNuuts/gogs
func (u *User) RelAvatarLink() string {
	defaultImgUrl := "/img/avatar_default.jpg"
	if u.Id == -1 {
		return defaultImgUrl
	}

	switch {
	case u.UseCustomAvatar:
		if !com.IsExist(u.CustomAvatarPath()) {
			return defaultImgUrl
		}
		return "/avatars/" + com.ToStr(u.Id)
	case setting.DisableGravatar, setting.OfflineMode:
		if !com.IsExist(u.CustomAvatarPath()) {
			if err := u.GenerateRandomAvatar(); err != nil {
				log.Error(3, "GenerateRandomAvatar: %v", err)
			}
		}

		return "/avatars/" + com.ToStr(u.Id)
	case setting.Service.EnableCacheAvatar:
		return "/avatar/" + u.Avatar
	}
	return setting.GravatarSource + u.Avatar
}
Esempio n. 5
0
// checkRefs checks if given packages are still referencing this one.
func checkRefs(pinfo *PkgInfo) {
	var buf bytes.Buffer
	pinfo.RefNum = 0
	refIDs := strings.Split(pinfo.RefIDs, "|")
	for i := range refIDs {
		if len(refIDs[i]) == 0 {
			continue
		}

		fmt.Println(com.StrTo(refIDs[i][1:]).MustInt64())
		pkg, _ := GetPkgInfoById(com.StrTo(refIDs[i][1:]).MustInt64())
		if pkg == nil {
			continue
		}

		if strings.Index(pkg.ImportIDs, "$"+com.ToStr(pinfo.ID)+"|") == -1 {
			continue
		}

		buf.WriteString("$")
		buf.WriteString(com.ToStr(pkg.ID))
		buf.WriteString("|")
		pinfo.RefNum++
	}
	pinfo.RefIDs = buf.String()
}
Esempio n. 6
0
func dumpGC(memStats *runtime.MemStats, gcstats *debug.GCStats, w io.Writer) {

	if gcstats.NumGC > 0 {
		lastPause := gcstats.Pause[0]
		elapsed := time.Now().Sub(startTime)
		overhead := float64(gcstats.PauseTotal) / float64(elapsed) * 100
		allocatedRate := float64(memStats.TotalAlloc) / elapsed.Seconds()

		fmt.Fprintf(w, "NumGC:%d Pause:%s Pause(Avg):%s Overhead:%3.2f%% Alloc:%s Sys:%s Alloc(Rate):%s/s Histogram:%s %s %s \n",
			gcstats.NumGC,
			com.ToStr(lastPause),
			com.ToStr(avg(gcstats.Pause)),
			overhead,
			com.HumaneFileSize(memStats.Alloc),
			com.HumaneFileSize(memStats.Sys),
			com.HumaneFileSize(uint64(allocatedRate)),
			com.ToStr(gcstats.PauseQuantiles[94]),
			com.ToStr(gcstats.PauseQuantiles[98]),
			com.ToStr(gcstats.PauseQuantiles[99]))
	} else {
		// while GC has disabled
		elapsed := time.Now().Sub(startTime)
		allocatedRate := float64(memStats.TotalAlloc) / elapsed.Seconds()

		fmt.Fprintf(w, "Alloc:%s Sys:%s Alloc(Rate):%s/s\n",
			com.HumaneFileSize(memStats.Alloc),
			com.HumaneFileSize(memStats.Sys),
			com.HumaneFileSize(uint64(allocatedRate)))
	}
}
Esempio n. 7
0
func (repo *Repository) commitsByRange(id sha1, page int) (*list.List, error) {
	stdout, stderr, err := com.ExecCmdDirBytes(repo.Path, "git", "log", id.String(),
		"--skip="+com.ToStr((page-1)*CommitsRangeSize), "--max-count="+com.ToStr(CommitsRangeSize), prettyLogFormat)
	if err != nil {
		return nil, errors.New(string(stderr))
	}
	return parsePrettyFormatLog(repo, stdout)
}
Esempio n. 8
0
// Generate maps CSRF to each request. If this request is a Get request, it will generate a new token.
// Additionally, depending on options set, generated tokens will be sent via Header and/or Cookie.
func Generate(options ...Options) macaron.Handler {
	opt := prepareOptions(options)
	return func(ctx *macaron.Context, sess session.Store) {
		x := &csrf{
			Secret:     opt.Secret,
			Header:     opt.Header,
			Form:       opt.Form,
			Cookie:     opt.Cookie,
			CookiePath: opt.CookiePath,
			ErrorFunc:  opt.ErrorFunc,
		}
		ctx.MapTo(x, (*CSRF)(nil))

		if opt.Origin && len(ctx.Req.Header.Get("Origin")) > 0 {
			return
		}

		x.ID = "0"
		uid := sess.Get(opt.SessionKey)
		if uid != nil {
			switch uid.(type) {
			case string:
				x.ID = uid.(string)
			case int:
				x.ID = com.ToStr(uid)
			case int64:
				x.ID = com.ToStr(uid)
			}
		}

		needsNew := false
		oldUid := sess.Get(opt.oldSeesionKey)
		if oldUid == nil || oldUid.(string) != x.ID {
			needsNew = true
			sess.Set(opt.oldSeesionKey, x.ID)
		} else {
			// If cookie present, map existing token, else generate a new one.
			if val := ctx.GetCookie(opt.Cookie); len(val) > 0 {
				// FIXME: test coverage.
				x.Token = val
			} else {
				needsNew = true
			}
		}

		if needsNew {
			// FIXME: actionId.
			x.Token = GenerateToken(x.Secret, x.ID, "POST")
		}

		if opt.SetCookie {
			ctx.SetCookie(opt.Cookie, x.Token, 0, opt.CookiePath)
		}
		if opt.SetHeader {
			ctx.Resp.Header().Add(opt.Header, x.Token)
		}
	}
}
Esempio n. 9
0
func (t *Tree) matchSubtree(globLevel int, segment, url string, params Params) (Handle, bool) {
	for i := 0; i < len(t.subtrees); i++ {
		switch t.subtrees[i].typ {
		case _PATTERN_STATIC:
			if t.subtrees[i].pattern == segment {
				if handle, ok := t.subtrees[i].matchNextSegment(globLevel, url, params); ok {
					return handle, true
				}
			}
		case _PATTERN_REGEXP:
			results := t.subtrees[i].reg.FindStringSubmatch(segment)
			if len(results)-1 != len(t.subtrees[i].wildcards) {
				break
			}

			for j := 0; j < len(t.subtrees[i].wildcards); j++ {
				params[t.subtrees[i].wildcards[j]] = results[j+1]
			}
			if handle, ok := t.subtrees[i].matchNextSegment(globLevel, url, params); ok {
				return handle, true
			}
		case _PATTERN_HOLDER:
			if handle, ok := t.subtrees[i].matchNextSegment(globLevel+1, url, params); ok {
				params[t.subtrees[i].wildcards[0]] = segment
				return handle, true
			}
		case _PATTERN_MATCH_ALL:
			if handle, ok := t.subtrees[i].matchNextSegment(globLevel+1, url, params); ok {
				params["*"+com.ToStr(globLevel)] = segment
				return handle, true
			}
		}
	}

	if len(t.leaves) > 0 {
		leaf := t.leaves[len(t.leaves)-1]
		if leaf.typ == _PATTERN_PATH_EXT {
			url = segment + "/" + url
			j := strings.LastIndex(url, ".")
			if j > -1 {
				params[":path"] = url[:j]
				params[":ext"] = url[j+1:]
			} else {
				params[":path"] = url
			}
			return leaf.handle, true
		} else if leaf.typ == _PATTERN_MATCH_ALL {
			params["*"] = segment + "/" + url
			params["*"+com.ToStr(globLevel)] = segment + "/" + url
			return leaf.handle, true
		}
	}
	return nil, false
}
Esempio n. 10
0
// updateWikiPage adds new page to repository wiki.
func (repo *Repository) updateWikiPage(doer *User, oldTitle, title, content, message string, isNew bool) (err error) {
	wikiWorkingPool.CheckIn(com.ToStr(repo.ID))
	defer wikiWorkingPool.CheckOut(com.ToStr(repo.ID))

	if err = repo.InitWiki(); err != nil {
		return fmt.Errorf("InitWiki: %v", err)
	}

	localPath := repo.LocalWikiPath()
	if err = discardLocalWikiChanges(localPath); err != nil {
		return fmt.Errorf("discardLocalWikiChanges: %v", err)
	} else if err = repo.UpdateLocalWiki(); err != nil {
		return fmt.Errorf("UpdateLocalWiki: %v", err)
	}

	title = ToWikiPageName(title)
	filename := path.Join(localPath, title+".md")

	// If not a new file, show perform update not create.
	if isNew {
		if com.IsExist(filename) {
			return ErrWikiAlreadyExist{filename}
		}
	} else {
		os.Remove(path.Join(localPath, oldTitle+".md"))
	}

	// SECURITY: if new file is a symlink to non-exist critical file,
	// attack content can be written to the target file (e.g. authorized_keys2)
	// as a new page operation.
	// So we want to make sure the symlink is removed before write anything.
	// The new file we created will be in normal text format.
	os.Remove(filename)

	if err = ioutil.WriteFile(filename, []byte(content), 0666); err != nil {
		return fmt.Errorf("WriteFile: %v", err)
	}

	if len(message) == 0 {
		message = "Update page '" + title + "'"
	}
	if err = git.AddChanges(localPath, true); err != nil {
		return fmt.Errorf("AddChanges: %v", err)
	} else if err = git.CommitChanges(localPath, git.CommitChangesOptions{
		Committer: doer.NewGitSig(),
		Message:   message,
	}); err != nil {
		return fmt.Errorf("CommitChanges: %v", err)
	} else if err = git.Push(localPath, "origin", "master"); err != nil {
		return fmt.Errorf("Push: %v", err)
	}

	return nil
}
Esempio n. 11
0
// updateWikiPage adds new page to repository wiki.
func (repo *Repository) updateWikiPage(doer *User, oldTitle, title, content, message string, isNew bool) (err error) {
	wikiWorkingPool.CheckIn(com.ToStr(repo.ID))
	defer wikiWorkingPool.CheckOut(com.ToStr(repo.ID))

	if err = repo.InitWiki(); err != nil {
		return fmt.Errorf("InitWiki: %v", err)
	}

	localPath := repo.LocalWikiPath()

	// Discard local commits make sure even to remote when local copy exists.
	if com.IsExist(localPath) {
		// No need to check if nothing in the repository.
		if git.IsBranchExist(localPath, "master") {
			if err = git.ResetHEAD(localPath, true, "origin/master"); err != nil {
				return fmt.Errorf("Reset: %v", err)
			}
		}
	}

	if err = repo.UpdateLocalWiki(); err != nil {
		return fmt.Errorf("UpdateLocalWiki: %v", err)
	}

	title = ToWikiPageName(strings.Replace(title, "/", " ", -1))
	filename := path.Join(localPath, title+".md")

	// If not a new file, show perform update not create.
	if isNew {
		if com.IsExist(filename) {
			return ErrWikiAlreadyExist{filename}
		}
	} else {
		os.Remove(path.Join(localPath, oldTitle+".md"))
	}

	if err = ioutil.WriteFile(filename, []byte(content), 0666); err != nil {
		return fmt.Errorf("WriteFile: %v", err)
	}

	if len(message) == 0 {
		message = "Update page '" + title + "'"
	}
	if err = git.AddChanges(localPath, true); err != nil {
		return fmt.Errorf("AddChanges: %v", err)
	} else if err = git.CommitChanges(localPath, message, doer.NewGitSig()); err != nil {
		return fmt.Errorf("CommitChanges: %v", err)
	} else if err = git.Push(localPath, "origin", "master"); err != nil {
		return fmt.Errorf("Push: %v", err)
	}

	return nil
}
Esempio n. 12
0
File: ledis.go Progetto: kenno/cache
// Put puts value into cache with key and expire time.
// If expired is 0, it lives forever.
func (c *LedisCacher) Put(key string, val interface{}, expire int64) (err error) {
	if expire == 0 {
		if err = c.c.Set([]byte(key), []byte(com.ToStr(val))); err != nil {
			return err
		}
		_, err = c.c.HSet([]byte(key), defaultHSetName, []byte("0"))
		return err
	}

	if err = c.c.SetEX([]byte(key), expire, []byte(com.ToStr(val))); err != nil {
		return err
	}
	_, err = c.c.HSet([]byte(key), defaultHSetName, []byte(com.ToStr(time.Now().Add(time.Duration(expire)*time.Second).Unix())))
	return err
}
Esempio n. 13
0
// RemoveRepository removes repository from team of organization.
func (t *Team) RemoveRepository(repoId int64) error {
	idStr := "$" + com.ToStr(repoId) + "|"
	if !strings.Contains(t.RepoIds, idStr) {
		return nil
	}

	repo, err := GetRepositoryById(repoId)
	if err != nil {
		return err
	}

	if err = repo.GetOwner(); err != nil {
		return err
	} else if err = t.GetMembers(); err != nil {
		return err
	}

	sess := x.NewSession()
	defer sess.Close()
	if err = sess.Begin(); err != nil {
		return err
	}

	t.NumRepos--
	t.RepoIds = strings.Replace(t.RepoIds, idStr, "", 1)
	if _, err = sess.Id(t.Id).AllCols().Update(t); err != nil {
		sess.Rollback()
		return err
	}

	// Remove access to team members.
	for _, u := range t.Members {
		auth, err := GetHighestAuthorize(t.OrgId, u.Id, repo.Id, t.Id)
		if err != nil {
			sess.Rollback()
			return err
		}

		access := &Access{
			UserName: u.LowerName,
			RepoName: path.Join(repo.Owner.LowerName, repo.LowerName),
		}
		if auth == 0 {
			if _, err = sess.Delete(access); err != nil {
				sess.Rollback()
				return fmt.Errorf("fail to delete access: %v", err)
			} else if err = WatchRepo(u.Id, repo.Id, false); err != nil {
				sess.Rollback()
				return err
			}
		} else if auth < t.Authorize {
			if err = addAccessWithAuthorize(sess, access, AuthorizeToAccessType(auth)); err != nil {
				sess.Rollback()
				return err
			}
		}
	}

	return sess.Commit()
}
Esempio n. 14
0
func init() {
	// Load data.
	if com.IsExist("data.txt") {
		data, err := ioutil.ReadFile("data.txt")
		if err != nil {
			log.Printf("Fail to load data file: %v", err)
			os.Exit(2)
		}
		if len(data) == 0 {
			log.Println("Data file cannot be empty")
			os.Exit(2)
		}
		for _, line := range strings.Split(string(data), "\n") {
			line := strings.TrimSpace(line)
			if len(line) == 0 {
				continue
			}

			infos := strings.Split(line, "\t")
			if len(infos) < 2 {
				continue
			}
			people = append(people, person{infos[0], infos[1]})
		}
	} else {
		// Generate fake data.
		s := rand.NewSource(int64(time.Now().Nanosecond()))
		r := rand.New(s)
		for i := 0; i < 100; i++ {
			info := com.ToStr(r.Int())
			people = append(people, person{info, info})
		}
	}
}
Esempio n. 15
0
// DeleteLabel delete a label of given repository.
func DeleteLabel(repoID, labelID int64) error {
	l, err := GetLabelById(labelID)
	if err != nil {
		if err == ErrLabelNotExist {
			return nil
		}
		return err
	}

	issues, err := GetIssuesByLabel(repoID, labelID)
	if err != nil {
		return err
	}

	sess := x.NewSession()
	defer sessionRelease(sess)
	if err = sess.Begin(); err != nil {
		return err
	}

	for _, issue := range issues {
		issue.LabelIds = strings.Replace(issue.LabelIds, "$"+com.ToStr(labelID)+"|", "", -1)
		if _, err = sess.Id(issue.ID).AllCols().Update(issue); err != nil {
			return err
		}
	}

	if _, err = sess.Delete(l); err != nil {
		return err
	}
	return sess.Commit()
}
Esempio n. 16
0
func listen(config *ssh.ServerConfig, port int) {
	listener, err := net.Listen("tcp", "0.0.0.0:"+com.ToStr(port))
	if err != nil {
		panic(err)
	}
	for {
		// Once a ServerConfig has been configured, connections can be accepted.
		conn, err := listener.Accept()
		if err != nil {
			log.Error(3, "Error accepting incoming connection: %v", err)
			continue
		}
		// Before use, a handshake must be performed on the incoming net.Conn.
		sConn, chans, reqs, err := ssh.NewServerConn(conn, config)
		if err != nil {
			log.Error(3, "Error on handshaking: %v", err)
			continue
		}

		log.Trace("Connection from %s (%s)", sConn.RemoteAddr(), sConn.ClientVersion())
		// The incoming Request channel must be serviced.
		go ssh.DiscardRequests(reqs)
		go handleServerConn(sConn.Permissions.Extensions["key-id"], chans)
	}
}
Esempio n. 17
0
// Listen starts a SSH server listens on given port.
func Listen(port int) {
	config := &ssh.ServerConfig{
		PublicKeyCallback: func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
			pkey, err := models.SearchPublicKeyByContent(strings.TrimSpace(string(ssh.MarshalAuthorizedKey(key))))
			if err != nil {
				log.Error(3, "SearchPublicKeyByContent: %v", err)
				return nil, err
			}
			return &ssh.Permissions{Extensions: map[string]string{"key-id": com.ToStr(pkey.ID)}}, nil
		},
	}

	keyPath := filepath.Join(setting.AppDataPath, "ssh/gogs.rsa")
	if !com.IsExist(keyPath) {
		os.MkdirAll(filepath.Dir(keyPath), os.ModePerm)
		_, stderr, err := com.ExecCmd("ssh-keygen", "-f", keyPath, "-t", "rsa", "-N", "")
		if err != nil {
			panic(fmt.Sprintf("Fail to generate private key: %v - %s", err, stderr))
		}
		log.Trace("New private key is generateed: %s", keyPath)
	}

	privateBytes, err := ioutil.ReadFile(keyPath)
	if err != nil {
		panic("Fail to load private key")
	}
	private, err := ssh.ParsePrivateKey(privateBytes)
	if err != nil {
		panic("Fail to parse private key")
	}
	config.AddHostKey(private)

	go listen(config, port)
}
Esempio n. 18
0
func updatePkgRef(pid int64, refPath string) error {
	if base.IsGoRepoPath(refPath) ||
		refPath == "C" ||
		refPath[1] == '.' {
		return nil
	}

	ref := new(PkgRef)
	has, err := x.Where("import_path=?", refPath).Get(ref)
	if err != nil {
		return fmt.Errorf("get PkgRef: %v", err)
	}

	queryStr := "$" + com.ToStr(pid) + "|"
	if !has {
		if _, err = x.Insert(&PkgRef{
			ImportPath: refPath,
			RefNum:     1,
			RefIDs:     queryStr,
		}); err != nil {
			return fmt.Errorf("insert PkgRef: %v", err)
		}
		return nil
	}

	i := strings.Index(ref.RefIDs, queryStr)
	if i > -1 {
		return nil
	}

	ref.RefIDs += queryStr
	ref.RefNum++
	_, err = x.Id(ref.ID).AllCols().Update(ref)
	return err
}
Esempio n. 19
0
// verify time limit code
func validateUserEmailCode(user *m.User, code string) bool {
	if len(code) <= 18 {
		return false
	}

	minutes := setting.EmailCodeValidMinutes
	code = code[:timeLimitCodeLength]

	// split code
	start := code[:12]
	lives := code[12:18]
	if d, err := com.StrTo(lives).Int(); err == nil {
		minutes = d
	}

	// right active code
	data := com.ToStr(user.Id) + user.Email + user.Login + user.Password + user.Rands
	retCode := createTimeLimitCode(data, minutes, start)
	fmt.Printf("code : %s\ncode2: %s", retCode, code)
	if retCode == code && minutes > 0 {
		// check time is expired or not
		before, _ := time.ParseInLocation("200601021504", start, time.Local)
		now := time.Now()
		if before.Add(time.Minute*time.Duration(minutes)).Unix() > now.Unix() {
			return true
		}
	}

	return false
}
Esempio n. 20
0
// AddRepository adds new repository to team of organization.
func (t *Team) AddRepository(repo *Repository) (err error) {
	idStr := "$" + com.ToStr(repo.Id) + "|"
	if repo.OwnerId != t.OrgId {
		return errors.New("Repository not belong to organization")
	} else if strings.Contains(t.RepoIds, idStr) {
		return nil
	}

	if err = repo.GetOwner(); err != nil {
		return err
	} else if err = t.GetMembers(); err != nil {
		return err
	}

	sess := x.NewSession()
	defer sess.Close()
	if err = sess.Begin(); err != nil {
		return err
	}

	t.NumRepos++
	t.RepoIds += idStr
	if _, err = sess.Id(t.Id).AllCols().Update(t); err != nil {
		sess.Rollback()
		return err
	}

	// Give access to team members.
	mode := AuthorizeToAccessType(t.Authorize)

	for _, u := range t.Members {
		auth, err := GetHighestAuthorize(t.OrgId, u.Id, t.Id, repo.Id)
		if err != nil {
			sess.Rollback()
			return err
		}

		access := &Access{
			UserName: u.LowerName,
			RepoName: path.Join(repo.Owner.LowerName, repo.LowerName),
		}
		if auth == 0 {
			access.Mode = mode
			if _, err = sess.Insert(access); err != nil {
				sess.Rollback()
				return fmt.Errorf("fail to insert access: %v", err)
			}
		} else if auth < t.Authorize {
			if err = addAccessWithAuthorize(sess, access, mode); err != nil {
				sess.Rollback()
				return err
			}
		}
		if err = WatchRepo(u.Id, repo.Id, true); err != nil {
			sess.Rollback()
			return err
		}
	}
	return sess.Commit()
}
Esempio n. 21
0
func (t CollectType) String() string {
	switch t {
	case COLLECT_TYPE_GITHUB:
		return "GitHub"
	}
	return com.ToStr(t)
}
Esempio n. 22
0
File: org.go Progetto: 0rax/gogs
// GetUserRepositories gets all repositories of an organization,
// that the user with the given userID has access to.
func (org *User) GetUserRepositories(userID int64) (err error) {
	teams := make([]*Team, 0, org.NumTeams)
	if err = x.Sql(`SELECT team.id FROM team
INNER JOIN team_user ON team_user.team_id = team.id
WHERE team_user.org_id = ? AND team_user.uid = ?`, org.Id, userID).Find(&teams); err != nil {
		return fmt.Errorf("get teams: %v", err)
	}

	teamIDs := make([]string, len(teams))
	for i := range teams {
		teamIDs[i] = com.ToStr(teams[i].ID)
	}
	if len(teamIDs) == 0 {
		// user has no team but "IN ()" is invalid SQL
		teamIDs = append(teamIDs, "-1") // there is no repo with id=-1
	}

	repos := make([]*Repository, 0, 5)
	if err = x.Sql(fmt.Sprintf(`SELECT repository.* FROM repository
INNER JOIN team_repo ON team_repo.repo_id = repository.id
WHERE (repository.owner_id = ? AND repository.is_private = ?) OR team_repo.team_id IN (%s)
GROUP BY repository.id`, strings.Join(teamIDs, ",")), org.Id, false).Find(&repos); err != nil {
		return fmt.Errorf("get repositories: %v", err)
	}
	org.Repos = repos

	// FIXME: should I change this value inside method,
	// or only in location of caller where it's really needed?
	org.NumRepos = len(org.Repos)
	return nil
}
Esempio n. 23
0
func targetString(ref, goos, goarch, goarm string) string {
	str := fmt.Sprintf("%s_%s_%s", ref, goos, goarch)
	if len(goarm) > 0 {
		str += "_arm" + com.ToStr(goarm)
	}
	return str
}
Esempio n. 24
0
File: pull.go Progetto: Janfred/gogs
func MergePullRequest(ctx *middleware.Context) {
	issue := checkPullInfo(ctx)
	if ctx.Written() {
		return
	}
	if issue.IsClosed {
		ctx.Handle(404, "MergePullRequest", nil)
		return
	}

	pr, err := models.GetPullRequestByIssueID(issue.ID)
	if err != nil {
		if models.IsErrPullRequestNotExist(err) {
			ctx.Handle(404, "GetPullRequestByIssueID", nil)
		} else {
			ctx.Handle(500, "GetPullRequestByIssueID", err)
		}
		return
	}

	if !pr.CanAutoMerge() || pr.HasMerged {
		ctx.Handle(404, "MergePullRequest", nil)
		return
	}

	pr.Issue = issue
	pr.Issue.Repo = ctx.Repo.Repository
	if err = pr.Merge(ctx.User, ctx.Repo.GitRepo); err != nil {
		ctx.Handle(500, "Merge", err)
		return
	}

	log.Trace("Pull request merged: %d", pr.ID)
	ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
}
Esempio n. 25
0
// Int64sToStrings converts a slice of int64 to a slice of string.
func Int64sToStrings(ints []int64) []string {
	strs := make([]string, len(ints))
	for i := range ints {
		strs[i] = com.ToStr(ints[i])
	}
	return strs
}
Esempio n. 26
0
func FormatNumString(num int64) (s string) {
	if num < 1000 {
		return com.ToStr(num)
	}

	for {
		d := num / 1000
		r := num % 1000
		s = "," + com.ToStr(r) + s
		if d == 0 {
			break
		}
		num = d
	}
	return s[1:]
}
Esempio n. 27
0
// create a time limit code
// code format: 12 length date time string + 6 minutes string + 40 sha1 encoded string
func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string {
	format := "200601021504"

	var start, end time.Time
	var startStr, endStr string

	if startInf == nil {
		// Use now time create code
		start = time.Now()
		startStr = start.Format(format)
	} else {
		// use start string create code
		startStr = startInf.(string)
		start, _ = time.ParseInLocation(format, startStr, time.Local)
		startStr = start.Format(format)
	}

	end = start.Add(time.Minute * time.Duration(minutes))
	endStr = end.Format(format)

	// create sha1 encode string
	sh := sha1.New()
	sh.Write([]byte(data + setting.SecretKey + startStr + endStr + com.ToStr(minutes)))
	encoded := hex.EncodeToString(sh.Sum(nil))

	code := fmt.Sprintf("%s%06d%s", startStr, minutes, encoded)
	return code
}
Esempio n. 28
0
// updateRef updates or crates corresponding reference import information.
func updateRef(pid int64, refPath string) (int64, error) {
	if len(refPath) == 0 {
		return 0, nil
	}

	pinfo, err := GetPkgInfo(refPath)
	if err != nil && pinfo == nil {
		if err == ErrPackageNotFound ||
			err == ErrPackageVersionTooOld {
			// Package hasn't existed yet, save to temporary place.
			return 0, updatePkgRef(pid, refPath)
		}
		return 0, fmt.Errorf("GetPkgInfo(%s): %v", refPath, err)
	}

	// Check if reference information has beed recorded.
	queryStr := "$" + com.ToStr(pid) + "|"
	i := strings.Index(pinfo.RefIDs, queryStr)
	if i > -1 {
		return pinfo.ID, nil
	}

	// Add new as needed.
	pinfo.RefIDs += queryStr
	pinfo.RefNum++
	_, err = x.Id(pinfo.ID).AllCols().Update(pinfo)
	return pinfo.ID, err
}
Esempio n. 29
0
func (repo *Repository) CommitsByFileAndRange(branch, file string, page int) (*list.List, error) {
	stdout, stderr, err := com.ExecCmdDirBytes(repo.Path, "git", "log", branch,
		"--skip="+com.ToStr((page-1)*50), "--max-count=50", prettyLogFormat, "--", file)
	if err != nil {
		return nil, errors.New(string(stderr))
	}
	return parsePrettyFormatLog(repo, stdout)
}
Esempio n. 30
0
// GetIssueStats returns issue statistic information by given conditions.
func GetIssueStats(repoID, uid, labelID, milestoneID int64, isShowClosed bool, filterMode int) *IssueStats {
	stats := &IssueStats{}
	issue := new(Issue)

	queryStr := "issue.repo_id=? AND issue.is_closed=?"
	if labelID > 0 {
		queryStr += " AND issue.label_ids like '%$" + com.ToStr(labelID) + "|%'"
	}
	if milestoneID > 0 {
		queryStr += " AND milestone_id=" + com.ToStr(milestoneID)
	}
	switch filterMode {
	case FM_ALL:
		stats.OpenCount, _ = x.Where(queryStr, repoID, false).Count(issue)
		stats.ClosedCount, _ = x.Where(queryStr, repoID, true).Count(issue)
		return stats

	case FM_ASSIGN:
		queryStr += " AND assignee_id=?"
		stats.OpenCount, _ = x.Where(queryStr, repoID, false, uid).Count(issue)
		stats.ClosedCount, _ = x.Where(queryStr, repoID, true, uid).Count(issue)
		return stats

	case FM_CREATE:
		queryStr += " AND poster_id=?"
		stats.OpenCount, _ = x.Where(queryStr, repoID, false, uid).Count(issue)
		stats.ClosedCount, _ = x.Where(queryStr, repoID, true, uid).Count(issue)
		return stats

	case FM_MENTION:
		queryStr += " AND uid=? AND is_mentioned=?"
		if labelID > 0 {
			stats.OpenCount, _ = x.Where(queryStr, repoID, false, uid, true).
				Join("INNER", "issue", "issue.id = issue_id").Count(new(IssueUser))
			stats.ClosedCount, _ = x.Where(queryStr, repoID, true, uid, true).
				Join("INNER", "issue", "issue.id = issue_id").Count(new(IssueUser))
			return stats
		}

		queryStr = strings.Replace(queryStr, "issue.", "", 2)
		stats.OpenCount, _ = x.Where(queryStr, repoID, false, uid, true).Count(new(IssueUser))
		stats.ClosedCount, _ = x.Where(queryStr, repoID, true, uid, true).Count(new(IssueUser))
		return stats
	}
	return stats
}