github.com/lmorg/murex@v0.0.0-20240217211045-e081c89cd4ef/builtins/types/jsonlines/index.go (about)

     1  package jsonlines
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"strconv"
     7  
     8  	"github.com/lmorg/murex/lang"
     9  	"github.com/lmorg/murex/lang/types"
    10  )
    11  
    12  func index(p *lang.Process, params []string) error {
    13  	// if it's purely a numeric param then well index by table (ie each row is
    14  	// an array index). Otherwise we'd do our best to splice things into the
    15  	// table
    16  	for i := range params {
    17  		for _, b := range params[i] {
    18  			if b < '0' || b > '9' {
    19  				return indexTable(p, params)
    20  			}
    21  		}
    22  	}
    23  
    24  	return indexObject(p, params)
    25  }
    26  
    27  func indexObject(p *lang.Process, params []string) error {
    28  	lines := make(map[int]bool)
    29  	for i := range params {
    30  		num, err := strconv.Atoi(params[i])
    31  		if err != nil {
    32  			return fmt.Errorf("parameter, `%s`, isn't an integer. %s", params[i], err)
    33  		}
    34  		lines[num] = true
    35  	}
    36  
    37  	var (
    38  		i   int
    39  		err error
    40  	)
    41  
    42  	err = p.Stdin.ReadArray(p.Context, func(b []byte) {
    43  		if lines[i] != p.IsNot {
    44  			_, err = p.Stdout.Writeln(b)
    45  			if err != nil {
    46  				return
    47  			}
    48  		}
    49  		i++
    50  	})
    51  
    52  	return err
    53  }
    54  
    55  func indexTable(p *lang.Process, params []string) error {
    56  	cRecords := make(chan []string, 10)
    57  	status := make(chan error)
    58  
    59  	go func() {
    60  		err1 := p.Stdin.ReadArray(p.Context, func(b []byte) {
    61  			var v []interface{}
    62  			err2 := json.Unmarshal(b, &v)
    63  			if err2 != nil {
    64  				//close(cRecords)
    65  				status <- err2
    66  				return
    67  			}
    68  			cRecords <- iface2Str(v)
    69  
    70  			/*switch v.(type) {
    71  			case []string:
    72  				cRecords <- v.([]string)
    73  				return
    74  			case []interface{}:
    75  			cRecords <- iface2Str(v.([]interface{}))
    76  			return
    77  			default:
    78  				//close(cRecords)
    79  				status <- fmt.Errorf("I don't know how to turn %T into []string", v)
    80  				return
    81  			}*/
    82  
    83  		})
    84  		if err1 != nil {
    85  			close(cRecords)
    86  			status <- err1
    87  			return
    88  		}
    89  		close(cRecords)
    90  	}()
    91  
    92  	marshaller := func(s []string) []byte {
    93  		b, err3 := lang.MarshalData(p, types.Json, s)
    94  		if err3 != nil {
    95  			close(cRecords)
    96  			status <- err3
    97  		}
    98  		return b
    99  	}
   100  
   101  	go func() {
   102  		err4 := lang.IndexTemplateTable(p, params, cRecords, marshaller)
   103  		status <- err4
   104  	}()
   105  
   106  	err0 := <-status
   107  	return err0
   108  }