func runCreateUser(c *cli.Context) error { if !c.IsSet("name") { return fmt.Errorf("Username is not specified") } else if !c.IsSet("password") { return fmt.Errorf("Password is not specified") } else if !c.IsSet("email") { return fmt.Errorf("Email is not specified") } if c.IsSet("config") { setting.CustomConf = c.String("config") } setting.NewContext() models.LoadConfigs() models.SetEngine() if err := models.CreateUser(&models.User{ Name: c.String("name"), Email: c.String("email"), Passwd: c.String("password"), IsActive: true, IsAdmin: c.Bool("admin"), }); err != nil { return fmt.Errorf("CreateUser: %v", err) } fmt.Printf("New user '%s' has been successfully created!\n", c.String("name")) return nil }
func setup(logPath string) { setting.NewConfigContext() log.NewGitLogger(filepath.Join(setting.LogRootPath, logPath)) models.LoadModelsConfig() if models.UseSQLite3 { workDir, _ := setting.WorkDir() os.Chdir(workDir) } models.SetEngine() }
func setup(logPath string) { workDir, _ := setting.WorkDir() newLogger(path.Join(workDir, logPath)) setting.NewConfigContext() models.LoadModelsConfig() if models.UseSQLite3 { os.Chdir(workDir) } models.SetEngine() }
func setup(logPath string) { setting.NewContext() log.NewGitLogger(filepath.Join(setting.LogRootPath, logPath)) if setting.DisableSSH { println("Gogs: SSH has been disabled") os.Exit(1) } models.LoadConfigs() if setting.UseSQLite3 || setting.UseTiDB { workDir, _ := setting.WorkDir() os.Chdir(workDir) } models.SetEngine() }
func runDump(ctx *cli.Context) { if ctx.IsSet("config") { setting.CustomConf = ctx.String("config") } setting.NewContext() models.LoadConfigs() models.SetEngine() log.Printf("Dumping local repositories...%s", setting.RepoRootPath) zip.Verbose = ctx.Bool("verbose") defer os.Remove("gogs-repo.zip") if err := zip.PackTo(setting.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) } workDir, _ := setting.WorkDir() z.AddFile("gogs-repo.zip", path.Join(workDir, "gogs-repo.zip")) z.AddFile("gogs-db.sql", path.Join(workDir, "gogs-db.sql")) z.AddDir("custom", path.Join(workDir, "custom")) z.AddDir("log", path.Join(workDir, "log")) // FIXME: SSH key file. if err = z.Close(); err != nil { os.Remove(fileName) log.Fatalf("Fail to save %s: %v", fileName, err) } log.Println("Finish dumping!") }
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!") } }
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!") }
// 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) }
// 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) } }
func runDump(ctx *cli.Context) error { if ctx.IsSet("config") { setting.CustomConf = ctx.String("config") } setting.NewContext() models.LoadConfigs() models.SetEngine() tmpDir := ctx.String("tempdir") if _, err := os.Stat(tmpDir); os.IsNotExist(err) { log.Fatalf("Path does not exist: %s", tmpDir) } TmpWorkDir, err := ioutil.TempDir(tmpDir, "gogs-dump-") if err != nil { log.Fatalf("Fail to create tmp work directory: %v", err) } log.Printf("Creating tmp work dir: %s", TmpWorkDir) reposDump := path.Join(TmpWorkDir, "gogs-repo.zip") dbDump := path.Join(TmpWorkDir, "gogs-db.sql") log.Printf("Dumping local repositories...%s", setting.RepoRootPath) zip.Verbose = ctx.Bool("verbose") if err := zip.PackTo(setting.RepoRootPath, reposDump, true); err != nil { log.Fatalf("Fail to dump local repositories: %v", err) } log.Printf("Dumping database...") if err := models.DumpDatabase(dbDump); 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) } if err := z.AddFile("gogs-repo.zip", reposDump); err != nil { log.Fatalf("Fail to include gogs-repo.zip: %v", err) } if err := z.AddFile("gogs-db.sql", dbDump); err != nil { log.Fatalf("Fail to include gogs-db.sql: %v", err) } customDir, err := os.Stat(setting.CustomPath) if err == nil && customDir.IsDir() { if err := z.AddDir("custom", setting.CustomPath); err != nil { log.Fatalf("Fail to include custom: %v", err) } } else { log.Printf("Custom dir %s doesn't exist, skipped", setting.CustomPath) } if err := z.AddDir("log", setting.LogRootPath); err != nil { log.Fatalf("Fail to include log: %v", err) } // FIXME: SSH key file. if err = z.Close(); err != nil { os.Remove(fileName) log.Fatalf("Fail to save %s: %v", fileName, err) } log.Printf("Removing tmp work dir: %s", TmpWorkDir) os.RemoveAll(TmpWorkDir) log.Printf("Finish dumping in file %s", fileName) return nil }
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 } }
func main() { runAsUser := defaultUser if len(os.Getenv("GOGS_RUN_USER")) > 0 { runAsUser = os.Getenv("GOGS_RUN_USER") } if os.Getenv("GOGS_SERVER__PROTOCOL") == "https" { createCerts() } if _, err := os.Stat(configFile); os.IsNotExist(err) { writeConfigFromEnvVars() } user, err := getUser(runAsUser, nil) if err != nil { log.Fatal(err) } if user == nil { log.Fatalf("Unknown user %s", runAsUser) } os.Chown(configFile, user.Uid, user.Gid) // clear HOME so that SetupUser will set it os.Setenv("HOME", "") err = SetupUser(runAsUser) if err != nil { log.Fatalf("error: failed switching to %q: %v", runAsUser, err) } os.Chdir(filepath.Dir(gogsBinary)) log.Println("Creating admin user: "******"ADMIN_USER_CREATE")) if val, err := strconv.ParseBool(os.Getenv("ADMIN_USER_CREATE")); err == nil && val { setting.CustomConf = "custom/conf/app.ini" routers.GlobalInit() log.Printf("Custom path: %s\n", setting.CustomPath) // Set test engine. var x *xorm.Engine if err := models.NewTestEngine(x); err != nil { log.Fatal("err: ", err) } models.LoadModelsConfig() models.SetEngine() // Create admin account. if err := models.CreateUser(&models.User{ Name: os.Getenv("ADMIN_USER_NAME"), Email: os.Getenv("ADMIN_USER_EMAIL"), Passwd: os.Getenv("ADMIN_USER_PASSWORD"), IsAdmin: true, IsActive: true, }); err != nil { if err != models.ErrUserAlreadyExist { log.Fatalf("error: %v", err) } else { log.Println("Admin account already exist") } } else { log.Println("Admin account created: ", os.Getenv("ADMIN_USER_NAME")) } } name, err := exec.LookPath(gogsBinary) if err != nil { log.Fatalf("error: %v", err) } err = syscall.Exec(name, []string{name, "web"}, os.Environ()) if err != nil { log.Fatalf("error: exec failed: %v", err) } }