gitee.com/sy_183/go-common@v1.0.5-0.20231205030221-958cfe129b47/config.v2/file.go (about)

     1  package config
     2  
     3  import (
     4  	"bufio"
     5  	"errors"
     6  	"gitee.com/sy_183/go-common/lock"
     7  	"gitee.com/sy_183/go-common/yaml"
     8  	"os"
     9  	"sync"
    10  )
    11  
    12  type fileContext struct {
    13  	path string
    14  	typ  Type
    15  }
    16  
    17  type FileLoader struct {
    18  	files []fileContext
    19  	mu    sync.RWMutex
    20  }
    21  
    22  func NewFileLoader() *FileLoader {
    23  	return new(FileLoader)
    24  }
    25  
    26  func (l *FileLoader) AddFile(path string, typ Type) {
    27  	if typ.Id == TypeUnknown.Id {
    28  		typ = ProbeType(path)
    29  		if typ.Id == TypeUnknown.Id {
    30  			return
    31  		}
    32  	}
    33  	lock.LockDo(&l.mu, func() {
    34  		l.files = append(l.files, fileContext{
    35  			path: path,
    36  			typ:  typ,
    37  		})
    38  	})
    39  }
    40  
    41  func (l *FileLoader) AddFilePrefix(prefix string, types ...Type) {
    42  	lock.LockDo(&l.mu, func() {
    43  		for _, typ := range types {
    44  			if typ.Id == TypeUnknown.Id {
    45  				continue
    46  			}
    47  			for _, suffix := range typ.Suffixes {
    48  				l.files = append(l.files, fileContext{
    49  					path: prefix + "." + suffix,
    50  					typ:  typ,
    51  				})
    52  			}
    53  		}
    54  	})
    55  }
    56  
    57  func (l *FileLoader) Load() (*yaml.Node, error) {
    58  	files := lock.RLockGet(&l.mu, func() []fileContext {
    59  		return append([]fileContext(nil), l.files...)
    60  	})
    61  	for i := len(files) - 1; i >= 0; i-- {
    62  		ctx := files[i]
    63  		fp, err := os.Open(ctx.path)
    64  		if err != nil {
    65  			if errors.Is(err, os.ErrNotExist) {
    66  				continue
    67  			}
    68  			return nil, err
    69  		}
    70  		node, err := ctx.typ.Parser.Parse(bufio.NewReader(fp))
    71  		if err != nil {
    72  			return nil, err
    73  		}
    74  		return node, nil
    75  	}
    76  	return nil, nil
    77  }