summaryrefslogtreecommitdiff
path: root/internal/datafs/context.go
blob: 30722f2b2aefc894717e88b433a9ff992bf31741 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package datafs

import (
	"context"
	"io"
	"io/fs"
	"os"
)

// withContexter is an fs.FS that can be configured with a custom context
// copied from go-fsimpl - see internal/types.go
type withContexter interface {
	WithContext(ctx context.Context) fs.FS
}

type withDataSourceRegistryer interface {
	WithDataSourceRegistry(registry Registry) fs.FS
}

// WithDataSourceRegistryFS injects a datasource registry into the filesystem fs, if the
// filesystem supports it (i.e. has a WithDataSourceRegistry method). This is used for
// the mergefs filesystem.
func WithDataSourceRegistryFS(registry Registry, fsys fs.FS) fs.FS {
	if fsys, ok := fsys.(withDataSourceRegistryer); ok {
		return fsys.WithDataSourceRegistry(registry)
	}

	return fsys
}

type stdinCtxKey struct{}

func ContextWithStdin(ctx context.Context, r io.Reader) context.Context {
	return context.WithValue(ctx, stdinCtxKey{}, r)
}

func StdinFromContext(ctx context.Context) io.Reader {
	if r, ok := ctx.Value(stdinCtxKey{}).(io.Reader); ok {
		return r
	}

	return os.Stdin
}