添加readme/{dir}接口 #22

Closed
wonderful wants to merge 2 commits from (deleted):develop into develop
4 changed files with 333 additions and 266 deletions

View File

@ -89,11 +89,6 @@ import (
"gitea.com/macaron/macaron"
)
func MustEnableWiki(ctx *context.Context) {
if !ctx.Repo.CanRead(models.UnitTypeWiki) &&
!ctx.Repo.CanRead(models.UnitTypeExternalWiki) {
@ -704,6 +699,7 @@ func RegisterRoutes(m *macaron.Macaron) {
// alter on 2021/01/15
m.Get("", viewfile.Readme) // reqRepoReader(models.UnitTypeCode),
m.Get("/*", viewfile.ReadmeByPath)
})
m.Group("/count", func() {

View File

@ -224,9 +224,9 @@ func GetAllCommits(ctx *context.APIContext) {
// GetAllCommits get all commits via
func GetAllCommitsSliceByTime(ctx *context.APIContext) {
// swagger:operation GET /repos/{owner}/{repo}/commits_slice repository repoGetAllCommits
// swagger:operation GET /repos/{owner}/{repo}/commits_slice repository repoAllCommits
// ---
// summary: Get a list of all commits from a repository
// summary: Get a list of all commits from a repository and slice by time
// produces:
// - application/json
// parameters:
@ -358,9 +358,9 @@ func GetAllCommitsSliceByTime(ctx *context.APIContext) {
}
func CommitSplitSlice(CommitsList []api.Commit) []api.CommitsSlice {
// sort by time
// sort by time
sort.Sort(api.SortCommit(CommitsList))
Commits := make([]api.CommitsSlice,0)
Commits := make([]api.CommitsSlice, 0)
i := 0
var j int
for {
@ -372,18 +372,17 @@ func CommitSplitSlice(CommitsList []api.Commit) []api.CommitsSlice {
}
// if equal, put commitdata in an array
commitDate := CommitsList[i].CommitDate
commitDatalist := CommitsList[i:j]
i = j // variable value
commitDatalist := CommitsList[i:j]
i = j // variable value
// get all the values,,,Commits
Commits = append(Commits, api.CommitsSlice{
CommitDate: commitDate,
Commits: commitDatalist,
Commits: commitDatalist,
})
}
return Commits
}
func toCommit(ctx *context.APIContext, repo *models.Repository, commit *git.Commit, userCache map[string]*models.User) (*api.Commit, error) {
var apiAuthor, apiCommitter *api.User
@ -483,7 +482,7 @@ func toCommit(ctx *context.APIContext, repo *models.Repository, commit *git.Comm
// add by qiubing
// 获取 Graph
func GetGraph(ctx *context.APIContext) {
if ctx.Repo.Repository.IsEmpty { // 项目是否为空
ctx.JSON(http.StatusConflict, api.APIError{
Message: "Git Repository is empty.",

View File

@ -2,6 +2,17 @@ package viewfile
import (
"bytes"
"encoding/base64"
"fmt"
gotemplate "html/template"
"io/ioutil"
"net/http"
"net/url"
"path"
"path/filepath"
"strconv"
"strings"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/charset"
@ -13,32 +24,21 @@ import (
"code.gitea.io/gitea/modules/repofiles"
repo_module "code.gitea.io/gitea/modules/repository"
"code.gitea.io/gitea/modules/setting"
"encoding/base64"
"fmt"
"gitea.com/macaron/macaron"
gotemplate "html/template"
"io/ioutil"
"net/http"
"net/url"
"path"
"path/filepath"
"strconv"
"strings"
)
func Map2DTO(ctx *context.APIContext) (dto *ReadmeDTO) {
dto=&ReadmeDTO{}
dto.Type="file"
dto.Encoding=ctx.Data["Encoding"].(string)
dto.Size=ctx.Data["FileSize"].(int64)
dto.Name=ctx.Repo.TreePath
dto.Path=ctx.Repo.TreePath
dto.Content=ctx.Data["FileContent"].(string)
dto.Sha=ctx.Repo.CommitID
dto = &ReadmeDTO{}
dto.Type = "file"
dto.Encoding = ctx.Data["Encoding"].(string)
dto.Size = ctx.Data["FileSize"].(int64)
dto.Name = ctx.Repo.TreePath
dto.Path = ctx.Repo.TreePath
dto.Content = ctx.Data["FileContent"].(string)
dto.Sha = ctx.Repo.CommitID
return
}
// RepoRefByType handles repository reference name for a specific type
// of repository reference
func RepoRefByType(refType context.RepoRefType) macaron.Handler {
@ -162,7 +162,6 @@ func RepoRefByType(refType context.RepoRefType) macaron.Handler {
}
}
func getRefName(ctx *context.APIContext, pathType context.RepoRefType) string {
path := ctx.Params("*")
switch pathType {
@ -198,7 +197,7 @@ func getRefName(ctx *context.APIContext, pathType context.RepoRefType) string {
}
return path
default:
ctx.Error(http.StatusBadRequest,"Unrecognized path type: %v", path)
ctx.Error(http.StatusBadRequest, "Unrecognized path type: %v", path)
}
return ""
}
@ -218,13 +217,11 @@ func getRefNameFromPath(ctx *context.APIContext, path string, isExist func(strin
func GetRefType() macaron.Handler {
return func(ctx *context.APIContext) {
ref:=ctx.ParamsInt64(":ref")
fmt.Println("ref:",ref)
ref := ctx.ParamsInt64(":ref")
fmt.Println("ref:", ref)
}
}
func CommitCount(ctx *context.APIContext) {
// swagger:operation GET /repos/{owner}/{repo}/count repository Count
// ---
@ -253,7 +250,6 @@ func CommitCount(ctx *context.APIContext) {
// "404":
// "$ref": "#/responses/notFound"
ref := ctx.QueryTrim("ref")
if ref == "" {
ref = ctx.Params(":ref")
@ -281,18 +277,17 @@ func CommitCount(ctx *context.APIContext) {
}()
}
// Get the commit object for the ref
commit, err := ctx.Repo.GitRepo.GetCommit(ref)
if err != nil || commit==nil{
ctx.Error(http.StatusInternalServerError,"ctx.Repo.GitRepo.GetCommit", err)
if err != nil || commit == nil {
ctx.Error(http.StatusInternalServerError, "ctx.Repo.GitRepo.GetCommit", err)
return
}
ctx.Repo.Commit=commit
ctx.Repo.Commit = commit
CommitCount,err:=ctx.Repo.Commit.CommitsCount()
if err !=nil {
ctx.Error(http.StatusInternalServerError,"ctx.Repo.Commit.CommitsCount", err)
CommitCount, err := ctx.Repo.Commit.CommitsCount()
if err != nil {
ctx.Error(http.StatusInternalServerError, "ctx.Repo.Commit.CommitsCount", err)
return
}
opts := models.FindReleasesOptions{
@ -316,29 +311,28 @@ func CommitCount(ctx *context.APIContext) {
return
}
tags,err:=ctx.Repo.GitRepo.GetTags()
tags, err := ctx.Repo.GitRepo.GetTags()
if err != nil {
ctx.Error(http.StatusInternalServerError, "ctx.Repo.GitRepo.GetTags", err)
return
}
dto:=&CountDTO{}
dto.Branch.CommitCount=CommitCount
dto.Branch.BranchName=ref
dto.BranchCount=int64(len(branches))
dto.TagCount=int64(len(tags))
dto.ReleaseCount=ReleaseCount
dto := &CountDTO{}
dto.Branch.CommitCount = CommitCount
dto.Branch.BranchName = ref
dto.BranchCount = int64(len(branches))
dto.TagCount = int64(len(tags))
dto.ReleaseCount = ReleaseCount
ctx.JSON(http.StatusOK, dto)
}
type CountDTO struct {
Branch struct{
CommitCount int64 `json:"commit_count"`
BranchName string `json:"branch_name"`
Branch struct {
CommitCount int64 `json:"commit_count"`
BranchName string `json:"branch_name"`
} `json:"branch"`
ReleaseCount int64 `json:"release_count"`
TagCount int64 `json:"tag_count"`
ReleaseCount int64 `json:"release_count"`
TagCount int64 `json:"tag_count"`
BranchCount int64 `json:"branch_count"`
}
@ -383,7 +377,6 @@ func LatestRelease(ctx *context.APIContext) {
}()
}
release, err := models.GetLatestReleaseByRepoIDExt(ctx.Repo.Repository.ID)
//fmt.Println("****************ctx.Repo.Repository.ID:",ctx.Repo.Repository.ID," ",release," ",err)
if err != nil {
@ -400,11 +393,10 @@ func LatestRelease(ctx *context.APIContext) {
return
}
release.Publisher.Passwd=""
release.Publisher.Passwd = ""
ctx.JSON(http.StatusOK, release)
}
func Readme(ctx *context.APIContext) {
// swagger:operation GET /repos/{owner}/{repo}/readme repository readme
// ---
@ -433,115 +425,29 @@ func Readme(ctx *context.APIContext) {
// "404":
// "$ref": "#/responses/notFound"
ctx.Data["Encoding"]="base64"
ctx.Data["Encoding"] = "base64"
treePath := ctx.Repo.TreePath
ref:= ctx.QueryTrim("ref")
ref := ctx.QueryTrim("ref")
if ref == "" {
ref= ctx.Params(":ref")
if ref=="" {
ref = ctx.Params(":ref")
if ref == "" {
ref = ctx.Repo.Repository.DefaultBranch
}
}
fmt.Println("***ref:",ref)
fmt.Println("***ref:", ref)
namedBlob,err:=getReadmeFileFromPathExt(ctx,treePath,ref)
if err !=nil || namedBlob==nil{
ctx.NotFound("getReadmeFileFromPath", err)
namedBlob, err := getReadmeFileFromPathExt(ctx, treePath, ref)
if err != nil || namedBlob == nil {
ctx.NotFound("getReadmeFileFromPath", err)
return
}
//fmt.Println("********getReadmeFileFromPathExt:",err," ",namedBlob)
FoundFileItem:=namedBlob.name
ctx.Repo.TreePath=FoundFileItem //找到指定文件;
FoundFileItem := namedBlob.name
ctx.Repo.TreePath = FoundFileItem //找到指定文件;
fmt.Println("-----treePath ===", ctx.Repo.TreePath)
//fmt.Println("**** reqRepoReader(models.UnitTypeCode):",FoundFileItem)
ctx.Data["PageIsViewCode"] = true
if ctx.Repo.Repository.IsEmpty {
ctx.NotFound("Home", fmt.Errorf(ctx.Tr("Repository is empty")))
return
}
title := ctx.Repo.Repository.Owner.Name + "/" + ctx.Repo.Repository.Name
if len(ctx.Repo.Repository.Description) > 0 {
title += ": " + ctx.Repo.Repository.Description
}
ctx.Data["Title"] = title
ctx.Repo.RepoLink=`/`+ctx.Repo.Owner.Name+`/`+ctx.Repo.Repository.Name
ctx.Repo.IsViewCommit=true //此处无实际意义;加上为了编译
branchLink := ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL()
treeLink := branchLink
rawLink := ctx.Repo.RepoLink + "/raw/" + ctx.Repo.BranchNameSubURL()
//fmt.Println("******rawLink:",rawLink)
if len(ctx.Repo.TreePath) > 0 {
treeLink += "/" + ctx.Repo.TreePath
treeLink=strings.ReplaceAll(treeLink,"//","/")
}
// Get current entry user currently looking at.
entry, err := ctx.Repo.Commit.GetTreeEntryByPath(ctx.Repo.TreePath)
//fmt.Println("*********GetTreeEntryByPath:",entry," ",err)
if err != nil {
ctx.NotFound("Repo.Commit.GetTreeEntryByPath", err)
return
}
if entry==nil {
ctx.NotFound("Repo.Commit.GetTreeEntryByPath", err)
return
}
renderFile(ctx, entry, treeLink, rawLink)
//if ctx.Written() {
// return
//}
var treeNames []string
paths := make([]string, 0, 5)
if len(ctx.Repo.TreePath) > 0 {
treeNames = strings.Split(ctx.Repo.TreePath, "/")
fmt.Println("***treeNames:",treeNames)
for i := range treeNames {
paths = append(paths, strings.Join(treeNames[:i+1], "/"))
fmt.Println("***paths:",paths)
}
ctx.Data["HasParentPath"] = true
if len(paths)-2 >= 0 {
ctx.Data["ParentPath"] = "/" + paths[len(paths)-2]
}
}
ctx.Data["Paths"] = paths
ctx.Data["TreeLink"] = treeLink
ctx.Data["TreeNames"] = treeNames
ctx.Data["BranchLink"] = branchLink
fmt.Println("***rawLink:",rawLink)
fmt.Println("***paths:",paths)
fmt.Println("***treeLink:",treeLink)
fmt.Println("***treeNames:",treeNames)
fmt.Println("***branchLink:",branchLink)
ctx.JSON(http.StatusOK, Map2DTO(ctx))
}
func ViewFile(ctx *context.APIContext) {
ctx.Data["Encoding"]="base64"
fmt.Println("*********viewFile.ctx.Repo.TreePath:",ctx.Repo.TreePath)
namedBlob,err:=getReadmeFileFromPath(ctx.Repo.Commit,ctx.Repo.TreePath)
if err !=nil || namedBlob==nil{
ctx.NotFound("getReadmeFileFromPath", err)
return
}
FoundFileItem:=namedBlob.name
ctx.Repo.TreePath=FoundFileItem //找到指定文件;
fmt.Println("****getReadmeFileFromPath:",FoundFileItem)
ctx.Data["PageIsViewCode"] = true
if ctx.Repo.Repository.IsEmpty {
ctx.NotFound("Home", fmt.Errorf(ctx.Tr("Repository is empty")))
@ -554,7 +460,155 @@ func ViewFile(ctx *context.APIContext) {
}
ctx.Data["Title"] = title
ctx.Repo.RepoLink=`/`+ctx.Repo.Owner.Name+`/`+ctx.Repo.Repository.Name
ctx.Repo.RepoLink = `/` + ctx.Repo.Owner.Name + `/` + ctx.Repo.Repository.Name
ctx.Repo.IsViewCommit = true //此处无实际意义;加上为了编译
branchLink := ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL()
treeLink := branchLink
rawLink := ctx.Repo.RepoLink + "/raw/" + ctx.Repo.BranchNameSubURL()
//fmt.Println("******rawLink:",rawLink)
if len(ctx.Repo.TreePath) > 0 {
treeLink += "/" + ctx.Repo.TreePath
treeLink = strings.ReplaceAll(treeLink, "//", "/")
}
// Get current entry user currently looking at.
entry, err := ctx.Repo.Commit.GetTreeEntryByPath(ctx.Repo.TreePath)
//fmt.Println("*********GetTreeEntryByPath:",entry," ",err)
if err != nil {
ctx.NotFound("Repo.Commit.GetTreeEntryByPath", err)
return
}
if entry == nil {
ctx.NotFound("Repo.Commit.GetTreeEntryByPath", err)
return
}
renderFile(ctx, entry, treeLink, rawLink)
//if ctx.Written() {
// return
//}
var treeNames []string
paths := make([]string, 0, 5)
if len(ctx.Repo.TreePath) > 0 {
treeNames = strings.Split(ctx.Repo.TreePath, "/")
fmt.Println("***treeNames:", treeNames)
for i := range treeNames {
paths = append(paths, strings.Join(treeNames[:i+1], "/"))
fmt.Println("***paths:", paths)
}
ctx.Data["HasParentPath"] = true
if len(paths)-2 >= 0 {
ctx.Data["ParentPath"] = "/" + paths[len(paths)-2]
}
}
ctx.Data["Paths"] = paths
ctx.Data["TreeLink"] = treeLink
ctx.Data["TreeNames"] = treeNames
ctx.Data["BranchLink"] = branchLink
fmt.Println("***rawLink:", rawLink)
fmt.Println("***paths:", paths)
fmt.Println("***treeLink:", treeLink)
fmt.Println("***treeNames:", treeNames)
fmt.Println("***branchLink:", branchLink)
ctx.JSON(http.StatusOK, Map2DTO(ctx))
}
/////////////
func ReadmeByPath(ctx *context.APIContext) {
// swagger:operation GET /repos/{owner}/{repo}/readme/{dir} repository readmePathContents
// ---
// summary: Gets the metadata and contents (if a file) of an entry in a repository, or a list of entries if a dir
// produces:
// - application/json
// parameters:
// - name: owner
// in: path
// description: owner of the repo
// type: string
// required: true
// - name: repo
// in: path
// description: name of the repo
// type: string
// required: true
// - name: dir
// in: path
// description: name of the path
// type: string
// required: true
// - name: ref
// in: query
// description: "The name of the commit/branch/tag. Default the repositorys default branch (usually master)"
// type: string
// required: false
// responses:
// "200":
// "$ref": "#/responses/ReadmeDTO"
// "404":
// "$ref": "#/responses/notFound"
treePath := ctx.Params("*")
ref := ctx.QueryTrim("ref")
if ref == "" {
ref = ctx.Params(":ref")
if ref == "" {
ref = ctx.Repo.Repository.DefaultBranch
}
}
namedBlob, err := getReadmeFileFromPathExt(ctx, treePath, ref)
if err != nil || namedBlob == nil {
ctx.NotFound("getReadmeFileFromPath", err)
return
}
FoundFileItem := namedBlob.name
newTreePath := treePath + "/" + FoundFileItem
contents, err := repofiles.GetContents(ctx.Repo.Repository, newTreePath, ref, false)
if err != nil {
if git.IsErrNotExist(err) {
ctx.NotFound("GetReadmeContentByPath", err)
return
}
ctx.Error(http.StatusInternalServerError, "GetReadmeContentByPath", err)
} else {
ctx.JSON(http.StatusOK, contents)
}
}
func ViewFile(ctx *context.APIContext) {
ctx.Data["Encoding"] = "base64"
fmt.Println("*********viewFile.ctx.Repo.TreePath:", ctx.Repo.TreePath)
namedBlob, err := getReadmeFileFromPath(ctx.Repo.Commit, ctx.Repo.TreePath)
if err != nil || namedBlob == nil {
ctx.NotFound("getReadmeFileFromPath", err)
return
}
FoundFileItem := namedBlob.name
ctx.Repo.TreePath = FoundFileItem //找到指定文件;
fmt.Println("****getReadmeFileFromPath:", FoundFileItem)
ctx.Data["PageIsViewCode"] = true
if ctx.Repo.Repository.IsEmpty {
ctx.NotFound("Home", fmt.Errorf(ctx.Tr("Repository is empty")))
return
}
title := ctx.Repo.Repository.Owner.Name + "/" + ctx.Repo.Repository.Name
if len(ctx.Repo.Repository.Description) > 0 {
title += ": " + ctx.Repo.Repository.Description
}
ctx.Data["Title"] = title
ctx.Repo.RepoLink = `/` + ctx.Repo.Owner.Name + `/` + ctx.Repo.Repository.Name
branchLink := ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL()
//fmt.Println("******branchLink:",branchLink)
@ -576,13 +630,13 @@ func ViewFile(ctx *context.APIContext) {
// Get current entry user currently looking at.
entry, err := ctx.Repo.Commit.GetTreeEntryByPath(ctx.Repo.TreePath)
fmt.Println("*********GetTreeEntryByPath:",entry," ",err)
if err != nil {
ctx.NotFound("Repo.Commit.GetTreeEntryByPath", err)
fmt.Println("*********GetTreeEntryByPath:", entry, " ", err)
if err != nil {
ctx.NotFound("Repo.Commit.GetTreeEntryByPath", err)
return
}
if entry==nil {
ctx.NotFound("Repo.Commit.GetTreeEntryByPath", err)
if entry == nil {
ctx.NotFound("Repo.Commit.GetTreeEntryByPath", err)
return
}
renderFile(ctx, entry, treeLink, rawLink)
@ -594,10 +648,10 @@ func ViewFile(ctx *context.APIContext) {
paths := make([]string, 0, 5)
if len(ctx.Repo.TreePath) > 0 {
treeNames = strings.Split(ctx.Repo.TreePath, "/")
fmt.Println("***treeNames:",treeNames)
fmt.Println("***treeNames:", treeNames)
for i := range treeNames {
paths = append(paths, strings.Join(treeNames[:i+1], "/"))
fmt.Println("***paths:",paths)
fmt.Println("***paths:", paths)
}
ctx.Data["HasParentPath"] = true
@ -606,17 +660,16 @@ func ViewFile(ctx *context.APIContext) {
}
}
ctx.Data["Paths"] = paths
ctx.Data["TreeLink"] = treeLink
ctx.Data["TreeNames"] = treeNames
ctx.Data["BranchLink"] = branchLink
fmt.Println("***rawLink:",rawLink)
fmt.Println("***paths:",paths)
fmt.Println("***treeLink:",treeLink)
fmt.Println("***treeNames:",treeNames)
fmt.Println("***branchLink:",branchLink)
fmt.Println("***rawLink:", rawLink)
fmt.Println("***paths:", paths)
fmt.Println("***treeLink:", treeLink)
fmt.Println("***treeNames:", treeNames)
fmt.Println("***branchLink:", branchLink)
ctx.JSON(http.StatusOK, Map2DTO(ctx))
@ -627,7 +680,7 @@ func renderFile(ctx *context.APIContext, entry *git.TreeEntry, treeLink, rawLink
blob := entry.Blob()
dataRc, err := blob.DataAsync()
if err != nil {
ctx.Error(http.StatusInternalServerError,"DataAsync", err)
ctx.Error(http.StatusInternalServerError, "DataAsync", err)
return
}
defer dataRc.Close()
@ -640,9 +693,9 @@ func renderFile(ctx *context.APIContext, entry *git.TreeEntry, treeLink, rawLink
ctx.Data["FileName"] = blob.Name()
ctx.Data["RawFileLink"] = rawLink + "/" + ctx.Repo.TreePath
Base64Encoding:=base64.StdEncoding
if ctx.Data["Encoding"]=="base64url" {
Base64Encoding=base64.RawURLEncoding
Base64Encoding := base64.StdEncoding
if ctx.Data["Encoding"] == "base64url" {
Base64Encoding = base64.RawURLEncoding
}
buf := make([]byte, 1024)
n, _ := dataRc.Read(buf)
@ -657,11 +710,11 @@ func renderFile(ctx *context.APIContext, entry *git.TreeEntry, treeLink, rawLink
if meta != nil {
meta, err = ctx.Repo.Repository.GetLFSMetaObjectByOid(meta.Oid)
if err != nil && err != models.ErrLFSObjectNotExist {
ctx.Error(http.StatusInternalServerError,"GetLFSMetaObject", err)
ctx.Error(http.StatusInternalServerError, "GetLFSMetaObject", err)
return
}
}
fmt.Println("***setting.LFS.StartServer:",meta)
fmt.Println("***setting.LFS.StartServer:", meta)
if meta != nil {
ctx.Data["IsLFSFile"] = true
isLFSFile = true
@ -670,7 +723,7 @@ func renderFile(ctx *context.APIContext, entry *git.TreeEntry, treeLink, rawLink
var err error
dataRc, err = lfs.ReadMetaObject(meta)
if err != nil {
ctx.Error(http.StatusInternalServerError,"ReadMetaObject", err)
ctx.Error(http.StatusInternalServerError, "ReadMetaObject", err)
return
}
defer dataRc.Close()
@ -678,7 +731,7 @@ func renderFile(ctx *context.APIContext, entry *git.TreeEntry, treeLink, rawLink
buf = make([]byte, 1024)
n, err = dataRc.Read(buf)
if err != nil {
ctx.Error(http.StatusInternalServerError,"Data", err)
ctx.Error(http.StatusInternalServerError, "Data", err)
return
}
buf = buf[:n]
@ -696,7 +749,7 @@ func renderFile(ctx *context.APIContext, entry *git.TreeEntry, treeLink, rawLink
lfsLock, err := ctx.Repo.Repository.GetTreePathLock(ctx.Repo.TreePath)
ctx.Data["LFSLock"] = lfsLock
if err != nil {
ctx.Error(http.StatusInternalServerError,"GetTreePathLock", err)
ctx.Error(http.StatusInternalServerError, "GetTreePathLock", err)
return
}
if lfsLock != nil {
@ -727,7 +780,7 @@ func renderFile(ctx *context.APIContext, entry *git.TreeEntry, treeLink, rawLink
ctx.Data["MarkupType"] = markupType
//ctx.Data["FileContent"] = string(markup.Render(blob.Name(), buf, path.Dir(treeLink), ctx.Repo.Repository.ComposeDocumentMetas()))
filenameBase64 := Base64Encoding.EncodeToString(buf)
ctx.Data["FileContent"] =filenameBase64
ctx.Data["FileContent"] = filenameBase64
//fmt.Println("************FileContent1:",ctx.Data["FileContent"].(string))
} else if readmeExist {
ctx.Data["IsRenderedHTML"] = true
@ -742,7 +795,7 @@ func renderFile(ctx *context.APIContext, entry *git.TreeEntry, treeLink, rawLink
//ctx.Data["FileContent"] = highlight.File(lineNums, blob.Name(), buf)
filenameBase64 := Base64Encoding.EncodeToString(buf)
ctx.Data["FileContent"] =filenameBase64
ctx.Data["FileContent"] = filenameBase64
//fmt.Println("************FileContent2:",ctx.Data["FileContent"].(string))
}
if !isLFSFile {
@ -783,12 +836,12 @@ func renderFile(ctx *context.APIContext, entry *git.TreeEntry, treeLink, rawLink
//ctx.Data["FileContent"] = string(markup.Render(blob.Name(), buf, path.Dir(treeLink), ctx.Repo.Repository.ComposeDocumentMetas()))
filenameBase64 := Base64Encoding.EncodeToString(buf)
ctx.Data["FileContent"] =filenameBase64
fmt.Println("************FileContent3:",ctx.Data["FileContent"].(string))
ctx.Data["FileContent"] = filenameBase64
fmt.Println("************FileContent3:", ctx.Data["FileContent"].(string))
}
}
}
}
func safeURL(address string) string {
u, err := url.Parse(address)
if err != nil {
@ -798,7 +851,6 @@ func safeURL(address string) string {
return u.String()
}
func linesBytesCount(s []byte) int {
nl := []byte{'\n'}
n := bytes.Count(s, nl)
@ -820,7 +872,6 @@ func linesBytesCount(s []byte) int {
}
*/
// FIXME: There has to be a more efficient way of doing this
func getReadmeFileFromPath(commit *git.Commit, treePath string) (*namedBlob, error) {
@ -897,13 +948,13 @@ func getReadmeFileFromPath(commit *git.Commit, treePath string) (*namedBlob, err
// FIXME: There has to be a more efficient way of doing this
func getReadmeFileFromPathExt(ctx *context.APIContext, treePath, ref string) (*namedBlob, error) {
log.Info("*****************getReadmeFileFromPathExt.GetCommit:ref:%s treepath:%s", ref, treePath)
var err error
var err error
if ctx.Repo.GitRepo == nil {
repoPath := models.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
ctx.Repo.GitRepo, err = git.OpenRepository(repoPath)
if err != nil {
ctx.ServerError("RepoRef Invalid repo "+repoPath, err)
return nil,err
return nil, err
}
// We opened it, we should close it
defer func() {
@ -913,28 +964,23 @@ func getReadmeFileFromPathExt(ctx *context.APIContext, treePath, ref string) (*n
}
}()
}
// Get the commit object for the ref
commit, err := ctx.Repo.GitRepo.GetCommit(ref)
if err != nil {
return nil, err
}
//log.Info("********GetCommit:%v",commit)
ctx.Repo.Commit=commit
ctx.Repo.Commit = commit
tree, err := commit.SubTree(treePath)
if err != nil {
return nil, err
}
//log.Info("********SubTree:%v",tree)
entries, err := tree.ListEntries()
if err != nil {
return nil, err
}
//log.Info("********ListEntries:%v, %v",err,entries)
var readmeFiles [4]*namedBlob
var exts = []string{".md", ".txt", ""} // sorted by priority
for _, entry := range entries {
@ -995,7 +1041,6 @@ func getReadmeFileFromPathExt(ctx *context.APIContext, treePath, ref string) (*n
return readmeFile, nil
}
func FindFiles(ctx *context.APIContext) {
// swagger:operation GET /repos/{owner}/{repo}/find repository find
// ---
@ -1030,23 +1075,23 @@ func FindFiles(ctx *context.APIContext) {
// "$ref": "#/responses/notFound"
treePath := ctx.Repo.TreePath
ref:= ctx.QueryTrim("ref")
ref := ctx.QueryTrim("ref")
if ref == "" {
ref = ctx.Repo.Repository.DefaultBranch
}
fmt.Println("***ref:",ref)
keyword:= ctx.QueryTrim("q")
fmt.Println("***ref:", ref)
keyword := ctx.QueryTrim("q")
if keyword == "" {
//keyword="README" //test
}
FindList,err:=FindFileFromPathExt(ctx,treePath,ref,keyword)
if err !=nil {
ctx.NotFound("FindFiles", err)
FindList, err := FindFileFromPathExt(ctx, treePath, ref, keyword)
if err != nil {
ctx.NotFound("FindFiles", err)
return
}
ctx.JSON(http.StatusOK,FindList)
ctx.JSON(http.StatusOK, FindList)
}
// TO DO
@ -1056,7 +1101,7 @@ func FindFileFromPathExt(ctx *context.APIContext, treePath, ref, key string) (fi
ctx.Repo.GitRepo, err = git.OpenRepository(repoPath)
if err != nil {
ctx.ServerError("RepoRef Invalid repo "+repoPath, err)
return nil,err
return nil, err
}
// We opened it, we should close it
defer func() {
@ -1067,14 +1112,12 @@ func FindFileFromPathExt(ctx *context.APIContext, treePath, ref, key string) (fi
}()
}
// Get the commit object for the ref
commit, err := ctx.Repo.GitRepo.GetCommit(ref)
if err != nil {
return nil, err
}
tree, err := commit.SubTree(treePath)
if err != nil {
return nil, err
@ -1089,21 +1132,20 @@ func FindFileFromPathExt(ctx *context.APIContext, treePath, ref, key string) (fi
return nil, err
}
fileList =make([]*SearchFileItem,0,0)
fileList = make([]*SearchFileItem, 0, 0)
for _, entry := range entries {
if entry.IsDir() {
continue
}
fileName := filepath.Base(entry.Name())
fileName:=filepath.Base(entry.Name())
if strings.Contains(strings.ToLower(fileName),strings.ToLower(key)) || key=="" {
if strings.Contains(strings.ToLower(fileName), strings.ToLower(key)) || key == "" {
name := entry.Name()
//isSymlink := entry.IsLink()
//target := entry
//_=target
//_=target
//
//if isSymlink {
// target, err = entry.FollowLinks()
@ -1111,7 +1153,7 @@ func FindFileFromPathExt(ctx *context.APIContext, treePath, ref, key string) (fi
// return nil, err
// }
//}
treePath=name
treePath = name
selfURL, err := url.Parse(fmt.Sprintf("%s/contents/%s?ref=%s", ctx.Repo.Repository.APIURL(), treePath, ref))
if err != nil {
return nil, err
@ -1129,15 +1171,14 @@ func FindFileFromPathExt(ctx *context.APIContext, treePath, ref, key string) (fi
}
htmlURLString := htmlURL.String()
Item := &SearchFileItem{
Name:fileName,
Path:treePath,
SHA:entry.ID.String(),
Type:entry.Type(),
Size:entry.Size(),
URL:&selfURLString,
HTMLURL:&htmlURLString,
Name: fileName,
Path: treePath,
SHA: entry.ID.String(),
Type: entry.Type(),
Size: entry.Size(),
URL: &selfURLString,
HTMLURL: &htmlURLString,
}
// Now populate the rest of the ContentsResponse based on entry type
@ -1152,29 +1193,28 @@ func FindFileFromPathExt(ctx *context.APIContext, treePath, ref, key string) (fi
} else if entry.IsSubModule() {
Item.Type = string(repofiles.ContentTypeSubmodule)
}
fileList=append(fileList,Item)
fileList = append(fileList, Item)
}
}
return
}
type SearchFileItem struct {
Name string `json:"name"`
Path string `json:"path"`
SHA string `json:"sha"`
// `type` will be `file`, `dir`, `symlink`, or `submodule`
Type string `json:"type"`
Size int64 `json:"size"`
URL *string `json:"url"`
HTMLURL *string `json:"html_url"`
// GitURL *string `json:"git_url"`
// DownloadURL *string `json:"download_url"`
// // `submodule_git_url` is populated when `type` is `submodule`, otherwise null
// SubmoduleGitURL *string `json:"submodule_git_url"`
// Links *api.FileLinksResponse `json:"_links"`
}
Type string `json:"type"`
Size int64 `json:"size"`
URL *string `json:"url"`
HTMLURL *string `json:"html_url"`
// GitURL *string `json:"git_url"`
// DownloadURL *string `json:"download_url"`
// // `submodule_git_url` is populated when `type` is `submodule`, otherwise null
// SubmoduleGitURL *string `json:"submodule_git_url"`
// Links *api.FileLinksResponse `json:"_links"`
}
func IsReadmeFileExt(name string, ext ...string) bool {
name = strings.ToLower(name)
@ -1189,7 +1229,6 @@ func IsReadmeFileExt(name string, ext ...string) bool {
return name[:7] == "readme_zh."
}
type namedBlob struct {
name string
isSymlink bool
@ -1197,13 +1236,13 @@ type namedBlob struct {
}
type ReadmeDTO struct {
Type string `json:"type"`
Encoding string `json:"encoding"`
Size int64 `json:"size"`
Name string `json:"name"`
Path string `json:"path"`
Content string `json:"content"`
Sha string `json:"sha"`
Type string `json:"type"`
Encoding string `json:"encoding"`
Size int64 `json:"size"`
Name string `json:"name"`
Path string `json:"path"`
Content string `json:"content"`
Sha string `json:"sha"`
//URL string `json:"url"`
//GitURL string `json:"git_url"`
//HTMLURL string `json:"html_url"`
@ -1216,7 +1255,7 @@ type ReadmeDTO struct {
}
type ReadmeResponeDTO struct {
Msg string
Code int
Msg string
Code int
ReadmeDTO *ReadmeDTO
}

View File

@ -2851,8 +2851,8 @@
"tags": [
"repository"
],
"summary": "Get a list of all commits from a repository",
"operationId": "repoGetAllCommits",
"summary": "Get a list of all commits from a repository and slice by time",
"operationId": "repoAllCommits",
"parameters": [
{
"type": "string",
@ -7753,6 +7753,55 @@
}
}
},
"/repos/{owner}/{repo}/readme/{dir}": {
"get": {
"produces": [
"application/json"
],
"tags": [
"repository"
],
"summary": "Gets the metadata and contents (if a file) of an entry in a repository, or a list of entries if a dir",
"operationId": "readmePathContents",
"parameters": [
{
"type": "string",
"description": "owner of the repo",
"name": "owner",
"in": "path",
"required": true
},
{
"type": "string",
"description": "name of the repo",
"name": "repo",
"in": "path",
"required": true
},
{
"type": "string",
"description": "name of the path",
"name": "dir",
"in": "path",
"required": true
},
{
"type": "string",
"description": "The name of the commit/branch/tag. Default the repositorys default branch (usually master)",
"name": "ref",
"in": "query"
}
],
"responses": {
"200": {
"$ref": "#/responses/ReadmeDTO"
},
"404": {
"$ref": "#/responses/notFound"
}
}
}
},
"/repos/{owner}/{repo}/releases": {
"get": {
"produces": [
@ -14086,17 +14135,14 @@
"type": "object",
"required": [
"clone_addr",
"uid"
"uid",
"repo_name"
],
"properties": {
"auth_password": {
"type": "string",
"x-go-name": "AuthPassword"
},
"auth_token": {
"type": "string",
"x-go-name": "AuthToken"
},
"auth_username": {
"type": "string",
"x-go-name": "AuthUsername"
@ -14125,10 +14171,6 @@
"type": "boolean",
"x-go-name": "Mirror"
},
"mirror_interval": {
"type": "string",
"x-go-name": "MirrorInterval"
},
"private": {
"type": "boolean",
"x-go-name": "Private"
@ -14145,15 +14187,6 @@
"type": "string",
"x-go-name": "RepoName"
},
"repo_owner": {
"type": "string",
"x-go-name": "RepoOwner"
},
"service": {
"description": "add configure",
"type": "string",
"x-go-name": "Service"
},
"uid": {
"type": "integer",
"format": "int64",