You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

repo.go 50 kB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
10 years ago
11 years ago
9 years ago
9 years ago
10 years ago
11 years ago
11 years ago
11 years ago
9 years ago
11 years ago
11 years ago
9 years ago
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
9 years ago
11 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
9 years ago
9 years ago
11 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "bytes"
  7. "errors"
  8. "fmt"
  9. "html/template"
  10. "io/ioutil"
  11. "os"
  12. "os/exec"
  13. "path"
  14. "path/filepath"
  15. "regexp"
  16. "sort"
  17. "strings"
  18. "time"
  19. "unicode/utf8"
  20. "github.com/Unknwon/cae/zip"
  21. "github.com/Unknwon/com"
  22. "github.com/go-xorm/xorm"
  23. "github.com/gogits/gogs/modules/base"
  24. "github.com/gogits/gogs/modules/bindata"
  25. "github.com/gogits/gogs/modules/git"
  26. "github.com/gogits/gogs/modules/log"
  27. "github.com/gogits/gogs/modules/process"
  28. "github.com/gogits/gogs/modules/setting"
  29. )
  30. const (
  31. _TPL_UPDATE_HOOK = "#!/usr/bin/env %s\n%s update $1 $2 $3 --config='%s'\n"
  32. )
  33. var (
  34. ErrRepoFileNotExist = errors.New("Repository file does not exist")
  35. ErrRepoFileNotLoaded = errors.New("Repository file not loaded")
  36. ErrMirrorNotExist = errors.New("Mirror does not exist")
  37. ErrInvalidReference = errors.New("Invalid reference specified")
  38. ErrNameEmpty = errors.New("Name is empty")
  39. )
  40. var (
  41. Gitignores, Licenses, Readmes []string
  42. )
  43. func LoadRepoConfig() {
  44. // Load .gitignore and license files and readme templates.
  45. types := []string{"gitignore", "license", "readme"}
  46. typeFiles := make([][]string, 3)
  47. for i, t := range types {
  48. files, err := bindata.AssetDir("conf/" + t)
  49. if err != nil {
  50. log.Fatal(4, "Fail to get %s files: %v", t, err)
  51. }
  52. customPath := path.Join(setting.CustomPath, "conf", t)
  53. if com.IsDir(customPath) {
  54. customFiles, err := com.StatDir(customPath)
  55. if err != nil {
  56. log.Fatal(4, "Fail to get custom %s files: %v", t, err)
  57. }
  58. for _, f := range customFiles {
  59. if !com.IsSliceContainsStr(files, f) {
  60. files = append(files, f)
  61. }
  62. }
  63. }
  64. typeFiles[i] = files
  65. }
  66. Gitignores = typeFiles[0]
  67. Licenses = typeFiles[1]
  68. Readmes = typeFiles[2]
  69. sort.Strings(Gitignores)
  70. sort.Strings(Licenses)
  71. sort.Strings(Readmes)
  72. }
  73. func NewRepoContext() {
  74. zip.Verbose = false
  75. // Check Git installation.
  76. if _, err := exec.LookPath("git"); err != nil {
  77. log.Fatal(4, "Fail to test 'git' command: %v (forgotten install?)", err)
  78. }
  79. // Check Git version.
  80. ver, err := git.GetVersion()
  81. if err != nil {
  82. log.Fatal(4, "Fail to get Git version: %v", err)
  83. }
  84. reqVer, err := git.ParseVersion("1.7.1")
  85. if err != nil {
  86. log.Fatal(4, "Fail to parse required Git version: %v", err)
  87. }
  88. if ver.LessThan(reqVer) {
  89. log.Fatal(4, "Gogs requires Git version greater or equal to 1.7.1")
  90. }
  91. // Git requires setting user.name and user.email in order to commit changes.
  92. for configKey, defaultValue := range map[string]string{"user.name": "Gogs", "user.email": "gogs@fake.local"} {
  93. if stdout, stderr, err := process.Exec("NewRepoContext(get setting)", "git", "config", "--get", configKey); err != nil || strings.TrimSpace(stdout) == "" {
  94. // ExitError indicates this config is not set
  95. if _, ok := err.(*exec.ExitError); ok || strings.TrimSpace(stdout) == "" {
  96. if _, stderr, gerr := process.Exec("NewRepoContext(set "+configKey+")", "git", "config", "--global", configKey, defaultValue); gerr != nil {
  97. log.Fatal(4, "Fail to set git %s(%s): %s", configKey, gerr, stderr)
  98. }
  99. log.Info("Git config %s set to %s", configKey, defaultValue)
  100. } else {
  101. log.Fatal(4, "Fail to get git %s(%s): %s", configKey, err, stderr)
  102. }
  103. }
  104. }
  105. // Set git some configurations.
  106. if _, stderr, err := process.Exec("NewRepoContext(git config --global core.quotepath false)",
  107. "git", "config", "--global", "core.quotepath", "false"); err != nil {
  108. log.Fatal(4, "Fail to execute 'git config --global core.quotepath false': %s", stderr)
  109. }
  110. }
  111. // Repository represents a git repository.
  112. type Repository struct {
  113. ID int64 `xorm:"pk autoincr"`
  114. OwnerID int64 `xorm:"UNIQUE(s)"`
  115. Owner *User `xorm:"-"`
  116. LowerName string `xorm:"UNIQUE(s) INDEX NOT NULL"`
  117. Name string `xorm:"INDEX NOT NULL"`
  118. Description string
  119. Website string
  120. DefaultBranch string
  121. NumWatches int
  122. NumStars int
  123. NumForks int
  124. NumIssues int
  125. NumClosedIssues int
  126. NumOpenIssues int `xorm:"-"`
  127. NumPulls int
  128. NumClosedPulls int
  129. NumOpenPulls int `xorm:"-"`
  130. NumMilestones int `xorm:"NOT NULL DEFAULT 0"`
  131. NumClosedMilestones int `xorm:"NOT NULL DEFAULT 0"`
  132. NumOpenMilestones int `xorm:"-"`
  133. NumTags int `xorm:"-"`
  134. IsPrivate bool
  135. IsBare bool
  136. IsMirror bool
  137. *Mirror `xorm:"-"`
  138. IsFork bool `xorm:"NOT NULL DEFAULT false"`
  139. ForkID int64
  140. BaseRepo *Repository `xorm:"-"`
  141. Created time.Time `xorm:"CREATED"`
  142. Updated time.Time `xorm:"UPDATED"`
  143. }
  144. func (repo *Repository) AfterSet(colName string, _ xorm.Cell) {
  145. switch colName {
  146. case "num_closed_issues":
  147. repo.NumOpenIssues = repo.NumIssues - repo.NumClosedIssues
  148. case "num_closed_pulls":
  149. repo.NumOpenPulls = repo.NumPulls - repo.NumClosedPulls
  150. case "num_closed_milestones":
  151. repo.NumOpenMilestones = repo.NumMilestones - repo.NumClosedMilestones
  152. case "updated":
  153. repo.Updated = regulateTimeZone(repo.Updated)
  154. }
  155. }
  156. func (repo *Repository) getOwner(e Engine) (err error) {
  157. if repo.Owner == nil {
  158. repo.Owner, err = getUserByID(e, repo.OwnerID)
  159. }
  160. return err
  161. }
  162. func (repo *Repository) GetOwner() error {
  163. return repo.getOwner(x)
  164. }
  165. // GetAssignees returns all users that have write access of repository.
  166. func (repo *Repository) GetAssignees() (_ []*User, err error) {
  167. if err = repo.GetOwner(); err != nil {
  168. return nil, err
  169. }
  170. accesses := make([]*Access, 0, 10)
  171. if err = x.Where("repo_id=? AND mode>=?", repo.ID, ACCESS_MODE_WRITE).Find(&accesses); err != nil {
  172. return nil, err
  173. }
  174. users := make([]*User, 0, len(accesses)+1) // Just waste 1 unit does not matter.
  175. if !repo.Owner.IsOrganization() {
  176. users = append(users, repo.Owner)
  177. }
  178. var u *User
  179. for i := range accesses {
  180. u, err = GetUserByID(accesses[i].UserID)
  181. if err != nil {
  182. return nil, err
  183. }
  184. users = append(users, u)
  185. }
  186. return users, nil
  187. }
  188. // GetAssigneeByID returns the user that has write access of repository by given ID.
  189. func (repo *Repository) GetAssigneeByID(userID int64) (*User, error) {
  190. return GetAssigneeByID(repo, userID)
  191. }
  192. // GetMilestoneByID returns the milestone belongs to repository by given ID.
  193. func (repo *Repository) GetMilestoneByID(milestoneID int64) (*Milestone, error) {
  194. return GetRepoMilestoneByID(repo.ID, milestoneID)
  195. }
  196. // IssueStats returns number of open and closed repository issues by given filter mode.
  197. func (repo *Repository) IssueStats(uid int64, filterMode int, isPull bool) (int64, int64) {
  198. return GetRepoIssueStats(repo.ID, uid, filterMode, isPull)
  199. }
  200. func (repo *Repository) GetMirror() (err error) {
  201. repo.Mirror, err = GetMirror(repo.ID)
  202. return err
  203. }
  204. func (repo *Repository) GetBaseRepo() (err error) {
  205. if !repo.IsFork {
  206. return nil
  207. }
  208. repo.BaseRepo, err = GetRepositoryByID(repo.ForkID)
  209. return err
  210. }
  211. func (repo *Repository) repoPath(e Engine) (string, error) {
  212. if err := repo.getOwner(e); err != nil {
  213. return "", err
  214. }
  215. return RepoPath(repo.Owner.Name, repo.Name), nil
  216. }
  217. func (repo *Repository) RepoPath() (string, error) {
  218. return repo.repoPath(x)
  219. }
  220. func (repo *Repository) RepoLink() (string, error) {
  221. if err := repo.GetOwner(); err != nil {
  222. return "", err
  223. }
  224. return setting.AppSubUrl + "/" + repo.Owner.Name + "/" + repo.Name, nil
  225. }
  226. func (repo *Repository) HasAccess(u *User) bool {
  227. has, _ := HasAccess(u, repo, ACCESS_MODE_READ)
  228. return has
  229. }
  230. func (repo *Repository) IsOwnedBy(userID int64) bool {
  231. return repo.OwnerID == userID
  232. }
  233. // CanBeForked returns true if repository meets the requirements of being forked.
  234. func (repo *Repository) CanBeForked() bool {
  235. return !repo.IsBare && !repo.IsMirror
  236. }
  237. func (repo *Repository) NextIssueIndex() int64 {
  238. return int64(repo.NumIssues+repo.NumPulls) + 1
  239. }
  240. var (
  241. DescPattern = regexp.MustCompile(`https?://\S+`)
  242. )
  243. // DescriptionHtml does special handles to description and return HTML string.
  244. func (repo *Repository) DescriptionHtml() template.HTML {
  245. sanitize := func(s string) string {
  246. return fmt.Sprintf(`<a href="%[1]s" target="_blank">%[1]s</a>`, s)
  247. }
  248. return template.HTML(DescPattern.ReplaceAllStringFunc(base.Sanitizer.Sanitize(repo.Description), sanitize))
  249. }
  250. func isRepositoryExist(e Engine, u *User, repoName string) (bool, error) {
  251. has, err := e.Get(&Repository{
  252. OwnerID: u.Id,
  253. LowerName: strings.ToLower(repoName),
  254. })
  255. return has && com.IsDir(RepoPath(u.Name, repoName)), err
  256. }
  257. // IsRepositoryExist returns true if the repository with given name under user has already existed.
  258. func IsRepositoryExist(u *User, repoName string) (bool, error) {
  259. return isRepositoryExist(x, u, repoName)
  260. }
  261. // CloneLink represents different types of clone URLs of repository.
  262. type CloneLink struct {
  263. SSH string
  264. HTTPS string
  265. Git string
  266. }
  267. // CloneLink returns clone URLs of repository.
  268. func (repo *Repository) CloneLink() (cl CloneLink, err error) {
  269. if err = repo.GetOwner(); err != nil {
  270. return cl, err
  271. }
  272. if setting.SSHPort != 22 {
  273. cl.SSH = fmt.Sprintf("ssh://%s@%s:%d/%s/%s.git", setting.RunUser, setting.SSHDomain, setting.SSHPort, repo.Owner.LowerName, repo.LowerName)
  274. } else {
  275. cl.SSH = fmt.Sprintf("%s@%s:%s/%s.git", setting.RunUser, setting.SSHDomain, repo.Owner.LowerName, repo.LowerName)
  276. }
  277. cl.HTTPS = fmt.Sprintf("%s%s/%s.git", setting.AppUrl, repo.Owner.LowerName, repo.LowerName)
  278. return cl, nil
  279. }
  280. var (
  281. reservedNames = []string{"debug", "raw", "install", "api", "avatar", "user", "org", "help", "stars", "issues", "pulls", "commits", "repo", "template", "admin", "new"}
  282. reservedPatterns = []string{"*.git", "*.keys"}
  283. )
  284. // IsUsableName checks if name is reserved or pattern of name is not allowed.
  285. func IsUsableName(name string) error {
  286. name = strings.TrimSpace(strings.ToLower(name))
  287. if utf8.RuneCountInString(name) == 0 {
  288. return ErrNameEmpty
  289. }
  290. for i := range reservedNames {
  291. if name == reservedNames[i] {
  292. return ErrNameReserved{name}
  293. }
  294. }
  295. for _, pat := range reservedPatterns {
  296. if pat[0] == '*' && strings.HasSuffix(name, pat[1:]) ||
  297. (pat[len(pat)-1] == '*' && strings.HasPrefix(name, pat[:len(pat)-1])) {
  298. return ErrNamePatternNotAllowed{pat}
  299. }
  300. }
  301. return nil
  302. }
  303. // Mirror represents a mirror information of repository.
  304. type Mirror struct {
  305. ID int64 `xorm:"pk autoincr"`
  306. RepoID int64
  307. Repo *Repository `xorm:"-"`
  308. Interval int // Hour.
  309. Updated time.Time `xorm:"UPDATED"`
  310. NextUpdate time.Time
  311. }
  312. func (m *Mirror) AfterSet(colName string, _ xorm.Cell) {
  313. var err error
  314. switch colName {
  315. case "repo_id":
  316. m.Repo, err = GetRepositoryByID(m.RepoID)
  317. if err != nil {
  318. log.Error(3, "GetRepositoryByID[%d]: %v", m.ID, err)
  319. }
  320. }
  321. }
  322. func getMirror(e Engine, repoId int64) (*Mirror, error) {
  323. m := &Mirror{RepoID: repoId}
  324. has, err := e.Get(m)
  325. if err != nil {
  326. return nil, err
  327. } else if !has {
  328. return nil, ErrMirrorNotExist
  329. }
  330. return m, nil
  331. }
  332. // GetMirror returns mirror object by given repository ID.
  333. func GetMirror(repoId int64) (*Mirror, error) {
  334. return getMirror(x, repoId)
  335. }
  336. func updateMirror(e Engine, m *Mirror) error {
  337. _, err := e.Id(m.ID).Update(m)
  338. return err
  339. }
  340. func UpdateMirror(m *Mirror) error {
  341. return updateMirror(x, m)
  342. }
  343. // MirrorRepository creates a mirror repository from source.
  344. func MirrorRepository(repoId int64, userName, repoName, repoPath, url string) error {
  345. _, stderr, err := process.ExecTimeout(10*time.Minute,
  346. fmt.Sprintf("MirrorRepository: %s/%s", userName, repoName),
  347. "git", "clone", "--mirror", url, repoPath)
  348. if err != nil {
  349. return errors.New("git clone --mirror: " + stderr)
  350. }
  351. if _, err = x.InsertOne(&Mirror{
  352. RepoID: repoId,
  353. Interval: 24,
  354. NextUpdate: time.Now().Add(24 * time.Hour),
  355. }); err != nil {
  356. return err
  357. }
  358. return nil
  359. }
  360. // MigrateRepository migrates a existing repository from other project hosting.
  361. func MigrateRepository(u *User, name, desc string, private, mirror bool, url string) (*Repository, error) {
  362. repo, err := CreateRepository(u, CreateRepoOptions{
  363. Name: name,
  364. Description: desc,
  365. IsPrivate: private,
  366. IsMirror: mirror,
  367. })
  368. if err != nil {
  369. return nil, err
  370. }
  371. // Clone to temprory path and do the init commit.
  372. tmpDir := filepath.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()))
  373. os.MkdirAll(tmpDir, os.ModePerm)
  374. repoPath := RepoPath(u.Name, name)
  375. if u.IsOrganization() {
  376. t, err := u.GetOwnerTeam()
  377. if err != nil {
  378. return nil, err
  379. }
  380. repo.NumWatches = t.NumMembers
  381. } else {
  382. repo.NumWatches = 1
  383. }
  384. repo.IsBare = false
  385. if mirror {
  386. if err = MirrorRepository(repo.ID, u.Name, repo.Name, repoPath, url); err != nil {
  387. return repo, err
  388. }
  389. repo.IsMirror = true
  390. return repo, UpdateRepository(repo, false)
  391. } else {
  392. os.RemoveAll(repoPath)
  393. }
  394. // FIXME: this command could for both migrate and mirror
  395. _, stderr, err := process.ExecTimeout(10*time.Minute,
  396. fmt.Sprintf("MigrateRepository: %s", repoPath),
  397. "git", "clone", "--mirror", "--bare", "--quiet", url, repoPath)
  398. if err != nil {
  399. return repo, fmt.Errorf("git clone --mirror --bare --quiet: %v", stderr)
  400. } else if err = createUpdateHook(repoPath); err != nil {
  401. return repo, fmt.Errorf("create update hook: %v", err)
  402. }
  403. // Check if repository is empty.
  404. _, stderr, err = com.ExecCmdDir(repoPath, "git", "log", "-1")
  405. if err != nil && strings.Contains(stderr, "fatal: bad default revision 'HEAD'") {
  406. repo.IsBare = true
  407. }
  408. // Check if repository has master branch, if so set it to default branch.
  409. gitRepo, err := git.OpenRepository(repoPath)
  410. if err != nil {
  411. return repo, fmt.Errorf("open git repository: %v", err)
  412. }
  413. if gitRepo.IsBranchExist("master") {
  414. repo.DefaultBranch = "master"
  415. }
  416. return repo, UpdateRepository(repo, false)
  417. }
  418. // initRepoCommit temporarily changes with work directory.
  419. func initRepoCommit(tmpPath string, sig *git.Signature) (err error) {
  420. var stderr string
  421. if _, stderr, err = process.ExecDir(-1,
  422. tmpPath, fmt.Sprintf("initRepoCommit(git add): %s", tmpPath),
  423. "git", "add", "--all"); err != nil {
  424. return fmt.Errorf("git add: %s", stderr)
  425. }
  426. if _, stderr, err = process.ExecDir(-1,
  427. tmpPath, fmt.Sprintf("initRepoCommit(git commit): %s", tmpPath),
  428. "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  429. "-m", "initial commit"); err != nil {
  430. return fmt.Errorf("git commit: %s", stderr)
  431. }
  432. if _, stderr, err = process.ExecDir(-1,
  433. tmpPath, fmt.Sprintf("initRepoCommit(git push): %s", tmpPath),
  434. "git", "push", "origin", "master"); err != nil {
  435. return fmt.Errorf("git push: %s", stderr)
  436. }
  437. return nil
  438. }
  439. func createUpdateHook(repoPath string) error {
  440. hookPath := path.Join(repoPath, "hooks/update")
  441. os.MkdirAll(path.Dir(hookPath), os.ModePerm)
  442. return ioutil.WriteFile(hookPath,
  443. []byte(fmt.Sprintf(_TPL_UPDATE_HOOK, setting.ScriptType, "\""+appPath+"\"", setting.CustomConf)), 0777)
  444. }
  445. type CreateRepoOptions struct {
  446. Name string
  447. Description string
  448. Gitignores string
  449. License string
  450. Readme string
  451. IsPrivate bool
  452. IsMirror bool
  453. AutoInit bool
  454. }
  455. func getRepoInitFile(tp, name string) ([]byte, error) {
  456. relPath := path.Join("conf", tp, name)
  457. // Use custom file when available.
  458. customPath := path.Join(setting.CustomPath, relPath)
  459. if com.IsFile(customPath) {
  460. return ioutil.ReadFile(customPath)
  461. }
  462. return bindata.Asset(relPath)
  463. }
  464. func prepareRepoCommit(repo *Repository, tmpDir, repoPath string, opts CreateRepoOptions) error {
  465. // Clone to temprory path and do the init commit.
  466. _, stderr, err := process.Exec(
  467. fmt.Sprintf("initRepository(git clone): %s", repoPath), "git", "clone", repoPath, tmpDir)
  468. if err != nil {
  469. return fmt.Errorf("git clone: %v - %s", err, stderr)
  470. }
  471. // README
  472. data, err := getRepoInitFile("readme", opts.Readme)
  473. if err != nil {
  474. return fmt.Errorf("getRepoInitFile[%s]: %v", opts.Readme, err)
  475. }
  476. cloneLink, err := repo.CloneLink()
  477. if err != nil {
  478. return fmt.Errorf("CloneLink: %v", err)
  479. }
  480. match := map[string]string{
  481. "Name": repo.Name,
  482. "Description": repo.Description,
  483. "CloneURL.SSH": cloneLink.SSH,
  484. "CloneURL.HTTPS": cloneLink.HTTPS,
  485. }
  486. if err = ioutil.WriteFile(filepath.Join(tmpDir, "README.md"),
  487. []byte(com.Expand(string(data), match)), 0644); err != nil {
  488. return fmt.Errorf("write README.md: %v", err)
  489. }
  490. // .gitignore
  491. if len(opts.Gitignores) > 0 {
  492. var buf bytes.Buffer
  493. names := strings.Split(opts.Gitignores, ",")
  494. for _, name := range names {
  495. data, err = getRepoInitFile("gitignore", name)
  496. if err != nil {
  497. return fmt.Errorf("getRepoInitFile[%s]: %v", name, err)
  498. }
  499. buf.WriteString("# ---> " + name + "\n")
  500. buf.Write(data)
  501. buf.WriteString("\n")
  502. }
  503. if buf.Len() > 0 {
  504. if err = ioutil.WriteFile(filepath.Join(tmpDir, ".gitignore"), buf.Bytes(), 0644); err != nil {
  505. return fmt.Errorf("write .gitignore: %v", err)
  506. }
  507. }
  508. }
  509. // LICENSE
  510. if len(opts.License) > 0 {
  511. data, err = getRepoInitFile("license", opts.License)
  512. if err != nil {
  513. return fmt.Errorf("getRepoInitFile[%s]: %v", opts.License, err)
  514. }
  515. if err = ioutil.WriteFile(filepath.Join(tmpDir, "LICENSE"), data, 0644); err != nil {
  516. return fmt.Errorf("write LICENSE: %v", err)
  517. }
  518. }
  519. return nil
  520. }
  521. // InitRepository initializes README and .gitignore if needed.
  522. func initRepository(e Engine, repoPath string, u *User, repo *Repository, opts CreateRepoOptions) error {
  523. // Somehow the directory could exist.
  524. if com.IsExist(repoPath) {
  525. return fmt.Errorf("initRepository: path already exists: %s", repoPath)
  526. }
  527. // Init bare new repository.
  528. os.MkdirAll(repoPath, os.ModePerm)
  529. _, stderr, err := process.ExecDir(-1, repoPath,
  530. fmt.Sprintf("initRepository(git init --bare): %s", repoPath), "git", "init", "--bare")
  531. if err != nil {
  532. return fmt.Errorf("git init --bare: %v - %s", err, stderr)
  533. }
  534. if err := createUpdateHook(repoPath); err != nil {
  535. return err
  536. }
  537. tmpDir := filepath.Join(os.TempDir(), "gogs-"+repo.Name+"-"+com.ToStr(time.Now().Nanosecond()))
  538. fmt.Println(tmpDir)
  539. // Initialize repository according to user's choice.
  540. if opts.AutoInit {
  541. os.MkdirAll(tmpDir, os.ModePerm)
  542. defer os.RemoveAll(tmpDir)
  543. if err = prepareRepoCommit(repo, tmpDir, repoPath, opts); err != nil {
  544. return fmt.Errorf("prepareRepoCommit: %v", err)
  545. }
  546. // Apply changes and commit.
  547. if err = initRepoCommit(tmpDir, u.NewGitSig()); err != nil {
  548. return fmt.Errorf("initRepoCommit: %v", err)
  549. }
  550. }
  551. // Re-fetch the repository from database before updating it (else it would
  552. // override changes that were done earlier with sql)
  553. if repo, err = getRepositoryByID(e, repo.ID); err != nil {
  554. return fmt.Errorf("getRepositoryByID: %v", err)
  555. }
  556. if !opts.AutoInit {
  557. repo.IsBare = true
  558. }
  559. repo.DefaultBranch = "master"
  560. if err = updateRepository(e, repo, false); err != nil {
  561. return fmt.Errorf("updateRepository: %v", err)
  562. }
  563. return nil
  564. }
  565. func createRepository(e *xorm.Session, u *User, repo *Repository) (err error) {
  566. if err = IsUsableName(repo.Name); err != nil {
  567. return err
  568. }
  569. has, err := isRepositoryExist(e, u, repo.Name)
  570. if err != nil {
  571. return fmt.Errorf("IsRepositoryExist: %v", err)
  572. } else if has {
  573. return ErrRepoAlreadyExist{u.Name, repo.Name}
  574. }
  575. if _, err = e.Insert(repo); err != nil {
  576. return err
  577. }
  578. u.NumRepos++
  579. // Remember visibility preference.
  580. u.LastRepoVisibility = repo.IsPrivate
  581. if err = updateUser(e, u); err != nil {
  582. return fmt.Errorf("updateUser: %v", err)
  583. }
  584. // Give access to all members in owner team.
  585. if u.IsOrganization() {
  586. t, err := u.getOwnerTeam(e)
  587. if err != nil {
  588. return fmt.Errorf("getOwnerTeam: %v", err)
  589. } else if err = t.addRepository(e, repo); err != nil {
  590. return fmt.Errorf("addRepository: %v", err)
  591. }
  592. } else {
  593. // Organization automatically called this in addRepository method.
  594. if err = repo.recalculateAccesses(e); err != nil {
  595. return fmt.Errorf("recalculateAccesses: %v", err)
  596. }
  597. }
  598. if err = watchRepo(e, u.Id, repo.ID, true); err != nil {
  599. return fmt.Errorf("watchRepo: %v", err)
  600. } else if err = newRepoAction(e, u, repo); err != nil {
  601. return fmt.Errorf("newRepoAction: %v", err)
  602. }
  603. return nil
  604. }
  605. // CreateRepository creates a repository for given user or organization.
  606. func CreateRepository(u *User, opts CreateRepoOptions) (_ *Repository, err error) {
  607. repo := &Repository{
  608. OwnerID: u.Id,
  609. Owner: u,
  610. Name: opts.Name,
  611. LowerName: strings.ToLower(opts.Name),
  612. Description: opts.Description,
  613. IsPrivate: opts.IsPrivate,
  614. }
  615. sess := x.NewSession()
  616. defer sessionRelease(sess)
  617. if err = sess.Begin(); err != nil {
  618. return nil, err
  619. }
  620. if err = createRepository(sess, u, repo); err != nil {
  621. return nil, err
  622. }
  623. // No need for init mirror.
  624. if !opts.IsMirror {
  625. repoPath := RepoPath(u.Name, repo.Name)
  626. if err = initRepository(sess, repoPath, u, repo, opts); err != nil {
  627. if err2 := os.RemoveAll(repoPath); err2 != nil {
  628. log.Error(4, "initRepository: %v", err)
  629. return nil, fmt.Errorf(
  630. "delete repo directory %s/%s failed(2): %v", u.Name, repo.Name, err2)
  631. }
  632. return nil, fmt.Errorf("initRepository: %v", err)
  633. }
  634. _, stderr, err := process.ExecDir(-1,
  635. repoPath, fmt.Sprintf("CreateRepository(git update-server-info): %s", repoPath),
  636. "git", "update-server-info")
  637. if err != nil {
  638. return nil, errors.New("CreateRepository(git update-server-info): " + stderr)
  639. }
  640. }
  641. return repo, sess.Commit()
  642. }
  643. func countRepositories(showPrivate bool) int64 {
  644. sess := x.NewSession()
  645. if !showPrivate {
  646. sess.Where("is_private=", false)
  647. }
  648. count, _ := sess.Count(new(Repository))
  649. return count
  650. }
  651. // CountRepositories returns number of repositories.
  652. func CountRepositories() int64 {
  653. return countRepositories(true)
  654. }
  655. // CountPublicRepositories returns number of public repositories.
  656. func CountPublicRepositories() int64 {
  657. return countRepositories(false)
  658. }
  659. // GetRepositoriesWithUsers returns given number of repository objects with offset.
  660. // It also auto-gets corresponding users.
  661. func GetRepositoriesWithUsers(num, offset int) ([]*Repository, error) {
  662. repos := make([]*Repository, 0, num)
  663. if err := x.Limit(num, offset).Asc("id").Find(&repos); err != nil {
  664. return nil, err
  665. }
  666. for _, repo := range repos {
  667. repo.Owner = &User{Id: repo.OwnerID}
  668. has, err := x.Get(repo.Owner)
  669. if err != nil {
  670. return nil, err
  671. } else if !has {
  672. return nil, ErrUserNotExist{repo.OwnerID, ""}
  673. }
  674. }
  675. return repos, nil
  676. }
  677. // RepoPath returns repository path by given user and repository name.
  678. func RepoPath(userName, repoName string) string {
  679. return filepath.Join(UserPath(userName), strings.ToLower(repoName)+".git")
  680. }
  681. // TransferOwnership transfers all corresponding setting from old user to new one.
  682. func TransferOwnership(u *User, newOwnerName string, repo *Repository) error {
  683. newOwner, err := GetUserByName(newOwnerName)
  684. if err != nil {
  685. return fmt.Errorf("get new owner '%s': %v", newOwnerName, err)
  686. }
  687. // Check if new owner has repository with same name.
  688. has, err := IsRepositoryExist(newOwner, repo.Name)
  689. if err != nil {
  690. return fmt.Errorf("IsRepositoryExist: %v", err)
  691. } else if has {
  692. return ErrRepoAlreadyExist{newOwnerName, repo.Name}
  693. }
  694. sess := x.NewSession()
  695. defer sessionRelease(sess)
  696. if err = sess.Begin(); err != nil {
  697. return fmt.Errorf("sess.Begin: %v", err)
  698. }
  699. owner := repo.Owner
  700. // Note: we have to set value here to make sure recalculate accesses is based on
  701. // new owner.
  702. repo.OwnerID = newOwner.Id
  703. repo.Owner = newOwner
  704. // Update repository.
  705. if _, err := sess.Id(repo.ID).Update(repo); err != nil {
  706. return fmt.Errorf("update owner: %v", err)
  707. }
  708. // Remove redundant collaborators.
  709. collaborators, err := repo.GetCollaborators()
  710. if err != nil {
  711. return fmt.Errorf("GetCollaborators: %v", err)
  712. }
  713. // Dummy object.
  714. collaboration := &Collaboration{RepoID: repo.ID}
  715. for _, c := range collaborators {
  716. collaboration.UserID = c.Id
  717. if c.Id == newOwner.Id || newOwner.IsOrgMember(c.Id) {
  718. if _, err = sess.Delete(collaboration); err != nil {
  719. return fmt.Errorf("remove collaborator '%d': %v", c.Id, err)
  720. }
  721. }
  722. }
  723. // Remove old team-repository relations.
  724. if owner.IsOrganization() {
  725. if err = owner.getTeams(sess); err != nil {
  726. return fmt.Errorf("getTeams: %v", err)
  727. }
  728. for _, t := range owner.Teams {
  729. if !t.hasRepository(sess, repo.ID) {
  730. continue
  731. }
  732. t.NumRepos--
  733. if _, err := sess.Id(t.ID).AllCols().Update(t); err != nil {
  734. return fmt.Errorf("decrease team repository count '%d': %v", t.ID, err)
  735. }
  736. }
  737. if err = owner.removeOrgRepo(sess, repo.ID); err != nil {
  738. return fmt.Errorf("removeOrgRepo: %v", err)
  739. }
  740. }
  741. if newOwner.IsOrganization() {
  742. t, err := newOwner.GetOwnerTeam()
  743. if err != nil {
  744. return fmt.Errorf("GetOwnerTeam: %v", err)
  745. } else if err = t.addRepository(sess, repo); err != nil {
  746. return fmt.Errorf("add to owner team: %v", err)
  747. }
  748. } else {
  749. // Organization called this in addRepository method.
  750. if err = repo.recalculateAccesses(sess); err != nil {
  751. return fmt.Errorf("recalculateAccesses: %v", err)
  752. }
  753. }
  754. // Update repository count.
  755. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos+1 WHERE id=?", newOwner.Id); err != nil {
  756. return fmt.Errorf("increase new owner repository count: %v", err)
  757. } else if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", owner.Id); err != nil {
  758. return fmt.Errorf("decrease old owner repository count: %v", err)
  759. }
  760. if err = watchRepo(sess, newOwner.Id, repo.ID, true); err != nil {
  761. return fmt.Errorf("watchRepo: %v", err)
  762. } else if err = transferRepoAction(sess, u, owner, newOwner, repo); err != nil {
  763. return fmt.Errorf("transferRepoAction: %v", err)
  764. }
  765. // Change repository directory name.
  766. if err = os.Rename(RepoPath(owner.Name, repo.Name), RepoPath(newOwner.Name, repo.Name)); err != nil {
  767. return fmt.Errorf("rename directory: %v", err)
  768. }
  769. return sess.Commit()
  770. }
  771. // ChangeRepositoryName changes all corresponding setting from old repository name to new one.
  772. func ChangeRepositoryName(u *User, oldRepoName, newRepoName string) (err error) {
  773. oldRepoName = strings.ToLower(oldRepoName)
  774. newRepoName = strings.ToLower(newRepoName)
  775. if err = IsUsableName(newRepoName); err != nil {
  776. return err
  777. }
  778. has, err := IsRepositoryExist(u, newRepoName)
  779. if err != nil {
  780. return fmt.Errorf("IsRepositoryExist: %v", err)
  781. } else if has {
  782. return ErrRepoAlreadyExist{u.Name, newRepoName}
  783. }
  784. // Change repository directory name.
  785. return os.Rename(RepoPath(u.LowerName, oldRepoName), RepoPath(u.LowerName, newRepoName))
  786. }
  787. func getRepositoriesByForkID(e Engine, forkID int64) ([]*Repository, error) {
  788. repos := make([]*Repository, 0, 10)
  789. return repos, e.Where("fork_id=?", forkID).Find(&repos)
  790. }
  791. // GetRepositoriesByForkID returns all repositories with given fork ID.
  792. func GetRepositoriesByForkID(forkID int64) ([]*Repository, error) {
  793. return getRepositoriesByForkID(x, forkID)
  794. }
  795. func updateRepository(e Engine, repo *Repository, visibilityChanged bool) (err error) {
  796. repo.LowerName = strings.ToLower(repo.Name)
  797. if len(repo.Description) > 255 {
  798. repo.Description = repo.Description[:255]
  799. }
  800. if len(repo.Website) > 255 {
  801. repo.Website = repo.Website[:255]
  802. }
  803. if _, err = e.Id(repo.ID).AllCols().Update(repo); err != nil {
  804. return fmt.Errorf("update: %v", err)
  805. }
  806. if visibilityChanged {
  807. if err = repo.getOwner(e); err != nil {
  808. return fmt.Errorf("getOwner: %v", err)
  809. }
  810. if !repo.Owner.IsOrganization() {
  811. return nil
  812. }
  813. // Organization repository need to recalculate access table when visivility is changed.
  814. if err = repo.recalculateTeamAccesses(e, 0); err != nil {
  815. return fmt.Errorf("recalculateTeamAccesses: %v", err)
  816. }
  817. forkRepos, err := getRepositoriesByForkID(e, repo.ID)
  818. if err != nil {
  819. return fmt.Errorf("getRepositoriesByForkID: %v", err)
  820. }
  821. for i := range forkRepos {
  822. forkRepos[i].IsPrivate = repo.IsPrivate
  823. if err = updateRepository(e, forkRepos[i], true); err != nil {
  824. return fmt.Errorf("updateRepository[%d]: %v", forkRepos[i].ID, err)
  825. }
  826. }
  827. }
  828. return nil
  829. }
  830. func UpdateRepository(repo *Repository, visibilityChanged bool) (err error) {
  831. sess := x.NewSession()
  832. defer sessionRelease(sess)
  833. if err = sess.Begin(); err != nil {
  834. return err
  835. }
  836. if err = updateRepository(x, repo, visibilityChanged); err != nil {
  837. return fmt.Errorf("updateRepository: %v", err)
  838. }
  839. return sess.Commit()
  840. }
  841. // DeleteRepository deletes a repository for a user or organization.
  842. func DeleteRepository(uid, repoID int64) error {
  843. repo := &Repository{ID: repoID, OwnerID: uid}
  844. has, err := x.Get(repo)
  845. if err != nil {
  846. return err
  847. } else if !has {
  848. return ErrRepoNotExist{repoID, uid, ""}
  849. }
  850. // In case is a organization.
  851. org, err := GetUserByID(uid)
  852. if err != nil {
  853. return err
  854. }
  855. if org.IsOrganization() {
  856. if err = org.GetTeams(); err != nil {
  857. return err
  858. }
  859. }
  860. sess := x.NewSession()
  861. defer sessionRelease(sess)
  862. if err = sess.Begin(); err != nil {
  863. return err
  864. }
  865. if org.IsOrganization() {
  866. for _, t := range org.Teams {
  867. if !t.hasRepository(sess, repoID) {
  868. continue
  869. } else if err = t.removeRepository(sess, repo, false); err != nil {
  870. return err
  871. }
  872. }
  873. }
  874. if _, err = sess.Delete(&Repository{ID: repoID}); err != nil {
  875. return err
  876. } else if _, err = sess.Delete(&Access{RepoID: repo.ID}); err != nil {
  877. return err
  878. } else if _, err = sess.Delete(&Action{RepoID: repo.ID}); err != nil {
  879. return err
  880. } else if _, err = sess.Delete(&Watch{RepoID: repoID}); err != nil {
  881. return err
  882. } else if _, err = sess.Delete(&Mirror{RepoID: repoID}); err != nil {
  883. return err
  884. } else if _, err = sess.Delete(&IssueUser{RepoID: repoID}); err != nil {
  885. return err
  886. } else if _, err = sess.Delete(&Milestone{RepoID: repoID}); err != nil {
  887. return err
  888. } else if _, err = sess.Delete(&Release{RepoId: repoID}); err != nil {
  889. return err
  890. } else if _, err = sess.Delete(&Collaboration{RepoID: repoID}); err != nil {
  891. return err
  892. } else if _, err = sess.Delete(&PullRequest{BaseRepoID: repoID}); err != nil {
  893. return err
  894. }
  895. // Delete comments and attachments.
  896. issues := make([]*Issue, 0, 25)
  897. attachmentPaths := make([]string, 0, len(issues))
  898. if err = sess.Where("repo_id=?", repoID).Find(&issues); err != nil {
  899. return err
  900. }
  901. for i := range issues {
  902. if _, err = sess.Delete(&Comment{IssueID: issues[i].ID}); err != nil {
  903. return err
  904. }
  905. attachments := make([]*Attachment, 0, 5)
  906. if err = sess.Where("issue_id=?", issues[i].ID).Find(&attachments); err != nil {
  907. return err
  908. }
  909. for j := range attachments {
  910. attachmentPaths = append(attachmentPaths, attachments[j].LocalPath())
  911. }
  912. if _, err = sess.Delete(&Attachment{IssueID: issues[i].ID}); err != nil {
  913. return err
  914. }
  915. }
  916. if _, err = sess.Delete(&Issue{RepoID: repoID}); err != nil {
  917. return err
  918. }
  919. if repo.IsFork {
  920. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks-1 WHERE id=?", repo.ForkID); err != nil {
  921. return fmt.Errorf("decrease fork count: %v", err)
  922. }
  923. }
  924. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", uid); err != nil {
  925. return err
  926. }
  927. // Remove repository files.
  928. repoPath, err := repo.repoPath(sess)
  929. if err != nil {
  930. return fmt.Errorf("RepoPath: %v", err)
  931. }
  932. if err = os.RemoveAll(repoPath); err != nil {
  933. desc := fmt.Sprintf("delete repository files[%s]: %v", repoPath, err)
  934. log.Warn(desc)
  935. if err = CreateRepositoryNotice(desc); err != nil {
  936. log.Error(4, "add notice: %v", err)
  937. }
  938. }
  939. // Remove attachment files.
  940. for i := range attachmentPaths {
  941. if err = os.Remove(attachmentPaths[i]); err != nil {
  942. log.Warn("delete attachment: %v", err)
  943. }
  944. }
  945. if err = sess.Commit(); err != nil {
  946. return fmt.Errorf("Commit: %v", err)
  947. }
  948. if repo.NumForks > 0 {
  949. if repo.IsPrivate {
  950. forkRepos, err := GetRepositoriesByForkID(repo.ID)
  951. if err != nil {
  952. return fmt.Errorf("getRepositoriesByForkID: %v", err)
  953. }
  954. for i := range forkRepos {
  955. if err = DeleteRepository(forkRepos[i].OwnerID, forkRepos[i].ID); err != nil {
  956. log.Error(4, "updateRepository[%d]: %v", forkRepos[i].ID, err)
  957. }
  958. }
  959. } else {
  960. if _, err = x.Exec("UPDATE `repository` SET fork_id=0,is_fork=? WHERE fork_id=?", false, repo.ID); err != nil {
  961. log.Error(4, "reset 'fork_id' and 'is_fork': %v", err)
  962. }
  963. }
  964. }
  965. return nil
  966. }
  967. // GetRepositoryByRef returns a Repository specified by a GFM reference.
  968. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  969. func GetRepositoryByRef(ref string) (*Repository, error) {
  970. n := strings.IndexByte(ref, byte('/'))
  971. if n < 2 {
  972. return nil, ErrInvalidReference
  973. }
  974. userName, repoName := ref[:n], ref[n+1:]
  975. user, err := GetUserByName(userName)
  976. if err != nil {
  977. return nil, err
  978. }
  979. return GetRepositoryByName(user.Id, repoName)
  980. }
  981. // GetRepositoryByName returns the repository by given name under user if exists.
  982. func GetRepositoryByName(uid int64, repoName string) (*Repository, error) {
  983. repo := &Repository{
  984. OwnerID: uid,
  985. LowerName: strings.ToLower(repoName),
  986. }
  987. has, err := x.Get(repo)
  988. if err != nil {
  989. return nil, err
  990. } else if !has {
  991. return nil, ErrRepoNotExist{0, uid, repoName}
  992. }
  993. return repo, err
  994. }
  995. func getRepositoryByID(e Engine, id int64) (*Repository, error) {
  996. repo := new(Repository)
  997. has, err := e.Id(id).Get(repo)
  998. if err != nil {
  999. return nil, err
  1000. } else if !has {
  1001. return nil, ErrRepoNotExist{id, 0, ""}
  1002. }
  1003. return repo, nil
  1004. }
  1005. // GetRepositoryByID returns the repository by given id if exists.
  1006. func GetRepositoryByID(id int64) (*Repository, error) {
  1007. return getRepositoryByID(x, id)
  1008. }
  1009. // GetRepositories returns a list of repositories of given user.
  1010. func GetRepositories(uid int64, private bool) ([]*Repository, error) {
  1011. repos := make([]*Repository, 0, 10)
  1012. sess := x.Desc("updated")
  1013. if !private {
  1014. sess.Where("is_private=?", false)
  1015. }
  1016. return repos, sess.Find(&repos, &Repository{OwnerID: uid})
  1017. }
  1018. // GetRecentUpdatedRepositories returns the list of repositories that are recently updated.
  1019. func GetRecentUpdatedRepositories(page int) (repos []*Repository, err error) {
  1020. return repos, x.Limit(setting.ExplorePagingNum, (page-1)*setting.ExplorePagingNum).
  1021. Where("is_private=?", false).Limit(setting.ExplorePagingNum).Desc("updated").Find(&repos)
  1022. }
  1023. func getRepositoryCount(e Engine, u *User) (int64, error) {
  1024. return x.Count(&Repository{OwnerID: u.Id})
  1025. }
  1026. // GetRepositoryCount returns the total number of repositories of user.
  1027. func GetRepositoryCount(u *User) (int64, error) {
  1028. return getRepositoryCount(x, u)
  1029. }
  1030. type SearchOption struct {
  1031. Keyword string
  1032. Uid int64
  1033. Limit int
  1034. Private bool
  1035. }
  1036. // SearchRepositoryByName returns given number of repositories whose name contains keyword.
  1037. func SearchRepositoryByName(opt SearchOption) (repos []*Repository, err error) {
  1038. if len(opt.Keyword) == 0 {
  1039. return repos, nil
  1040. }
  1041. opt.Keyword = strings.ToLower(opt.Keyword)
  1042. repos = make([]*Repository, 0, opt.Limit)
  1043. // Append conditions.
  1044. sess := x.Limit(opt.Limit)
  1045. if opt.Uid > 0 {
  1046. sess.Where("owner_id=?", opt.Uid)
  1047. }
  1048. if !opt.Private {
  1049. sess.And("is_private=false")
  1050. }
  1051. sess.And("lower_name like ?", "%"+opt.Keyword+"%").Find(&repos)
  1052. return repos, err
  1053. }
  1054. // DeleteRepositoryArchives deletes all repositories' archives.
  1055. func DeleteRepositoryArchives() error {
  1056. return x.Where("id > 0").Iterate(new(Repository),
  1057. func(idx int, bean interface{}) error {
  1058. repo := bean.(*Repository)
  1059. if err := repo.GetOwner(); err != nil {
  1060. return err
  1061. }
  1062. return os.RemoveAll(filepath.Join(RepoPath(repo.Owner.Name, repo.Name), "archives"))
  1063. })
  1064. }
  1065. // RewriteRepositoryUpdateHook rewrites all repositories' update hook.
  1066. func RewriteRepositoryUpdateHook() error {
  1067. return x.Where("id > 0").Iterate(new(Repository),
  1068. func(idx int, bean interface{}) error {
  1069. repo := bean.(*Repository)
  1070. if err := repo.GetOwner(); err != nil {
  1071. return err
  1072. }
  1073. return createUpdateHook(RepoPath(repo.Owner.Name, repo.Name))
  1074. })
  1075. }
  1076. var (
  1077. // Prevent duplicate running tasks.
  1078. isMirrorUpdating = false
  1079. isGitFscking = false
  1080. isCheckingRepos = false
  1081. )
  1082. // MirrorUpdate checks and updates mirror repositories.
  1083. func MirrorUpdate() {
  1084. if isMirrorUpdating {
  1085. return
  1086. }
  1087. isMirrorUpdating = true
  1088. defer func() { isMirrorUpdating = false }()
  1089. log.Trace("Doing: MirrorUpdate")
  1090. mirrors := make([]*Mirror, 0, 10)
  1091. if err := x.Iterate(new(Mirror), func(idx int, bean interface{}) error {
  1092. m := bean.(*Mirror)
  1093. if m.NextUpdate.After(time.Now()) {
  1094. return nil
  1095. }
  1096. if m.Repo == nil {
  1097. log.Error(4, "Disconnected mirror repository found: %d", m.ID)
  1098. return nil
  1099. }
  1100. repoPath, err := m.Repo.RepoPath()
  1101. if err != nil {
  1102. return fmt.Errorf("Repo.RepoPath: %v", err)
  1103. }
  1104. if _, stderr, err := process.ExecDir(10*time.Minute,
  1105. repoPath, fmt.Sprintf("MirrorUpdate: %s", repoPath),
  1106. "git", "remote", "update", "--prune"); err != nil {
  1107. desc := fmt.Sprintf("Fail to update mirror repository(%s): %s", repoPath, stderr)
  1108. log.Error(4, desc)
  1109. if err = CreateRepositoryNotice(desc); err != nil {
  1110. log.Error(4, "CreateRepositoryNotice: %v", err)
  1111. }
  1112. return nil
  1113. }
  1114. m.NextUpdate = time.Now().Add(time.Duration(m.Interval) * time.Hour)
  1115. mirrors = append(mirrors, m)
  1116. return nil
  1117. }); err != nil {
  1118. log.Error(4, "MirrorUpdate: %v", err)
  1119. }
  1120. for i := range mirrors {
  1121. if err := UpdateMirror(mirrors[i]); err != nil {
  1122. log.Error(4, "UpdateMirror[%d]: %v", mirrors[i].ID, err)
  1123. }
  1124. }
  1125. }
  1126. // GitFsck calls 'git fsck' to check repository health.
  1127. func GitFsck() {
  1128. if isGitFscking {
  1129. return
  1130. }
  1131. isGitFscking = true
  1132. defer func() { isGitFscking = false }()
  1133. log.Trace("Doing: GitFsck")
  1134. args := append([]string{"fsck"}, setting.Cron.RepoHealthCheck.Args...)
  1135. if err := x.Where("id>0").Iterate(new(Repository),
  1136. func(idx int, bean interface{}) error {
  1137. repo := bean.(*Repository)
  1138. repoPath, err := repo.RepoPath()
  1139. if err != nil {
  1140. return fmt.Errorf("RepoPath: %v", err)
  1141. }
  1142. _, _, err = process.ExecDir(-1, repoPath, "Repository health check", "git", args...)
  1143. if err != nil {
  1144. desc := fmt.Sprintf("Fail to health check repository(%s)", repoPath)
  1145. log.Warn(desc)
  1146. if err = CreateRepositoryNotice(desc); err != nil {
  1147. log.Error(4, "CreateRepositoryNotice: %v", err)
  1148. }
  1149. }
  1150. return nil
  1151. }); err != nil {
  1152. log.Error(4, "GitFsck: %v", err)
  1153. }
  1154. }
  1155. func GitGcRepos() error {
  1156. args := append([]string{"gc"}, setting.Git.GcArgs...)
  1157. return x.Where("id > 0").Iterate(new(Repository),
  1158. func(idx int, bean interface{}) error {
  1159. repo := bean.(*Repository)
  1160. if err := repo.GetOwner(); err != nil {
  1161. return err
  1162. }
  1163. _, stderr, err := process.ExecDir(-1, RepoPath(repo.Owner.Name, repo.Name), "Repository garbage collection", "git", args...)
  1164. if err != nil {
  1165. return fmt.Errorf("%v: %v", err, stderr)
  1166. }
  1167. return nil
  1168. })
  1169. }
  1170. type repoChecker struct {
  1171. querySQL, correctSQL string
  1172. desc string
  1173. }
  1174. func repoStatsCheck(checker *repoChecker) {
  1175. results, err := x.Query(checker.querySQL)
  1176. if err != nil {
  1177. log.Error(4, "Select %s: %v", checker.desc, err)
  1178. return
  1179. }
  1180. for _, result := range results {
  1181. id := com.StrTo(result["id"]).MustInt64()
  1182. log.Trace("Updating %s: %d", checker.desc, id)
  1183. _, err = x.Exec(checker.correctSQL, id, id)
  1184. if err != nil {
  1185. log.Error(4, "Update %s[%d]: %v", checker.desc, id, err)
  1186. }
  1187. }
  1188. }
  1189. func CheckRepoStats() {
  1190. if isCheckingRepos {
  1191. return
  1192. }
  1193. isCheckingRepos = true
  1194. defer func() { isCheckingRepos = false }()
  1195. log.Trace("Doing: CheckRepoStats")
  1196. checkers := []*repoChecker{
  1197. // Repository.NumWatches
  1198. {
  1199. "SELECT repo.id FROM `repository` repo WHERE repo.num_watches!=(SELECT COUNT(*) FROM `watch` WHERE repo_id=repo.id)",
  1200. "UPDATE `repository` SET num_watches=(SELECT COUNT(*) FROM `watch` WHERE repo_id=?) WHERE id=?",
  1201. "repository count 'num_watches'",
  1202. },
  1203. // Repository.NumStars
  1204. {
  1205. "SELECT repo.id FROM `repository` repo WHERE repo.num_stars!=(SELECT COUNT(*) FROM `star` WHERE repo_id=repo.id)",
  1206. "UPDATE `repository` SET num_stars=(SELECT COUNT(*) FROM `star` WHERE repo_id=?) WHERE id=?",
  1207. "repository count 'num_stars'",
  1208. },
  1209. // Label.NumIssues
  1210. {
  1211. "SELECT label.id FROM `label` WHERE label.num_issues!=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=label.id)",
  1212. "UPDATE `label` SET num_issues=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=?) WHERE id=?",
  1213. "label count 'num_issues'",
  1214. },
  1215. // User.NumRepos
  1216. {
  1217. "SELECT `user`.id FROM `user` WHERE `user`.num_repos!=(SELECT COUNT(*) FROM `repository` WHERE owner_id=`user`.id)",
  1218. "UPDATE `user` SET num_repos=(SELECT COUNT(*) FROM `repository` WHERE owner_id=?) WHERE id=?",
  1219. "user count 'num_repos'",
  1220. },
  1221. }
  1222. for i := range checkers {
  1223. repoStatsCheck(checkers[i])
  1224. }
  1225. // FIXME: use checker when v0.8, stop supporting old fork repo format.
  1226. // ***** START: Repository.NumForks *****
  1227. results, err := x.Query("SELECT repo.id FROM `repository` repo WHERE repo.num_forks!=(SELECT COUNT(*) FROM `repository` WHERE fork_id=repo.id)")
  1228. if err != nil {
  1229. log.Error(4, "Select repository count 'num_forks': %v", err)
  1230. } else {
  1231. for _, result := range results {
  1232. id := com.StrTo(result["id"]).MustInt64()
  1233. log.Trace("Updating repository count 'num_forks': %d", id)
  1234. repo, err := GetRepositoryByID(id)
  1235. if err != nil {
  1236. log.Error(4, "GetRepositoryByID[%d]: %v", id, err)
  1237. continue
  1238. }
  1239. rawResult, err := x.Query("SELECT COUNT(*) FROM `repository` WHERE fork_id=?", repo.ID)
  1240. if err != nil {
  1241. log.Error(4, "Select count of forks[%d]: %v", repo.ID, err)
  1242. continue
  1243. }
  1244. repo.NumForks = int(parseCountResult(rawResult))
  1245. if err = UpdateRepository(repo, false); err != nil {
  1246. log.Error(4, "UpdateRepository[%d]: %v", id, err)
  1247. continue
  1248. }
  1249. }
  1250. }
  1251. // ***** END: Repository.NumForks *****
  1252. }
  1253. // _________ .__ .__ ___. __ .__
  1254. // \_ ___ \ ____ | | | | _____ \_ |__ ________________ _/ |_|__| ____ ____
  1255. // / \ \/ / _ \| | | | \__ \ | __ \ / _ \_ __ \__ \\ __\ |/ _ \ / \
  1256. // \ \___( <_> ) |_| |__/ __ \| \_\ ( <_> ) | \// __ \| | | ( <_> ) | \
  1257. // \______ /\____/|____/____(____ /___ /\____/|__| (____ /__| |__|\____/|___| /
  1258. // \/ \/ \/ \/ \/
  1259. // A Collaboration is a relation between an individual and a repository
  1260. type Collaboration struct {
  1261. ID int64 `xorm:"pk autoincr"`
  1262. RepoID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  1263. UserID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  1264. Created time.Time `xorm:"CREATED"`
  1265. }
  1266. // Add collaborator and accompanying access
  1267. func (repo *Repository) AddCollaborator(u *User) error {
  1268. collaboration := &Collaboration{
  1269. RepoID: repo.ID,
  1270. UserID: u.Id,
  1271. }
  1272. has, err := x.Get(collaboration)
  1273. if err != nil {
  1274. return err
  1275. } else if has {
  1276. return nil
  1277. }
  1278. if err = repo.GetOwner(); err != nil {
  1279. return fmt.Errorf("GetOwner: %v", err)
  1280. }
  1281. sess := x.NewSession()
  1282. defer sessionRelease(sess)
  1283. if err = sess.Begin(); err != nil {
  1284. return err
  1285. }
  1286. if _, err = sess.InsertOne(collaboration); err != nil {
  1287. return err
  1288. }
  1289. if repo.Owner.IsOrganization() {
  1290. err = repo.recalculateTeamAccesses(sess, 0)
  1291. } else {
  1292. err = repo.recalculateAccesses(sess)
  1293. }
  1294. if err != nil {
  1295. return fmt.Errorf("recalculateAccesses 'team=%v': %v", repo.Owner.IsOrganization(), err)
  1296. }
  1297. return sess.Commit()
  1298. }
  1299. func (repo *Repository) getCollaborators(e Engine) ([]*User, error) {
  1300. collaborations := make([]*Collaboration, 0)
  1301. if err := e.Find(&collaborations, &Collaboration{RepoID: repo.ID}); err != nil {
  1302. return nil, err
  1303. }
  1304. users := make([]*User, len(collaborations))
  1305. for i, c := range collaborations {
  1306. user, err := getUserByID(e, c.UserID)
  1307. if err != nil {
  1308. return nil, err
  1309. }
  1310. users[i] = user
  1311. }
  1312. return users, nil
  1313. }
  1314. // GetCollaborators returns the collaborators for a repository
  1315. func (repo *Repository) GetCollaborators() ([]*User, error) {
  1316. return repo.getCollaborators(x)
  1317. }
  1318. // Delete collaborator and accompanying access
  1319. func (repo *Repository) DeleteCollaborator(u *User) (err error) {
  1320. collaboration := &Collaboration{
  1321. RepoID: repo.ID,
  1322. UserID: u.Id,
  1323. }
  1324. sess := x.NewSession()
  1325. defer sessionRelease(sess)
  1326. if err = sess.Begin(); err != nil {
  1327. return err
  1328. }
  1329. if has, err := sess.Delete(collaboration); err != nil || has == 0 {
  1330. return err
  1331. } else if err = repo.recalculateAccesses(sess); err != nil {
  1332. return err
  1333. }
  1334. return sess.Commit()
  1335. }
  1336. // __ __ __ .__
  1337. // / \ / \_____ _/ |_ ____ | |__
  1338. // \ \/\/ /\__ \\ __\/ ___\| | \
  1339. // \ / / __ \| | \ \___| Y \
  1340. // \__/\ / (____ /__| \___ >___| /
  1341. // \/ \/ \/ \/
  1342. // Watch is connection request for receiving repository notification.
  1343. type Watch struct {
  1344. ID int64 `xorm:"pk autoincr"`
  1345. UserID int64 `xorm:"UNIQUE(watch)"`
  1346. RepoID int64 `xorm:"UNIQUE(watch)"`
  1347. }
  1348. // IsWatching checks if user has watched given repository.
  1349. func IsWatching(uid, repoId int64) bool {
  1350. has, _ := x.Get(&Watch{0, uid, repoId})
  1351. return has
  1352. }
  1353. func watchRepo(e Engine, uid, repoId int64, watch bool) (err error) {
  1354. if watch {
  1355. if IsWatching(uid, repoId) {
  1356. return nil
  1357. }
  1358. if _, err = e.Insert(&Watch{RepoID: repoId, UserID: uid}); err != nil {
  1359. return err
  1360. }
  1361. _, err = e.Exec("UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?", repoId)
  1362. } else {
  1363. if !IsWatching(uid, repoId) {
  1364. return nil
  1365. }
  1366. if _, err = e.Delete(&Watch{0, uid, repoId}); err != nil {
  1367. return err
  1368. }
  1369. _, err = e.Exec("UPDATE `repository` SET num_watches=num_watches-1 WHERE id=?", repoId)
  1370. }
  1371. return err
  1372. }
  1373. // Watch or unwatch repository.
  1374. func WatchRepo(uid, repoId int64, watch bool) (err error) {
  1375. return watchRepo(x, uid, repoId, watch)
  1376. }
  1377. func getWatchers(e Engine, rid int64) ([]*Watch, error) {
  1378. watches := make([]*Watch, 0, 10)
  1379. err := e.Find(&watches, &Watch{RepoID: rid})
  1380. return watches, err
  1381. }
  1382. // GetWatchers returns all watchers of given repository.
  1383. func GetWatchers(rid int64) ([]*Watch, error) {
  1384. return getWatchers(x, rid)
  1385. }
  1386. func notifyWatchers(e Engine, act *Action) error {
  1387. // Add feeds for user self and all watchers.
  1388. watches, err := getWatchers(e, act.RepoID)
  1389. if err != nil {
  1390. return fmt.Errorf("get watchers: %v", err)
  1391. }
  1392. // Add feed for actioner.
  1393. act.UserID = act.ActUserID
  1394. if _, err = e.InsertOne(act); err != nil {
  1395. return fmt.Errorf("insert new actioner: %v", err)
  1396. }
  1397. for i := range watches {
  1398. if act.ActUserID == watches[i].UserID {
  1399. continue
  1400. }
  1401. act.ID = 0
  1402. act.UserID = watches[i].UserID
  1403. if _, err = e.InsertOne(act); err != nil {
  1404. return fmt.Errorf("insert new action: %v", err)
  1405. }
  1406. }
  1407. return nil
  1408. }
  1409. // NotifyWatchers creates batch of actions for every watcher.
  1410. func NotifyWatchers(act *Action) error {
  1411. return notifyWatchers(x, act)
  1412. }
  1413. // _________ __
  1414. // / _____// |______ _______
  1415. // \_____ \\ __\__ \\_ __ \
  1416. // / \| | / __ \| | \/
  1417. // /_______ /|__| (____ /__|
  1418. // \/ \/
  1419. type Star struct {
  1420. ID int64 `xorm:"pk autoincr"`
  1421. UID int64 `xorm:"uid UNIQUE(s)"`
  1422. RepoID int64 `xorm:"UNIQUE(s)"`
  1423. }
  1424. // Star or unstar repository.
  1425. func StarRepo(uid, repoId int64, star bool) (err error) {
  1426. if star {
  1427. if IsStaring(uid, repoId) {
  1428. return nil
  1429. }
  1430. if _, err = x.Insert(&Star{UID: uid, RepoID: repoId}); err != nil {
  1431. return err
  1432. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars + 1 WHERE id = ?", repoId); err != nil {
  1433. return err
  1434. }
  1435. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars + 1 WHERE id = ?", uid)
  1436. } else {
  1437. if !IsStaring(uid, repoId) {
  1438. return nil
  1439. }
  1440. if _, err = x.Delete(&Star{0, uid, repoId}); err != nil {
  1441. return err
  1442. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars - 1 WHERE id = ?", repoId); err != nil {
  1443. return err
  1444. }
  1445. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars - 1 WHERE id = ?", uid)
  1446. }
  1447. return err
  1448. }
  1449. // IsStaring checks if user has starred given repository.
  1450. func IsStaring(uid, repoId int64) bool {
  1451. has, _ := x.Get(&Star{0, uid, repoId})
  1452. return has
  1453. }
  1454. // ___________ __
  1455. // \_ _____/__________| | __
  1456. // | __)/ _ \_ __ \ |/ /
  1457. // | \( <_> ) | \/ <
  1458. // \___ / \____/|__| |__|_ \
  1459. // \/ \/
  1460. // HasForkedRepo checks if given user has already forked a repository with given ID.
  1461. func HasForkedRepo(ownerID, repoID int64) (*Repository, bool) {
  1462. repo := new(Repository)
  1463. has, _ := x.Where("owner_id=? AND fork_id=?", ownerID, repoID).Get(repo)
  1464. return repo, has
  1465. }
  1466. func ForkRepository(u *User, oldRepo *Repository, name, desc string) (_ *Repository, err error) {
  1467. repo := &Repository{
  1468. OwnerID: u.Id,
  1469. Owner: u,
  1470. Name: name,
  1471. LowerName: strings.ToLower(name),
  1472. Description: desc,
  1473. DefaultBranch: oldRepo.DefaultBranch,
  1474. IsPrivate: oldRepo.IsPrivate,
  1475. IsFork: true,
  1476. ForkID: oldRepo.ID,
  1477. }
  1478. sess := x.NewSession()
  1479. defer sessionRelease(sess)
  1480. if err = sess.Begin(); err != nil {
  1481. return nil, err
  1482. }
  1483. if err = createRepository(sess, u, repo); err != nil {
  1484. return nil, err
  1485. }
  1486. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks+1 WHERE id=?", oldRepo.ID); err != nil {
  1487. return nil, err
  1488. }
  1489. oldRepoPath, err := oldRepo.RepoPath()
  1490. if err != nil {
  1491. return nil, fmt.Errorf("get old repository path: %v", err)
  1492. }
  1493. repoPath := RepoPath(u.Name, repo.Name)
  1494. _, stderr, err := process.ExecTimeout(10*time.Minute,
  1495. fmt.Sprintf("ForkRepository(git clone): %s/%s", u.Name, repo.Name),
  1496. "git", "clone", "--bare", oldRepoPath, repoPath)
  1497. if err != nil {
  1498. return nil, fmt.Errorf("git clone: %v", stderr)
  1499. }
  1500. _, stderr, err = process.ExecDir(-1,
  1501. repoPath, fmt.Sprintf("ForkRepository(git update-server-info): %s", repoPath),
  1502. "git", "update-server-info")
  1503. if err != nil {
  1504. return nil, fmt.Errorf("git update-server-info: %v", err)
  1505. }
  1506. if err = createUpdateHook(repoPath); err != nil {
  1507. return nil, fmt.Errorf("createUpdateHook: %v", err)
  1508. }
  1509. return repo, sess.Commit()
  1510. }