github.com/mattbailey/reviewdog@v0.10.0/service/serviceutil/serviceutil.go (about)

     1  package serviceutil
     2  
     3  import (
     4  	"fmt"
     5  	"os/exec"
     6  	"strings"
     7  
     8  	"github.com/reviewdog/reviewdog"
     9  )
    10  
    11  // `path` to `position`(Lnum for new file) to comment `body`s
    12  type PostedComments map[string]map[int][]string
    13  
    14  // IsPosted returns true if a given comment has been posted in code review service already,
    15  // otherwise returns false. It sees comments with same path, same position,
    16  // and same body as same comments.
    17  func (p PostedComments) IsPosted(c *reviewdog.Comment, lineNum int) bool {
    18  	if _, ok := p[c.Path]; !ok {
    19  		return false
    20  	}
    21  	bodies, ok := p[c.Path][lineNum]
    22  	if !ok {
    23  		return false
    24  	}
    25  	for _, body := range bodies {
    26  		if body == CommentBody(c) {
    27  			return true
    28  		}
    29  	}
    30  	return false
    31  }
    32  
    33  // AddPostedComment adds a posted comment.
    34  func (p PostedComments) AddPostedComment(path string, lineNum int, body string) {
    35  	if _, ok := p[path]; !ok {
    36  		p[path] = make(map[int][]string)
    37  	}
    38  	if _, ok := p[path][lineNum]; !ok {
    39  		p[path][lineNum] = make([]string, 0)
    40  	}
    41  	p[path][lineNum] = append(p[path][lineNum], body)
    42  }
    43  
    44  // BodyPrefix is prefix text of comment body.
    45  const BodyPrefix = `<sub>reported by [reviewdog](https://github.com/reviewdog/reviewdog) :dog:</sub>`
    46  
    47  // CommentBody creates comment body text.
    48  func CommentBody(c *reviewdog.Comment) string {
    49  	tool := ""
    50  	if c.ToolName != "" {
    51  		tool = fmt.Sprintf("**[%s]** ", c.ToolName)
    52  	}
    53  	return tool + BodyPrefix + "\n" + c.Body
    54  }
    55  
    56  // GitRelWorkdir returns git relative workdir of current directory.
    57  func GitRelWorkdir() (string, error) {
    58  	b, err := exec.Command("git", "rev-parse", "--show-prefix").Output()
    59  	if err != nil {
    60  		return "", fmt.Errorf("failed to run 'git rev-parse --show-prefix': %v", err)
    61  	}
    62  	return strings.Trim(string(b), "\n"), nil
    63  }