diff options
author | Alberto Cortés <alberto@sourced.tech> | 2015-11-16 03:20:01 +0100 |
---|---|---|
committer | Alberto Cortés <alberto@sourced.tech> | 2015-11-25 11:09:51 +0100 |
commit | d643cea1e8a6d618b2eddfdbed086c7bdf208658 (patch) | |
tree | b862c72ccb674910d24eac2ab424a7fb5ea3f0fb /common.go | |
parent | caab43e7f4ee10a15b2af826485b688473b34356 (diff) | |
download | go-git-d643cea1e8a6d618b2eddfdbed086c7bdf208658.tar.gz |
Blame support for files
This also includes a diff package and revlist package (needed by
blame)
Some extra packfiles (<1MB) are also included, to be used as fixtures in
the tests.
Diffstat (limited to 'common.go')
-rw-r--r-- | common.go | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/common.go b/common.go new file mode 100644 index 0000000..3e25fc7 --- /dev/null +++ b/common.go @@ -0,0 +1,49 @@ +package git + +import ( + "bytes" + "strings" +) + +// CountLines returns the number of lines in a string. +// The newline character is assumed to be '\n'. +// The empty string contains 0 lines. +// If the last line of the string doesn't end with a newline, it will +// still be considered a line. +func CountLines(s string) int { + if s == "" { + return 0 + } + nEol := strings.Count(s, "\n") + if strings.HasSuffix(s, "\n") { + return nEol + } + return nEol + 1 +} + +// FindFile searches for a path in a commit. Returns the file and true if found. +// Returns nil and false if not found. +// TODO: should this be a method of git.Commit instead? +func FindFile(path string, commit *Commit) (file *File, found bool) { + tree := commit.Tree() + for file := range tree.Files() { + if file.Name == path { + return file, true + } + } + return nil, false +} + +// Data returns the contents of a file in a commit and true if found. +// Returns an empty string and false if the file is not found in the +// commit. +// TODO: should this be a method of git.Commit instead? +func Data(path string, commit *Commit) (contents string, found bool) { + file, found := FindFile(path, commit) + if !found { + return "", found + } + buf := new(bytes.Buffer) + buf.ReadFrom(file) + return buf.String(), found +} |