Exemplo n.º 1
0
Arquivo: user.go Projeto: 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
}
Exemplo n.º 2
0
Arquivo: init.go Projeto: 52M/peach
func runNew(ctx *cli.Context) {
	target := ctx.String("target")
	if com.IsExist(target) && !ctx.Bool("yes") {
		fmt.Printf(toYellow("Directory '%s' already exists, do you want to overwrite?[Y/n] "), target)
		if !checkYesNo() {
			os.Exit(0)
		}
	}

	fmt.Printf("➜  Creating '%s'...\n", target)
	os.MkdirAll(target, os.ModePerm)

	// Create default files.
	dirs := []string{"templates", "public"}
	for _, dir := range dirs {
		fmt.Printf("➜  Creating '%s'...\n", dir)
		os.RemoveAll(filepath.Join(target, dir))
		restoreAssets(target, dir)
	}

	// Create custom templates.
	yes := ctx.Bool("yes")
	if !yes {
		fmt.Printf(toYellow("Do you want to use custom templates?[Y/n] "))
		yes = checkYesNo()
	}

	if yes {
		fmt.Println("➜  Creating 'custom/templates'...")
		restoreAssets(filepath.Join(target, "custom"), "templates")

		// Update configuration to use custom templates.
		fmt.Println("➜  Updating custom configuration...")
		var cfg *ini.File
		var err error
		customPath := filepath.Join(target, "custom/app.ini")
		if com.IsExist(customPath) {
			cfg, err = ini.Load(customPath)
			if err != nil {
				fmt.Printf(toRed("✗  %v\n"), err)
				os.Exit(1)
			}
		} else {
			cfg = ini.Empty()
		}

		cfg.Section("page").Key("USE_CUSTOM_TPL").SetValue("true")
		if err = cfg.SaveTo(customPath); err != nil {
			fmt.Printf(toRed("✗  %v\n"), err)
			os.Exit(1)
		}
	}

	fmt.Println(toGreen("✓  Done!"))
}
Exemplo n.º 3
0
func getVcsName(dirPath string) string {
	switch {
	case com.IsExist(path.Join(dirPath, ".git")):
		return "git"
	case com.IsExist(path.Join(dirPath, ".hg")):
		return "hg"
	case com.IsExist(path.Join(dirPath, ".svn")):
		return "svn"
	}
	return ""
}
Exemplo n.º 4
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
}
Exemplo n.º 5
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})
		}
	}
}
Exemplo n.º 6
0
Arquivo: repo.go Projeto: jcfrank/gogs
func NewRepoContext() {
	zip.Verbose = false

	// Check if server has basic git setting.
	stdout, stderr, err := com.ExecCmd("git", "config", "--get", "user.name")
	if strings.Contains(stderr, "fatal:") {
		log.Fatal("repo.NewRepoContext(fail to get git user.name): %s", stderr)
	} else if err != nil || len(strings.TrimSpace(stdout)) == 0 {
		if _, stderr, err = com.ExecCmd("git", "config", "--global", "user.email", "*****@*****.**"); err != nil {
			log.Fatal("repo.NewRepoContext(fail to set git user.email): %s", stderr)
		} else if _, stderr, err = com.ExecCmd("git", "config", "--global", "user.name", "Gogs"); err != nil {
			log.Fatal("repo.NewRepoContext(fail to set git user.name): %s", stderr)
		}
	}

	barePath := path.Join(setting.RepoRootPath, "git-bare.zip")
	if !com.IsExist(barePath) {
		data, err := bin.Asset("conf/content/git-bare.zip")
		if err != nil {
			log.Fatal("Fail to get asset 'git-bare.zip': %v", err)
		} else if err := ioutil.WriteFile(barePath, data, os.ModePerm); err != nil {
			log.Fatal("Fail to write asset 'git-bare.zip': %v", err)
		}
	}
}
Exemplo n.º 7
0
func ExampleIsExist() {
	if com.IsExist("file.go") {
		fmt.Println("file.go exists")
		return
	}
	fmt.Println("file.go does not exist")
}
Exemplo n.º 8
0
func (p *FileProvider) regenerate(oldsid, sid string) (err error) {
	p.lock.Lock()
	defer p.lock.Unlock()

	filename := p.filepath(sid)
	if com.IsExist(filename) {
		return fmt.Errorf("new sid '%s' already exists", sid)
	}

	oldname := p.filepath(oldsid)
	if !com.IsFile(oldname) {
		data, err := EncodeGob(make(map[interface{}]interface{}))
		if err != nil {
			return err
		}
		if err = os.MkdirAll(path.Dir(oldname), os.ModePerm); err != nil {
			return err
		}
		if err = ioutil.WriteFile(oldname, data, os.ModePerm); err != nil {
			return err
		}
	}

	if err = os.MkdirAll(path.Dir(filename), os.ModePerm); err != nil {
		return err
	}
	if err = os.Rename(oldname, filename); err != nil {
		return err
	}
	return nil
}
Exemplo n.º 9
0
func init() {
	hd, err := com.HomeDir()
	if err != nil {
		log.Error("", "Fail to get current user")
		log.Fatal("", err.Error())
	}

	HomeDir = strings.Replace(RawHomeDir, "~", hd, -1)

	cfgPath := path.Join(HomeDir, GOPM_CONFIG_FILE)
	if !com.IsExist(cfgPath) {
		os.MkdirAll(path.Dir(cfgPath), os.ModePerm)
		if _, err = os.Create(cfgPath); err != nil {
			log.Error("", "Fail to create gopm config file")
			log.Fatal("", err.Error())
		}
	}
	Cfg, err = goconfig.LoadConfigFile(cfgPath)
	if err != nil {
		log.Error("", "Fail to load gopm config file")
		log.Fatal("", err.Error())
	}

	LoadLocalNodes()
	LoadPkgNameList(path.Join(HomeDir, PKG_NAME_LIST_PATH))
}
Exemplo n.º 10
0
// LoadConfig loads configuration file.
func LoadConfig(cfgPath string) {
	if !com.IsExist(cfgPath) {
		os.Create(cfgPath)
	}

	var err error
	Cfg, err = goconfig.LoadConfigFile(cfgPath)
	if err != nil {
		log.Fatalf("Fail to load configuration file: %v", err)
	}
	if com.IsFile("custom/app.ini") {
		if err = Cfg.AppendFiles("custom/app.ini"); err != nil {
			log.Fatalf("Fail to load custom configuration file: %v", err)
		}
	}

	DocsJsPath, err = Cfg.GetValue("server", "docs_js_path")
	if err != nil {
		log.Fatalln("Fail to load configuration file: cannot find key docs_js_path")
	}

	HvJsPath, err = Cfg.GetValue("server", "hv_js_path")
	if err != nil {
		log.Fatalln("Fail to load configuration file: cannot find key hv_js_path")
	}
}
Exemplo n.º 11
0
// LoadConfig loads configuration file.
func LoadConfig(cfgPath string) (*goconfig.ConfigFile, error) {
	if !com.IsExist(cfgPath) {
		os.Create(cfgPath)
	}

	return goconfig.LoadConfigFile(cfgPath)
}
Exemplo n.º 12
0
// CheckIsExistWithVCS returns false if directory only has VCS folder,
// or doesn't exist.
func CheckIsExistWithVCS(path string) bool {
	// Check if directory exist.
	if !com.IsExist(path) {
		return false
	}

	// Check if only has VCS folder.
	dirs, err := GetDirsInfo(path)
	if err != nil {
		log.Error("", "Fail to get directory's information")
		log.Fatal("", err.Error())
	}

	if len(dirs) > 1 {
		return true
	} else if len(dirs) == 0 {
		return false
	}

	switch dirs[0].Name() {
	case ".git", ".hg", ".svn":
		return false
	}

	return true
}
Exemplo n.º 13
0
Arquivo: init.go Projeto: zzhua/bra
func runInit(ctx *cli.Context) {
	if com.IsExist(".bra.toml") {
		fmt.Print("There is a .bra.toml in the work directory, do you want to overwrite?(y/n): ")
		var answer string
		fmt.Scan(&answer)
		if strings.ToLower(answer) != "y" {
			fmt.Println("Existed file is untouched.")
			return
		}
	}

	wd, err := os.Getwd()
	if err != nil {
		log.Fatal("Fail to get work directory: %v", err)
	}

	data, err := bindata.Asset("templates/default.bra.toml")
	if err != nil {
		log.Fatal("Fail to get asset: %v", err)
	}

	appName := filepath.Base(wd)
	if runtime.GOOS == "windows" {
		appName += ".exe"
	}

	data = bytes.Replace(data, []byte("$APP_NAME"), []byte(appName), -1)
	if err := ioutil.WriteFile(".bra.toml", data, os.ModePerm); err != nil {
		log.Fatal("Fail to generate default .bra.toml: %v", err)
	}
}
Exemplo n.º 14
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)
}
Exemplo n.º 15
0
Arquivo: gen.go Projeto: nashtsai/gopm
// scan a directory and gen a gopm file
func runGen(ctx *cli.Context) {
	setup(ctx)

	if !com.IsExist(".gopmfile") {
		os.Create(".gopmfile")
	}

	gf, err := goconfig.LoadConfigFile(".gopmfile")
	if err != nil {
		log.Error("gen", "Cannot load gopmfile:")
		log.Fatal("", "\t"+err.Error())
	}

	// Get dependencies.
	imports := doc.GetAllImports([]string{workDir},
		parseTarget(gf.MustValue("target", "path")), ctx.Bool("example"))

	for _, p := range imports {
		p = doc.GetProjectPath(p)
		if strings.HasSuffix(workDir, p) {
			continue
		}
		if value := gf.MustValue("deps", p); len(value) == 0 {
			gf.SetValue("deps", p, "")
		}
	}

	err = goconfig.SaveConfigFile(gf, ".gopmfile")
	if err != nil {
		log.Error("gen", "Fail to save gopmfile:")
		log.Fatal("", "\t"+err.Error())
	}

	log.Success("SUCC", "gen", "Generate gopmfile successfully!")
}
Exemplo n.º 16
0
// RewriteAllPublicKeys removes any authorized key and rewrite all keys from database again.
func RewriteAllPublicKeys() error {
	sshOpLocker.Lock()
	defer sshOpLocker.Unlock()

	tmpPath := filepath.Join(setting.SSHRootPath, "authorized_keys.tmp")
	f, err := os.OpenFile(tmpPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
	if err != nil {
		return err
	}
	defer os.Remove(tmpPath)

	err = x.Iterate(new(PublicKey), func(idx int, bean interface{}) (err error) {
		_, err = f.WriteString((bean.(*PublicKey)).GetAuthorizedString())
		return err
	})
	f.Close()
	if err != nil {
		return err
	}

	fpath := filepath.Join(setting.SSHRootPath, "authorized_keys")
	if com.IsExist(fpath) {
		if err = os.Remove(fpath); err != nil {
			return err
		}
	}
	if err = os.Rename(tmpPath, fpath); err != nil {
		return err
	}

	return nil
}
Exemplo n.º 17
0
Arquivo: gen.go Projeto: puma007/gopm
func runGen(ctx *cli.Context) {
	setup(ctx)

	if !com.IsExist(".gopmfile") {
		os.Create(".gopmfile")
	}

	gf, err := goconfig.LoadConfigFile(".gopmfile")
	if err != nil {
		log.Error("gen", "Cannot load gopmfile:")
		log.Fatal("", "\t"+err.Error())
	}

	targetPath := parseTarget(gf.MustValue("target", "path"))
	// Get and set dependencies.
	imports := doc.GetAllImports([]string{workDir}, targetPath, ctx.Bool("example"), false)
	for _, p := range imports {
		p = doc.GetProjectPath(p)
		// Skip subpackage(s) of current project.
		if isSubpackage(p, targetPath) {
			continue
		}

		// Check if user specified the version.
		if value := gf.MustValue("deps", p); len(value) == 0 {
			gf.SetValue("deps", p, "")
		}
	}

	// Get and set resources.
	res := make([]string, 0, len(commonRes))
	for _, cr := range commonRes {
		if com.IsExist(cr) {
			res = append(res, cr)
		}
	}
	gf.SetValue("res", "include", strings.Join(res, "|"))

	err = goconfig.SaveConfigFile(gf, ".gopmfile")
	if err != nil {
		log.Error("gen", "Fail to save gopmfile:")
		log.Fatal("", "\t"+err.Error())
	}

	log.Success("SUCC", "gen", "Generate gopmfile successfully!")
}
Exemplo n.º 18
0
// Update updates hook settings.
func (h *Hook) Update() error {
	if len(strings.TrimSpace(h.Content)) == 0 {
		if com.IsExist(h.path) {
			return os.Remove(h.path)
		}
		return nil
	}
	return ioutil.WriteFile(h.path, []byte(strings.Replace(h.Content, "\r", "", -1)), os.ModePerm)
}
Exemplo n.º 19
0
func RegisterDB() {
	if !com.IsExist(_DB_NAME) {
		os.MkdirAll(path.Dir(_DB_NAME), os.ModePerm)
		os.Create(_DB_NAME)
	}
	orm.RegisterModel(new(Todo))
	orm.RegisterDriver(_SQLITE3_DRIVER, orm.DR_Sqlite)
	orm.RegisterDataBase("default", _SQLITE3_DRIVER, _DB_NAME, 10)
}
Exemplo n.º 20
0
func RegisterDB() {
	if !com.IsExist(_DB_NAME) {
		os.Mkdir(path.Dir(_DB_NAME), os.ModePerm)
		os.Create(_DB_NAME)
	}
	orm.RegisterModel(new(Category), new(User), new(Companyinfo), new(Inquery), new(Product), new(Feedback), new(Log))
	//orm.RegisterDriver(_SQLITE3_DRIVE, orm.DR_Sqlite)
	orm.RegisterDataBase("default", _SQLITE3_DRIVE, _DB_NAME, 10)
}
Exemplo n.º 21
0
func (u *User) RelAvatarLink() string {
	defaultImgUrl := "/img/avatar_default.jpg"
	if u.Id == -1 {
		return defaultImgUrl
	}

	imgPath := path.Join(setting.AvatarUploadPath, com.ToStr(u.Id))
	switch {
	case u.UseCustomAvatar:
		if !com.IsExist(imgPath) {
			return defaultImgUrl
		}
		return "/avatars/" + com.ToStr(u.Id)
	case setting.DisableGravatar, setting.OfflineMode:
		if !com.IsExist(imgPath) {
			img, err := avatar.RandomImage([]byte(u.Email))
			if err != nil {
				log.Error(3, "RandomImage: %v", err)
				return defaultImgUrl
			}
			if err = os.MkdirAll(path.Dir(imgPath), os.ModePerm); err != nil {
				log.Error(3, "MkdirAll: %v", err)
				return defaultImgUrl
			}
			fw, err := os.Create(imgPath)
			if err != nil {
				log.Error(3, "Create: %v", err)
				return defaultImgUrl
			}
			defer fw.Close()

			if err = jpeg.Encode(fw, img, nil); err != nil {
				log.Error(3, "Encode: %v", err)
				return defaultImgUrl
			}
			log.Info("New random avatar created: %d", u.Id)
		}

		return "/avatars/" + com.ToStr(u.Id)
	case setting.Service.EnableCacheAvatar:
		return "/avatar/" + u.Avatar
	}
	return setting.GravatarSource + u.Avatar
}
Exemplo n.º 22
0
func RegisterDB() {
	if !com.IsExist(_DB_NAME) {
		os.MkdirAll(path.Dir(_DB_NAME), os.ModePerm)
		os.Create(_DB_NAME)
	}
	orm.RegisterModel(new(User), new(Category), new(Topic), new(Photoalbum), new(Photograph))
	orm.RegisterDriver(_MYSQL_DRIVER, orm.DRMySQL)
	orm.RegisterDataBase("default", _MYSQL_DRIVER, "root:Aa1234@/Jayblog?charset=utf8", 20, 20)

}
Exemplo n.º 23
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
}
Exemplo n.º 24
0
Arquivo: doc.go Projeto: 52M/peach
func NewContext() {
	if com.IsExist(HTMLRoot) {
		if err := os.RemoveAll(HTMLRoot); err != nil {
			log.Fatal("Fail to clean up HTMLRoot: %v", err)
		}
	}

	if err := ReloadDocs(); err != nil {
		log.Fatal("Fail to init docs: %v", err)
	}
}
Exemplo n.º 25
0
func RegisterDB() {
	//由主进程去调用,告诉orm进行一个创建,注册模型,注册驱动,注册数据库了
	if !com.IsExist(_DB_NAME) {
		os.MkdirAll(path.Dir(_DB_NAME), os.ModePerm)
		os.Create(_DB_NAME)
	}
	//orm 需要先注册模型,什么是模型呢,就是刚才的两个结构体
	orm.RegisterModel(new(Character), new(AllPeopleTags), new(AllMovieTags), new(AllMusicTags), new(DevAppKey)) //传进去一个指针
	orm.RegisterDriver(_SQLITE3_DRIVER, orm.DRSqlite)
	orm.RegisterDataBase("default", _SQLITE3_DRIVER, _DB_NAME, 10)
	orm.RunSyncdb("default", false, true) //自动建表的功能,第一个flase表示不需要每次都重新建表,第二个true表示显示debug信息
}
Exemplo n.º 26
0
func RegisterDB() {
	if !com.IsExist(_DB_NAME) {
		os.MkdirAll(path.Dir(_DB_NAME), os.ModePerm)
		os.Create(_DB_NAME)
	}
	//注册模型
	orm.RegisterModel(new(Category), new(Topic))
	//注册驱动
	orm.RegisterDriver(_SQLITE3_DRIVER, orm.DRSqlite)
	orm.RegisterDataBase("default", _SQLITE3_DRIVER, _DB_NAME, 10)

}
Exemplo n.º 27
0
func RegisterDB() {
	if !com.IsExist(_DB_NAME) {
		os.MkdirAll(path.Dir(_DB_NAME), os.ModePerm)
		os.Create(_DB_NAME)
	}

	orm.RegisterModel(new(Emotion), new(Series), new(Tag))
	orm.RegisterDriver((_SQLITE3_DRIVER), orm.DR_Sqlite)
	//必须要有注册为default的数据库
	//最大连接数10
	orm.RegisterDataBase("default", _SQLITE3_DRIVER, _DB_NAME, 10)
}
Exemplo n.º 28
0
func RegisterDB() {
	if !com.IsExist(_DB_NAME) {
		// create directory
		os.MkdirAll(path.Dir(_DB_NAME), os.ModePerm)
		// create file
		os.Create(_DB_NAME)
	}
	orm.RegisterModel(new(Category), new(Topic), new(Comment), new(Tag))
	// this one can be omitted
	orm.RegisterDriver(_SQLITE3_DRIVER, orm.DR_Sqlite)
	orm.RegisterDataBase("default", _SQLITE3_DRIVER, _DB_NAME, 10)
}
Exemplo n.º 29
0
// InitRepository initializes README and .gitignore if needed.
func initRepository(e Engine, repoPath string, u *User, repo *Repository, opts CreateRepoOptions) error {
	// Somehow the directory could exist.
	if com.IsExist(repoPath) {
		return fmt.Errorf("initRepository: path already exists: %s", repoPath)
	}

	// Init bare new repository.
	os.MkdirAll(repoPath, os.ModePerm)
	_, stderr, err := process.ExecDir(-1, repoPath,
		fmt.Sprintf("initRepository(git init --bare): %s", repoPath), "git", "init", "--bare")
	if err != nil {
		return fmt.Errorf("git init --bare: %v - %s", err, stderr)
	}

	if err := createUpdateHook(repoPath); err != nil {
		return err
	}

	tmpDir := filepath.Join(os.TempDir(), "gogs", repo.Name, com.ToStr(time.Now().Nanosecond()))

	// Initialize repository according to user's choice.
	if opts.AutoInit {
		os.MkdirAll(tmpDir, os.ModePerm)
		defer os.RemoveAll(tmpDir)

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

		// Apply changes and commit.
		if err = initRepoCommit(tmpDir, u.NewGitSig()); err != nil {
			return fmt.Errorf("initRepoCommit: %v", err)
		}
	}

	// Re-fetch the repository from database before updating it (else it would
	// override changes that were done earlier with sql)
	if repo, err = getRepositoryByID(e, repo.ID); err != nil {
		return fmt.Errorf("getRepositoryByID: %v", err)
	}

	if !opts.AutoInit {
		repo.IsBare = true
	}

	repo.DefaultBranch = "master"
	if err = updateRepository(e, repo, false); err != nil {
		return fmt.Errorf("updateRepository: %v", err)
	}

	return nil
}
Exemplo n.º 30
0
// SetUpdateHook writes given content to update hook of the reposiotry.
func SetUpdateHook(repoPath, content string) (err error) {
	log("Setting update hook: %s", repoPath)
	hookPath := path.Join(repoPath, HOOK_PATH_UPDATE)
	if com.IsExist(hookPath) {
		err = os.Remove(hookPath)
	} else {
		err = os.MkdirAll(path.Dir(hookPath), os.ModePerm)
	}
	if err != nil {
		return err
	}
	return ioutil.WriteFile(hookPath, []byte(content), 0777)
}