| @@ -13,6 +13,7 @@ import ( | |||||
| "html/template" | "html/template" | ||||
| "math/rand" | "math/rand" | ||||
| "code.gitea.io/gitea/modules/git" | |||||
| "xorm.io/xorm" | "xorm.io/xorm" | ||||
| "code.gitea.io/gitea/modules/blockchain" | "code.gitea.io/gitea/modules/blockchain" | ||||
| @@ -2559,6 +2560,56 @@ func UpdateRepositoryCommitNum(repo *Repository) error { | |||||
| return nil | return nil | ||||
| } | } | ||||
| type RepoFile struct { | |||||
| CommitId string | |||||
| Content []byte | |||||
| } | |||||
| // ReadLatestFileInRepo read latest version of file in repository | |||||
| // return a RepoFile | |||||
| func ReadLatestFileInRepo(userName, repoName, refName, treePath string) (*RepoFile, error) { | |||||
| var err error | |||||
| repoPath := RepoPath(userName, repoName) | |||||
| gitRepo, err := git.OpenRepository(repoPath) | |||||
| if err != nil { | |||||
| log.Error("ReadLatestFileInRepo error when OpenRepository,error=%v", err) | |||||
| return nil, err | |||||
| } | |||||
| commitID, err := gitRepo.GetBranchCommitID(refName) | |||||
| if err != nil { | |||||
| log.Error("ReadLatestFileInRepo error when GetBranchCommitID,error=%v", err) | |||||
| return nil, err | |||||
| } | |||||
| commit, err := gitRepo.GetBranchCommit(refName) | |||||
| if err != nil { | |||||
| log.Error("ReadLatestFileInRepo error when GetBranchCommit,error=%v", err) | |||||
| return nil, err | |||||
| } | |||||
| blob, err := commit.GetBlobByPath(treePath) | |||||
| if err != nil { | |||||
| log.Error("ReadLatestFileInRepo error when GetBlobByPath,error=%v", err) | |||||
| return nil, err | |||||
| } | |||||
| reader, err := blob.DataAsync() | |||||
| if err != nil { | |||||
| return nil, err | |||||
| } | |||||
| defer func() { | |||||
| if err = reader.Close(); err != nil { | |||||
| log.Error("ReadLatestFileInRepo: Close: %v", err) | |||||
| } | |||||
| }() | |||||
| buf := make([]byte, 1024) | |||||
| n, _ := reader.Read(buf) | |||||
| if n >= 0 { | |||||
| buf = buf[:n] | |||||
| } | |||||
| return &RepoFile{CommitId: commitID, Content: buf}, nil | |||||
| } | |||||
| func GenerateDefaultRepoName(ownerName string) string { | func GenerateDefaultRepoName(ownerName string) string { | ||||
| if len(ownerName) > 5 { | if len(ownerName) > 5 { | ||||
| ownerName = ownerName[:5] | ownerName = ownerName[:5] | ||||