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.

73 lines
1.8 KiB

  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package git
  5. import (
  6. "bytes"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "os"
  11. "os/exec"
  12. )
  13. // Blob represents a Git object.
  14. type Blob struct {
  15. repo *Repository
  16. *TreeEntry
  17. }
  18. // Data gets content of blob all at once and wrap it as io.Reader.
  19. // This can be very slow and memory consuming for huge content.
  20. func (b *Blob) Data() (io.Reader, error) {
  21. stdout := new(bytes.Buffer)
  22. stderr := new(bytes.Buffer)
  23. // Preallocate memory to save ~50% memory usage on big files.
  24. stdout.Grow(int(b.Size() + 2048))
  25. if err := b.DataPipeline(stdout, stderr); err != nil {
  26. return nil, concatenateError(err, stderr.String())
  27. }
  28. return stdout, nil
  29. }
  30. // DataPipeline gets content of blob and write the result or error to stdout or stderr
  31. func (b *Blob) DataPipeline(stdout, stderr io.Writer) error {
  32. return NewCommand("show", b.ID.String()).RunInDirPipeline(b.repo.Path, stdout, stderr)
  33. }
  34. type cmdReadCloser struct {
  35. cmd *exec.Cmd
  36. stdout io.Reader
  37. }
  38. func (c cmdReadCloser) Read(p []byte) (int, error) {
  39. return c.stdout.Read(p)
  40. }
  41. func (c cmdReadCloser) Close() error {
  42. io.Copy(ioutil.Discard, c.stdout)
  43. return c.cmd.Wait()
  44. }
  45. // DataAsync gets a ReadCloser for the contents of a blob without reading it all.
  46. // Calling the Close function on the result will discard all unread output.
  47. func (b *Blob) DataAsync() (io.ReadCloser, error) {
  48. cmd := exec.Command("git", "show", b.ID.String())
  49. cmd.Dir = b.repo.Path
  50. cmd.Stderr = os.Stderr
  51. stdout, err := cmd.StdoutPipe()
  52. if err != nil {
  53. return nil, fmt.Errorf("StdoutPipe: %v", err)
  54. }
  55. if err = cmd.Start(); err != nil {
  56. return nil, fmt.Errorf("Start: %v", err)
  57. }
  58. return cmdReadCloser{stdout: stdout, cmd: cmd}, nil
  59. }