repo.go 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520
  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 db
  5. import (
  6. "bytes"
  7. "fmt"
  8. "image"
  9. _ "image/jpeg"
  10. "image/png"
  11. "io/ioutil"
  12. "os"
  13. "os/exec"
  14. "path"
  15. "path/filepath"
  16. "sort"
  17. "strings"
  18. "time"
  19. "github.com/mcuadros/go-version"
  20. "github.com/nfnt/resize"
  21. "github.com/unknwon/cae/zip"
  22. "github.com/unknwon/com"
  23. "gopkg.in/ini.v1"
  24. log "unknwon.dev/clog/v2"
  25. "xorm.io/xorm"
  26. "github.com/gogs/git-module"
  27. api "github.com/gogs/go-gogs-client"
  28. "gogs.io/gogs/internal/avatar"
  29. "gogs.io/gogs/internal/conf"
  30. "gogs.io/gogs/internal/db/errors"
  31. "gogs.io/gogs/internal/errutil"
  32. "gogs.io/gogs/internal/markup"
  33. "gogs.io/gogs/internal/osutil"
  34. "gogs.io/gogs/internal/process"
  35. "gogs.io/gogs/internal/sync"
  36. )
  37. // REPO_AVATAR_URL_PREFIX is used to identify a URL is to access repository avatar.
  38. const REPO_AVATAR_URL_PREFIX = "repo-avatars"
  39. var repoWorkingPool = sync.NewExclusivePool()
  40. var (
  41. Gitignores, Licenses, Readmes, LabelTemplates []string
  42. // Maximum items per page in forks, watchers and stars of a repo
  43. ItemsPerPage = 40
  44. )
  45. func LoadRepoConfig() {
  46. // Load .gitignore and license files and readme templates.
  47. types := []string{"gitignore", "license", "readme", "label"}
  48. typeFiles := make([][]string, 4)
  49. for i, t := range types {
  50. files, err := conf.AssetDir("conf/" + t)
  51. if err != nil {
  52. log.Fatal("Failed to get %s files: %v", t, err)
  53. }
  54. customPath := filepath.Join(conf.CustomDir(), "conf", t)
  55. if com.IsDir(customPath) {
  56. customFiles, err := com.StatDir(customPath)
  57. if err != nil {
  58. log.Fatal("Failed to get custom %s files: %v", t, err)
  59. }
  60. for _, f := range customFiles {
  61. if !com.IsSliceContainsStr(files, f) {
  62. files = append(files, f)
  63. }
  64. }
  65. }
  66. typeFiles[i] = files
  67. }
  68. Gitignores = typeFiles[0]
  69. Licenses = typeFiles[1]
  70. Readmes = typeFiles[2]
  71. LabelTemplates = typeFiles[3]
  72. sort.Strings(Gitignores)
  73. sort.Strings(Licenses)
  74. sort.Strings(Readmes)
  75. sort.Strings(LabelTemplates)
  76. // Filter out invalid names and promote preferred licenses.
  77. sortedLicenses := make([]string, 0, len(Licenses))
  78. for _, name := range conf.Repository.PreferredLicenses {
  79. if com.IsSliceContainsStr(Licenses, name) {
  80. sortedLicenses = append(sortedLicenses, name)
  81. }
  82. }
  83. for _, name := range Licenses {
  84. if !com.IsSliceContainsStr(conf.Repository.PreferredLicenses, name) {
  85. sortedLicenses = append(sortedLicenses, name)
  86. }
  87. }
  88. Licenses = sortedLicenses
  89. }
  90. func NewRepoContext() {
  91. zip.Verbose = false
  92. // Check Git installation.
  93. if _, err := exec.LookPath("git"); err != nil {
  94. log.Fatal("Failed to test 'git' command: %v (forgotten install?)", err)
  95. }
  96. // Check Git version.
  97. var err error
  98. conf.Git.Version, err = git.BinVersion()
  99. if err != nil {
  100. log.Fatal("Failed to get Git version: %v", err)
  101. }
  102. log.Trace("Git version: %s", conf.Git.Version)
  103. if version.Compare("1.8.3", conf.Git.Version, ">") {
  104. log.Fatal("Gogs requires Git version greater or equal to 1.8.3")
  105. }
  106. // Git requires setting user.name and user.email in order to commit changes.
  107. for configKey, defaultValue := range map[string]string{"user.name": "Gogs", "user.email": "gogs@fake.local"} {
  108. if stdout, stderr, err := process.Exec("NewRepoContext(get setting)", "git", "config", "--get", configKey); err != nil || strings.TrimSpace(stdout) == "" {
  109. // ExitError indicates this config is not set
  110. if _, ok := err.(*exec.ExitError); ok || strings.TrimSpace(stdout) == "" {
  111. if _, stderr, gerr := process.Exec("NewRepoContext(set "+configKey+")", "git", "config", "--global", configKey, defaultValue); gerr != nil {
  112. log.Fatal("Failed to set git %s(%s): %s", configKey, gerr, stderr)
  113. }
  114. log.Info("Git config %s set to %s", configKey, defaultValue)
  115. } else {
  116. log.Fatal("Failed to get git %s(%s): %s", configKey, err, stderr)
  117. }
  118. }
  119. }
  120. // Set git some configurations.
  121. if _, stderr, err := process.Exec("NewRepoContext(git config --global core.quotepath false)",
  122. "git", "config", "--global", "core.quotepath", "false"); err != nil {
  123. log.Fatal("Failed to execute 'git config --global core.quotepath false': %v - %s", err, stderr)
  124. }
  125. RemoveAllWithNotice("Clean up repository temporary data", filepath.Join(conf.Server.AppDataPath, "tmp"))
  126. }
  127. // Repository contains information of a repository.
  128. type Repository struct {
  129. ID int64
  130. OwnerID int64 `xorm:"UNIQUE(s)"`
  131. Owner *User `xorm:"-" json:"-"`
  132. LowerName string `xorm:"UNIQUE(s) INDEX NOT NULL"`
  133. Name string `xorm:"INDEX NOT NULL"`
  134. Description string `xorm:"VARCHAR(512)"`
  135. Website string
  136. DefaultBranch string
  137. Size int64 `xorm:"NOT NULL DEFAULT 0"`
  138. UseCustomAvatar bool
  139. // Counters
  140. NumWatches int
  141. NumStars int
  142. NumForks int
  143. NumIssues int
  144. NumClosedIssues int
  145. NumOpenIssues int `xorm:"-" json:"-"`
  146. NumPulls int
  147. NumClosedPulls int
  148. NumOpenPulls int `xorm:"-" json:"-"`
  149. NumMilestones int `xorm:"NOT NULL DEFAULT 0"`
  150. NumClosedMilestones int `xorm:"NOT NULL DEFAULT 0"`
  151. NumOpenMilestones int `xorm:"-" json:"-"`
  152. NumTags int `xorm:"-" json:"-"`
  153. IsPrivate bool
  154. IsBare bool
  155. IsMirror bool
  156. *Mirror `xorm:"-" json:"-"`
  157. // Advanced settings
  158. EnableWiki bool `xorm:"NOT NULL DEFAULT true"`
  159. AllowPublicWiki bool
  160. EnableExternalWiki bool
  161. ExternalWikiURL string
  162. EnableIssues bool `xorm:"NOT NULL DEFAULT true"`
  163. AllowPublicIssues bool
  164. EnableExternalTracker bool
  165. ExternalTrackerURL string
  166. ExternalTrackerFormat string
  167. ExternalTrackerStyle string
  168. ExternalMetas map[string]string `xorm:"-" json:"-"`
  169. EnablePulls bool `xorm:"NOT NULL DEFAULT true"`
  170. PullsIgnoreWhitespace bool `xorm:"NOT NULL DEFAULT false"`
  171. PullsAllowRebase bool `xorm:"NOT NULL DEFAULT false"`
  172. IsFork bool `xorm:"NOT NULL DEFAULT false"`
  173. ForkID int64
  174. BaseRepo *Repository `xorm:"-" json:"-"`
  175. Created time.Time `xorm:"-" json:"-"`
  176. CreatedUnix int64
  177. Updated time.Time `xorm:"-" json:"-"`
  178. UpdatedUnix int64
  179. }
  180. func (repo *Repository) BeforeInsert() {
  181. repo.CreatedUnix = time.Now().Unix()
  182. repo.UpdatedUnix = repo.CreatedUnix
  183. }
  184. func (repo *Repository) BeforeUpdate() {
  185. repo.UpdatedUnix = time.Now().Unix()
  186. }
  187. func (repo *Repository) AfterSet(colName string, _ xorm.Cell) {
  188. switch colName {
  189. case "default_branch":
  190. // FIXME: use db migration to solve all at once.
  191. if len(repo.DefaultBranch) == 0 {
  192. repo.DefaultBranch = "master"
  193. }
  194. case "num_closed_issues":
  195. repo.NumOpenIssues = repo.NumIssues - repo.NumClosedIssues
  196. case "num_closed_pulls":
  197. repo.NumOpenPulls = repo.NumPulls - repo.NumClosedPulls
  198. case "num_closed_milestones":
  199. repo.NumOpenMilestones = repo.NumMilestones - repo.NumClosedMilestones
  200. case "external_tracker_style":
  201. if len(repo.ExternalTrackerStyle) == 0 {
  202. repo.ExternalTrackerStyle = markup.ISSUE_NAME_STYLE_NUMERIC
  203. }
  204. case "created_unix":
  205. repo.Created = time.Unix(repo.CreatedUnix, 0).Local()
  206. case "updated_unix":
  207. repo.Updated = time.Unix(repo.UpdatedUnix, 0)
  208. }
  209. }
  210. func (repo *Repository) loadAttributes(e Engine) (err error) {
  211. if repo.Owner == nil {
  212. repo.Owner, err = getUserByID(e, repo.OwnerID)
  213. if err != nil {
  214. return fmt.Errorf("getUserByID [%d]: %v", repo.OwnerID, err)
  215. }
  216. }
  217. if repo.IsFork && repo.BaseRepo == nil {
  218. repo.BaseRepo, err = getRepositoryByID(e, repo.ForkID)
  219. if err != nil {
  220. if IsErrRepoNotExist(err) {
  221. repo.IsFork = false
  222. repo.ForkID = 0
  223. } else {
  224. return fmt.Errorf("get fork repository by ID: %v", err)
  225. }
  226. }
  227. }
  228. return nil
  229. }
  230. func (repo *Repository) LoadAttributes() error {
  231. return repo.loadAttributes(x)
  232. }
  233. // IsPartialPublic returns true if repository is public or allow public access to wiki or issues.
  234. func (repo *Repository) IsPartialPublic() bool {
  235. return !repo.IsPrivate || repo.AllowPublicWiki || repo.AllowPublicIssues
  236. }
  237. func (repo *Repository) CanGuestViewWiki() bool {
  238. return repo.EnableWiki && !repo.EnableExternalWiki && repo.AllowPublicWiki
  239. }
  240. func (repo *Repository) CanGuestViewIssues() bool {
  241. return repo.EnableIssues && !repo.EnableExternalTracker && repo.AllowPublicIssues
  242. }
  243. // MustOwner always returns a valid *User object to avoid conceptually impossible error handling.
  244. // It creates a fake object that contains error deftail when error occurs.
  245. func (repo *Repository) MustOwner() *User {
  246. return repo.mustOwner(x)
  247. }
  248. func (repo *Repository) FullName() string {
  249. return repo.MustOwner().Name + "/" + repo.Name
  250. }
  251. func (repo *Repository) HTMLURL() string {
  252. return conf.Server.ExternalURL + repo.FullName()
  253. }
  254. // CustomAvatarPath returns repository custom avatar file path.
  255. func (repo *Repository) CustomAvatarPath() string {
  256. return filepath.Join(conf.Picture.RepositoryAvatarUploadPath, com.ToStr(repo.ID))
  257. }
  258. // RelAvatarLink returns relative avatar link to the site domain,
  259. // which includes app sub-url as prefix.
  260. // Since Gravatar support not needed here - just check for image path.
  261. func (repo *Repository) RelAvatarLink() string {
  262. defaultImgUrl := ""
  263. if !com.IsExist(repo.CustomAvatarPath()) {
  264. return defaultImgUrl
  265. }
  266. return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, REPO_AVATAR_URL_PREFIX, repo.ID)
  267. }
  268. // AvatarLink returns repository avatar absolute link.
  269. func (repo *Repository) AvatarLink() string {
  270. link := repo.RelAvatarLink()
  271. if link[0] == '/' && link[1] != '/' {
  272. return conf.Server.ExternalURL + strings.TrimPrefix(link, conf.Server.Subpath)[1:]
  273. }
  274. return link
  275. }
  276. // UploadAvatar saves custom avatar for repository.
  277. // FIXME: split uploads to different subdirs in case we have massive number of repositories.
  278. func (repo *Repository) UploadAvatar(data []byte) error {
  279. img, _, err := image.Decode(bytes.NewReader(data))
  280. if err != nil {
  281. return fmt.Errorf("decode image: %v", err)
  282. }
  283. _ = os.MkdirAll(conf.Picture.RepositoryAvatarUploadPath, os.ModePerm)
  284. fw, err := os.Create(repo.CustomAvatarPath())
  285. if err != nil {
  286. return fmt.Errorf("create custom avatar directory: %v", err)
  287. }
  288. defer fw.Close()
  289. m := resize.Resize(avatar.AVATAR_SIZE, avatar.AVATAR_SIZE, img, resize.NearestNeighbor)
  290. if err = png.Encode(fw, m); err != nil {
  291. return fmt.Errorf("encode image: %v", err)
  292. }
  293. return nil
  294. }
  295. // DeleteAvatar deletes the repository custom avatar.
  296. func (repo *Repository) DeleteAvatar() error {
  297. log.Trace("DeleteAvatar [%d]: %s", repo.ID, repo.CustomAvatarPath())
  298. if err := os.Remove(repo.CustomAvatarPath()); err != nil {
  299. return err
  300. }
  301. repo.UseCustomAvatar = false
  302. return UpdateRepository(repo, false)
  303. }
  304. // This method assumes following fields have been assigned with valid values:
  305. // Required - BaseRepo (if fork)
  306. // Arguments that are allowed to be nil: permission
  307. func (repo *Repository) APIFormat(permission *api.Permission, user ...*User) *api.Repository {
  308. cloneLink := repo.CloneLink()
  309. apiRepo := &api.Repository{
  310. ID: repo.ID,
  311. Owner: repo.Owner.APIFormat(),
  312. Name: repo.Name,
  313. FullName: repo.FullName(),
  314. Description: repo.Description,
  315. Private: repo.IsPrivate,
  316. Fork: repo.IsFork,
  317. Empty: repo.IsBare,
  318. Mirror: repo.IsMirror,
  319. Size: repo.Size,
  320. HTMLURL: repo.HTMLURL(),
  321. SSHURL: cloneLink.SSH,
  322. CloneURL: cloneLink.HTTPS,
  323. Website: repo.Website,
  324. Stars: repo.NumStars,
  325. Forks: repo.NumForks,
  326. Watchers: repo.NumWatches,
  327. OpenIssues: repo.NumOpenIssues,
  328. DefaultBranch: repo.DefaultBranch,
  329. Created: repo.Created,
  330. Updated: repo.Updated,
  331. Permissions: permission,
  332. // Reserved for go-gogs-client change
  333. // AvatarUrl: repo.AvatarLink(),
  334. }
  335. if repo.IsFork {
  336. p := &api.Permission{Pull: true}
  337. if len(user) != 0 {
  338. p.Admin = user[0].IsAdminOfRepo(repo)
  339. p.Push = user[0].IsWriterOfRepo(repo)
  340. }
  341. apiRepo.Parent = repo.BaseRepo.APIFormat(p)
  342. }
  343. return apiRepo
  344. }
  345. func (repo *Repository) getOwner(e Engine) (err error) {
  346. if repo.Owner != nil {
  347. return nil
  348. }
  349. repo.Owner, err = getUserByID(e, repo.OwnerID)
  350. return err
  351. }
  352. func (repo *Repository) GetOwner() error {
  353. return repo.getOwner(x)
  354. }
  355. func (repo *Repository) mustOwner(e Engine) *User {
  356. if err := repo.getOwner(e); err != nil {
  357. return &User{
  358. Name: "error",
  359. FullName: err.Error(),
  360. }
  361. }
  362. return repo.Owner
  363. }
  364. func (repo *Repository) UpdateSize() error {
  365. countObject, err := git.RepoCountObjects(repo.RepoPath())
  366. if err != nil {
  367. return fmt.Errorf("count repository objects: %v", err)
  368. }
  369. repo.Size = countObject.Size + countObject.SizePack
  370. if _, err = x.Id(repo.ID).Cols("size").Update(repo); err != nil {
  371. return fmt.Errorf("update size: %v", err)
  372. }
  373. return nil
  374. }
  375. // ComposeMetas composes a map of metas for rendering external issue tracker URL.
  376. func (repo *Repository) ComposeMetas() map[string]string {
  377. if !repo.EnableExternalTracker {
  378. return nil
  379. } else if repo.ExternalMetas == nil {
  380. repo.ExternalMetas = map[string]string{
  381. "format": repo.ExternalTrackerFormat,
  382. "user": repo.MustOwner().Name,
  383. "repo": repo.Name,
  384. }
  385. switch repo.ExternalTrackerStyle {
  386. case markup.ISSUE_NAME_STYLE_ALPHANUMERIC:
  387. repo.ExternalMetas["style"] = markup.ISSUE_NAME_STYLE_ALPHANUMERIC
  388. default:
  389. repo.ExternalMetas["style"] = markup.ISSUE_NAME_STYLE_NUMERIC
  390. }
  391. }
  392. return repo.ExternalMetas
  393. }
  394. // DeleteWiki removes the actual and local copy of repository wiki.
  395. func (repo *Repository) DeleteWiki() {
  396. wikiPaths := []string{repo.WikiPath(), repo.LocalWikiPath()}
  397. for _, wikiPath := range wikiPaths {
  398. RemoveAllWithNotice("Delete repository wiki", wikiPath)
  399. }
  400. }
  401. // getUsersWithAccesMode returns users that have at least given access mode to the repository.
  402. func (repo *Repository) getUsersWithAccesMode(e Engine, mode AccessMode) (_ []*User, err error) {
  403. if err = repo.getOwner(e); err != nil {
  404. return nil, err
  405. }
  406. accesses := make([]*Access, 0, 10)
  407. if err = e.Where("repo_id = ? AND mode >= ?", repo.ID, mode).Find(&accesses); err != nil {
  408. return nil, err
  409. }
  410. // Leave a seat for owner itself to append later, but if owner is an organization
  411. // and just waste 1 unit is cheaper than re-allocate memory once.
  412. users := make([]*User, 0, len(accesses)+1)
  413. if len(accesses) > 0 {
  414. userIDs := make([]int64, len(accesses))
  415. for i := 0; i < len(accesses); i++ {
  416. userIDs[i] = accesses[i].UserID
  417. }
  418. if err = e.In("id", userIDs).Find(&users); err != nil {
  419. return nil, err
  420. }
  421. }
  422. if !repo.Owner.IsOrganization() {
  423. users = append(users, repo.Owner)
  424. }
  425. return users, nil
  426. }
  427. // getAssignees returns a list of users who can be assigned to issues in this repository.
  428. func (repo *Repository) getAssignees(e Engine) (_ []*User, err error) {
  429. return repo.getUsersWithAccesMode(e, AccessModeRead)
  430. }
  431. // GetAssignees returns all users that have read access and can be assigned to issues
  432. // of the repository,
  433. func (repo *Repository) GetAssignees() (_ []*User, err error) {
  434. return repo.getAssignees(x)
  435. }
  436. // GetAssigneeByID returns the user that has write access of repository by given ID.
  437. func (repo *Repository) GetAssigneeByID(userID int64) (*User, error) {
  438. return GetAssigneeByID(repo, userID)
  439. }
  440. // GetWriters returns all users that have write access to the repository.
  441. func (repo *Repository) GetWriters() (_ []*User, err error) {
  442. return repo.getUsersWithAccesMode(x, AccessModeWrite)
  443. }
  444. // GetMilestoneByID returns the milestone belongs to repository by given ID.
  445. func (repo *Repository) GetMilestoneByID(milestoneID int64) (*Milestone, error) {
  446. return GetMilestoneByRepoID(repo.ID, milestoneID)
  447. }
  448. // IssueStats returns number of open and closed repository issues by given filter mode.
  449. func (repo *Repository) IssueStats(userID int64, filterMode FilterMode, isPull bool) (int64, int64) {
  450. return GetRepoIssueStats(repo.ID, userID, filterMode, isPull)
  451. }
  452. func (repo *Repository) GetMirror() (err error) {
  453. repo.Mirror, err = GetMirrorByRepoID(repo.ID)
  454. return err
  455. }
  456. func (repo *Repository) repoPath(e Engine) string {
  457. return RepoPath(repo.mustOwner(e).Name, repo.Name)
  458. }
  459. func (repo *Repository) RepoPath() string {
  460. return repo.repoPath(x)
  461. }
  462. func (repo *Repository) GitConfigPath() string {
  463. return filepath.Join(repo.RepoPath(), "config")
  464. }
  465. func (repo *Repository) RelLink() string {
  466. return "/" + repo.FullName()
  467. }
  468. func (repo *Repository) Link() string {
  469. return conf.Server.Subpath + "/" + repo.FullName()
  470. }
  471. func (repo *Repository) ComposeCompareURL(oldCommitID, newCommitID string) string {
  472. return fmt.Sprintf("%s/%s/compare/%s...%s", repo.MustOwner().Name, repo.Name, oldCommitID, newCommitID)
  473. }
  474. func (repo *Repository) HasAccess(userID int64) bool {
  475. has, _ := HasAccess(userID, repo, AccessModeRead)
  476. return has
  477. }
  478. func (repo *Repository) IsOwnedBy(userID int64) bool {
  479. return repo.OwnerID == userID
  480. }
  481. // CanBeForked returns true if repository meets the requirements of being forked.
  482. func (repo *Repository) CanBeForked() bool {
  483. return !repo.IsBare
  484. }
  485. // CanEnablePulls returns true if repository meets the requirements of accepting pulls.
  486. func (repo *Repository) CanEnablePulls() bool {
  487. return !repo.IsMirror && !repo.IsBare
  488. }
  489. // AllowPulls returns true if repository meets the requirements of accepting pulls and has them enabled.
  490. func (repo *Repository) AllowsPulls() bool {
  491. return repo.CanEnablePulls() && repo.EnablePulls
  492. }
  493. func (repo *Repository) IsBranchRequirePullRequest(name string) bool {
  494. return IsBranchOfRepoRequirePullRequest(repo.ID, name)
  495. }
  496. // CanEnableEditor returns true if repository meets the requirements of web editor.
  497. func (repo *Repository) CanEnableEditor() bool {
  498. return !repo.IsMirror
  499. }
  500. // FIXME: should have a mutex to prevent producing same index for two issues that are created
  501. // closely enough.
  502. func (repo *Repository) NextIssueIndex() int64 {
  503. return int64(repo.NumIssues+repo.NumPulls) + 1
  504. }
  505. func (repo *Repository) LocalCopyPath() string {
  506. return filepath.Join(conf.Server.AppDataPath, "tmp", "local-repo", com.ToStr(repo.ID))
  507. }
  508. // UpdateLocalCopy fetches latest changes of given branch from repoPath to localPath.
  509. // It creates a new clone if local copy does not exist, but does not checks out to a
  510. // specific branch if the local copy belongs to a wiki.
  511. // For existing local copy, it checks out to target branch by default, and safe to
  512. // assume subsequent operations are against target branch when caller has confidence
  513. // about no race condition.
  514. func UpdateLocalCopyBranch(repoPath, localPath, branch string, isWiki bool) (err error) {
  515. if !osutil.IsExist(localPath) {
  516. // Checkout to a specific branch fails when wiki is an empty repository.
  517. if isWiki {
  518. branch = ""
  519. }
  520. if err = git.Clone(repoPath, localPath, git.CloneOptions{
  521. Branch: branch,
  522. Timeout: time.Duration(conf.Git.Timeout.Clone) * time.Second,
  523. }); err != nil {
  524. return fmt.Errorf("git clone [branch: %s]: %v", branch, err)
  525. }
  526. return nil
  527. }
  528. gitRepo, err := git.Open(localPath)
  529. if err != nil {
  530. return fmt.Errorf("open repository: %v", err)
  531. }
  532. if err = gitRepo.Fetch(git.FetchOptions{
  533. Prune: true,
  534. }); err != nil {
  535. return fmt.Errorf("fetch: %v", err)
  536. }
  537. if err = gitRepo.Checkout(branch); err != nil {
  538. return fmt.Errorf("checkout [branch: %s]: %v", branch, err)
  539. }
  540. // Reset to align with remote in case of force push.
  541. rev := "origin/" + branch
  542. if err = gitRepo.Reset(rev, git.ResetOptions{
  543. Hard: true,
  544. }); err != nil {
  545. return fmt.Errorf("reset [revision: %s]: %v", rev, err)
  546. }
  547. return nil
  548. }
  549. // UpdateLocalCopyBranch makes sure local copy of repository in given branch is up-to-date.
  550. func (repo *Repository) UpdateLocalCopyBranch(branch string) error {
  551. return UpdateLocalCopyBranch(repo.RepoPath(), repo.LocalCopyPath(), branch, false)
  552. }
  553. // PatchPath returns corresponding patch file path of repository by given issue ID.
  554. func (repo *Repository) PatchPath(index int64) (string, error) {
  555. if err := repo.GetOwner(); err != nil {
  556. return "", err
  557. }
  558. return filepath.Join(RepoPath(repo.Owner.Name, repo.Name), "pulls", com.ToStr(index)+".patch"), nil
  559. }
  560. // SavePatch saves patch data to corresponding location by given issue ID.
  561. func (repo *Repository) SavePatch(index int64, patch []byte) error {
  562. patchPath, err := repo.PatchPath(index)
  563. if err != nil {
  564. return fmt.Errorf("PatchPath: %v", err)
  565. }
  566. if err = os.MkdirAll(filepath.Dir(patchPath), os.ModePerm); err != nil {
  567. return err
  568. }
  569. if err = ioutil.WriteFile(patchPath, patch, 0644); err != nil {
  570. return fmt.Errorf("WriteFile: %v", err)
  571. }
  572. return nil
  573. }
  574. func isRepositoryExist(e Engine, u *User, repoName string) (bool, error) {
  575. has, err := e.Get(&Repository{
  576. OwnerID: u.ID,
  577. LowerName: strings.ToLower(repoName),
  578. })
  579. return has && com.IsDir(RepoPath(u.Name, repoName)), err
  580. }
  581. // IsRepositoryExist returns true if the repository with given name under user has already existed.
  582. func IsRepositoryExist(u *User, repoName string) (bool, error) {
  583. return isRepositoryExist(x, u, repoName)
  584. }
  585. // CloneLink represents different types of clone URLs of repository.
  586. type CloneLink struct {
  587. SSH string
  588. HTTPS string
  589. Git string
  590. }
  591. // ComposeHTTPSCloneURL returns HTTPS clone URL based on given owner and repository name.
  592. func ComposeHTTPSCloneURL(owner, repo string) string {
  593. return fmt.Sprintf("%s%s/%s.git", conf.Server.ExternalURL, owner, repo)
  594. }
  595. func (repo *Repository) cloneLink(isWiki bool) *CloneLink {
  596. repoName := repo.Name
  597. if isWiki {
  598. repoName += ".wiki"
  599. }
  600. repo.Owner = repo.MustOwner()
  601. cl := new(CloneLink)
  602. if conf.SSH.Port != 22 {
  603. cl.SSH = fmt.Sprintf("ssh://%s@%s:%d/%s/%s.git", conf.App.RunUser, conf.SSH.Domain, conf.SSH.Port, repo.Owner.Name, repoName)
  604. } else {
  605. cl.SSH = fmt.Sprintf("%s@%s:%s/%s.git", conf.App.RunUser, conf.SSH.Domain, repo.Owner.Name, repoName)
  606. }
  607. cl.HTTPS = ComposeHTTPSCloneURL(repo.Owner.Name, repoName)
  608. return cl
  609. }
  610. // CloneLink returns clone URLs of repository.
  611. func (repo *Repository) CloneLink() (cl *CloneLink) {
  612. return repo.cloneLink(false)
  613. }
  614. type MigrateRepoOptions struct {
  615. Name string
  616. Description string
  617. IsPrivate bool
  618. IsMirror bool
  619. RemoteAddr string
  620. }
  621. /*
  622. GitHub, GitLab, Gogs: *.wiki.git
  623. BitBucket: *.git/wiki
  624. */
  625. var commonWikiURLSuffixes = []string{".wiki.git", ".git/wiki"}
  626. // wikiRemoteURL returns accessible repository URL for wiki if exists.
  627. // Otherwise, it returns an empty string.
  628. func wikiRemoteURL(remote string) string {
  629. remote = strings.TrimSuffix(remote, ".git")
  630. for _, suffix := range commonWikiURLSuffixes {
  631. wikiURL := remote + suffix
  632. if git.IsURLAccessible(time.Minute, wikiURL) {
  633. return wikiURL
  634. }
  635. }
  636. return ""
  637. }
  638. // MigrateRepository migrates a existing repository from other project hosting.
  639. func MigrateRepository(doer, owner *User, opts MigrateRepoOptions) (*Repository, error) {
  640. repo, err := CreateRepository(doer, owner, CreateRepoOptions{
  641. Name: opts.Name,
  642. Description: opts.Description,
  643. IsPrivate: opts.IsPrivate,
  644. IsMirror: opts.IsMirror,
  645. })
  646. if err != nil {
  647. return nil, err
  648. }
  649. repoPath := RepoPath(owner.Name, opts.Name)
  650. wikiPath := WikiPath(owner.Name, opts.Name)
  651. if owner.IsOrganization() {
  652. t, err := owner.GetOwnerTeam()
  653. if err != nil {
  654. return nil, err
  655. }
  656. repo.NumWatches = t.NumMembers
  657. } else {
  658. repo.NumWatches = 1
  659. }
  660. migrateTimeout := time.Duration(conf.Git.Timeout.Migrate) * time.Second
  661. RemoveAllWithNotice("Repository path erase before creation", repoPath)
  662. if err = git.Clone(opts.RemoteAddr, repoPath, git.CloneOptions{
  663. Mirror: true,
  664. Quiet: true,
  665. Timeout: migrateTimeout,
  666. }); err != nil {
  667. return repo, fmt.Errorf("clone: %v", err)
  668. }
  669. wikiRemotePath := wikiRemoteURL(opts.RemoteAddr)
  670. if len(wikiRemotePath) > 0 {
  671. RemoveAllWithNotice("Repository wiki path erase before creation", wikiPath)
  672. if err = git.Clone(wikiRemotePath, wikiPath, git.CloneOptions{
  673. Mirror: true,
  674. Quiet: true,
  675. Timeout: migrateTimeout,
  676. }); err != nil {
  677. log.Error("Failed to clone wiki: %v", err)
  678. RemoveAllWithNotice("Delete repository wiki for initialization failure", wikiPath)
  679. }
  680. }
  681. // Check if repository is empty.
  682. _, stderr, err := com.ExecCmdDir(repoPath, "git", "log", "-1")
  683. if err != nil {
  684. if strings.Contains(stderr, "fatal: bad default revision 'HEAD'") {
  685. repo.IsBare = true
  686. } else {
  687. return repo, fmt.Errorf("check bare: %v - %s", err, stderr)
  688. }
  689. }
  690. if !repo.IsBare {
  691. // Try to get HEAD branch and set it as default branch.
  692. gitRepo, err := git.Open(repoPath)
  693. if err != nil {
  694. return repo, fmt.Errorf("open repository: %v", err)
  695. }
  696. refspec, err := gitRepo.SymbolicRef()
  697. if err != nil {
  698. return repo, fmt.Errorf("get HEAD branch: %v", err)
  699. }
  700. repo.DefaultBranch = git.RefShortName(refspec)
  701. if err = repo.UpdateSize(); err != nil {
  702. log.Error("UpdateSize [repo_id: %d]: %v", repo.ID, err)
  703. }
  704. }
  705. if opts.IsMirror {
  706. if _, err = x.InsertOne(&Mirror{
  707. RepoID: repo.ID,
  708. Interval: conf.Mirror.DefaultInterval,
  709. EnablePrune: true,
  710. NextSync: time.Now().Add(time.Duration(conf.Mirror.DefaultInterval) * time.Hour),
  711. }); err != nil {
  712. return repo, fmt.Errorf("InsertOne: %v", err)
  713. }
  714. repo.IsMirror = true
  715. return repo, UpdateRepository(repo, false)
  716. }
  717. return CleanUpMigrateInfo(repo)
  718. }
  719. // cleanUpMigrateGitConfig removes mirror info which prevents "push --all".
  720. // This also removes possible user credentials.
  721. func cleanUpMigrateGitConfig(configPath string) error {
  722. cfg, err := ini.Load(configPath)
  723. if err != nil {
  724. return fmt.Errorf("open config file: %v", err)
  725. }
  726. cfg.DeleteSection("remote \"origin\"")
  727. if err = cfg.SaveToIndent(configPath, "\t"); err != nil {
  728. return fmt.Errorf("save config file: %v", err)
  729. }
  730. return nil
  731. }
  732. var hooksTpls = map[git.HookName]string{
  733. "pre-receive": "#!/usr/bin/env %s\n\"%s\" hook --config='%s' pre-receive\n",
  734. "update": "#!/usr/bin/env %s\n\"%s\" hook --config='%s' update $1 $2 $3\n",
  735. "post-receive": "#!/usr/bin/env %s\n\"%s\" hook --config='%s' post-receive\n",
  736. }
  737. func createDelegateHooks(repoPath string) (err error) {
  738. for _, name := range git.ServerSideHooks {
  739. hookPath := filepath.Join(repoPath, "hooks", string(name))
  740. if err = ioutil.WriteFile(hookPath,
  741. []byte(fmt.Sprintf(hooksTpls[name], conf.Repository.ScriptType, conf.AppPath(), conf.CustomConf)),
  742. os.ModePerm); err != nil {
  743. return fmt.Errorf("create delegate hook '%s': %v", hookPath, err)
  744. }
  745. }
  746. return nil
  747. }
  748. // Finish migrating repository and/or wiki with things that don't need to be done for mirrors.
  749. func CleanUpMigrateInfo(repo *Repository) (*Repository, error) {
  750. repoPath := repo.RepoPath()
  751. if err := createDelegateHooks(repoPath); err != nil {
  752. return repo, fmt.Errorf("createDelegateHooks: %v", err)
  753. }
  754. if repo.HasWiki() {
  755. if err := createDelegateHooks(repo.WikiPath()); err != nil {
  756. return repo, fmt.Errorf("createDelegateHooks.(wiki): %v", err)
  757. }
  758. }
  759. if err := cleanUpMigrateGitConfig(repo.GitConfigPath()); err != nil {
  760. return repo, fmt.Errorf("cleanUpMigrateGitConfig: %v", err)
  761. }
  762. if repo.HasWiki() {
  763. if err := cleanUpMigrateGitConfig(path.Join(repo.WikiPath(), "config")); err != nil {
  764. return repo, fmt.Errorf("cleanUpMigrateGitConfig.(wiki): %v", err)
  765. }
  766. }
  767. return repo, UpdateRepository(repo, false)
  768. }
  769. // initRepoCommit temporarily changes with work directory.
  770. func initRepoCommit(tmpPath string, sig *git.Signature) (err error) {
  771. var stderr string
  772. if _, stderr, err = process.ExecDir(-1,
  773. tmpPath, fmt.Sprintf("initRepoCommit (git add): %s", tmpPath),
  774. "git", "add", "--all"); err != nil {
  775. return fmt.Errorf("git add: %s", stderr)
  776. }
  777. if _, stderr, err = process.ExecDir(-1,
  778. tmpPath, fmt.Sprintf("initRepoCommit (git commit): %s", tmpPath),
  779. "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  780. "-m", "Initial commit"); err != nil {
  781. return fmt.Errorf("git commit: %s", stderr)
  782. }
  783. if _, stderr, err = process.ExecDir(-1,
  784. tmpPath, fmt.Sprintf("initRepoCommit (git push): %s", tmpPath),
  785. "git", "push", "origin", "master"); err != nil {
  786. return fmt.Errorf("git push: %s", stderr)
  787. }
  788. return nil
  789. }
  790. type CreateRepoOptions struct {
  791. Name string
  792. Description string
  793. Gitignores string
  794. License string
  795. Readme string
  796. IsPrivate bool
  797. IsMirror bool
  798. AutoInit bool
  799. }
  800. func getRepoInitFile(tp, name string) ([]byte, error) {
  801. relPath := path.Join("conf", tp, strings.TrimLeft(path.Clean("/"+name), "/"))
  802. // Use custom file when available.
  803. customPath := filepath.Join(conf.CustomDir(), relPath)
  804. if osutil.IsFile(customPath) {
  805. return ioutil.ReadFile(customPath)
  806. }
  807. return conf.Asset(relPath)
  808. }
  809. func prepareRepoCommit(repo *Repository, tmpDir, repoPath string, opts CreateRepoOptions) error {
  810. // Clone to temprory path and do the init commit.
  811. _, stderr, err := process.Exec(
  812. fmt.Sprintf("initRepository(git clone): %s", repoPath), "git", "clone", repoPath, tmpDir)
  813. if err != nil {
  814. return fmt.Errorf("git clone: %v - %s", err, stderr)
  815. }
  816. // README
  817. data, err := getRepoInitFile("readme", opts.Readme)
  818. if err != nil {
  819. return fmt.Errorf("getRepoInitFile[%s]: %v", opts.Readme, err)
  820. }
  821. cloneLink := repo.CloneLink()
  822. match := map[string]string{
  823. "Name": repo.Name,
  824. "Description": repo.Description,
  825. "CloneURL.SSH": cloneLink.SSH,
  826. "CloneURL.HTTPS": cloneLink.HTTPS,
  827. }
  828. if err = ioutil.WriteFile(filepath.Join(tmpDir, "README.md"),
  829. []byte(com.Expand(string(data), match)), 0644); err != nil {
  830. return fmt.Errorf("write README.md: %v", err)
  831. }
  832. // .gitignore
  833. if len(opts.Gitignores) > 0 {
  834. var buf bytes.Buffer
  835. names := strings.Split(opts.Gitignores, ",")
  836. for _, name := range names {
  837. data, err = getRepoInitFile("gitignore", name)
  838. if err != nil {
  839. return fmt.Errorf("getRepoInitFile[%s]: %v", name, err)
  840. }
  841. buf.WriteString("# ---> " + name + "\n")
  842. buf.Write(data)
  843. buf.WriteString("\n")
  844. }
  845. if buf.Len() > 0 {
  846. if err = ioutil.WriteFile(filepath.Join(tmpDir, ".gitignore"), buf.Bytes(), 0644); err != nil {
  847. return fmt.Errorf("write .gitignore: %v", err)
  848. }
  849. }
  850. }
  851. // LICENSE
  852. if len(opts.License) > 0 {
  853. data, err = getRepoInitFile("license", opts.License)
  854. if err != nil {
  855. return fmt.Errorf("getRepoInitFile[%s]: %v", opts.License, err)
  856. }
  857. if err = ioutil.WriteFile(filepath.Join(tmpDir, "LICENSE"), data, 0644); err != nil {
  858. return fmt.Errorf("write LICENSE: %v", err)
  859. }
  860. }
  861. return nil
  862. }
  863. // initRepository performs initial commit with chosen setup files on behave of doer.
  864. func initRepository(e Engine, repoPath string, doer *User, repo *Repository, opts CreateRepoOptions) (err error) {
  865. // Somehow the directory could exist.
  866. if com.IsExist(repoPath) {
  867. return fmt.Errorf("initRepository: path already exists: %s", repoPath)
  868. }
  869. // Init bare new repository.
  870. if err = git.Init(repoPath, git.InitOptions{Bare: true}); err != nil {
  871. return fmt.Errorf("init repository: %v", err)
  872. } else if err = createDelegateHooks(repoPath); err != nil {
  873. return fmt.Errorf("createDelegateHooks: %v", err)
  874. }
  875. tmpDir := filepath.Join(os.TempDir(), "gogs-"+repo.Name+"-"+com.ToStr(time.Now().Nanosecond()))
  876. // Initialize repository according to user's choice.
  877. if opts.AutoInit {
  878. if err = os.MkdirAll(tmpDir, os.ModePerm); err != nil {
  879. return err
  880. }
  881. defer RemoveAllWithNotice("Delete repository for auto-initialization", tmpDir)
  882. if err = prepareRepoCommit(repo, tmpDir, repoPath, opts); err != nil {
  883. return fmt.Errorf("prepareRepoCommit: %v", err)
  884. }
  885. // Apply changes and commit.
  886. if err = initRepoCommit(tmpDir, doer.NewGitSig()); err != nil {
  887. return fmt.Errorf("initRepoCommit: %v", err)
  888. }
  889. }
  890. // Re-fetch the repository from database before updating it (else it would
  891. // override changes that were done earlier with sql)
  892. if repo, err = getRepositoryByID(e, repo.ID); err != nil {
  893. return fmt.Errorf("getRepositoryByID: %v", err)
  894. }
  895. if !opts.AutoInit {
  896. repo.IsBare = true
  897. }
  898. repo.DefaultBranch = "master"
  899. if err = updateRepository(e, repo, false); err != nil {
  900. return fmt.Errorf("updateRepository: %v", err)
  901. }
  902. return nil
  903. }
  904. var (
  905. reservedRepoNames = []string{".", ".."}
  906. reservedRepoPatterns = []string{"*.git", "*.wiki"}
  907. )
  908. // IsUsableRepoName return an error if given name is a reserved name or pattern.
  909. func IsUsableRepoName(name string) error {
  910. return isUsableName(reservedRepoNames, reservedRepoPatterns, name)
  911. }
  912. func createRepository(e *xorm.Session, doer, owner *User, repo *Repository) (err error) {
  913. if err = IsUsableRepoName(repo.Name); err != nil {
  914. return err
  915. }
  916. has, err := isRepositoryExist(e, owner, repo.Name)
  917. if err != nil {
  918. return fmt.Errorf("IsRepositoryExist: %v", err)
  919. } else if has {
  920. return ErrRepoAlreadyExist{owner.Name, repo.Name}
  921. }
  922. if _, err = e.Insert(repo); err != nil {
  923. return err
  924. }
  925. owner.NumRepos++
  926. // Remember visibility preference.
  927. owner.LastRepoVisibility = repo.IsPrivate
  928. if err = updateUser(e, owner); err != nil {
  929. return fmt.Errorf("updateUser: %v", err)
  930. }
  931. // Give access to all members in owner team.
  932. if owner.IsOrganization() {
  933. t, err := owner.getOwnerTeam(e)
  934. if err != nil {
  935. return fmt.Errorf("getOwnerTeam: %v", err)
  936. } else if err = t.addRepository(e, repo); err != nil {
  937. return fmt.Errorf("addRepository: %v", err)
  938. }
  939. } else {
  940. // Organization automatically called this in addRepository method.
  941. if err = repo.recalculateAccesses(e); err != nil {
  942. return fmt.Errorf("recalculateAccesses: %v", err)
  943. }
  944. }
  945. if err = watchRepo(e, owner.ID, repo.ID, true); err != nil {
  946. return fmt.Errorf("watchRepo: %v", err)
  947. } else if err = newRepoAction(e, doer, owner, repo); err != nil {
  948. return fmt.Errorf("newRepoAction: %v", err)
  949. }
  950. return repo.loadAttributes(e)
  951. }
  952. type ErrReachLimitOfRepo struct {
  953. Limit int
  954. }
  955. func IsErrReachLimitOfRepo(err error) bool {
  956. _, ok := err.(ErrReachLimitOfRepo)
  957. return ok
  958. }
  959. func (err ErrReachLimitOfRepo) Error() string {
  960. return fmt.Sprintf("user has reached maximum limit of repositories [limit: %d]", err.Limit)
  961. }
  962. // CreateRepository creates a repository for given user or organization.
  963. func CreateRepository(doer, owner *User, opts CreateRepoOptions) (_ *Repository, err error) {
  964. if !owner.CanCreateRepo() {
  965. return nil, ErrReachLimitOfRepo{Limit: owner.RepoCreationNum()}
  966. }
  967. repo := &Repository{
  968. OwnerID: owner.ID,
  969. Owner: owner,
  970. Name: opts.Name,
  971. LowerName: strings.ToLower(opts.Name),
  972. Description: opts.Description,
  973. IsPrivate: opts.IsPrivate,
  974. EnableWiki: true,
  975. EnableIssues: true,
  976. EnablePulls: true,
  977. }
  978. sess := x.NewSession()
  979. defer sess.Close()
  980. if err = sess.Begin(); err != nil {
  981. return nil, err
  982. }
  983. if err = createRepository(sess, doer, owner, repo); err != nil {
  984. return nil, err
  985. }
  986. // No need for init mirror.
  987. if !opts.IsMirror {
  988. repoPath := RepoPath(owner.Name, repo.Name)
  989. if err = initRepository(sess, repoPath, doer, repo, opts); err != nil {
  990. RemoveAllWithNotice("Delete repository for initialization failure", repoPath)
  991. return nil, fmt.Errorf("initRepository: %v", err)
  992. }
  993. _, stderr, err := process.ExecDir(-1,
  994. repoPath, fmt.Sprintf("CreateRepository 'git update-server-info': %s", repoPath),
  995. "git", "update-server-info")
  996. if err != nil {
  997. return nil, fmt.Errorf("CreateRepository 'git update-server-info': %s", stderr)
  998. }
  999. }
  1000. return repo, sess.Commit()
  1001. }
  1002. func countRepositories(userID int64, private bool) int64 {
  1003. sess := x.Where("id > 0")
  1004. if userID > 0 {
  1005. sess.And("owner_id = ?", userID)
  1006. }
  1007. if !private {
  1008. sess.And("is_private=?", false)
  1009. }
  1010. count, err := sess.Count(new(Repository))
  1011. if err != nil {
  1012. log.Error("countRepositories: %v", err)
  1013. }
  1014. return count
  1015. }
  1016. // CountRepositories returns number of repositories.
  1017. // Argument private only takes effect when it is false,
  1018. // set it true to count all repositories.
  1019. func CountRepositories(private bool) int64 {
  1020. return countRepositories(-1, private)
  1021. }
  1022. // CountUserRepositories returns number of repositories user owns.
  1023. // Argument private only takes effect when it is false,
  1024. // set it true to count all repositories.
  1025. func CountUserRepositories(userID int64, private bool) int64 {
  1026. return countRepositories(userID, private)
  1027. }
  1028. func Repositories(page, pageSize int) (_ []*Repository, err error) {
  1029. repos := make([]*Repository, 0, pageSize)
  1030. return repos, x.Limit(pageSize, (page-1)*pageSize).Asc("id").Find(&repos)
  1031. }
  1032. // RepositoriesWithUsers returns number of repos in given page.
  1033. func RepositoriesWithUsers(page, pageSize int) (_ []*Repository, err error) {
  1034. repos, err := Repositories(page, pageSize)
  1035. if err != nil {
  1036. return nil, fmt.Errorf("Repositories: %v", err)
  1037. }
  1038. for i := range repos {
  1039. if err = repos[i].GetOwner(); err != nil {
  1040. return nil, err
  1041. }
  1042. }
  1043. return repos, nil
  1044. }
  1045. // FilterRepositoryWithIssues selects repositories that are using interal issue tracker
  1046. // and has disabled external tracker from given set.
  1047. // It returns nil if result set is empty.
  1048. func FilterRepositoryWithIssues(repoIDs []int64) ([]int64, error) {
  1049. if len(repoIDs) == 0 {
  1050. return nil, nil
  1051. }
  1052. repos := make([]*Repository, 0, len(repoIDs))
  1053. if err := x.Where("enable_issues=?", true).
  1054. And("enable_external_tracker=?", false).
  1055. In("id", repoIDs).
  1056. Cols("id").
  1057. Find(&repos); err != nil {
  1058. return nil, fmt.Errorf("filter valid repositories %v: %v", repoIDs, err)
  1059. }
  1060. if len(repos) == 0 {
  1061. return nil, nil
  1062. }
  1063. repoIDs = make([]int64, len(repos))
  1064. for i := range repos {
  1065. repoIDs[i] = repos[i].ID
  1066. }
  1067. return repoIDs, nil
  1068. }
  1069. // RepoPath returns repository path by given user and repository name.
  1070. func RepoPath(userName, repoName string) string {
  1071. return filepath.Join(UserPath(userName), strings.ToLower(repoName)+".git")
  1072. }
  1073. // TransferOwnership transfers all corresponding setting from old user to new one.
  1074. func TransferOwnership(doer *User, newOwnerName string, repo *Repository) error {
  1075. newOwner, err := GetUserByName(newOwnerName)
  1076. if err != nil {
  1077. return fmt.Errorf("get new owner '%s': %v", newOwnerName, err)
  1078. }
  1079. // Check if new owner has repository with same name.
  1080. has, err := IsRepositoryExist(newOwner, repo.Name)
  1081. if err != nil {
  1082. return fmt.Errorf("IsRepositoryExist: %v", err)
  1083. } else if has {
  1084. return ErrRepoAlreadyExist{newOwnerName, repo.Name}
  1085. }
  1086. sess := x.NewSession()
  1087. defer sess.Close()
  1088. if err = sess.Begin(); err != nil {
  1089. return fmt.Errorf("sess.Begin: %v", err)
  1090. }
  1091. owner := repo.Owner
  1092. // Note: we have to set value here to make sure recalculate accesses is based on
  1093. // new owner.
  1094. repo.OwnerID = newOwner.ID
  1095. repo.Owner = newOwner
  1096. // Update repository.
  1097. if _, err := sess.ID(repo.ID).Update(repo); err != nil {
  1098. return fmt.Errorf("update owner: %v", err)
  1099. }
  1100. // Remove redundant collaborators.
  1101. collaborators, err := repo.getCollaborators(sess)
  1102. if err != nil {
  1103. return fmt.Errorf("getCollaborators: %v", err)
  1104. }
  1105. // Dummy object.
  1106. collaboration := &Collaboration{RepoID: repo.ID}
  1107. for _, c := range collaborators {
  1108. collaboration.UserID = c.ID
  1109. if c.ID == newOwner.ID || newOwner.IsOrgMember(c.ID) {
  1110. if _, err = sess.Delete(collaboration); err != nil {
  1111. return fmt.Errorf("remove collaborator '%d': %v", c.ID, err)
  1112. }
  1113. }
  1114. }
  1115. // Remove old team-repository relations.
  1116. if owner.IsOrganization() {
  1117. if err = owner.getTeams(sess); err != nil {
  1118. return fmt.Errorf("getTeams: %v", err)
  1119. }
  1120. for _, t := range owner.Teams {
  1121. if !t.hasRepository(sess, repo.ID) {
  1122. continue
  1123. }
  1124. t.NumRepos--
  1125. if _, err := sess.ID(t.ID).AllCols().Update(t); err != nil {
  1126. return fmt.Errorf("decrease team repository count '%d': %v", t.ID, err)
  1127. }
  1128. }
  1129. if err = owner.removeOrgRepo(sess, repo.ID); err != nil {
  1130. return fmt.Errorf("removeOrgRepo: %v", err)
  1131. }
  1132. }
  1133. if newOwner.IsOrganization() {
  1134. t, err := newOwner.getOwnerTeam(sess)
  1135. if err != nil {
  1136. return fmt.Errorf("getOwnerTeam: %v", err)
  1137. } else if err = t.addRepository(sess, repo); err != nil {
  1138. return fmt.Errorf("add to owner team: %v", err)
  1139. }
  1140. } else {
  1141. // Organization called this in addRepository method.
  1142. if err = repo.recalculateAccesses(sess); err != nil {
  1143. return fmt.Errorf("recalculateAccesses: %v", err)
  1144. }
  1145. }
  1146. // Update repository count.
  1147. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos+1 WHERE id=?", newOwner.ID); err != nil {
  1148. return fmt.Errorf("increase new owner repository count: %v", err)
  1149. } else if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", owner.ID); err != nil {
  1150. return fmt.Errorf("decrease old owner repository count: %v", err)
  1151. }
  1152. if err = watchRepo(sess, newOwner.ID, repo.ID, true); err != nil {
  1153. return fmt.Errorf("watchRepo: %v", err)
  1154. } else if err = transferRepoAction(sess, doer, owner, repo); err != nil {
  1155. return fmt.Errorf("transferRepoAction: %v", err)
  1156. }
  1157. // Rename remote repository to new path and delete local copy.
  1158. if err = os.MkdirAll(UserPath(newOwner.Name), os.ModePerm); err != nil {
  1159. return err
  1160. }
  1161. if err = os.Rename(RepoPath(owner.Name, repo.Name), RepoPath(newOwner.Name, repo.Name)); err != nil {
  1162. return fmt.Errorf("rename repository directory: %v", err)
  1163. }
  1164. deleteRepoLocalCopy(repo)
  1165. // Rename remote wiki repository to new path and delete local copy.
  1166. wikiPath := WikiPath(owner.Name, repo.Name)
  1167. if com.IsExist(wikiPath) {
  1168. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  1169. if err = os.Rename(wikiPath, WikiPath(newOwner.Name, repo.Name)); err != nil {
  1170. return fmt.Errorf("rename repository wiki: %v", err)
  1171. }
  1172. }
  1173. return sess.Commit()
  1174. }
  1175. func deleteRepoLocalCopy(repo *Repository) {
  1176. repoWorkingPool.CheckIn(com.ToStr(repo.ID))
  1177. defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
  1178. RemoveAllWithNotice("Delete repository local copy", repo.LocalCopyPath())
  1179. }
  1180. // ChangeRepositoryName changes all corresponding setting from old repository name to new one.
  1181. func ChangeRepositoryName(u *User, oldRepoName, newRepoName string) (err error) {
  1182. oldRepoName = strings.ToLower(oldRepoName)
  1183. newRepoName = strings.ToLower(newRepoName)
  1184. if err = IsUsableRepoName(newRepoName); err != nil {
  1185. return err
  1186. }
  1187. has, err := IsRepositoryExist(u, newRepoName)
  1188. if err != nil {
  1189. return fmt.Errorf("IsRepositoryExist: %v", err)
  1190. } else if has {
  1191. return ErrRepoAlreadyExist{u.Name, newRepoName}
  1192. }
  1193. repo, err := GetRepositoryByName(u.ID, oldRepoName)
  1194. if err != nil {
  1195. return fmt.Errorf("GetRepositoryByName: %v", err)
  1196. }
  1197. // Change repository directory name
  1198. if err = os.Rename(repo.RepoPath(), RepoPath(u.Name, newRepoName)); err != nil {
  1199. return fmt.Errorf("rename repository directory: %v", err)
  1200. }
  1201. wikiPath := repo.WikiPath()
  1202. if com.IsExist(wikiPath) {
  1203. if err = os.Rename(wikiPath, WikiPath(u.Name, newRepoName)); err != nil {
  1204. return fmt.Errorf("rename repository wiki: %v", err)
  1205. }
  1206. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  1207. }
  1208. deleteRepoLocalCopy(repo)
  1209. return nil
  1210. }
  1211. func getRepositoriesByForkID(e Engine, forkID int64) ([]*Repository, error) {
  1212. repos := make([]*Repository, 0, 10)
  1213. return repos, e.Where("fork_id=?", forkID).Find(&repos)
  1214. }
  1215. // GetRepositoriesByForkID returns all repositories with given fork ID.
  1216. func GetRepositoriesByForkID(forkID int64) ([]*Repository, error) {
  1217. return getRepositoriesByForkID(x, forkID)
  1218. }
  1219. func getNonMirrorRepositories(e Engine) ([]*Repository, error) {
  1220. repos := make([]*Repository, 0, 10)
  1221. return repos, e.Where("is_mirror = ?", false).Find(&repos)
  1222. }
  1223. // GetRepositoriesMirror returns only mirror repositories with user.
  1224. func GetNonMirrorRepositories() ([]*Repository, error) {
  1225. return getNonMirrorRepositories(x)
  1226. }
  1227. func updateRepository(e Engine, repo *Repository, visibilityChanged bool) (err error) {
  1228. repo.LowerName = strings.ToLower(repo.Name)
  1229. if len(repo.Description) > 512 {
  1230. repo.Description = repo.Description[:512]
  1231. }
  1232. if len(repo.Website) > 255 {
  1233. repo.Website = repo.Website[:255]
  1234. }
  1235. if _, err = e.ID(repo.ID).AllCols().Update(repo); err != nil {
  1236. return fmt.Errorf("update: %v", err)
  1237. }
  1238. if visibilityChanged {
  1239. if err = repo.getOwner(e); err != nil {
  1240. return fmt.Errorf("getOwner: %v", err)
  1241. }
  1242. if repo.Owner.IsOrganization() {
  1243. // Organization repository need to recalculate access table when visivility is changed
  1244. if err = repo.recalculateTeamAccesses(e, 0); err != nil {
  1245. return fmt.Errorf("recalculateTeamAccesses: %v", err)
  1246. }
  1247. }
  1248. // Create/Remove git-daemon-export-ok for git-daemon
  1249. daemonExportFile := path.Join(repo.RepoPath(), "git-daemon-export-ok")
  1250. if repo.IsPrivate && com.IsExist(daemonExportFile) {
  1251. if err = os.Remove(daemonExportFile); err != nil {
  1252. log.Error("Failed to remove %s: %v", daemonExportFile, err)
  1253. }
  1254. } else if !repo.IsPrivate && !com.IsExist(daemonExportFile) {
  1255. if f, err := os.Create(daemonExportFile); err != nil {
  1256. log.Error("Failed to create %s: %v", daemonExportFile, err)
  1257. } else {
  1258. f.Close()
  1259. }
  1260. }
  1261. forkRepos, err := getRepositoriesByForkID(e, repo.ID)
  1262. if err != nil {
  1263. return fmt.Errorf("getRepositoriesByForkID: %v", err)
  1264. }
  1265. for i := range forkRepos {
  1266. forkRepos[i].IsPrivate = repo.IsPrivate
  1267. if err = updateRepository(e, forkRepos[i], true); err != nil {
  1268. return fmt.Errorf("updateRepository[%d]: %v", forkRepos[i].ID, err)
  1269. }
  1270. }
  1271. // Change visibility of generated actions
  1272. if _, err = e.Where("repo_id = ?", repo.ID).Cols("is_private").Update(&Action{IsPrivate: repo.IsPrivate}); err != nil {
  1273. return fmt.Errorf("change action visibility of repository: %v", err)
  1274. }
  1275. }
  1276. return nil
  1277. }
  1278. func UpdateRepository(repo *Repository, visibilityChanged bool) (err error) {
  1279. sess := x.NewSession()
  1280. defer sess.Close()
  1281. if err = sess.Begin(); err != nil {
  1282. return err
  1283. }
  1284. if err = updateRepository(x, repo, visibilityChanged); err != nil {
  1285. return fmt.Errorf("updateRepository: %v", err)
  1286. }
  1287. return sess.Commit()
  1288. }
  1289. // DeleteRepository deletes a repository for a user or organization.
  1290. func DeleteRepository(ownerID, repoID int64) error {
  1291. repo := &Repository{ID: repoID, OwnerID: ownerID}
  1292. has, err := x.Get(repo)
  1293. if err != nil {
  1294. return err
  1295. } else if !has {
  1296. return ErrRepoNotExist{args: map[string]interface{}{"ownerID": ownerID, "repoID": repoID}}
  1297. }
  1298. // In case is a organization.
  1299. org, err := GetUserByID(ownerID)
  1300. if err != nil {
  1301. return err
  1302. }
  1303. if org.IsOrganization() {
  1304. if err = org.GetTeams(); err != nil {
  1305. return err
  1306. }
  1307. }
  1308. sess := x.NewSession()
  1309. defer sess.Close()
  1310. if err = sess.Begin(); err != nil {
  1311. return err
  1312. }
  1313. if org.IsOrganization() {
  1314. for _, t := range org.Teams {
  1315. if !t.hasRepository(sess, repoID) {
  1316. continue
  1317. } else if err = t.removeRepository(sess, repo, false); err != nil {
  1318. return err
  1319. }
  1320. }
  1321. }
  1322. if err = deleteBeans(sess,
  1323. &Repository{ID: repoID},
  1324. &Access{RepoID: repo.ID},
  1325. &Action{RepoID: repo.ID},
  1326. &Watch{RepoID: repoID},
  1327. &Star{RepoID: repoID},
  1328. &Mirror{RepoID: repoID},
  1329. &IssueUser{RepoID: repoID},
  1330. &Milestone{RepoID: repoID},
  1331. &Release{RepoID: repoID},
  1332. &Collaboration{RepoID: repoID},
  1333. &PullRequest{BaseRepoID: repoID},
  1334. &ProtectBranch{RepoID: repoID},
  1335. &ProtectBranchWhitelist{RepoID: repoID},
  1336. &Webhook{RepoID: repoID},
  1337. &HookTask{RepoID: repoID},
  1338. ); err != nil {
  1339. return fmt.Errorf("deleteBeans: %v", err)
  1340. }
  1341. // Delete comments and attachments.
  1342. issues := make([]*Issue, 0, 25)
  1343. attachmentPaths := make([]string, 0, len(issues))
  1344. if err = sess.Where("repo_id=?", repoID).Find(&issues); err != nil {
  1345. return err
  1346. }
  1347. for i := range issues {
  1348. if _, err = sess.Delete(&Comment{IssueID: issues[i].ID}); err != nil {
  1349. return err
  1350. }
  1351. attachments := make([]*Attachment, 0, 5)
  1352. if err = sess.Where("issue_id=?", issues[i].ID).Find(&attachments); err != nil {
  1353. return err
  1354. }
  1355. for j := range attachments {
  1356. attachmentPaths = append(attachmentPaths, attachments[j].LocalPath())
  1357. }
  1358. if _, err = sess.Delete(&Attachment{IssueID: issues[i].ID}); err != nil {
  1359. return err
  1360. }
  1361. }
  1362. if _, err = sess.Delete(&Issue{RepoID: repoID}); err != nil {
  1363. return err
  1364. }
  1365. if repo.IsFork {
  1366. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks-1 WHERE id=?", repo.ForkID); err != nil {
  1367. return fmt.Errorf("decrease fork count: %v", err)
  1368. }
  1369. }
  1370. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", ownerID); err != nil {
  1371. return err
  1372. }
  1373. if err = sess.Commit(); err != nil {
  1374. return fmt.Errorf("Commit: %v", err)
  1375. }
  1376. // Remove repository files.
  1377. repoPath := repo.RepoPath()
  1378. RemoveAllWithNotice("Delete repository files", repoPath)
  1379. repo.DeleteWiki()
  1380. // Remove attachment files.
  1381. for i := range attachmentPaths {
  1382. RemoveAllWithNotice("Delete attachment", attachmentPaths[i])
  1383. }
  1384. if repo.NumForks > 0 {
  1385. if _, err = x.Exec("UPDATE `repository` SET fork_id=0,is_fork=? WHERE fork_id=?", false, repo.ID); err != nil {
  1386. log.Error("reset 'fork_id' and 'is_fork': %v", err)
  1387. }
  1388. }
  1389. return nil
  1390. }
  1391. // GetRepositoryByRef returns a Repository specified by a GFM reference.
  1392. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  1393. func GetRepositoryByRef(ref string) (*Repository, error) {
  1394. n := strings.IndexByte(ref, byte('/'))
  1395. if n < 2 {
  1396. return nil, errors.InvalidRepoReference{Ref: ref}
  1397. }
  1398. userName, repoName := ref[:n], ref[n+1:]
  1399. user, err := GetUserByName(userName)
  1400. if err != nil {
  1401. return nil, err
  1402. }
  1403. return GetRepositoryByName(user.ID, repoName)
  1404. }
  1405. var _ errutil.NotFound = (*ErrRepoNotExist)(nil)
  1406. type ErrRepoNotExist struct {
  1407. args map[string]interface{}
  1408. }
  1409. func IsErrRepoNotExist(err error) bool {
  1410. _, ok := err.(ErrRepoNotExist)
  1411. return ok
  1412. }
  1413. func (err ErrRepoNotExist) Error() string {
  1414. return fmt.Sprintf("repository does not exist: %v", err.args)
  1415. }
  1416. func (ErrRepoNotExist) NotFound() bool {
  1417. return true
  1418. }
  1419. // GetRepositoryByName returns the repository by given name under user if exists.
  1420. // Deprecated: Use Repos.GetByName instead.
  1421. func GetRepositoryByName(ownerID int64, name string) (*Repository, error) {
  1422. repo := &Repository{
  1423. OwnerID: ownerID,
  1424. LowerName: strings.ToLower(name),
  1425. }
  1426. has, err := x.Get(repo)
  1427. if err != nil {
  1428. return nil, err
  1429. } else if !has {
  1430. return nil, ErrRepoNotExist{args: map[string]interface{}{"ownerID": ownerID, "name": name}}
  1431. }
  1432. return repo, repo.LoadAttributes()
  1433. }
  1434. func getRepositoryByID(e Engine, id int64) (*Repository, error) {
  1435. repo := new(Repository)
  1436. has, err := e.ID(id).Get(repo)
  1437. if err != nil {
  1438. return nil, err
  1439. } else if !has {
  1440. return nil, ErrRepoNotExist{args: map[string]interface{}{"repoID": id}}
  1441. }
  1442. return repo, repo.loadAttributes(e)
  1443. }
  1444. // GetRepositoryByID returns the repository by given id if exists.
  1445. func GetRepositoryByID(id int64) (*Repository, error) {
  1446. return getRepositoryByID(x, id)
  1447. }
  1448. type UserRepoOptions struct {
  1449. UserID int64
  1450. Private bool
  1451. Page int
  1452. PageSize int
  1453. }
  1454. // GetUserRepositories returns a list of repositories of given user.
  1455. func GetUserRepositories(opts *UserRepoOptions) ([]*Repository, error) {
  1456. sess := x.Where("owner_id=?", opts.UserID).Desc("updated_unix")
  1457. if !opts.Private {
  1458. sess.And("is_private=?", false)
  1459. }
  1460. if opts.Page <= 0 {
  1461. opts.Page = 1
  1462. }
  1463. sess.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize)
  1464. repos := make([]*Repository, 0, opts.PageSize)
  1465. return repos, sess.Find(&repos)
  1466. }
  1467. // GetUserRepositories returns a list of mirror repositories of given user.
  1468. func GetUserMirrorRepositories(userID int64) ([]*Repository, error) {
  1469. repos := make([]*Repository, 0, 10)
  1470. return repos, x.Where("owner_id = ?", userID).And("is_mirror = ?", true).Find(&repos)
  1471. }
  1472. // GetRecentUpdatedRepositories returns the list of repositories that are recently updated.
  1473. func GetRecentUpdatedRepositories(page, pageSize int) (repos []*Repository, err error) {
  1474. return repos, x.Limit(pageSize, (page-1)*pageSize).
  1475. Where("is_private=?", false).Limit(pageSize).Desc("updated_unix").Find(&repos)
  1476. }
  1477. // GetUserAndCollaborativeRepositories returns list of repositories the user owns and collaborates.
  1478. func GetUserAndCollaborativeRepositories(userID int64) ([]*Repository, error) {
  1479. repos := make([]*Repository, 0, 10)
  1480. if err := x.Alias("repo").
  1481. Join("INNER", "collaboration", "collaboration.repo_id = repo.id").
  1482. Where("collaboration.user_id = ?", userID).
  1483. Find(&repos); err != nil {
  1484. return nil, fmt.Errorf("select collaborative repositories: %v", err)
  1485. }
  1486. ownRepos := make([]*Repository, 0, 10)
  1487. if err := x.Where("owner_id = ?", userID).Find(&ownRepos); err != nil {
  1488. return nil, fmt.Errorf("select own repositories: %v", err)
  1489. }
  1490. return append(repos, ownRepos...), nil
  1491. }
  1492. func getRepositoryCount(e Engine, u *User) (int64, error) {
  1493. return x.Count(&Repository{OwnerID: u.ID})
  1494. }
  1495. // GetRepositoryCount returns the total number of repositories of user.
  1496. func GetRepositoryCount(u *User) (int64, error) {
  1497. return getRepositoryCount(x, u)
  1498. }
  1499. type SearchRepoOptions struct {
  1500. Keyword string
  1501. OwnerID int64
  1502. UserID int64 // When set results will contain all public/private repositories user has access to
  1503. OrderBy string
  1504. Private bool // Include private repositories in results
  1505. Page int
  1506. PageSize int // Can be smaller than or equal to setting.ExplorePagingNum
  1507. }
  1508. // SearchRepositoryByName takes keyword and part of repository name to search,
  1509. // it returns results in given range and number of total results.
  1510. func SearchRepositoryByName(opts *SearchRepoOptions) (repos []*Repository, count int64, err error) {
  1511. if opts.Page <= 0 {
  1512. opts.Page = 1
  1513. }
  1514. repos = make([]*Repository, 0, opts.PageSize)
  1515. sess := x.Alias("repo")
  1516. // Attempt to find repositories that opts.UserID has access to,
  1517. // this does not include other people's private repositories even if opts.UserID is an admin.
  1518. if !opts.Private && opts.UserID > 0 {
  1519. sess.Join("LEFT", "access", "access.repo_id = repo.id").
  1520. Where("repo.owner_id = ? OR access.user_id = ? OR repo.is_private = ? OR (repo.is_private = ? AND (repo.allow_public_wiki = ? OR repo.allow_public_issues = ?))", opts.UserID, opts.UserID, false, true, true, true)
  1521. } else {
  1522. // Only return public repositories if opts.Private is not set
  1523. if !opts.Private {
  1524. sess.And("repo.is_private = ? OR (repo.is_private = ? AND (repo.allow_public_wiki = ? OR repo.allow_public_issues = ?))", false, true, true, true)
  1525. }
  1526. }
  1527. if len(opts.Keyword) > 0 {
  1528. sess.And("repo.lower_name LIKE ? OR repo.description LIKE ?", "%"+strings.ToLower(opts.Keyword)+"%", "%"+strings.ToLower(opts.Keyword)+"%")
  1529. }
  1530. if opts.OwnerID > 0 {
  1531. sess.And("repo.owner_id = ?", opts.OwnerID)
  1532. }
  1533. // We need all fields (repo.*) in final list but only ID (repo.id) is good enough for counting.
  1534. count, err = sess.Clone().Distinct("repo.id").Count(new(Repository))
  1535. if err != nil {
  1536. return nil, 0, fmt.Errorf("Count: %v", err)
  1537. }
  1538. if len(opts.OrderBy) > 0 {
  1539. sess.OrderBy("repo." + opts.OrderBy)
  1540. }
  1541. return repos, count, sess.Distinct("repo.*").Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).Find(&repos)
  1542. }
  1543. func DeleteOldRepositoryArchives() {
  1544. if taskStatusTable.IsRunning(_CLEAN_OLD_ARCHIVES) {
  1545. return
  1546. }
  1547. taskStatusTable.Start(_CLEAN_OLD_ARCHIVES)
  1548. defer taskStatusTable.Stop(_CLEAN_OLD_ARCHIVES)
  1549. log.Trace("Doing: DeleteOldRepositoryArchives")
  1550. formats := []string{"zip", "targz"}
  1551. oldestTime := time.Now().Add(-conf.Cron.RepoArchiveCleanup.OlderThan)
  1552. if err := x.Where("id > 0").Iterate(new(Repository),
  1553. func(idx int, bean interface{}) error {
  1554. repo := bean.(*Repository)
  1555. basePath := filepath.Join(repo.RepoPath(), "archives")
  1556. for _, format := range formats {
  1557. dirPath := filepath.Join(basePath, format)
  1558. if !com.IsDir(dirPath) {
  1559. continue
  1560. }
  1561. dir, err := os.Open(dirPath)
  1562. if err != nil {
  1563. log.Error("Failed to open directory '%s': %v", dirPath, err)
  1564. continue
  1565. }
  1566. fis, err := dir.Readdir(0)
  1567. dir.Close()
  1568. if err != nil {
  1569. log.Error("Failed to read directory '%s': %v", dirPath, err)
  1570. continue
  1571. }
  1572. for _, fi := range fis {
  1573. if fi.IsDir() || fi.ModTime().After(oldestTime) {
  1574. continue
  1575. }
  1576. archivePath := filepath.Join(dirPath, fi.Name())
  1577. if err = os.Remove(archivePath); err != nil {
  1578. desc := fmt.Sprintf("Failed to health delete archive '%s': %v", archivePath, err)
  1579. log.Warn(desc)
  1580. if err = CreateRepositoryNotice(desc); err != nil {
  1581. log.Error("CreateRepositoryNotice: %v", err)
  1582. }
  1583. }
  1584. }
  1585. }
  1586. return nil
  1587. }); err != nil {
  1588. log.Error("DeleteOldRepositoryArchives: %v", err)
  1589. }
  1590. }
  1591. // DeleteRepositoryArchives deletes all repositories' archives.
  1592. func DeleteRepositoryArchives() error {
  1593. if taskStatusTable.IsRunning(_CLEAN_OLD_ARCHIVES) {
  1594. return nil
  1595. }
  1596. taskStatusTable.Start(_CLEAN_OLD_ARCHIVES)
  1597. defer taskStatusTable.Stop(_CLEAN_OLD_ARCHIVES)
  1598. return x.Where("id > 0").Iterate(new(Repository),
  1599. func(idx int, bean interface{}) error {
  1600. repo := bean.(*Repository)
  1601. return os.RemoveAll(filepath.Join(repo.RepoPath(), "archives"))
  1602. })
  1603. }
  1604. func gatherMissingRepoRecords() ([]*Repository, error) {
  1605. repos := make([]*Repository, 0, 10)
  1606. if err := x.Where("id > 0").Iterate(new(Repository),
  1607. func(idx int, bean interface{}) error {
  1608. repo := bean.(*Repository)
  1609. if !com.IsDir(repo.RepoPath()) {
  1610. repos = append(repos, repo)
  1611. }
  1612. return nil
  1613. }); err != nil {
  1614. if err2 := CreateRepositoryNotice(fmt.Sprintf("gatherMissingRepoRecords: %v", err)); err2 != nil {
  1615. return nil, fmt.Errorf("CreateRepositoryNotice: %v", err)
  1616. }
  1617. }
  1618. return repos, nil
  1619. }
  1620. // DeleteMissingRepositories deletes all repository records that lost Git files.
  1621. func DeleteMissingRepositories() error {
  1622. repos, err := gatherMissingRepoRecords()
  1623. if err != nil {
  1624. return fmt.Errorf("gatherMissingRepoRecords: %v", err)
  1625. }
  1626. if len(repos) == 0 {
  1627. return nil
  1628. }
  1629. for _, repo := range repos {
  1630. log.Trace("Deleting %d/%d...", repo.OwnerID, repo.ID)
  1631. if err := DeleteRepository(repo.OwnerID, repo.ID); err != nil {
  1632. if err2 := CreateRepositoryNotice(fmt.Sprintf("DeleteRepository [%d]: %v", repo.ID, err)); err2 != nil {
  1633. return fmt.Errorf("CreateRepositoryNotice: %v", err)
  1634. }
  1635. }
  1636. }
  1637. return nil
  1638. }
  1639. // ReinitMissingRepositories reinitializes all repository records that lost Git files.
  1640. func ReinitMissingRepositories() error {
  1641. repos, err := gatherMissingRepoRecords()
  1642. if err != nil {
  1643. return fmt.Errorf("gatherMissingRepoRecords: %v", err)
  1644. }
  1645. if len(repos) == 0 {
  1646. return nil
  1647. }
  1648. for _, repo := range repos {
  1649. log.Trace("Initializing %d/%d...", repo.OwnerID, repo.ID)
  1650. if err := git.Init(repo.RepoPath(), git.InitOptions{Bare: true}); err != nil {
  1651. if err2 := CreateRepositoryNotice(fmt.Sprintf("init repository [repo_id: %d]: %v", repo.ID, err)); err2 != nil {
  1652. return fmt.Errorf("create repository notice: %v", err)
  1653. }
  1654. }
  1655. }
  1656. return nil
  1657. }
  1658. // SyncRepositoryHooks rewrites all repositories' pre-receive, update and post-receive hooks
  1659. // to make sure the binary and custom conf path are up-to-date.
  1660. func SyncRepositoryHooks() error {
  1661. return x.Where("id > 0").Iterate(new(Repository),
  1662. func(idx int, bean interface{}) error {
  1663. repo := bean.(*Repository)
  1664. if err := createDelegateHooks(repo.RepoPath()); err != nil {
  1665. return err
  1666. }
  1667. if repo.HasWiki() {
  1668. return createDelegateHooks(repo.WikiPath())
  1669. }
  1670. return nil
  1671. })
  1672. }
  1673. // Prevent duplicate running tasks.
  1674. var taskStatusTable = sync.NewStatusTable()
  1675. const (
  1676. _MIRROR_UPDATE = "mirror_update"
  1677. _GIT_FSCK = "git_fsck"
  1678. _CHECK_REPO_STATS = "check_repos_stats"
  1679. _CLEAN_OLD_ARCHIVES = "clean_old_archives"
  1680. )
  1681. // GitFsck calls 'git fsck' to check repository health.
  1682. func GitFsck() {
  1683. if taskStatusTable.IsRunning(_GIT_FSCK) {
  1684. return
  1685. }
  1686. taskStatusTable.Start(_GIT_FSCK)
  1687. defer taskStatusTable.Stop(_GIT_FSCK)
  1688. log.Trace("Doing: GitFsck")
  1689. if err := x.Where("id>0").Iterate(new(Repository),
  1690. func(idx int, bean interface{}) error {
  1691. repo := bean.(*Repository)
  1692. repoPath := repo.RepoPath()
  1693. err := git.RepoFsck(repoPath, git.FsckOptions{
  1694. Args: conf.Cron.RepoHealthCheck.Args,
  1695. Timeout: conf.Cron.RepoHealthCheck.Timeout,
  1696. })
  1697. if err != nil {
  1698. desc := fmt.Sprintf("Failed to perform health check on repository '%s': %v", repoPath, err)
  1699. log.Warn(desc)
  1700. if err = CreateRepositoryNotice(desc); err != nil {
  1701. log.Error("CreateRepositoryNotice: %v", err)
  1702. }
  1703. }
  1704. return nil
  1705. }); err != nil {
  1706. log.Error("GitFsck: %v", err)
  1707. }
  1708. }
  1709. func GitGcRepos() error {
  1710. args := append([]string{"gc"}, conf.Git.GCArgs...)
  1711. return x.Where("id > 0").Iterate(new(Repository),
  1712. func(idx int, bean interface{}) error {
  1713. repo := bean.(*Repository)
  1714. if err := repo.GetOwner(); err != nil {
  1715. return err
  1716. }
  1717. _, stderr, err := process.ExecDir(
  1718. time.Duration(conf.Git.Timeout.GC)*time.Second,
  1719. RepoPath(repo.Owner.Name, repo.Name), "Repository garbage collection",
  1720. "git", args...)
  1721. if err != nil {
  1722. return fmt.Errorf("%v: %v", err, stderr)
  1723. }
  1724. return nil
  1725. })
  1726. }
  1727. type repoChecker struct {
  1728. querySQL, correctSQL string
  1729. desc string
  1730. }
  1731. func repoStatsCheck(checker *repoChecker) {
  1732. results, err := x.Query(checker.querySQL)
  1733. if err != nil {
  1734. log.Error("Select %s: %v", checker.desc, err)
  1735. return
  1736. }
  1737. for _, result := range results {
  1738. id := com.StrTo(result["id"]).MustInt64()
  1739. log.Trace("Updating %s: %d", checker.desc, id)
  1740. _, err = x.Exec(checker.correctSQL, id, id)
  1741. if err != nil {
  1742. log.Error("Update %s[%d]: %v", checker.desc, id, err)
  1743. }
  1744. }
  1745. }
  1746. func CheckRepoStats() {
  1747. if taskStatusTable.IsRunning(_CHECK_REPO_STATS) {
  1748. return
  1749. }
  1750. taskStatusTable.Start(_CHECK_REPO_STATS)
  1751. defer taskStatusTable.Stop(_CHECK_REPO_STATS)
  1752. log.Trace("Doing: CheckRepoStats")
  1753. checkers := []*repoChecker{
  1754. // Repository.NumWatches
  1755. {
  1756. "SELECT repo.id FROM `repository` repo WHERE repo.num_watches!=(SELECT COUNT(*) FROM `watch` WHERE repo_id=repo.id)",
  1757. "UPDATE `repository` SET num_watches=(SELECT COUNT(*) FROM `watch` WHERE repo_id=?) WHERE id=?",
  1758. "repository count 'num_watches'",
  1759. },
  1760. // Repository.NumStars
  1761. {
  1762. "SELECT repo.id FROM `repository` repo WHERE repo.num_stars!=(SELECT COUNT(*) FROM `star` WHERE repo_id=repo.id)",
  1763. "UPDATE `repository` SET num_stars=(SELECT COUNT(*) FROM `star` WHERE repo_id=?) WHERE id=?",
  1764. "repository count 'num_stars'",
  1765. },
  1766. // Label.NumIssues
  1767. {
  1768. "SELECT label.id FROM `label` WHERE label.num_issues!=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=label.id)",
  1769. "UPDATE `label` SET num_issues=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=?) WHERE id=?",
  1770. "label count 'num_issues'",
  1771. },
  1772. // User.NumRepos
  1773. {
  1774. "SELECT `user`.id FROM `user` WHERE `user`.num_repos!=(SELECT COUNT(*) FROM `repository` WHERE owner_id=`user`.id)",
  1775. "UPDATE `user` SET num_repos=(SELECT COUNT(*) FROM `repository` WHERE owner_id=?) WHERE id=?",
  1776. "user count 'num_repos'",
  1777. },
  1778. // Issue.NumComments
  1779. {
  1780. "SELECT `issue`.id FROM `issue` WHERE `issue`.num_comments!=(SELECT COUNT(*) FROM `comment` WHERE issue_id=`issue`.id AND type=0)",
  1781. "UPDATE `issue` SET num_comments=(SELECT COUNT(*) FROM `comment` WHERE issue_id=? AND type=0) WHERE id=?",
  1782. "issue count 'num_comments'",
  1783. },
  1784. }
  1785. for i := range checkers {
  1786. repoStatsCheck(checkers[i])
  1787. }
  1788. // ***** START: Repository.NumClosedIssues *****
  1789. desc := "repository count 'num_closed_issues'"
  1790. results, err := x.Query("SELECT repo.id FROM `repository` repo WHERE repo.num_closed_issues!=(SELECT COUNT(*) FROM `issue` WHERE repo_id=repo.id AND is_closed=? AND is_pull=?)", true, false)
  1791. if err != nil {
  1792. log.Error("Select %s: %v", desc, err)
  1793. } else {
  1794. for _, result := range results {
  1795. id := com.StrTo(result["id"]).MustInt64()
  1796. log.Trace("Updating %s: %d", desc, id)
  1797. _, err = x.Exec("UPDATE `repository` SET num_closed_issues=(SELECT COUNT(*) FROM `issue` WHERE repo_id=? AND is_closed=? AND is_pull=?) WHERE id=?", id, true, false, id)
  1798. if err != nil {
  1799. log.Error("Update %s[%d]: %v", desc, id, err)
  1800. }
  1801. }
  1802. }
  1803. // ***** END: Repository.NumClosedIssues *****
  1804. // FIXME: use checker when stop supporting old fork repo format.
  1805. // ***** START: Repository.NumForks *****
  1806. results, err = x.Query("SELECT repo.id FROM `repository` repo WHERE repo.num_forks!=(SELECT COUNT(*) FROM `repository` WHERE fork_id=repo.id)")
  1807. if err != nil {
  1808. log.Error("Select repository count 'num_forks': %v", err)
  1809. } else {
  1810. for _, result := range results {
  1811. id := com.StrTo(result["id"]).MustInt64()
  1812. log.Trace("Updating repository count 'num_forks': %d", id)
  1813. repo, err := GetRepositoryByID(id)
  1814. if err != nil {
  1815. log.Error("GetRepositoryByID[%d]: %v", id, err)
  1816. continue
  1817. }
  1818. rawResult, err := x.Query("SELECT COUNT(*) FROM `repository` WHERE fork_id=?", repo.ID)
  1819. if err != nil {
  1820. log.Error("Select count of forks[%d]: %v", repo.ID, err)
  1821. continue
  1822. }
  1823. repo.NumForks = int(parseCountResult(rawResult))
  1824. if err = UpdateRepository(repo, false); err != nil {
  1825. log.Error("UpdateRepository[%d]: %v", id, err)
  1826. continue
  1827. }
  1828. }
  1829. }
  1830. // ***** END: Repository.NumForks *****
  1831. }
  1832. type RepositoryList []*Repository
  1833. func (repos RepositoryList) loadAttributes(e Engine) error {
  1834. if len(repos) == 0 {
  1835. return nil
  1836. }
  1837. // Load owners
  1838. userSet := make(map[int64]*User)
  1839. for i := range repos {
  1840. userSet[repos[i].OwnerID] = nil
  1841. }
  1842. userIDs := make([]int64, 0, len(userSet))
  1843. for userID := range userSet {
  1844. userIDs = append(userIDs, userID)
  1845. }
  1846. users := make([]*User, 0, len(userIDs))
  1847. if err := e.Where("id > 0").In("id", userIDs).Find(&users); err != nil {
  1848. return fmt.Errorf("find users: %v", err)
  1849. }
  1850. for i := range users {
  1851. userSet[users[i].ID] = users[i]
  1852. }
  1853. for i := range repos {
  1854. repos[i].Owner = userSet[repos[i].OwnerID]
  1855. }
  1856. // Load base repositories
  1857. repoSet := make(map[int64]*Repository)
  1858. for i := range repos {
  1859. if repos[i].IsFork {
  1860. repoSet[repos[i].ForkID] = nil
  1861. }
  1862. }
  1863. baseIDs := make([]int64, 0, len(repoSet))
  1864. for baseID := range repoSet {
  1865. baseIDs = append(baseIDs, baseID)
  1866. }
  1867. baseRepos := make([]*Repository, 0, len(baseIDs))
  1868. if err := e.Where("id > 0").In("id", baseIDs).Find(&baseRepos); err != nil {
  1869. return fmt.Errorf("find base repositories: %v", err)
  1870. }
  1871. for i := range baseRepos {
  1872. repoSet[baseRepos[i].ID] = baseRepos[i]
  1873. }
  1874. for i := range repos {
  1875. if repos[i].IsFork {
  1876. repos[i].BaseRepo = repoSet[repos[i].ForkID]
  1877. }
  1878. }
  1879. return nil
  1880. }
  1881. func (repos RepositoryList) LoadAttributes() error {
  1882. return repos.loadAttributes(x)
  1883. }
  1884. type MirrorRepositoryList []*Repository
  1885. func (repos MirrorRepositoryList) loadAttributes(e Engine) error {
  1886. if len(repos) == 0 {
  1887. return nil
  1888. }
  1889. // Load mirrors.
  1890. repoIDs := make([]int64, 0, len(repos))
  1891. for i := range repos {
  1892. if !repos[i].IsMirror {
  1893. continue
  1894. }
  1895. repoIDs = append(repoIDs, repos[i].ID)
  1896. }
  1897. mirrors := make([]*Mirror, 0, len(repoIDs))
  1898. if err := e.Where("id > 0").In("repo_id", repoIDs).Find(&mirrors); err != nil {
  1899. return fmt.Errorf("find mirrors: %v", err)
  1900. }
  1901. set := make(map[int64]*Mirror)
  1902. for i := range mirrors {
  1903. set[mirrors[i].RepoID] = mirrors[i]
  1904. }
  1905. for i := range repos {
  1906. repos[i].Mirror = set[repos[i].ID]
  1907. }
  1908. return nil
  1909. }
  1910. func (repos MirrorRepositoryList) LoadAttributes() error {
  1911. return repos.loadAttributes(x)
  1912. }
  1913. // __ __ __ .__
  1914. // / \ / \_____ _/ |_ ____ | |__
  1915. // \ \/\/ /\__ \\ __\/ ___\| | \
  1916. // \ / / __ \| | \ \___| Y \
  1917. // \__/\ / (____ /__| \___ >___| /
  1918. // \/ \/ \/ \/
  1919. // Watch is connection request for receiving repository notification.
  1920. type Watch struct {
  1921. ID int64
  1922. UserID int64 `xorm:"UNIQUE(watch)"`
  1923. RepoID int64 `xorm:"UNIQUE(watch)"`
  1924. }
  1925. func isWatching(e Engine, userID, repoID int64) bool {
  1926. has, _ := e.Get(&Watch{0, userID, repoID})
  1927. return has
  1928. }
  1929. // IsWatching checks if user has watched given repository.
  1930. func IsWatching(userID, repoID int64) bool {
  1931. return isWatching(x, userID, repoID)
  1932. }
  1933. func watchRepo(e Engine, userID, repoID int64, watch bool) (err error) {
  1934. if watch {
  1935. if isWatching(e, userID, repoID) {
  1936. return nil
  1937. }
  1938. if _, err = e.Insert(&Watch{RepoID: repoID, UserID: userID}); err != nil {
  1939. return err
  1940. }
  1941. _, err = e.Exec("UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?", repoID)
  1942. } else {
  1943. if !isWatching(e, userID, repoID) {
  1944. return nil
  1945. }
  1946. if _, err = e.Delete(&Watch{0, userID, repoID}); err != nil {
  1947. return err
  1948. }
  1949. _, err = e.Exec("UPDATE `repository` SET num_watches = num_watches - 1 WHERE id = ?", repoID)
  1950. }
  1951. return err
  1952. }
  1953. // Watch or unwatch repository.
  1954. func WatchRepo(userID, repoID int64, watch bool) (err error) {
  1955. return watchRepo(x, userID, repoID, watch)
  1956. }
  1957. func getWatchers(e Engine, repoID int64) ([]*Watch, error) {
  1958. watches := make([]*Watch, 0, 10)
  1959. return watches, e.Find(&watches, &Watch{RepoID: repoID})
  1960. }
  1961. // GetWatchers returns all watchers of given repository.
  1962. func GetWatchers(repoID int64) ([]*Watch, error) {
  1963. return getWatchers(x, repoID)
  1964. }
  1965. // Repository.GetWatchers returns range of users watching given repository.
  1966. func (repo *Repository) GetWatchers(page int) ([]*User, error) {
  1967. users := make([]*User, 0, ItemsPerPage)
  1968. sess := x.Limit(ItemsPerPage, (page-1)*ItemsPerPage).Where("watch.repo_id=?", repo.ID)
  1969. if conf.UsePostgreSQL {
  1970. sess = sess.Join("LEFT", "watch", `"user".id=watch.user_id`)
  1971. } else {
  1972. sess = sess.Join("LEFT", "watch", "user.id=watch.user_id")
  1973. }
  1974. return users, sess.Find(&users)
  1975. }
  1976. func notifyWatchers(e Engine, act *Action) error {
  1977. // Add feeds for user self and all watchers.
  1978. watchers, err := getWatchers(e, act.RepoID)
  1979. if err != nil {
  1980. return fmt.Errorf("getWatchers: %v", err)
  1981. }
  1982. // Reset ID to reuse Action object
  1983. act.ID = 0
  1984. // Add feed for actioner.
  1985. act.UserID = act.ActUserID
  1986. if _, err = e.Insert(act); err != nil {
  1987. return fmt.Errorf("insert new action: %v", err)
  1988. }
  1989. for i := range watchers {
  1990. if act.ActUserID == watchers[i].UserID {
  1991. continue
  1992. }
  1993. act.ID = 0
  1994. act.UserID = watchers[i].UserID
  1995. if _, err = e.Insert(act); err != nil {
  1996. return fmt.Errorf("insert new action: %v", err)
  1997. }
  1998. }
  1999. return nil
  2000. }
  2001. // NotifyWatchers creates batch of actions for every watcher.
  2002. func NotifyWatchers(act *Action) error {
  2003. return notifyWatchers(x, act)
  2004. }
  2005. // _________ __
  2006. // / _____// |______ _______
  2007. // \_____ \\ __\__ \\_ __ \
  2008. // / \| | / __ \| | \/
  2009. // /_______ /|__| (____ /__|
  2010. // \/ \/
  2011. type Star struct {
  2012. ID int64
  2013. UID int64 `xorm:"UNIQUE(s)"`
  2014. RepoID int64 `xorm:"UNIQUE(s)"`
  2015. }
  2016. // Star or unstar repository.
  2017. func StarRepo(userID, repoID int64, star bool) (err error) {
  2018. if star {
  2019. if IsStaring(userID, repoID) {
  2020. return nil
  2021. }
  2022. if _, err = x.Insert(&Star{UID: userID, RepoID: repoID}); err != nil {
  2023. return err
  2024. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars + 1 WHERE id = ?", repoID); err != nil {
  2025. return err
  2026. }
  2027. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars + 1 WHERE id = ?", userID)
  2028. } else {
  2029. if !IsStaring(userID, repoID) {
  2030. return nil
  2031. }
  2032. if _, err = x.Delete(&Star{0, userID, repoID}); err != nil {
  2033. return err
  2034. } else if _, err = x.Exec("UPDATE `repository` SET num_stars = num_stars - 1 WHERE id = ?", repoID); err != nil {
  2035. return err
  2036. }
  2037. _, err = x.Exec("UPDATE `user` SET num_stars = num_stars - 1 WHERE id = ?", userID)
  2038. }
  2039. return err
  2040. }
  2041. // IsStaring checks if user has starred given repository.
  2042. func IsStaring(userID, repoID int64) bool {
  2043. has, _ := x.Get(&Star{0, userID, repoID})
  2044. return has
  2045. }
  2046. func (repo *Repository) GetStargazers(page int) ([]*User, error) {
  2047. users := make([]*User, 0, ItemsPerPage)
  2048. sess := x.Limit(ItemsPerPage, (page-1)*ItemsPerPage).Where("star.repo_id=?", repo.ID)
  2049. if conf.UsePostgreSQL {
  2050. sess = sess.Join("LEFT", "star", `"user".id=star.uid`)
  2051. } else {
  2052. sess = sess.Join("LEFT", "star", "user.id=star.uid")
  2053. }
  2054. return users, sess.Find(&users)
  2055. }
  2056. // ___________ __
  2057. // \_ _____/__________| | __
  2058. // | __)/ _ \_ __ \ |/ /
  2059. // | \( <_> ) | \/ <
  2060. // \___ / \____/|__| |__|_ \
  2061. // \/ \/
  2062. // HasForkedRepo checks if given user has already forked a repository.
  2063. // When user has already forked, it returns true along with the repository.
  2064. func HasForkedRepo(ownerID, repoID int64) (*Repository, bool, error) {
  2065. repo := new(Repository)
  2066. has, err := x.Where("owner_id = ? AND fork_id = ?", ownerID, repoID).Get(repo)
  2067. if err != nil {
  2068. return nil, false, err
  2069. } else if !has {
  2070. return nil, false, nil
  2071. }
  2072. return repo, true, repo.LoadAttributes()
  2073. }
  2074. // ForkRepository creates a fork of target repository under another user domain.
  2075. func ForkRepository(doer, owner *User, baseRepo *Repository, name, desc string) (_ *Repository, err error) {
  2076. if !owner.CanCreateRepo() {
  2077. return nil, ErrReachLimitOfRepo{Limit: owner.RepoCreationNum()}
  2078. }
  2079. repo := &Repository{
  2080. OwnerID: owner.ID,
  2081. Owner: owner,
  2082. Name: name,
  2083. LowerName: strings.ToLower(name),
  2084. Description: desc,
  2085. DefaultBranch: baseRepo.DefaultBranch,
  2086. IsPrivate: baseRepo.IsPrivate,
  2087. IsFork: true,
  2088. ForkID: baseRepo.ID,
  2089. }
  2090. sess := x.NewSession()
  2091. defer sess.Close()
  2092. if err = sess.Begin(); err != nil {
  2093. return nil, err
  2094. }
  2095. if err = createRepository(sess, doer, owner, repo); err != nil {
  2096. return nil, err
  2097. } else if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks+1 WHERE id=?", baseRepo.ID); err != nil {
  2098. return nil, err
  2099. }
  2100. repoPath := repo.repoPath(sess)
  2101. RemoveAllWithNotice("Repository path erase before creation", repoPath)
  2102. _, stderr, err := process.ExecTimeout(10*time.Minute,
  2103. fmt.Sprintf("ForkRepository 'git clone': %s/%s", owner.Name, repo.Name),
  2104. "git", "clone", "--bare", baseRepo.RepoPath(), repoPath)
  2105. if err != nil {
  2106. return nil, fmt.Errorf("git clone: %v - %s", err, stderr)
  2107. }
  2108. _, stderr, err = process.ExecDir(-1,
  2109. repoPath, fmt.Sprintf("ForkRepository 'git update-server-info': %s", repoPath),
  2110. "git", "update-server-info")
  2111. if err != nil {
  2112. return nil, fmt.Errorf("git update-server-info: %v - %s", err, stderr)
  2113. }
  2114. if err = createDelegateHooks(repoPath); err != nil {
  2115. return nil, fmt.Errorf("createDelegateHooks: %v", err)
  2116. }
  2117. if err = sess.Commit(); err != nil {
  2118. return nil, fmt.Errorf("Commit: %v", err)
  2119. }
  2120. if err = repo.UpdateSize(); err != nil {
  2121. log.Error("UpdateSize [repo_id: %d]: %v", repo.ID, err)
  2122. }
  2123. if err = PrepareWebhooks(baseRepo, HOOK_EVENT_FORK, &api.ForkPayload{
  2124. Forkee: repo.APIFormat(nil),
  2125. Repo: baseRepo.APIFormat(nil),
  2126. Sender: doer.APIFormat(),
  2127. }); err != nil {
  2128. log.Error("PrepareWebhooks [repo_id: %d]: %v", baseRepo.ID, err)
  2129. }
  2130. return repo, nil
  2131. }
  2132. func (repo *Repository) GetForks() ([]*Repository, error) {
  2133. forks := make([]*Repository, 0, repo.NumForks)
  2134. if err := x.Find(&forks, &Repository{ForkID: repo.ID}); err != nil {
  2135. return nil, err
  2136. }
  2137. for _, fork := range forks {
  2138. fork.BaseRepo = repo
  2139. }
  2140. return forks, nil
  2141. }
  2142. // __________ .__
  2143. // \______ \____________ ____ ____ | |__
  2144. // | | _/\_ __ \__ \ / \_/ ___\| | \
  2145. // | | \ | | \// __ \| | \ \___| Y \
  2146. // |______ / |__| (____ /___| /\___ >___| /
  2147. // \/ \/ \/ \/ \/
  2148. //
  2149. func (repo *Repository) CreateNewBranch(oldBranch, newBranch string) (err error) {
  2150. repoWorkingPool.CheckIn(com.ToStr(repo.ID))
  2151. defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
  2152. localPath := repo.LocalCopyPath()
  2153. if err = discardLocalRepoBranchChanges(localPath, oldBranch); err != nil {
  2154. return fmt.Errorf("discard changes in local copy [path: %s, branch: %s]: %v", localPath, oldBranch, err)
  2155. } else if err = repo.UpdateLocalCopyBranch(oldBranch); err != nil {
  2156. return fmt.Errorf("update branch for local copy [path: %s, branch: %s]: %v", localPath, oldBranch, err)
  2157. }
  2158. if err = repo.CheckoutNewBranch(oldBranch, newBranch); err != nil {
  2159. return fmt.Errorf("create new branch [base: %s, new: %s]: %v", oldBranch, newBranch, err)
  2160. }
  2161. if err = git.RepoPush(localPath, "origin", newBranch); err != nil {
  2162. return fmt.Errorf("push [branch: %s]: %v", newBranch, err)
  2163. }
  2164. return nil
  2165. }