github.com/lmorg/murex@v0.0.0-20240217211045-e081c89cd4ef/builtins/core/tabulate/writer_map.go (about)

     1  package tabulate
     2  
     3  import (
     4  	"strings"
     5  
     6  	"github.com/lmorg/murex/lang/stdio"
     7  	"github.com/lmorg/murex/utils/json"
     8  )
     9  
    10  type mapWriter struct {
    11  	m      map[string]string
    12  	err    error
    13  	out    stdio.Io
    14  	joiner string
    15  }
    16  
    17  func newMapWriter(writer stdio.Io, joiner string) *mapWriter {
    18  	return &mapWriter{
    19  		m:      make(map[string]string),
    20  		out:    writer,
    21  		joiner: joiner,
    22  	}
    23  }
    24  
    25  func (mw *mapWriter) Write(array []string) error {
    26  	mw.m[array[0]] = strings.Join(array[1:], mw.joiner)
    27  	return nil
    28  }
    29  
    30  func (mw *mapWriter) Flush() {
    31  	var b []byte
    32  
    33  	b, mw.err = json.Marshal(mw.m, mw.out.IsTTY())
    34  	if mw.err != nil {
    35  		return
    36  	}
    37  
    38  	_, mw.err = mw.out.Write(b)
    39  	return
    40  }
    41  
    42  func (mw *mapWriter) Error() error {
    43  	return mw.err
    44  }