Exemplo n.º 1
0
Arquivo: repo.go Projeto: j20/gogs
func LoadRepoConfig() {
	workDir, err := base.ExecDir()
	if err != nil {
		qlog.Fatalf("Fail to get work directory: %s\n", err)
	}

	// Load .gitignore and license files.
	types := []string{"gitignore", "license"}
	typeFiles := make([][]string, 2)
	for i, t := range types {
		cfgPath := filepath.Join(workDir, "conf", t)
		files, err := com.StatDir(cfgPath)
		if err != nil {
			qlog.Fatalf("Fail to get default %s files: %v\n", t, err)
		}
		cfgPath = filepath.Join(workDir, "custom/conf/gitignore")
		if com.IsDir(cfgPath) {
			customFiles, err := com.StatDir(cfgPath)
			if err != nil {
				qlog.Fatalf("Fail to get custom %s files: %v\n", t, err)
			}

			for _, f := range customFiles {
				if !com.IsSliceContainsStr(files, f) {
					files = append(files, f)
				}
			}
		}
		typeFiles[i] = files
	}

	LanguageIgns = typeFiles[0]
	Licenses = typeFiles[1]
}
Exemplo n.º 2
0
func SetEngine() (err error) {
	switch DbCfg.Type {
	case "mysql":
		orm, err = xorm.NewEngine("mysql", fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8",
			DbCfg.User, DbCfg.Pwd, DbCfg.Host, DbCfg.Name))
	case "postgres":
		orm, err = xorm.NewEngine("postgres", fmt.Sprintf("user=%s password=%s dbname=%s sslmode=%s",
			DbCfg.User, DbCfg.Pwd, DbCfg.Name, DbCfg.SslMode))
	case "sqlite3":
		os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm)
		orm, err = xorm.NewEngine("sqlite3", DbCfg.Path)
	default:
		return fmt.Errorf("Unknown database type: %s", DbCfg.Type)
	}
	if err != nil {
		return fmt.Errorf("models.init(fail to conntect database): %v", err)
	}

	// WARNNING: for serv command, MUST remove the output to os.stdout,
	// so use log file to instead print to stdout.
	execDir, _ := base.ExecDir()
	logPath := execDir + "/log/xorm.log"
	os.MkdirAll(path.Dir(logPath), os.ModePerm)

	f, err := os.Create(logPath)
	if err != nil {
		return fmt.Errorf("models.init(fail to create xorm.log): %v", err)
	}
	orm.Logger = f

	orm.ShowSQL = true
	orm.ShowDebug = true
	orm.ShowErr = true
	return nil
}
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
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.º 5
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.º 6
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.º 7
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.º 8
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
	}
}