github.com/qri-io/qri@v0.10.1-0.20220104210721-c771715036cb/transform/startf/qri/qri.go (about)

     1  package qri
     2  
     3  import (
     4  	"fmt"
     5  	"sync"
     6  
     7  	"github.com/qri-io/dataset"
     8  	"github.com/qri-io/qri/repo"
     9  	"go.starlark.net/starlark"
    10  	"go.starlark.net/starlarkstruct"
    11  )
    12  
    13  // ModuleName defines the expected name for this module when used
    14  // in starlark's load() function, eg: load('qri.star', 'qri')
    15  const ModuleName = "qri.star"
    16  
    17  var (
    18  	once      sync.Once
    19  	qriModule starlark.StringDict
    20  )
    21  
    22  // NewModule creates a new qri module instance
    23  func NewModule(repo repo.Repo) *Module {
    24  	return &Module{repo: repo}
    25  }
    26  
    27  // Module encapsulates state for a qri starlark module
    28  type Module struct {
    29  	repo repo.Repo
    30  	ds   *dataset.Dataset
    31  }
    32  
    33  // Namespace produces this module's exported namespace
    34  func (m *Module) Namespace() starlark.StringDict {
    35  	return starlark.StringDict{
    36  		"qri": m.Struct(),
    37  	}
    38  }
    39  
    40  // Struct returns this module's methods as a starlark Struct
    41  func (m *Module) Struct() *starlarkstruct.Struct {
    42  	return starlarkstruct.FromStringDict(starlarkstruct.Default, m.AddAllMethods(starlark.StringDict{}))
    43  }
    44  
    45  // AddAllMethods augments a starlark.StringDict with all qri builtins. Should really only be used during "transform" step
    46  func (m *Module) AddAllMethods(sd starlark.StringDict) starlark.StringDict {
    47  	sd["list_datasets"] = starlark.NewBuiltin("list_datasets", m.ListDatasets)
    48  	return sd
    49  }
    50  
    51  // ListDatasets shows current local datasets
    52  func (m *Module) ListDatasets(thread *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
    53  	if m.repo == nil {
    54  		return starlark.None, fmt.Errorf("no qri repo available to list datasets")
    55  	}
    56  
    57  	refs, err := m.repo.References(0, -1)
    58  	if err != nil {
    59  		return starlark.None, fmt.Errorf("error getting dataset list: %s", err.Error())
    60  	}
    61  
    62  	l := &starlark.List{}
    63  	for _, ref := range refs {
    64  		l.Append(starlark.String(ref.String()))
    65  	}
    66  	return l, nil
    67  }