Exemplo n.º 1
0
// globalInit is for global configuration reload-able.
func globalInit() {
	base.NewConfigContext()
	mailer.NewMailerContext()
	models.LoadModelsConfig()
	models.LoadRepoConfig()
	models.NewRepoContext()
	models.NewEngine()
}
Exemplo n.º 2
0
// GlobalInit is for global configuration reload-able.
func GlobalInit() {
	base.NewConfigContext()
	mailer.NewMailerContext()
	models.LoadModelsConfig()
	models.LoadRepoConfig()
	models.NewRepoContext()

	if base.InstallLock {
		if err := models.NewEngine(); err != nil {
			fmt.Println("%v", err)
			os.Exit(2)
		}

		models.HasEngine = true
	}
	base.NewServices()
	checkRunMode()
}
Exemplo n.º 3
0
func runFix(k *cli.Context) {
	execDir, _ := base.ExecDir()
	newLogger(execDir)

	base.NewConfigContext()
	models.LoadModelsConfig()

	if models.UseSQLite3 {
		os.Chdir(execDir)
	}

	models.SetEngine()

	err := models.Fix()
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println("Fix successfully!")
	}
}
Exemplo n.º 4
0
// GlobalInit is for global configuration reload-able.
func GlobalInit() {
	base.NewConfigContext()
	mailer.NewMailerContext()
	models.LoadModelsConfig()
	models.LoadRepoConfig()
	models.NewRepoContext()
	NewServices()

	if base.InstallLock {
		if err := models.NewEngine(); err != nil {
			qlog.Fatal(err)
		}

		models.HasEngine = true
		if models.EnableSQLite3 {
			log.Info("SQLite3 Enabled")
		}
		cron.NewCronContext()
	}
	checkRunMode()
}
Exemplo n.º 5
0
Arquivo: dump.go Projeto: numo16/gogs
func runDump(*cli.Context) {
	base.NewConfigContext()
	models.LoadModelsConfig()
	models.SetEngine()

	log.Printf("Dumping local repositories...%s", base.RepoRootPath)
	zip.Verbose = false
	defer os.Remove("gogs-repo.zip")
	if err := zip.PackTo(base.RepoRootPath, "gogs-repo.zip", true); err != nil {
		log.Fatalf("Fail to dump local repositories: %v", err)
	}

	log.Printf("Dumping database...")
	defer os.Remove("gogs-db.sql")
	if err := models.DumpDatabase("gogs-db.sql"); err != nil {
		log.Fatalf("Fail to dump database: %v", err)
	}

	fileName := fmt.Sprintf("gogs-dump-%d.zip", time.Now().Unix())
	log.Printf("Packing dump files...")
	z, err := zip.Create(fileName)
	if err != nil {
		os.Remove(fileName)
		log.Fatalf("Fail to create %s: %v", fileName, err)
	}

	execDir, _ := base.ExecDir()
	z.AddFile("gogs-repo.zip", path.Join(execDir, "gogs-repo.zip"))
	z.AddFile("gogs-db.sql", path.Join(execDir, "gogs-db.sql"))
	z.AddFile("custom/conf/app.ini", path.Join(execDir, "custom/conf/app.ini"))
	z.AddDir("log", path.Join(execDir, "log"))
	if err = z.Close(); err != nil {
		os.Remove(fileName)
		log.Fatalf("Fail to save %s: %v", fileName, err)
	}

	log.Println("Finish dumping!")
}
Exemplo n.º 6
0
// for command: ./gogs update
func runUpdate(c *cli.Context) {
	cmd := os.Getenv("SSH_ORIGINAL_COMMAND")
	if cmd == "" {
		return
	}

	execDir, _ := base.ExecDir()
	newUpdateLogger(execDir)

	base.NewConfigContext()
	models.LoadModelsConfig()

	if models.UseSQLite3 {
		os.Chdir(execDir)
	}

	models.SetEngine()

	args := c.Args()
	if len(args) != 3 {
		qlog.Fatal("received less 3 parameters")
	}

	if args[0] == "" {
		qlog.Fatal("refName is empty, shouldn't use")
	}

	//updateEnv(args[0], args[1], args[2])

	userName := os.Getenv("userName")
	userId, _ := strconv.ParseInt(os.Getenv("userId"), 10, 64)
	//repoId := os.Getenv("repoId")
	repoUserName := os.Getenv("repoUserName")
	repoName := os.Getenv("repoName")

	models.Update(args[0], args[1], args[2], userName, repoUserName, repoName, userId)
}
Exemplo n.º 7
0
func runDump(*cli.Context) {
	base.NewConfigContext()

	log.Printf("Dumping local repositories...%s", base.RepoRootPath)
	zip.Verbose = false
	defer os.Remove("gogs-repo.zip")
	if err := zip.PackTo(base.RepoRootPath, "gogs-repo.zip", true); err != nil {
		log.Fatalf("Fail to dump local repositories: %v", err)
	}

	z, err := zip.Create("gogs-dump.zip")
	if err != nil {
		os.Remove("gogs-dump.zip")
		log.Fatalf("Fail to create gogs-dump.zip: %v", err)
	}

	execDir, _ := base.ExecDir()
	z.AddFile("gogs-repo.zip", path.Join(execDir, "gogs-repo.zip"))
	z.AddFile("custom/conf/app.ini", path.Join(execDir, "custom/conf/app.ini"))
	z.AddDir("log", path.Join(execDir, "log"))
	z.Close()

	log.Println("Finish dumping!")
}
Exemplo n.º 8
0
// for command: ./gogs update
func runUpdate(c *cli.Context) {
	execDir, _ := base.ExecDir()
	newLogger(execDir)

	base.NewConfigContext()
	models.LoadModelsConfig()

	if models.UseSQLite3 {
		os.Chdir(execDir)
	}

	models.SetEngine()

	args := c.Args()
	if len(args) != 3 {
		log.Error("received less 3 parameters")
		return
	}

	refName := args[0]
	if refName == "" {
		log.Error("refName is empty, shouldn't use")
		return
	}
	oldCommitId := args[1]
	newCommitId := args[2]

	isNew := strings.HasPrefix(oldCommitId, "0000000")
	if isNew &&
		strings.HasPrefix(newCommitId, "0000000") {
		log.Error("old rev and new rev both 000000")
		return
	}

	userName := os.Getenv("userName")
	userId := os.Getenv("userId")
	//repoId := os.Getenv("repoId")
	repoName := os.Getenv("repoName")

	f := models.RepoPath(userName, repoName)

	gitUpdate := exec.Command("git", "update-server-info")
	gitUpdate.Dir = f
	gitUpdate.Run()

	repo, err := git.OpenRepository(f)
	if err != nil {
		log.Error("runUpdate.Open repoId: %v", err)
		return
	}

	newOid, err := git.NewOidFromString(newCommitId)
	if err != nil {
		log.Error("runUpdate.Ref repoId: %v", err)
		return
	}

	newCommit, err := repo.LookupCommit(newOid)
	if err != nil {
		log.Error("runUpdate.Ref repoId: %v", err)
		return
	}

	var l *list.List
	// if a new branch
	if isNew {
		l, err = repo.CommitsBefore(newCommit.Id())
		if err != nil {
			log.Error("Find CommitsBefore erro:", err)
			return
		}
	} else {
		oldOid, err := git.NewOidFromString(oldCommitId)
		if err != nil {
			log.Error("runUpdate.Ref repoId: %v", err)
			return
		}

		oldCommit, err := repo.LookupCommit(oldOid)
		if err != nil {
			log.Error("runUpdate.Ref repoId: %v", err)
			return
		}
		l = repo.CommitsBetween(newCommit, oldCommit)
	}

	if err != nil {
		log.Error("runUpdate.Commit repoId: %v", err)
		return
	}

	sUserId, err := strconv.Atoi(userId)
	if err != nil {
		log.Error("runUpdate.Parse userId: %v", err)
		return
	}

	repos, err := models.GetRepositoryByName(int64(sUserId), repoName)
	if err != nil {
		log.Error("runUpdate.GetRepositoryByName userId: %v", err)
		return
	}

	commits := make([]*base.PushCommit, 0)
	var maxCommits = 3
	var actEmail string
	for e := l.Front(); e != nil; e = e.Next() {
		commit := e.Value.(*git.Commit)
		if actEmail == "" {
			actEmail = commit.Committer.Email
		}
		commits = append(commits,
			&base.PushCommit{commit.Id().String(),
				commit.Message(),
				commit.Author.Email,
				commit.Author.Name})
		if len(commits) >= maxCommits {
			break
		}
	}

	//commits = append(commits, []string{lastCommit.Id().String(), lastCommit.Message()})
	if err = models.CommitRepoAction(int64(sUserId), userName, actEmail,
		repos.Id, repoName, git.BranchName(refName), &base.PushCommits{l.Len(), commits}); err != nil {
		log.Error("runUpdate.models.CommitRepoAction: %v", err)
	}
}
Exemplo n.º 9
0
func runServ(k *cli.Context) {
	execDir, _ := base.ExecDir()
	newLogger(execDir)

	base.NewConfigContext()
	models.LoadModelsConfig()

	if models.UseSQLite3 {
		os.Chdir(execDir)
	}

	models.SetEngine()

	keys := strings.Split(os.Args[2], "-")
	if len(keys) != 2 {
		println("auth file format error")
		log.Error("auth file format error")
		return
	}

	keyId, err := strconv.ParseInt(keys[1], 10, 64)
	if err != nil {
		println("auth file format error")
		log.Error("auth file format error", err)
		return
	}
	user, err := models.GetUserByKeyId(keyId)
	if err != nil {
		println("You have no right to access")
		log.Error("SSH visit error: %v", err)
		return
	}

	cmd := os.Getenv("SSH_ORIGINAL_COMMAND")
	if cmd == "" {
		println("Hi", user.Name, "! You've successfully authenticated, but Gogs does not provide shell access.")
		return
	}

	verb, args := parseCmd(cmd)
	repoPath := strings.Trim(args, "'")
	rr := strings.SplitN(repoPath, "/", 2)
	if len(rr) != 2 {
		println("Unavilable repository", args)
		log.Error("Unavilable repository %v", args)
		return
	}
	repoUserName := rr[0]
	repoName := rr[1]
	if strings.HasSuffix(repoName, ".git") {
		repoName = repoName[:len(repoName)-4]
	}

	isWrite := In(verb, COMMANDS_WRITE)
	isRead := In(verb, COMMANDS_READONLY)

	repoUser, err := models.GetUserByName(repoUserName)
	if err != nil {
		fmt.Println("You have no right to access")
		log.Error("Get user failed", err)
		return
	}

	// access check
	switch {
	case isWrite:
		has, err := models.HasAccess(user.LowerName, path.Join(repoUserName, repoName), models.AU_WRITABLE)
		if err != nil {
			println("Inernel error:", err)
			log.Error(err.Error())
			return
		} else if !has {
			println("You have no right to write this repository")
			log.Error("User %s has no right to write repository %s", user.Name, repoPath)
			return
		}
	case isRead:
		repo, err := models.GetRepositoryByName(repoUser.Id, repoName)
		if err != nil {
			println("Get repository error:", err)
			log.Error("Get repository error: " + err.Error())
			return
		}

		if !repo.IsPrivate {
			break
		}

		has, err := models.HasAccess(user.Name, repoPath, models.AU_READABLE)
		if err != nil {
			println("Inernel error")
			log.Error(err.Error())
			return
		}
		if !has {
			has, err = models.HasAccess(user.Name, repoPath, models.AU_WRITABLE)
			if err != nil {
				println("Inernel error")
				log.Error(err.Error())
				return
			}
		}
		if !has {
			println("You have no right to access this repository")
			log.Error("You have no right to access this repository")
			return
		}
	default:
		println("Unknown command")
		log.Error("Unknown command")
		return
	}

	// for update use
	os.Setenv("userName", user.Name)
	os.Setenv("userId", strconv.Itoa(int(user.Id)))
	os.Setenv("repoName", repoName)

	gitcmd := exec.Command(verb, repoPath)
	gitcmd.Dir = base.RepoRootPath
	gitcmd.Stdout = os.Stdout
	gitcmd.Stdin = os.Stdin
	gitcmd.Stderr = os.Stderr

	if err = gitcmd.Run(); err != nil {
		println("execute command error:", err.Error())
		log.Error("execute command error: " + err.Error())
		return
	}
}
Exemplo n.º 10
0
func runServ(k *cli.Context) {
	base.NewConfigContext()
	models.LoadModelsConfig()
	models.NewEngine()

	keys := strings.Split(os.Args[2], "-")
	if len(keys) != 2 {
		fmt.Println("auth file format error")
		return
	}

	keyId, err := strconv.ParseInt(keys[1], 10, 64)
	if err != nil {
		fmt.Println("auth file format error")
		return
	}
	user, err := models.GetUserByKeyId(keyId)
	if err != nil {
		fmt.Println("You have no right to access")
		return
	}

	cmd := os.Getenv("SSH_ORIGINAL_COMMAND")
	if cmd == "" {
		println("Hi", user.Name, "! You've successfully authenticated, but Gogs does not provide shell access.")
		return
	}

	verb, args := parseCmd(cmd)
	rRepo := strings.Trim(args, "'")
	rr := strings.SplitN(rRepo, "/", 2)
	if len(rr) != 2 {
		println("Unavilable repository", args)
		return
	}
	repoName := rr[1]
	if strings.HasSuffix(repoName, ".git") {
		repoName = repoName[:len(repoName)-4]
	}

	repo, err := models.GetRepositoryByName(user.Id, repoName)
	var isExist bool = true
	if err != nil {
		if err == models.ErrRepoNotExist {
			isExist = false
		} else {
			println("Unavilable repository", err)
			return
		}
	}

	isWrite := In(verb, COMMANDS_WRITE)
	isRead := In(verb, COMMANDS_READONLY)

	switch {
	case isWrite:
		has, err := models.HasAccess(user.Name, repoName, models.AU_WRITABLE)
		if err != nil {
			println("Inernel error:", err)
			return
		}
		if !has {
			println("You have no right to write this repository")
			return
		}
	case isRead:
		has, err := models.HasAccess(user.Name, repoName, models.AU_READABLE)
		if err != nil {
			println("Inernel error")
			return
		}
		if !has {
			has, err = models.HasAccess(user.Name, repoName, models.AU_WRITABLE)
			if err != nil {
				println("Inernel error")
				return
			}
		}
		if !has {
			println("You have no right to access this repository")
			return
		}
	default:
		println("Unknown command")
		return
	}

	if !isExist {
		if isRead {
			println("Repository", user.Name+"/"+repoName, "is not exist")
			return
		} else if isWrite {
			_, err := models.CreateRepository(user, repoName, "", "", "", false, true)
			if err != nil {
				println("Create repository failed")
				return
			}
		}
	}

	rep, err := git.OpenRepository(models.RepoPath(user.Name, repoName))
	if err != nil {
		println(err.Error())
		return
	}

	refs, err := rep.AllReferencesMap()
	if err != nil {
		println(err.Error())
		return
	}

	gitcmd := exec.Command(verb, rRepo)
	gitcmd.Dir = base.RepoRootPath

	var s string
	b := bytes.NewBufferString(s)

	gitcmd.Stdout = io.MultiWriter(os.Stdout, b)
	//gitcmd.Stdin = io.MultiReader(os.Stdin, b)
	gitcmd.Stdin = os.Stdin
	gitcmd.Stderr = os.Stderr

	if err = gitcmd.Run(); err != nil {
		println("execute command error:", err.Error())
	}

	if !strings.HasPrefix(cmd, "git-receive-pack") {
		return
	}

	// update
	//w, _ := os.Create("serve.log")
	//defer w.Close()
	//log.SetOutput(w)

	var t = "ok refs/heads/"
	var i int
	var refname string
	for {
		l, err := b.ReadString('\n')
		if err != nil {
			break
		}
		i = i + 1
		l = l[:len(l)-1]
		idx := strings.Index(l, t)
		if idx > 0 {
			refname = l[idx+len(t):]
		}
	}
	var ref *git.Reference
	var ok bool

	var l *list.List
	//log.Info("----", refname, "-----")
	if ref, ok = refs[refname]; !ok {
		refs, err = rep.AllReferencesMap()
		if err != nil {
			println(err.Error())
			return
		}
		if ref, ok = refs[refname]; !ok {
			println("unknow reference name -", refname, "-")
			return
		}
		l, err = ref.AllCommits()
		if err != nil {
			println(err.Error())
			return
		}
	} else {
		//log.Info("----", ref, "-----")
		var last *git.Commit
		//log.Info("00000", ref.Oid.String())
		last, err = ref.LastCommit()
		if err != nil {
			println(err.Error())
			return
		}

		ref2, err := rep.LookupReference(ref.Name)
		if err != nil {
			println(err.Error())
			return
		}

		//log.Info("11111", ref2.Oid.String())
		before, err := ref2.LastCommit()
		if err != nil {
			println(err.Error())
			return
		}
		//log.Info("----", before.Id(), "-----", last.Id())
		l = ref.CommitsBetween(before, last)
	}

	commits := make([][]string, 0)
	var maxCommits = 3
	for e := l.Front(); e != nil; e = e.Next() {
		commit := e.Value.(*git.Commit)
		commits = append(commits, []string{commit.Id().String(), commit.Message()})
		if len(commits) >= maxCommits {
			break
		}
	}

	if err = models.CommitRepoAction(user.Id, user.Name,
		repo.Id, repoName, refname, &base.PushCommits{l.Len(), commits}); err != nil {
		log.Error("runUpdate.models.CommitRepoAction: %v", err, commits)
	} else {
		//log.Info("refname", refname)
		//log.Info("Listen: %v", cmd)
		//fmt.Println("...", cmd)

		//runUpdate(k)
		c := exec.Command("git", "update-server-info")
		c.Dir = models.RepoPath(user.Name, repoName)
		err := c.Run()
		if err != nil {
			log.Error("update-server-info: %v", err)
		}
	}
}