diff options
author | Sunny <me@darkowlzz.space> | 2017-10-06 17:17:29 +0530 |
---|---|---|
committer | Sunny <me@darkowlzz.space> | 2017-11-02 18:50:20 +0530 |
commit | 69b72d30b125b07f69f2b1f53c44b273d7cb4da9 (patch) | |
tree | 13f926f35b05630ff039c4950f9cdd770c2258a3 /plumbing/object/commit.go | |
parent | 06728688aa3026a6edb36d3319922e25bce89392 (diff) | |
download | go-git-69b72d30b125b07f69f2b1f53c44b273d7cb4da9.tar.gz |
Add Stats() to Commit
Stats() is similar to `git show --stat <hash>`.
Diffstat (limited to 'plumbing/object/commit.go')
-rw-r--r-- | plumbing/object/commit.go | 66 |
1 files changed, 66 insertions, 0 deletions
diff --git a/plumbing/object/commit.go b/plumbing/object/commit.go index 66ecabd..e5faa38 100644 --- a/plumbing/object/commit.go +++ b/plumbing/object/commit.go @@ -265,6 +265,72 @@ func (b *Commit) Encode(o plumbing.EncodedObject) error { return err } +// FileStat stores the status of changes in content of a file. +type FileStat struct { + Name string + Addition int + Deletion int +} + +func (fs FileStat) String() string { + totalChanges := fs.Addition + fs.Deletion + adds := strings.Repeat("+", fs.Addition) + dels := strings.Repeat("-", fs.Deletion) + return fmt.Sprintf(" %s | %d %s%s", fs.Name, totalChanges, adds, dels) +} + +// FileStats is a collection of FileStat. +type FileStats []FileStat + +// Stats shows the status +func (c *Commit) Stats() (FileStats, error) { + var fileStats FileStats + + // Get the previous commit. + ci := c.Parents() + parentCommit, err := ci.Next() + if err != nil { + return nil, err + } + + patch, err := parentCommit.Patch(c) + if err != nil { + return nil, err + } + + filePatches := patch.FilePatches() + for _, fp := range filePatches { + cs := FileStat{} + from, to := fp.Files() + if from == nil { + // New File is created. + cs.Name = to.Path() + } else if to == nil { + // File is deleted. + cs.Name = from.Path() + } else if from.Path() != to.Path() { + // File is renamed. + cs.Name = fmt.Sprintf("%s => %s", from.Path(), to.Path()) + } else { + // File is modified. + cs.Name = from.Path() + } + + for _, chunk := range fp.Chunks() { + switch chunk.Type() { + case 1: + cs.Addition += strings.Count(chunk.Content(), "\n") + case 2: + cs.Deletion += strings.Count(chunk.Content(), "\n") + } + } + + fileStats = append(fileStats, cs) + } + + return fileStats, nil +} + func (c *Commit) String() string { return fmt.Sprintf( "%s %s\nAuthor: %s\nDate: %s\n\n%s\n", |