code.gitea.io/gitea@v1.19.3/modules/git/blob.go (about) 1 // Copyright 2015 The Gogs Authors. All rights reserved. 2 // Copyright 2019 The Gitea Authors. All rights reserved. 3 // SPDX-License-Identifier: MIT 4 5 package git 6 7 import ( 8 "bytes" 9 "encoding/base64" 10 "io" 11 12 "code.gitea.io/gitea/modules/typesniffer" 13 "code.gitea.io/gitea/modules/util" 14 ) 15 16 // This file contains common functions between the gogit and !gogit variants for git Blobs 17 18 // Name returns name of the tree entry this blob object was created from (or empty string) 19 func (b *Blob) Name() string { 20 return b.name 21 } 22 23 // GetBlobContent Gets the content of the blob as raw text 24 func (b *Blob) GetBlobContent() (string, error) { 25 dataRc, err := b.DataAsync() 26 if err != nil { 27 return "", err 28 } 29 defer dataRc.Close() 30 buf := make([]byte, 1024) 31 n, _ := util.ReadAtMost(dataRc, buf) 32 buf = buf[:n] 33 return string(buf), nil 34 } 35 36 // GetBlobLineCount gets line count of the blob 37 func (b *Blob) GetBlobLineCount() (int, error) { 38 reader, err := b.DataAsync() 39 if err != nil { 40 return 0, err 41 } 42 defer reader.Close() 43 buf := make([]byte, 32*1024) 44 count := 1 45 lineSep := []byte{'\n'} 46 47 c, err := reader.Read(buf) 48 if c == 0 && err == io.EOF { 49 return 0, nil 50 } 51 for { 52 count += bytes.Count(buf[:c], lineSep) 53 switch { 54 case err == io.EOF: 55 return count, nil 56 case err != nil: 57 return count, err 58 } 59 c, err = reader.Read(buf) 60 } 61 } 62 63 // GetBlobContentBase64 Reads the content of the blob with a base64 encode and returns the encoded string 64 func (b *Blob) GetBlobContentBase64() (string, error) { 65 dataRc, err := b.DataAsync() 66 if err != nil { 67 return "", err 68 } 69 defer dataRc.Close() 70 71 pr, pw := io.Pipe() 72 encoder := base64.NewEncoder(base64.StdEncoding, pw) 73 74 go func() { 75 _, err := io.Copy(encoder, dataRc) 76 _ = encoder.Close() 77 78 if err != nil { 79 _ = pw.CloseWithError(err) 80 } else { 81 _ = pw.Close() 82 } 83 }() 84 85 out, err := io.ReadAll(pr) 86 if err != nil { 87 return "", err 88 } 89 return string(out), nil 90 } 91 92 // GuessContentType guesses the content type of the blob. 93 func (b *Blob) GuessContentType() (typesniffer.SniffedType, error) { 94 r, err := b.DataAsync() 95 if err != nil { 96 return typesniffer.SniffedType{}, err 97 } 98 defer r.Close() 99 100 return typesniffer.DetectContentTypeFromReader(r) 101 }