Implement status --json

This commit is contained in:
Anthony Sottile 2017-06-08 15:41:14 -07:00
parent e266f8e875
commit 692b2e54ef
3 changed files with 72 additions and 1 deletions

@ -2,6 +2,7 @@ package commands
import (
"crypto/sha256"
"encoding/json"
"fmt"
"io"
"os"
@ -14,7 +15,8 @@ import (
)
var (
porcelain = false
porcelain = false
statusJson = false
)
func statusCommand(cmd *cobra.Command, args []string) {
@ -31,6 +33,9 @@ func statusCommand(cmd *cobra.Command, args []string) {
if porcelain {
porcelainStagedPointers(scanIndexAt)
return
} else if statusJson {
jsonStagedPointers(scanIndexAt)
return
}
statusScanRefRange(ref)
@ -224,6 +229,43 @@ func statusScanRefRange(ref *git.Ref) {
}
type JSONStatusEntry struct {
Status string `json:"status"`
From string `json:"from,omitempty"`
}
type JSONStatus struct {
Files map[string]JSONStatusEntry `json:"files"`
}
func jsonStagedPointers(ref string) {
staged, unstaged, err := scanIndex(ref)
if err != nil {
ExitWithError(err)
}
status := JSONStatus{Files: make(map[string]JSONStatusEntry)}
for _, entry := range append(unstaged, staged...) {
switch entry.Status {
case lfs.StatusRename, lfs.StatusCopy:
status.Files[entry.DstName] = JSONStatusEntry{
Status: string(entry.Status), From: entry.SrcName,
}
default:
status.Files[entry.SrcName] = JSONStatusEntry{
Status: string(entry.Status),
}
}
}
ret, err := json.Marshal(status)
if err != nil {
ExitWithError(err)
}
Print(string(ret))
}
func porcelainStagedPointers(ref string) {
staged, unstaged, err := scanIndex(ref)
if err != nil {
@ -260,5 +302,6 @@ func porcelainStatusLine(entry *lfs.DiffIndexEntry) string {
func init() {
RegisterCommand("status", statusCommand, func(cmd *cobra.Command) {
cmd.Flags().BoolVarP(&porcelain, "porcelain", "p", false, "Give the output in an easy-to-parse format for scripts.")
cmd.Flags().BoolVarP(&statusJson, "json", "j", false, "Give the output in a stable json format for scripts.")
})
}

@ -22,6 +22,8 @@ Display paths of Git LFS objects that
* `--porcelain`:
Give the output in an easy-to-parse format for scripts.
* `--json`:
Give the output in a stable json format for scripts.
## SEE ALSO

@ -85,6 +85,32 @@ A file2.dat"
)
end_test
begin_test "status --json"
(
set -e
mkdir repo-3
cd repo-3
git init
git lfs track "*.dat"
echo "some data" > file1.dat
git add file1.dat
git commit -m "file1.dat"
echo "other data" > file1.dat
expected='{"files":{"file1.dat":{"status":"M"}}}'
[ "$expected" = "$(git lfs status --json)" ]
git add file1.dat
git commit -m "file1.dat changed"
git mv file1.dat file2.dat
expected='{"files":{"file2.dat":{"status":"R","from":"file1.dat"}}}'
[ "$expected" = "$(git lfs status --json)" ]
)
end_test
begin_test "status: outside git repository"
(