github.com/googollee/clic@v0.1.5/source/file.go (about)

     1  package source
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"reflect"
     7  
     8  	"github.com/googollee/clic/structtags"
     9  )
    10  
    11  type FileCodec interface {
    12  	TagName() string
    13  	ExtName() string
    14  	Encode(path string, v any) error
    15  	Decode(path string, v any) error
    16  }
    17  
    18  type FileOption func(*fileSource) error
    19  
    20  func FileFormat(codec FileCodec) FileOption {
    21  	return func(s *fileSource) error {
    22  		if codec == nil {
    23  			return fmt.Errorf("invalid codec: %v", codec)
    24  		}
    25  		s.codec = codec
    26  		return nil
    27  	}
    28  }
    29  
    30  func FilePathFlag(name string) FileOption {
    31  	return func(s *fileSource) error {
    32  		if name == "" {
    33  			return fmt.Errorf("invalid flag name of the config file path: %q", name)
    34  		}
    35  		s.filepathFlag = name
    36  		return nil
    37  	}
    38  }
    39  
    40  type fileSource struct {
    41  	codec        FileCodec
    42  	filepathFlag string
    43  	filepath     string
    44  	err          error
    45  
    46  	value reflect.Value
    47  }
    48  
    49  func File(options ...FileOption) Source {
    50  	ret := fileSource{
    51  		codec:        JSON{},
    52  		filepathFlag: "config",
    53  	}
    54  
    55  	for _, option := range options {
    56  		if err := option(&ret); err != nil {
    57  			ret.err = err
    58  		}
    59  	}
    60  
    61  	return &ret
    62  }
    63  
    64  func (s *fileSource) Error() error {
    65  	return s.err
    66  }
    67  
    68  func (s *fileSource) Register(fset FlagSet, fields []structtags.Field) error {
    69  	if s.err != nil {
    70  		return s.err
    71  	}
    72  
    73  	s.value = newFromFields(fields, 0, s.codec.TagName()+":\"%s\"")
    74  	fset.StringVar(&s.filepath, s.filepathFlag, "", "the path of the config file")
    75  
    76  	return nil
    77  }
    78  
    79  func (s *fileSource) Parse(ctx context.Context, args []string) error {
    80  	if s.err != nil {
    81  		return s.err
    82  	}
    83  
    84  	if s.filepath == "" {
    85  		return nil
    86  	}
    87  
    88  	return s.codec.Decode(s.filepath, s.value.Interface())
    89  }