repo.go 71 KB

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