github.com/massongit/reviewdog@v0.0.0-20240331071725-4a16675475a8/comment_iowriter.go (about)

     1  package reviewdog
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"io"
     7  )
     8  
     9  var _ CommentService = &RawCommentWriter{}
    10  
    11  // RawCommentWriter is comment writer which writes results to given writer
    12  // without any formatting.
    13  type RawCommentWriter struct {
    14  	w io.Writer
    15  }
    16  
    17  func NewRawCommentWriter(w io.Writer) *RawCommentWriter {
    18  	return &RawCommentWriter{w: w}
    19  }
    20  
    21  func (s *RawCommentWriter) Post(_ context.Context, c *Comment) error {
    22  	_, err := fmt.Fprintln(s.w, c.Result.Diagnostic.OriginalOutput)
    23  	return err
    24  }
    25  
    26  var _ CommentService = &UnifiedCommentWriter{}
    27  
    28  // UnifiedCommentWriter is comment writer which writes results to given writer
    29  // in one of following unified formats.
    30  //
    31  // Format:
    32  //   - <file>: [<tool name>] <message>
    33  //   - <file>:<lnum>: [<tool name>] <message>
    34  //   - <file>:<lnum>:<col>: [<tool name>] <message>
    35  //
    36  // where <message> can be multiple lines.
    37  type UnifiedCommentWriter struct {
    38  	w io.Writer
    39  }
    40  
    41  func NewUnifiedCommentWriter(w io.Writer) *UnifiedCommentWriter {
    42  	return &UnifiedCommentWriter{w: w}
    43  }
    44  
    45  func (mc *UnifiedCommentWriter) Post(_ context.Context, c *Comment) error {
    46  	loc := c.Result.Diagnostic.GetLocation()
    47  	s := loc.GetPath()
    48  	start := loc.GetRange().GetStart()
    49  	if start.GetLine() > 0 {
    50  		s += fmt.Sprintf(":%d", start.GetLine())
    51  		if start.GetColumn() > 0 {
    52  			s += fmt.Sprintf(":%d", start.GetColumn())
    53  		}
    54  	}
    55  	s += fmt.Sprintf(": [%s] %s", c.ToolName, c.Result.Diagnostic.GetMessage())
    56  	_, err := fmt.Fprintln(mc.w, s)
    57  	return err
    58  }