git rest api 操作代码的简单说明

对于基于rest api 进行git 操作相比使用git 自带工具实现起来考虑的东西就比较多了,codefever 目前暂时是不支持的

gogs web 操作处理 (但是目前没提供rest api)

  • 简单原理
    gogs 对于web 文件编辑操作是基于了临时clone +添加文件本地提交+push 的操作机制
    处理流程就是先本地clone 一个,然后在进行本地文件写入,git add, git commit git push
    具体操作部分使用了gogs 自己包装的一个git 模块, 实现代码复用
  • 参考编辑处理
    internal/route/repo/editor.go
    internal/db/repo_editor.go
 
if err := c.Repo.Repository.UpdateRepoFile(c.User, db.UpdateRepoFileOptions{
        LastCommitID: lastCommit,
        OldBranch:    oldBranchName,
        NewBranch:    branchName,
        OldTreeName:  oldTreePath,
        NewTreeName:  f.TreePath,
        Message:      message,
        Content:      strings.Replace(f.Content, "\r", "", -1),
        IsNewFile:    isNewFile,
    }); err != nil {
        log.Error("Failed to update repo file: %v", err)
        c.FormErr("TreePath")
        c.RenderWithErr(c.Tr("repo.editor.fail_to_update_file", f.TreePath, errors.InternalServerError), tmplEditorEdit, &f)
        return
    }

gitea 关于rest api 的处理

gitea 是提供了rest api 进行git 代码操作的
参考代码routers/api/v1/repo/file.go,services/repository/files/update.go
整体处理部分类似,也是使用了一个临时的git repo,然后进行的提交处理
核心是gitea 自己包装的一个文件服务

 
func CreateOrUpdateRepoFile(ctx context.Context, repo *repo_model.Repository, doer *user_model.User, opts *UpdateRepoFileOptions) (*structs.FileResponse, error) {

说明

目前对于git 基于rest api 进行操作还是不是太灵活,基本设计上都会使用类似临时git 的处理,基于临时处理潜在的问题也比较明显,就是临时文件的占用,以及
大git repo 的问题,对于文件系统很容易造成性能问题(后边研究下gitlab 的处理机制),还好因为git 自带的冲突解决机制,不然多人api 操作很容易造成一些数据
丢失或者数据不一致的问题

参考资料

https://github.com/gogs/gogs
https://github.com/go-gitea/gitea

posted on 2022-02-24 13:05  荣锋亮  阅读(413)  评论(0编辑  收藏  举报

导航