Debian Codegraph @

confmap/provider/fileprovider/provider.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 //go:generate mdatagen metadata.yaml
5
6 package fileprovider // import "go.opentelemetry.io/collector/confmap/provider/fileprovider"
7
8 import (
9 "context"
10 "fmt"
11 "os"
12 "path/filepath"
13 "strings"
14
15 "go.opentelemetry.io/collector/confmap"
16 )
17
18 const schemeName = "file"
19
20 type provider struct{}
21
22 // NewFactory returns a factory for a confmap.Provider that reads the configuration from a file.
23 //
24 // This Provider supports "file" scheme, and can be called with a "uri" that follows:
25 //
26 // file-uri = "file:" local-path
27 // local-path = [ drive-letter ] file-path
28 // drive-letter = ALPHA ":"
29 //
30 // The "file-path" can be relative or absolute, and it can be any OS supported format.
31 //
32 // Examples:
33 // `file:path/to/file` - relative path (unix, windows)
34 // `file:/path/to/file` - absolute path (unix, windows)
35 // `file:c:/path/to/file` - absolute path including drive-letter (windows)
36 // `file:c:\path\to\file` - absolute path including drive-letter (windows)
37 func NewFactory() confmap.ProviderFactory {
38 return confmap.NewProviderFactory(newProvider)
39 }
40
41 func newProvider(confmap.ProviderSettings) confmap.Provider {
42 return &provider{}
43 }
44
45 func (fmp *provider) Retrieve(_ context.Context, uri string, _ confmap.WatcherFunc) (*confmap.Retrieved, error) {
46 if !strings.HasPrefix(uri, schemeName+":") {
47 return nil, fmt.Errorf("%q uri is not supported by %q provider", uri, schemeName)
48 }
49
50 // Clean the path before using it.
51 content, err := os.ReadFile(filepath.Clean(uri[len(schemeName)+1:]))
52 if err != nil {
53 return nil, fmt.Errorf("unable to read the file %v: %w", uri, err)
54 }
55
56 return confmap.NewRetrievedFromYAML(content)
57 }
58
59 func (*provider) Scheme() string {
60 return schemeName
61 }
62
63 func (*provider) Shutdown(context.Context) error {
64 return nil
65 }