repo.go 70 KB

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