github.com/driusan/dgit@v0.0.0-20221118233547-f39f0c15edbb/git/show.go (about) 1 package git 2 3 import ( 4 "fmt" 5 "strings" 6 ) 7 8 type FormatString string 9 10 func (f FormatString) FormatCommit(c *Client, cmt CommitID) (string, error) { 11 if f == "" || f == "medium" { 12 output, err := formatCommitMedium(cmt, c) 13 if err != nil { 14 return "", err 15 } 16 return fmt.Sprintf("%v\n", output), nil 17 } 18 if f == "raw" { 19 output := fmt.Sprintf("commit %v\n", cmt) 20 cmtObject, err := c.GetCommitObject(cmt) 21 if err != nil { 22 return "", err 23 } 24 return fmt.Sprintf("%v%v\n", output, cmtObject), nil 25 } 26 27 return "", fmt.Errorf("Format %s is not supported.\n", f) 28 } 29 30 type ShowOptions struct { 31 DiffOptions 32 Format FormatString 33 } 34 35 // Show implementes the "git show" command. 36 func Show(c *Client, opts ShowOptions, objects []string) error { 37 if len(objects) < 1 { 38 return fmt.Errorf("Provide at least one commit.") 39 } 40 41 commitIds := []CommitID{} 42 43 for _, object := range objects { 44 // Commits only for now 45 commit, err := RevParseCommit(c, &RevParseOptions{}, object) 46 if err != nil { 47 return err 48 } 49 50 commitIds = append(commitIds, commit) 51 } 52 53 for _, commit := range commitIds { 54 output, err := opts.Format.FormatCommit(c, commit) 55 if err != nil { 56 return err 57 } 58 fmt.Printf("%v", output) 59 } 60 61 return nil 62 } 63 64 func formatCommitMedium(cmt CommitID, c *Client) (string, error) { 65 author, err := cmt.GetAuthor(c) 66 if err != nil { 67 return "", err 68 } 69 70 date, err := cmt.GetDate(c) 71 if err != nil { 72 return "", err 73 } 74 75 msg, err := cmt.GetCommitMessage(c) 76 if err != nil { 77 return "", err 78 } 79 80 // Headers 81 output := fmt.Sprintf("commit %v\nAuthor: %s\nDate: %v\n\n", cmt, author, date.Format("Mon Jan 2 15:04:05 2006 -0700")) 82 83 // Commit message body 84 lines := strings.Split(strings.TrimSpace(msg.String()), "\n") 85 for _, l := range lines { 86 output = fmt.Sprintf("%v %v\n", output, l) 87 } 88 89 return output, nil 90 }