diff --git a/README.md b/README.md index 093888749..ce5c0b612 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ Gogs - Go Git Service [![Build Status](https://travis-ci.org/gogits/gogs.svg?bra ![](https://github.com/gogits/gogs/blob/master/public/img/gogs-large-resize.png?raw=true) -##### Current tip version: 0.9.94 (see [Releases](https://github.com/gogits/gogs/releases) for binary versions) +##### Current tip version: 0.9.95 (see [Releases](https://github.com/gogits/gogs/releases) for binary versions) | Web | UI | Preview | |:-------------:|:-------:|:-------:| diff --git a/cmd/web.go b/cmd/web.go index 3a1108a45..92e7fef42 100644 --- a/cmd/web.go +++ b/cmd/web.go @@ -505,12 +505,20 @@ func runWeb(ctx *cli.Context) error { m.Combo("/_new/*").Get(repo.NewFile). Post(bindIgnErr(auth.EditRepoFileForm{}), repo.NewFilePost) m.Post("/_preview/*", bindIgnErr(auth.EditPreviewDiffForm{}), repo.DiffPreviewPost) - m.Combo("/_upload/*").Get(repo.UploadFile). - Post(bindIgnErr(auth.UploadRepoFileForm{}), repo.UploadFilePost) m.Combo("/_delete/*").Get(repo.DeleteFile). Post(bindIgnErr(auth.DeleteRepoFileForm{}), repo.DeleteFilePost) - // m.Post("/upload-file", repo.UploadFileToServer) - // m.Post("/upload-remove", bindIgnErr(auth.RemoveUploadFileForm{}), repo.RemoveUploadFileFromServer) + + m.Group("", func() { + m.Combo("/_upload/*").Get(repo.UploadFile). + Post(bindIgnErr(auth.UploadRepoFileForm{}), repo.UploadFilePost) + m.Post("/upload-file", repo.UploadFileToServer) + m.Post("/upload-remove", bindIgnErr(auth.RemoveUploadFileForm{}), repo.RemoveUploadFileFromServer) + }, func(ctx *context.Context) { + if !setting.Repository.Upload.Enabled { + ctx.Handle(404, "", nil) + return + } + }) }, reqRepoWriter, context.RepoRef(), func(ctx *context.Context) { if !ctx.Repo.Repository.CanEnableEditor() || ctx.Repo.IsViewCommit { ctx.Handle(404, "", nil) diff --git a/conf/app.ini b/conf/app.ini index 5206d4c3b..328777549 100644 --- a/conf/app.ini +++ b/conf/app.ini @@ -38,10 +38,10 @@ ENABLED = true TEMP_PATH = data/tmp/uploads ; One or more allowed types, e.g. image/jpeg|image/png. Nothing means any file type ALLOWED_TYPES = -; Max size of each file in MB. Defaults to 32MB -FILE_MAX_SIZE = 32 -; Max number of files per upload. Defaults to 10 -MAX_FILES = 10 +; Max size of each file in MB. Defaults to 3MB +FILE_MAX_SIZE = 3 +; Max number of files per upload. Defaults to 5 +MAX_FILES = 5 [ui] ; Number of repositories that are showed in one explore page diff --git a/conf/locale/locale_en-US.ini b/conf/locale/locale_en-US.ini index 2aa2bf0d6..d2ffde68c 100644 --- a/conf/locale/locale_en-US.ini +++ b/conf/locale/locale_en-US.ini @@ -427,6 +427,7 @@ file_permalink = Permalink file_too_large = This file is too large to be shown editor.new_file = New file +editor.upload_file = Upload file editor.edit_file = Edit file editor.preview_changes = Preview Changes editor.cannot_edit_non_text_files = Cannot edit non-text files @@ -459,10 +460,9 @@ editor.file_changed_while_editing = File content has been changed since you star editor.file_already_exists = A file with name '%s' already exists in this repository. editor.no_changes_to_show = There are no changes to show. editor.fail_to_update_file = Failed to update/create file '%s' with error: %v -upload_files = Upload files -upload_file = Upload file -add_files_to_dir = Add files to %s -add_subdir = Add subdirectory... +editor.add_subdir = Add subdirectory... +editor.unable_to_upload_files = Failed to upload files to '%s' with error: %v +editor.upload_files_to_dir = Upload files to '%s' commits.commits = Commits commits.search = Search commits diff --git a/gogs.go b/gogs.go index 369ef9930..3dd7add7a 100644 --- a/gogs.go +++ b/gogs.go @@ -17,7 +17,7 @@ import ( "github.com/gogits/gogs/modules/setting" ) -const APP_VER = "0.9.94.0830" +const APP_VER = "0.9.95.0830" func init() { runtime.GOMAXPROCS(runtime.NumCPU()) diff --git a/models/error.go b/models/error.go index 240e60677..dd1d4a668 100644 --- a/models/error.go +++ b/models/error.go @@ -652,10 +652,8 @@ func (err ErrTeamAlreadyExist) Error() string { // type ErrUploadNotExist struct { - ID int64 - UUID string - UserID int64 - RepoID int64 + ID int64 + UUID string } func IsErrUploadNotExist(err error) bool { @@ -664,5 +662,5 @@ func IsErrUploadNotExist(err error) bool { } func (err ErrUploadNotExist) Error() string { - return fmt.Sprintf("attachment does not exist [id: %d, uuid: %s, user_id: %d, repo_id: %d]", err.ID, err.UUID, err.UserID, err.RepoID) + return fmt.Sprintf("attachment does not exist [id: %d, uuid: %s]", err.ID, err.UUID) } diff --git a/models/issue.go b/models/issue.go index a90ebaf86..208204b07 100644 --- a/models/issue.go +++ b/models/issue.go @@ -1685,11 +1685,12 @@ func NewAttachment(name string, buf []byte, file multipart.File) (_ *Attachment, Name: name, } - if err = os.MkdirAll(path.Dir(attach.LocalPath()), os.ModePerm); err != nil { + localPath := attach.LocalPath() + if err = os.MkdirAll(path.Dir(localPath), os.ModePerm); err != nil { return nil, fmt.Errorf("MkdirAll: %v", err) } - fw, err := os.Create(attach.LocalPath()) + fw, err := os.Create(localPath) if err != nil { return nil, fmt.Errorf("Create: %v", err) } @@ -1701,17 +1702,11 @@ func NewAttachment(name string, buf []byte, file multipart.File) (_ *Attachment, return nil, fmt.Errorf("Copy: %v", err) } - sess := x.NewSession() - defer sessionRelease(sess) - if err := sess.Begin(); err != nil { + if _, err := x.Insert(attach); err != nil { return nil, err } - if _, err := sess.Insert(attach); err != nil { - return nil, err - } - - return attach, sess.Commit() + return attach, nil } func getAttachmentByUUID(e Engine, uuid string) (*Attachment, error) { diff --git a/models/models.go b/models/models.go index 582c4403a..481e53e36 100644 --- a/models/models.go +++ b/models/models.go @@ -60,7 +60,7 @@ var ( func init() { tables = append(tables, new(User), new(PublicKey), new(AccessToken), - new(Repository), new(DeployKey), new(Collaboration), new(Access), + new(Repository), new(DeployKey), new(Collaboration), new(Access), new(Upload), new(Watch), new(Star), new(Follow), new(Action), new(Issue), new(PullRequest), new(Comment), new(Attachment), new(IssueUser), new(Label), new(IssueLabel), new(Milestone), diff --git a/models/pull.go b/models/pull.go index fa9a44897..64b347554 100644 --- a/models/pull.go +++ b/models/pull.go @@ -339,9 +339,6 @@ var patchConflicts = []string{ // testPatch checks if patch can be merged to base repository without conflit. // FIXME: make a mechanism to clean up stable local copies. func (pr *PullRequest) testPatch() (err error) { - repoWorkingPool.CheckIn(com.ToStr(pr.BaseRepoID)) - defer repoWorkingPool.CheckOut(com.ToStr(pr.BaseRepoID)) - if pr.BaseRepo == nil { pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID) if err != nil { @@ -360,6 +357,9 @@ func (pr *PullRequest) testPatch() (err error) { return nil } + repoWorkingPool.CheckIn(com.ToStr(pr.BaseRepoID)) + defer repoWorkingPool.CheckOut(com.ToStr(pr.BaseRepoID)) + log.Trace("PullRequest[%d].testPatch (patchPath): %s", pr.ID, patchPath) if err := pr.BaseRepo.UpdateLocalCopyBranch(pr.BaseBranch); err != nil { diff --git a/models/repo.go b/models/repo.go index 2c19afbd1..a26ba9248 100644 --- a/models/repo.go +++ b/models/repo.go @@ -9,9 +9,7 @@ import ( "errors" "fmt" "html/template" - "io" "io/ioutil" - "mime/multipart" "os" "os/exec" "path" @@ -29,7 +27,6 @@ import ( git "github.com/gogits/git-module" api "github.com/gogits/go-gogs-client" - gouuid "github.com/satori/go.uuid" "github.com/gogits/gogs/modules/bindata" "github.com/gogits/gogs/modules/log" @@ -2272,197 +2269,6 @@ func (repo *Repository) GetForks() ([]*Repository, error) { return forks, x.Find(&forks, &Repository{ForkID: repo.ID}) } -// ____ ___ .__ .___ ___________.___.__ -// | | \______ | | _________ __| _/ \_ _____/| | | ____ ______ -// | | /\____ \| | / _ \__ \ / __ | | __) | | | _/ __ \ / ___/ -// | | / | |_> > |_( <_> ) __ \_/ /_/ | | \ | | |_\ ___/ \___ \ -// |______/ | __/|____/\____(____ /\____ | \___ / |___|____/\___ >____ > -// |__| \/ \/ \/ \/ \/ -// - -// uploadRepoFiles uploads new files to repository. -func (repo *Repository) UploadRepoFiles(doer *User, oldBranchName, branchName, treePath, message string, uuids []string) (err error) { - repoWorkingPool.CheckIn(com.ToStr(repo.ID)) - defer repoWorkingPool.CheckOut(com.ToStr(repo.ID)) - - localPath := repo.LocalCopyPath() - - if err = discardLocalRepoBranchChanges(localPath, oldBranchName); err != nil { - return fmt.Errorf("discardLocalRepoChanges: %v", err) - } else if err = repo.UpdateLocalCopyBranch(oldBranchName); err != nil { - return fmt.Errorf("UpdateLocalCopyBranch: %v", err) - } - - if oldBranchName != branchName { - repo.CheckoutNewBranch(oldBranchName, branchName) - } - - dirPath := path.Join(localPath, treePath) - os.MkdirAll(dirPath, os.ModePerm) - - // Copy uploaded files into repository. - for _, uuid := range uuids { - upload, err := getUpload(uuid, doer.ID, repo.ID) - if err != nil { - if IsErrUploadNotExist(err) { - continue - } - return fmt.Errorf("getUpload[%s]: %v", uuid, err) - } - uuidPath := upload.LocalPath() - filePath := dirPath + "/" + upload.Name - if err := os.Rename(uuidPath, filePath); err != nil { - DeleteUpload(upload, true) - return fmt.Errorf("Rename[%s -> %s]: %v", uuidPath, filePath, err) - } - DeleteUpload(upload, false) // false because we have moved the file - } - - if len(message) == 0 { - message = "Add files to '" + treePath + "'" - } - - if err = git.AddChanges(localPath, true); err != nil { - return fmt.Errorf("AddChanges: %v", err) - } else if err = git.CommitChanges(localPath, git.CommitChangesOptions{ - Committer: doer.NewGitSig(), - Message: message, - }); err != nil { - return fmt.Errorf("CommitChanges: %v", err) - } else if err = git.Push(localPath, "origin", branchName); err != nil { - return fmt.Errorf("Push: %v", err) - } - - return nil -} - -// Upload represent a uploaded file to a repo to be deleted when moved -type Upload struct { - ID int64 `xorm:"pk autoincr"` - UUID string `xorm:"uuid UNIQUE"` - UID int64 `xorm:"INDEX"` - RepoID int64 `xorm:"INDEX"` - Name string - Created time.Time `xorm:"-"` - CreatedUnix int64 -} - -func (u *Upload) BeforeInsert() { - u.CreatedUnix = time.Now().UTC().Unix() -} - -func (u *Upload) AfterSet(colName string, _ xorm.Cell) { - switch colName { - case "created_unix": - u.Created = time.Unix(u.CreatedUnix, 0).Local() - } -} - -// UploadLocalPath returns where uploads is stored in local file system based on given UUID. -func UploadLocalPath(uuid string) string { - return path.Join(setting.Repository.Upload.TempPath, uuid[0:1], uuid[1:2], uuid) -} - -// LocalPath returns where uploads are temporarily stored in local file system. -func (upload *Upload) LocalPath() string { - return UploadLocalPath(upload.UUID) -} - -// NewUpload creates a new upload object. -func NewUpload(name string, buf []byte, file multipart.File, userId, repoId int64) (_ *Upload, err error) { - up := &Upload{ - UUID: gouuid.NewV4().String(), - Name: name, - UID: userId, - RepoID: repoId, - } - - if err = os.MkdirAll(path.Dir(up.LocalPath()), os.ModePerm); err != nil { - return nil, fmt.Errorf("MkdirAll: %v", err) - } - - fw, err := os.Create(up.LocalPath()) - if err != nil { - return nil, fmt.Errorf("Create: %v", err) - } - defer fw.Close() - - if _, err = fw.Write(buf); err != nil { - return nil, fmt.Errorf("Write: %v", err) - } else if _, err = io.Copy(fw, file); err != nil { - return nil, fmt.Errorf("Copy: %v", err) - } - - sess := x.NewSession() - defer sessionRelease(sess) - if err := sess.Begin(); err != nil { - return nil, err - } - if _, err := sess.Insert(up); err != nil { - return nil, err - } - - return up, sess.Commit() -} - -// RemoveUpload removes the file by UUID -func RemoveUpload(uuid string, userId, repoId int64) (err error) { - sess := x.NewSession() - defer sessionRelease(sess) - if err := sess.Begin(); err != nil { - return err - } - upload, err := getUpload(uuid, userId, repoId) - if err != nil { - return fmt.Errorf("getUpload[%s]: %v", uuid, err) - } - - if err := DeleteUpload(upload, true); err != nil { - return fmt.Errorf("DeleteUpload[%s]: %v", uuid, err) - } - - return nil -} - -func getUpload(uuid string, userID, repoID int64) (*Upload, error) { - up := &Upload{UUID: uuid, UID: userID, RepoID: repoID} - has, err := x.Get(up) - if err != nil { - return nil, err - } else if !has { - return nil, ErrUploadNotExist{0, uuid, userID, repoID} - } - return up, nil -} - -// GetUpload returns Upload by given UUID. -func GetUpload(uuid string, userId, repoId int64) (*Upload, error) { - return getUpload(uuid, userId, repoId) -} - -// DeleteUpload deletes the given upload -func DeleteUpload(u *Upload, remove bool) error { - _, err := DeleteUploads([]*Upload{u}, remove) - return err -} - -// DeleteUploads deletes the given uploads -func DeleteUploads(uploads []*Upload, remove bool) (int, error) { - for i, u := range uploads { - if remove { - if err := os.Remove(u.LocalPath()); err != nil { - return i, err - } - } - - if _, err := x.Delete(u); err != nil { - return i, err - } - } - - return len(uploads), nil -} - // __________ .__ // \______ \____________ ____ ____ | |__ // | | _/\_ __ \__ \ / \_/ ___\| | \ diff --git a/models/repo_editor.go b/models/repo_editor.go index 31b94f631..dfdb864a1 100644 --- a/models/repo_editor.go +++ b/models/repo_editor.go @@ -6,7 +6,9 @@ package models import ( "fmt" + "io" "io/ioutil" + "mime/multipart" "os" "os/exec" "path" @@ -14,6 +16,7 @@ import ( "time" "github.com/Unknwon/com" + gouuid "github.com/satori/go.uuid" git "github.com/gogits/git-module" @@ -291,3 +294,227 @@ func (repo *Repository) DeleteRepoFile(doer *User, opts DeleteRepoFileOptions) ( return nil } + +// ____ ___ .__ .___ ___________.___.__ +// | | \______ | | _________ __| _/ \_ _____/| | | ____ ______ +// | | /\____ \| | / _ \__ \ / __ | | __) | | | _/ __ \ / ___/ +// | | / | |_> > |_( <_> ) __ \_/ /_/ | | \ | | |_\ ___/ \___ \ +// |______/ | __/|____/\____(____ /\____ | \___ / |___|____/\___ >____ > +// |__| \/ \/ \/ \/ \/ +// + +// Upload represent a uploaded file to a repo to be deleted when moved +type Upload struct { + ID int64 `xorm:"pk autoincr"` + UUID string `xorm:"uuid UNIQUE"` + Name string +} + +// UploadLocalPath returns where uploads is stored in local file system based on given UUID. +func UploadLocalPath(uuid string) string { + return path.Join(setting.Repository.Upload.TempPath, uuid[0:1], uuid[1:2], uuid) +} + +// LocalPath returns where uploads are temporarily stored in local file system. +func (upload *Upload) LocalPath() string { + return UploadLocalPath(upload.UUID) +} + +// NewUpload creates a new upload object. +func NewUpload(name string, buf []byte, file multipart.File) (_ *Upload, err error) { + upload := &Upload{ + UUID: gouuid.NewV4().String(), + Name: name, + } + + localPath := upload.LocalPath() + if err = os.MkdirAll(path.Dir(localPath), os.ModePerm); err != nil { + return nil, fmt.Errorf("MkdirAll: %v", err) + } + + fw, err := os.Create(localPath) + if err != nil { + return nil, fmt.Errorf("Create: %v", err) + } + defer fw.Close() + + if _, err = fw.Write(buf); err != nil { + return nil, fmt.Errorf("Write: %v", err) + } else if _, err = io.Copy(fw, file); err != nil { + return nil, fmt.Errorf("Copy: %v", err) + } + + if _, err := x.Insert(upload); err != nil { + return nil, err + } + + return upload, nil +} + +func GetUploadByUUID(uuid string) (*Upload, error) { + upload := &Upload{UUID: uuid} + has, err := x.Get(upload) + if err != nil { + return nil, err + } else if !has { + return nil, ErrUploadNotExist{0, uuid} + } + return upload, nil +} + +func GetUploadsByUUIDs(uuids []string) ([]*Upload, error) { + if len(uuids) == 0 { + return []*Upload{}, nil + } + + // Silently drop invalid uuids. + uploads := make([]*Upload, 0, len(uuids)) + return uploads, x.In("uuid", uuids).Find(&uploads) +} + +func DeleteUploads(uploads ...*Upload) (err error) { + if len(uploads) == 0 { + return nil + } + + sess := x.NewSession() + defer sessionRelease(sess) + if err = sess.Begin(); err != nil { + return err + } + + ids := make([]int64, len(uploads)) + for i := 0; i < len(uploads); i++ { + ids[i] = uploads[i].ID + } + if _, err = sess.In("id", ids).Delete(new(Upload)); err != nil { + return fmt.Errorf("delete uploads: %v", err) + } + + for _, upload := range uploads { + localPath := upload.LocalPath() + if !com.IsFile(localPath) { + continue + } + + if err := os.Remove(localPath); err != nil { + return fmt.Errorf("remove upload: %v", err) + } + } + + return sess.Commit() +} + +func DeleteUpload(u *Upload) error { + return DeleteUploads(u) +} + +func DeleteUploadByUUID(uuid string) error { + upload, err := GetUploadByUUID(uuid) + if err != nil { + if IsErrUploadNotExist(err) { + return nil + } + return fmt.Errorf("GetUploadByUUID: %v", err) + } + + if err := DeleteUpload(upload); err != nil { + return fmt.Errorf("DeleteUpload: %v", err) + } + + return nil +} + +type UploadRepoFileOptions struct { + LastCommitID string + OldBranch string + NewBranch string + TreePath string + Message string + Files []string // In UUID format. +} + +func (repo *Repository) UploadRepoFiles(doer *User, opts UploadRepoFileOptions) (err error) { + if len(opts.Files) == 0 { + return nil + } + + uploads, err := GetUploadsByUUIDs(opts.Files) + if err != nil { + return fmt.Errorf("GetUploadsByUUIDs [uuids: %v]: %v", opts.Files, err) + } + + repoWorkingPool.CheckIn(com.ToStr(repo.ID)) + defer repoWorkingPool.CheckOut(com.ToStr(repo.ID)) + + if err = repo.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil { + return fmt.Errorf("DiscardLocalRepoBranchChanges [branch: %s]: %v", opts.OldBranch, err) + } else if err = repo.UpdateLocalCopyBranch(opts.OldBranch); err != nil { + return fmt.Errorf("UpdateLocalCopyBranch [branch: %s]: %v", opts.OldBranch, err) + } + + if opts.OldBranch != opts.NewBranch { + if err = repo.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil { + return fmt.Errorf("CheckoutNewBranch [old_branch: %s, new_branch: %s]: %v", opts.OldBranch, opts.NewBranch, err) + } + } + + localPath := repo.LocalCopyPath() + dirPath := path.Join(localPath, opts.TreePath) + os.MkdirAll(dirPath, os.ModePerm) + + // Copy uploaded files into repository. + for _, upload := range uploads { + tmpPath := upload.LocalPath() + targetPath := path.Join(dirPath, upload.Name) + if !com.IsFile(tmpPath) { + continue + } + + if err = com.Copy(tmpPath, targetPath); err != nil { + return fmt.Errorf("Copy: %v", err) + } + } + + if err = git.AddChanges(localPath, true); err != nil { + return fmt.Errorf("git add --all: %v", err) + } else if err = git.CommitChanges(localPath, git.CommitChangesOptions{ + Committer: doer.NewGitSig(), + Message: opts.Message, + }); err != nil { + return fmt.Errorf("CommitChanges: %v", err) + } else if err = git.Push(localPath, "origin", opts.NewBranch); err != nil { + return fmt.Errorf("git push origin %s: %v", opts.NewBranch, err) + } + + gitRepo, err := git.OpenRepository(repo.RepoPath()) + if err != nil { + log.Error(4, "OpenRepository: %v", err) + return nil + } + commit, err := gitRepo.GetBranchCommit(opts.NewBranch) + if err != nil { + log.Error(4, "GetBranchCommit [branch: %s]: %v", opts.NewBranch, err) + return nil + } + + // Simulate push event. + pushCommits := &PushCommits{ + Len: 1, + Commits: []*PushCommit{CommitToPushCommit(commit)}, + } + if err := CommitRepoAction(CommitRepoActionOptions{ + PusherName: doer.Name, + RepoOwnerID: repo.MustOwner().ID, + RepoName: repo.Name, + RefFullName: git.BRANCH_PREFIX + opts.NewBranch, + OldCommitID: opts.LastCommitID, + NewCommitID: commit.ID.String(), + Commits: pushCommits, + }); err != nil { + log.Error(4, "CommitRepoAction: %v", err) + return nil + } + + return DeleteUploads(uploads...) +} diff --git a/modules/auth/repo_form.go b/modules/auth/repo_form.go index 0ed4c1b22..d1e28dc11 100644 --- a/modules/auth/repo_form.go +++ b/modules/auth/repo_form.go @@ -316,7 +316,7 @@ func (f *EditPreviewDiffForm) Validate(ctx *macaron.Context, errs binding.Errors // type UploadRepoFileForm struct { - TreeName string `binding:MaxSize(500)"` + TreePath string `binding:MaxSize(500)"` CommitSummary string `binding:"MaxSize(100)` CommitMessage string CommitChoice string `binding:"Required;MaxSize(50)"` diff --git a/modules/template/template.go b/modules/template/template.go index 433c41278..707697df3 100644 --- a/modules/template/template.go +++ b/modules/template/template.go @@ -86,6 +86,7 @@ func NewFuncMap() []template.FuncMap { } return str[start:end] }, + "EllipsisString": base.EllipsisString, "DiffTypeToStr": DiffTypeToStr, "DiffLineTypeToStr": DiffLineTypeToStr, "Sha1": Sha1, diff --git a/public/css/gogs.css b/public/css/gogs.css index d95f0b423..9e3b92fa5 100644 --- a/public/css/gogs.css +++ b/public/css/gogs.css @@ -1198,8 +1198,8 @@ footer .ui.language .menu { } .repository #clone-panel { margin-top: -8px; - width: 100%; - padding-left: 20px; + margin-left: 5px; + width: 350px; } .repository #clone-panel input { border-radius: 0; @@ -2270,13 +2270,13 @@ footer .ui.language .menu { .page.buttons { padding-top: 15px; } -.ui.comments .dropzone { +.ui.form .dropzone { width: 100%; margin-bottom: 10px; border: 2px dashed #0087F7; box-shadow: none!important; } -.ui.comments .dropzone .dz-error-message { +.ui.form .dropzone .dz-error-message { top: 140px; } .settings .content { diff --git a/public/less/_repository.less b/public/less/_repository.less index 24a0bfa01..dbbffdfeb 100644 --- a/public/less/_repository.less +++ b/public/less/_repository.less @@ -126,8 +126,8 @@ #clone-panel { margin-top: -8px; - width: 100%; - padding-left: 20px; + margin-left: 5px; + width: 350px; input { border-radius: 0; @@ -1303,7 +1303,7 @@ padding-top: 15px; } -.ui.comments { +.ui.form { .dropzone { width: 100%; margin-bottom: 10px; diff --git a/routers/repo/editor.go b/routers/repo/editor.go index 465de0021..f471e5ee2 100644 --- a/routers/repo/editor.go +++ b/routers/repo/editor.go @@ -5,7 +5,9 @@ package repo import ( + "fmt" "io/ioutil" + "net/http" "path" "strings" @@ -23,6 +25,7 @@ const ( EDIT_FILE base.TplName = "repo/editor/edit" EDIT_DIFF_PREVIEW base.TplName = "repo/editor/diff_preview" DELETE_FILE base.TplName = "repo/editor/delete" + UPLOAD_FILE base.TplName = "repo/editor/upload" ) func editFile(ctx *context.Context, isNewFile bool) { @@ -31,8 +34,6 @@ func editFile(ctx *context.Context, isNewFile bool) { ctx.Data["RequireHighlightJS"] = true ctx.Data["RequireSimpleMDE"] = true - branchLink := ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchName - var treeNames []string if len(ctx.Repo.TreePath) > 0 { treeNames = strings.Split(ctx.Repo.TreePath, "/") @@ -41,11 +42,7 @@ func editFile(ctx *context.Context, isNewFile bool) { if !isNewFile { entry, err := ctx.Repo.Commit.GetTreeEntryByPath(ctx.Repo.TreePath) if err != nil { - if git.IsErrNotExist(err) { - ctx.Handle(404, "GetTreeEntryByPath", err) - } else { - ctx.Handle(500, "GetTreeEntryByPath", err) - } + ctx.NotFoundOrServerError("GetTreeEntryByPath", git.IsErrNotExist, err) return } @@ -91,9 +88,8 @@ func editFile(ctx *context.Context, isNewFile bool) { treeNames = append(treeNames, "") // Append empty string to allow user name the new file. } - ctx.Data["TreePath"] = ctx.Repo.TreePath ctx.Data["TreeNames"] = treeNames - ctx.Data["BranchLink"] = branchLink + ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchName ctx.Data["commit_summary"] = "" ctx.Data["commit_message"] = "" ctx.Data["commit_choice"] = "direct" @@ -122,7 +118,6 @@ func editFilePost(ctx *context.Context, form auth.EditRepoFileForm, isNewFile bo oldBranchName := ctx.Repo.BranchName branchName := oldBranchName - branchLink := ctx.Repo.RepoLink + "/src/" + branchName oldTreePath := ctx.Repo.TreePath lastCommit := form.LastCommit form.LastCommit = ctx.Repo.Commit.ID.String() @@ -140,7 +135,7 @@ func editFilePost(ctx *context.Context, form auth.EditRepoFileForm, isNewFile bo ctx.Data["TreePath"] = form.TreePath ctx.Data["TreeNames"] = treeNames - ctx.Data["BranchLink"] = branchLink + ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + branchName ctx.Data["FileContent"] = form.Content ctx.Data["commit_summary"] = form.CommitSummary ctx.Data["commit_message"] = form.CommitMessage @@ -180,7 +175,7 @@ func editFilePost(ctx *context.Context, form auth.EditRepoFileForm, isNewFile bo break } - ctx.Handle(500, "GetTreeEntryByPath", err) + ctx.Handle(500, "Repo.Commit.GetTreeEntryByPath", err) return } if index != len(treeNames)-1 { @@ -326,7 +321,6 @@ func DeleteFilePost(ctx *context.Context, form auth.DeleteRepoFileForm) { oldBranchName := ctx.Repo.BranchName branchName := oldBranchName - treePath := ctx.Repo.TreePath if form.CommitChoice == "commit-to-new-branch" { branchName = form.NewBranchName @@ -351,7 +345,7 @@ func DeleteFilePost(ctx *context.Context, form auth.DeleteRepoFileForm) { message := strings.TrimSpace(form.CommitSummary) if len(message) == 0 { - message = ctx.Tr("repo.editor.delete", treePath) + message = ctx.Tr("repo.editor.delete", ctx.Repo.TreePath) } form.CommitMessage = strings.TrimSpace(form.CommitMessage) @@ -363,13 +357,186 @@ func DeleteFilePost(ctx *context.Context, form auth.DeleteRepoFileForm) { LastCommitID: ctx.Repo.CommitID, OldBranch: oldBranchName, NewBranch: branchName, - TreePath: treePath, + TreePath: ctx.Repo.TreePath, Message: message, }); err != nil { ctx.Handle(500, "DeleteRepoFile", err) return } - ctx.Flash.Success(ctx.Tr("repo.editor.file_delete_success", treePath)) + ctx.Flash.Success(ctx.Tr("repo.editor.file_delete_success", ctx.Repo.TreePath)) ctx.Redirect(ctx.Repo.RepoLink + "/src/" + branchName) } + +func renderUploadSettings(ctx *context.Context) { + ctx.Data["RequireDropzone"] = true + ctx.Data["UploadAllowedTypes"] = strings.Join(setting.Repository.Upload.AllowedTypes, ",") + ctx.Data["UploadMaxSize"] = setting.Repository.Upload.FileMaxSize + ctx.Data["UploadMaxFiles"] = setting.Repository.Upload.MaxFiles +} + +func UploadFile(ctx *context.Context) { + ctx.Data["PageIsUpload"] = true + renderUploadSettings(ctx) + + // We must at least have one element for user to input. + treeNames := []string{""} + if len(ctx.Repo.TreePath) > 0 { + treeNames = strings.Split(ctx.Repo.TreePath, "/") + } + + ctx.Data["TreeNames"] = treeNames + ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchName + ctx.Data["commit_summary"] = "" + ctx.Data["commit_message"] = "" + ctx.Data["commit_choice"] = "direct" + ctx.Data["new_branch_name"] = "" + + ctx.HTML(200, UPLOAD_FILE) +} + +func UploadFilePost(ctx *context.Context, form auth.UploadRepoFileForm) { + ctx.Data["PageIsUpload"] = true + renderUploadSettings(ctx) + + oldBranchName := ctx.Repo.BranchName + branchName := oldBranchName + + if form.CommitChoice == "commit-to-new-branch" { + branchName = form.NewBranchName + } + + form.TreePath = strings.Trim(form.TreePath, " /") + + // We must at least have one element for user to input. + treeNames := []string{""} + if len(form.TreePath) > 0 { + treeNames = strings.Split(form.TreePath, "/") + } + + ctx.Data["TreePath"] = form.TreePath + ctx.Data["TreeNames"] = treeNames + ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + branchName + ctx.Data["commit_summary"] = form.CommitSummary + ctx.Data["commit_message"] = form.CommitMessage + ctx.Data["commit_choice"] = form.CommitChoice + ctx.Data["new_branch_name"] = branchName + + if ctx.HasError() { + ctx.HTML(200, UPLOAD_FILE) + return + } + + if oldBranchName != branchName { + if _, err := ctx.Repo.Repository.GetBranch(branchName); err == nil { + ctx.Data["Err_NewBranchName"] = true + ctx.RenderWithErr(ctx.Tr("repo.editor.branch_already_exists", branchName), UPLOAD_FILE, &form) + return + } + } + + var newTreePath string + for _, part := range treeNames { + newTreePath = path.Join(newTreePath, part) + entry, err := ctx.Repo.Commit.GetTreeEntryByPath(newTreePath) + if err != nil { + if git.IsErrNotExist(err) { + // Means there is no item with that name, so we're good + break + } + + ctx.Handle(500, "Repo.Commit.GetTreeEntryByPath", err) + return + } + + // User can only upload files to a directory. + if !entry.IsDir() { + ctx.Data["Err_TreePath"] = true + ctx.RenderWithErr(ctx.Tr("repo.editor.directory_is_a_file", part), UPLOAD_FILE, &form) + return + } + } + + message := strings.TrimSpace(form.CommitSummary) + if len(message) == 0 { + message = ctx.Tr("repo.editor.upload_files_to_dir", form.TreePath) + } + + form.CommitMessage = strings.TrimSpace(form.CommitMessage) + if len(form.CommitMessage) > 0 { + message += "\n\n" + form.CommitMessage + } + + if err := ctx.Repo.Repository.UploadRepoFiles(ctx.User, models.UploadRepoFileOptions{ + LastCommitID: ctx.Repo.CommitID, + OldBranch: oldBranchName, + NewBranch: branchName, + TreePath: form.TreePath, + Message: message, + Files: form.Files, + }); err != nil { + ctx.Data["Err_TreePath"] = true + ctx.RenderWithErr(ctx.Tr("repo.editor.unable_to_upload_files", form.TreePath, err), UPLOAD_FILE, &form) + return + } + + ctx.Redirect(ctx.Repo.RepoLink + "/src/" + branchName + "/" + form.TreePath) +} + +func UploadFileToServer(ctx *context.Context) { + file, header, err := ctx.Req.FormFile("file") + if err != nil { + ctx.Error(500, fmt.Sprintf("FormFile: %v", err)) + return + } + defer file.Close() + + buf := make([]byte, 1024) + n, _ := file.Read(buf) + if n > 0 { + buf = buf[:n] + } + fileType := http.DetectContentType(buf) + + if len(setting.Repository.Upload.AllowedTypes) > 0 { + allowed := false + for _, t := range setting.Repository.Upload.AllowedTypes { + t := strings.Trim(t, " ") + if t == "*/*" || t == fileType { + allowed = true + break + } + } + + if !allowed { + ctx.Error(400, ErrFileTypeForbidden.Error()) + return + } + } + + upload, err := models.NewUpload(header.Filename, buf, file) + if err != nil { + ctx.Error(500, fmt.Sprintf("NewUpload: %v", err)) + return + } + + log.Trace("New file uploaded: %s", upload.UUID) + ctx.JSON(200, map[string]string{ + "uuid": upload.UUID, + }) +} + +func RemoveUploadFileFromServer(ctx *context.Context, form auth.RemoveUploadFileForm) { + if len(form.File) == 0 { + ctx.Status(204) + return + } + + if err := models.DeleteUploadByUUID(form.File); err != nil { + ctx.Error(500, fmt.Sprintf("DeleteUploadByUUID: %v", err)) + return + } + + log.Trace("Upload file removed: %s", form.File) + ctx.Status(204) +} diff --git a/routers/repo/issue.go b/routers/repo/issue.go index a5908c182..e2d8000e5 100644 --- a/routers/repo/issue.go +++ b/routers/repo/issue.go @@ -447,7 +447,6 @@ func UploadIssueAttachment(ctx *context.Context) { return } - allowedTypes := strings.Split(setting.AttachmentAllowedTypes, ",") file, header, err := ctx.Req.FormFile("file") if err != nil { ctx.Error(500, fmt.Sprintf("FormFile: %v", err)) @@ -462,6 +461,7 @@ func UploadIssueAttachment(ctx *context.Context) { } fileType := http.DetectContentType(buf) + allowedTypes := strings.Split(setting.AttachmentAllowedTypes, ",") allowed := false for _, t := range allowedTypes { t := strings.Trim(t, " ") diff --git a/routers/repo/upload.go b/routers/repo/upload.go deleted file mode 100644 index 5e0f91668..000000000 --- a/routers/repo/upload.go +++ /dev/null @@ -1,253 +0,0 @@ -// Copyright 2016 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. - -package repo - -import ( - "fmt" - "net/http" - "path" - "strings" - - git "github.com/gogits/git-module" - - "github.com/gogits/gogs/models" - "github.com/gogits/gogs/modules/auth" - "github.com/gogits/gogs/modules/base" - "github.com/gogits/gogs/modules/context" - "github.com/gogits/gogs/modules/log" - "github.com/gogits/gogs/modules/setting" -) - -const ( - UPLOAD base.TplName = "repo/upload" -) - -func renderUploadSettings(ctx *context.Context) { - ctx.Data["RequireDropzone"] = true - ctx.Data["IsUploadEnabled"] = setting.Repository.Upload.Enabled - ctx.Data["UploadAllowedTypes"] = strings.Join(setting.Repository.Upload.AllowedTypes, ",") - ctx.Data["UploadMaxSize"] = setting.Repository.Upload.FileMaxSize - ctx.Data["UploadMaxFiles"] = setting.Repository.Upload.MaxFiles -} - -func UploadFile(ctx *context.Context) { - ctx.Data["PageIsUpload"] = true - - userName := ctx.Repo.Owner.Name - repoName := ctx.Repo.Repository.Name - branchName := ctx.Repo.BranchName - branchLink := ctx.Repo.RepoLink + "/src/" + branchName - treeName := ctx.Repo.TreePath - - treeNames := []string{""} - if len(treeName) > 0 { - treeNames = strings.Split(treeName, "/") - } - - ctx.Data["UserName"] = userName - ctx.Data["RepoName"] = repoName - ctx.Data["BranchName"] = branchName - ctx.Data["TreeName"] = treeName - ctx.Data["TreeNames"] = treeNames - ctx.Data["BranchLink"] = branchLink - ctx.Data["CommitSummary"] = "" - ctx.Data["CommitMessage"] = "" - ctx.Data["CommitChoice"] = "direct" - ctx.Data["NewBranchName"] = "" - ctx.Data["CommitDirectlyToThisBranch"] = ctx.Tr("repo.commit_directly_to_this_branch", ""+branchName+"") - ctx.Data["CreateNewBranch"] = ctx.Tr("repo.create_new_branch", ""+ctx.Tr("repo.new_branch")+"") - renderUploadSettings(ctx) - - ctx.HTML(200, UPLOAD) -} - -func UploadFilePost(ctx *context.Context, form auth.UploadRepoFileForm) { - ctx.Data["PageIsUpload"] = true - renderUploadSettings(ctx) - - userName := ctx.Repo.Owner.Name - repoName := ctx.Repo.Repository.Name - oldBranchName := ctx.Repo.BranchName - branchName := oldBranchName - branchLink := ctx.Repo.RepoLink + "/src/" + branchName - commitChoice := form.CommitChoice - files := form.Files - - if commitChoice == "commit-to-new-branch" { - branchName = form.NewBranchName - } - - treeName := form.TreeName - treeName = strings.Trim(treeName, " ") - treeName = strings.Trim(treeName, "/") - - treeNames := []string{""} - if len(treeName) > 0 { - treeNames = strings.Split(treeName, "/") - } - - ctx.Data["UserName"] = userName - ctx.Data["RepoName"] = repoName - ctx.Data["BranchName"] = branchName - ctx.Data["TreeName"] = treeName - ctx.Data["TreeNames"] = treeNames - ctx.Data["BranchLink"] = branchLink - ctx.Data["CommitSummary"] = form.CommitSummary - ctx.Data["CommitMessage"] = form.CommitMessage - ctx.Data["CommitChoice"] = commitChoice - ctx.Data["NewBranchName"] = branchName - ctx.Data["CommitDirectlyToThisBranch"] = ctx.Tr("repo.commit_directly_to_this_branch", ""+oldBranchName+"") - ctx.Data["CreateNewBranch"] = ctx.Tr("repo.create_new_branch", ""+ctx.Tr("repo.new_branch")+"") - - if ctx.HasError() { - ctx.HTML(200, UPLOAD) - return - } - - if oldBranchName != branchName { - if _, err := ctx.Repo.Repository.GetBranch(branchName); err == nil { - ctx.Data["Err_Branchname"] = true - ctx.RenderWithErr(ctx.Tr("repo.branch_already_exists"), UPLOAD, &form) - log.Error(4, "%s: %s - %s", "BranchName", branchName, "Branch already exists") - return - } - - } - - treepath := "" - for _, part := range treeNames { - treepath = path.Join(treepath, part) - entry, err := ctx.Repo.Commit.GetTreeEntryByPath(treepath) - if err != nil { - // Means there is no item with that name, so we're good - break - } - if !entry.IsDir() { - ctx.Data["Err_Filename"] = true - ctx.RenderWithErr(ctx.Tr("repo.directory_is_a_file"), UPLOAD, &form) - log.Error(4, "%s: %s - %s", "UploadFile", treeName, "Directory given is a file") - return - } - } - - message := "" - if form.CommitSummary != "" { - message = strings.Trim(form.CommitSummary, " ") - } else { - message = ctx.Tr("repo.add_files_to_dir", "'"+treeName+"'") - } - if strings.Trim(form.CommitMessage, " ") != "" { - message += "\n\n" + strings.Trim(form.CommitMessage, " ") - } - - if err := ctx.Repo.Repository.UploadRepoFiles(ctx.User, oldBranchName, branchName, treeName, message, files); err != nil { - ctx.Data["Err_Directory"] = true - ctx.RenderWithErr(ctx.Tr("repo.unable_to_upload_files"), UPLOAD, &form) - log.Error(4, "%s: %v", "UploadFile", err) - return - } - - // Was successful, so now need to call models.CommitRepoAction() with the new commitID for webhooks and watchers - if branch, err := ctx.Repo.Repository.GetBranch(branchName); err != nil { - log.Error(4, "repo.Repository.GetBranch(%s): %v", branchName, err) - } else if commit, err := branch.GetCommit(); err != nil { - log.Error(4, "branch.GetCommit(): %v", err) - } else { - pc := &models.PushCommits{ - Len: 1, - Commits: []*models.PushCommit{models.CommitToPushCommit(commit)}, - } - oldCommitID := ctx.Repo.CommitID - newCommitID := commit.ID.String() - if branchName != oldBranchName { - oldCommitID = "0000000000000000000000000000000000000000" // New Branch so we use all 0s - } - if err := models.CommitRepoAction(models.CommitRepoActionOptions{ - PusherName: ctx.User.Name, - RepoOwnerID: ctx.Repo.Owner.ID, - RepoName: ctx.Repo.Owner.Name, - RefFullName: git.BRANCH_PREFIX + branchName, - OldCommitID: oldCommitID, - NewCommitID: newCommitID, - Commits: pc, - }); err != nil { - log.Error(4, "models.CommitRepoAction(branch = %s): %v", branchName, err) - } - } - - ctx.Redirect(ctx.Repo.RepoLink + "/src/" + branchName + "/" + treeName) -} - -func UploadFileToServer(ctx *context.Context) { - if !setting.Repository.Upload.Enabled { - ctx.Error(404, "upload is not enabled") - return - } - - file, header, err := ctx.Req.FormFile("file") - if err != nil { - ctx.Error(500, fmt.Sprintf("FormFile: %v", err)) - return - } - defer file.Close() - - buf := make([]byte, 1024) - n, _ := file.Read(buf) - if n > 0 { - buf = buf[:n] - } - fileType := http.DetectContentType(buf) - - if len(setting.Repository.Upload.AllowedTypes) > 0 { - allowed := false - for _, t := range setting.Repository.Upload.AllowedTypes { - t := strings.Trim(t, " ") - if t == "*/*" || t == fileType { - allowed = true - break - } - } - - if !allowed { - ctx.Error(400, ErrFileTypeForbidden.Error()) - return - } - } - - up, err := models.NewUpload(header.Filename, buf, file, ctx.User.ID, ctx.Repo.Repository.ID) - if err != nil { - ctx.Error(500, fmt.Sprintf("NewUpload: %v", err)) - return - } - - log.Trace("New file uploaded: %s", up.UUID) - ctx.JSON(200, map[string]string{ - "uuid": up.UUID, - }) -} - -func RemoveUploadFileFromServer(ctx *context.Context, form auth.RemoveUploadFileForm) { - if !setting.Repository.Upload.Enabled { - ctx.Error(404, "upload is not enabled") - return - } - - if len(form.File) == 0 { - ctx.Error(404, "invalid params") - return - } - - uuid := form.File - - if err := models.RemoveUpload(uuid, ctx.User.ID, ctx.Repo.Repository.ID); err != nil { - ctx.Error(500, fmt.Sprintf("RemoveUpload: %v", err)) - return - } - - log.Trace("Upload file removed: %s", uuid) - ctx.JSON(200, map[string]string{ - "uuid": uuid, - }) -} diff --git a/routers/repo/view.go b/routers/repo/view.go index 42bf62c60..055785564 100644 --- a/routers/repo/view.go +++ b/routers/repo/view.go @@ -113,10 +113,7 @@ func renderDirectory(ctx *context.Context, treeLink string) { // Check permission to add or upload new file. if ctx.Repo.IsWriter() && ctx.Repo.IsViewBranch { ctx.Data["CanAddFile"] = true - // uploadFileLink := ctx.Repo.RepoLink + "/upload/" + branchName - // if setting.Repository.Upload.Enabled { - // ctx.Data["UploadFileLink"] = uploadFileLink + "/" + ctx.Repo.TreePath - // } + ctx.Data["CanUploadFile"] = setting.Repository.Upload.Enabled } } @@ -253,7 +250,7 @@ func Home(ctx *context.Context) { ec, err := ctx.Repo.GetEditorconfig() if err != nil && !git.IsErrNotExist(err) { - ctx.Handle(500, "ErrGettingEditorconfig", err) + ctx.Handle(500, "Repo.GetEditorconfig", err) return } ctx.Data["Editorconfig"] = ec diff --git a/templates/.VERSION b/templates/.VERSION index bbf71e421..68c6d095c 100644 --- a/templates/.VERSION +++ b/templates/.VERSION @@ -1 +1 @@ -0.9.94.0830 \ No newline at end of file +0.9.95.0830 \ No newline at end of file diff --git a/templates/repo/editor/commit_form.tmpl b/templates/repo/editor/commit_form.tmpl index 74126ac01..d76f3fb1c 100644 --- a/templates/repo/editor/commit_form.tmpl +++ b/templates/repo/editor/commit_form.tmpl @@ -3,7 +3,7 @@