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