You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

filesystem_client.go 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. if err := callback(p, f, nil); err != nil {
  38. return err
  39. }
  40. }
  41. return nil
  42. }
  43. // Upload writes the specific LFS object to the target path
  44. func (c *FilesystemClient) Upload(ctx context.Context, objects []Pointer, callback UploadCallback) error {
  45. for _, object := range objects {
  46. p := Pointer{object.Oid, object.Size}
  47. objectPath := c.objectPath(p.Oid)
  48. if err := os.MkdirAll(filepath.Dir(objectPath), os.ModePerm); err != nil {
  49. return err
  50. }
  51. content, err := callback(p, nil)
  52. if err != nil {
  53. return err
  54. }
  55. err = func() error {
  56. defer content.Close()
  57. f, err := os.Create(objectPath)
  58. if err != nil {
  59. return err
  60. }
  61. _, err = io.Copy(f, content)
  62. return err
  63. }()
  64. if err != nil {
  65. return err
  66. }
  67. }
  68. return nil
  69. }