gitea源码

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package lfs
  4. import (
  5. "context"
  6. "io"
  7. "net/url"
  8. "os"
  9. "path/filepath"
  10. "code.gitea.io/gitea/modules/util"
  11. )
  12. // FilesystemClient is used to read LFS data from a filesystem path
  13. type FilesystemClient struct {
  14. lfsDir string
  15. }
  16. // BatchSize returns the preferred size of batchs to process
  17. func (c *FilesystemClient) BatchSize() int {
  18. return 1
  19. }
  20. func newFilesystemClient(endpoint *url.URL) *FilesystemClient {
  21. path, _ := util.FileURLToPath(endpoint)
  22. lfsDir := filepath.Join(path, "lfs", "objects")
  23. return &FilesystemClient{lfsDir}
  24. }
  25. func (c *FilesystemClient) objectPath(oid string) string {
  26. return filepath.Join(c.lfsDir, oid[0:2], oid[2:4], oid)
  27. }
  28. // Download reads the specific LFS object from the target path
  29. func (c *FilesystemClient) Download(ctx context.Context, objects []Pointer, callback DownloadCallback) error {
  30. for _, object := range objects {
  31. p := Pointer{object.Oid, object.Size}
  32. objectPath := c.objectPath(p.Oid)
  33. f, err := os.Open(objectPath)
  34. if err != nil {
  35. return err
  36. }
  37. defer f.Close()
  38. if err := callback(p, f, nil); err != nil {
  39. return err
  40. }
  41. }
  42. return nil
  43. }
  44. // Upload writes the specific LFS object to the target path
  45. func (c *FilesystemClient) Upload(ctx context.Context, objects []Pointer, callback UploadCallback) error {
  46. for _, object := range objects {
  47. p := Pointer{object.Oid, object.Size}
  48. objectPath := c.objectPath(p.Oid)
  49. if err := os.MkdirAll(filepath.Dir(objectPath), os.ModePerm); err != nil {
  50. return err
  51. }
  52. content, err := callback(p, nil)
  53. if err != nil {
  54. return err
  55. }
  56. err = func() error {
  57. defer content.Close()
  58. f, err := os.Create(objectPath)
  59. if err != nil {
  60. return err
  61. }
  62. defer f.Close()
  63. _, err = io.Copy(f, content)
  64. return err
  65. }()
  66. if err != nil {
  67. return err
  68. }
  69. }
  70. return nil
  71. }