config

package module
v0.0.38 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 6, 2025 License: GPL-3.0 Imports: 14 Imported by: 21

README

Configuration Library

Theory of Operation

The core philosophy of this library is to standardize configuration handling with sensible, consistent defaults.

There are two types of configuration files:

  1. A simple environment-style KEY=VALUE file (defined by config.proto in this package).
  2. An application-specific Protobuf file (e.g., <appname>.proto).

1. Basic Application Configuration

This configuration uses a simple, environment-style file for basic settings. The file is loaded from the following locations, in order of precedence (later files override earlier ones):

  1. /usr/share/doc/<appname>/config.text
  2. /etc/default/<appname>
  3. ~/.config/<appname>/config.text

Note: These files must only contain KEY=VALUE pairs.


2. Application-Specific Protobuf Configuration

This is for the application's main data structure, defined in its own .proto file. By default, these files are always located in a standard location.

For an application named forge using a forge.proto definition, the default file path is:

  • ~/.config/forge/forge.text

The default paths and filenames can be overridden by setting the appropriate values in the basic application config file (see #1 above).


Code Example & Notes

The autogenpb tool provides powerful automation. If you follow its conventions, the configuration and cache management functions work seamlessly.

For a .proto file containing the message Repos, the function GetProtobufName(pb) will return "repos".

Consequently, the standard functions ConfigLoad(), ConfigSave(), CacheLoad(), and CacheSave() will automatically handle the correct files without any extra code:

  • Config: ~/.config/<appname>/repos.pb
  • Cache: ~/.cache/<appname>/repos.pb
// message Repos {
//         string                      uuid                     = 1;
//         string                      version                  = 2;
//         repeated Repo               repos                    = 3;

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrEmpty error = fmt.Errorf("config file was empty")
View Source
var ErrKeyNotSet = KeyNotSetError{}

A generic sentinel error for this category.

View Source
var ErrMarshal error = fmt.Errorf("protobuf parse error")
View Source
var ErrNotInitialized = NotInitializedError{}

Finally, declare a package-level variable of your new type. This is the "sentinel" error that users will compare against.

View Source
var ErrProtoFilename error = fmt.Errorf("proto does not have Filename")
View Source
var ErrProtoNoVarName error = errors.New("name not in .proto")
View Source
var ErrProtoVarNotString error = errors.New("name exists but is not a string")
View Source
var NotInitialized error = errors.New("your application config not initialized")
View Source
var VersionMismatch error = errors.New("your PB version does not match")

Functions

func CreateCacheDirPB added in v0.0.30

func CreateCacheDirPB(pb proto.Message, dirname string, filename string) error

checks the UUID and Version of the .pb file

func ErrdKeyFalse added in v0.0.24

func ErrdKeyFalse(varname string) error

func ErrdKeyNotSet added in v0.0.24

func ErrdKeyNotSet(varname string) error

func Exists added in v0.0.10

func Exists(filename string) bool

a simple function name shortcut

func ForceCreateCacheDirPB added in v0.0.33

func ForceCreateCacheDirPB(pb proto.Message, dirname string, filename string) error

checks the UUID and Version of the .pb file

func ForceCreatePB added in v0.0.37

func ForceCreatePB(pb proto.Message) error

checks the UUID and Version of the .pb file should re-create the file with the new .proto (unless the filename is bank)

func GetFilename

func GetFilename(pb proto.Message) (string, error)

this will try both "filename" and "Filename"

func GetProtoFile added in v0.0.30

func GetProtoFile(pb proto.Message) (string, error)

GetProtoFile returns the name of the .proto file that defined the message.

func GetProtobufName added in v0.0.30

func GetProtobufName(pb proto.Message) (string, error)

Because you followed autogenpb's advice (you did follow it right?) you now win the automation lottery.

for this .proto file, GetProtobufName(pb) returns "repos" Then, ConfigLoad(), ConfigSave(), CacheLoad() and CacheSave() all do exactly what is expected:

Automatically work with the files:

~/.config/<appname>/repos.pb

or

~/.cache/<appname/repos.pb

message Repos {
        string                      uuid                     = 1;
        string                      version                  = 2;
        repeated Repo               repos                    = 3;

func GetString added in v0.0.16

func GetString(pb proto.Message, varname string) (string, error)

this will try both "filename" and "Filename"

func GetThirdFieldName added in v0.0.30

func GetThirdFieldName(pb proto.Message) (string, error)

func HasChanged added in v0.0.3

func HasChanged(name string) bool

func IsDir added in v0.0.10

func IsDir(dirname string) bool

simple function name shortcut

func LoadCacheDir added in v0.0.30

func LoadCacheDir(pb proto.Message) error

loads foo.proto from ~/.cache/<appname>/foo.pb

func LoadCacheDirByAppname added in v0.0.30

func LoadCacheDirByAppname(pb proto.Message, appname string) error

loads foo.proto from ~/.cache/<appname>/foo.pb

func LoadConfigDir added in v0.0.30

func LoadConfigDir(pb proto.Message) error

loads foo.proto from ~/.config/<appname>/foo.text

func LoadConfigPB added in v0.0.22

func LoadConfigPB(pb proto.Message, appname string, protoname string) (string, error)

func LoadFromFilename added in v0.0.22

func LoadFromFilename(pb proto.Message, fullname string) error

func LoadPanic added in v0.0.30

func LoadPanic(pb proto.Message) error

should this be a function?

func MakeCacheFilename added in v0.0.30

func MakeCacheFilename(appname string, protoname string) string

~/.cache/appname/protoname.pb

func MakeConfigFilename added in v0.0.30

func MakeConfigFilename(appname string, protoname string) string

~/.config/appname/protoname.text

func NewKeyNotSetError added in v0.0.24

func NewKeyNotSetError(varname string) error

A helper function to create this error.

func Path added in v0.0.10

func Path(filename string) string

notsure if this is a thing anymore. don't care much either

func ReLoad added in v0.0.30

func ReLoad(pb proto.Message) error

uses the version to die. This is needed because loading binary protobuf files with rearranged messages is indeterminate

func Save added in v0.0.8

func Save(pb proto.Message) error

writes the protobuf to disk uses the already configured Filename

func SaveToFilename added in v0.0.22

func SaveToFilename(pb proto.Message, fullname string) error

writes the protobuf to disk (sets Filename if PB has 'Filename')

func SaveWithHeader added in v0.0.30

func SaveWithHeader(pb proto.Message, header string) error

special case. adds a header to the TEXT output

func SetChanged added in v0.0.3

func SetChanged(name string, b bool)

func SetFilename

func SetFilename(pb proto.Message, filename string) (bool, error)

sets "Filename" if it exists in the protobuf

func VersionCheck added in v0.0.30

func VersionCheck(pb proto.Message) (string, string, error)

verify 'version' for .pb files application should die if they don't match returns (newVersion, oldVersion, error)

func VersionCheckFile added in v0.0.30

func VersionCheckFile(pb proto.Message, filename string) (string, string, error)

verify 'version' for .pb files application should die if they don't match returns (newVersion, oldVersion, error)

Types

type KeyNotSetError added in v0.0.24

type KeyNotSetError struct {
	KeyName string // It can hold data!
}

Let's make a more complex error for key-not-set issues.

func (KeyNotSetError) Error added in v0.0.24

func (e KeyNotSetError) Error() string

Make it satisfy the 'error' interface.

func (KeyNotSetError) Is added in v0.0.24

func (e KeyNotSetError) Is(target error) bool

(Your Goal) Define a custom Is() method. errors.Is(someError, ErrKeyNotSet) will call this method.

type NotInitializedError added in v0.0.24

type NotInitializedError struct{}

First, define a new, named type for your error. A struct is common.

func (NotInitializedError) Error added in v0.0.24

func (e NotInitializedError) Error() string

Now, attach the Error() method to your new type. This makes it satisfy the built-in 'error' interface.

func (NotInitializedError) String added in v0.0.24

func (e NotInitializedError) String() string

(Your Goal) Attach a custom String() method for pretty printing. This will be used by fmt.Println, for example.

type PatchError added in v0.0.17

type PatchError struct {
	// Note: The `XXX_` fields are part of the older struct tags,
	// but the reflection logic comes from the modern API.
	// In a real generated file, you wouldn't see these tags.
	UserName  string                 `protobuf:"bytes,1,opt,name=user_name,json=userName,proto3" json:"user_name,omitempty"`
	UserId    int64                  `protobuf:"varint,2,opt,name=user_id,json=userId,proto3" json:"user_id,omitempty"`
	Email     string                 `protobuf:"bytes,3,opt,name=email,proto3" json:"email,omitempty"`
	LastLogin *timestamppb.Timestamp `protobuf:"bytes,4,opt,name=last_login,json=lastLogin,proto3" json:"last_login,omitempty"`
}

--- Mock of a generated user.pb.go file ---

func (*PatchError) ProtoMessage added in v0.0.17

func (*PatchError) ProtoMessage()

func (*PatchError) ProtoReflect added in v0.0.17

func (x *PatchError) ProtoReflect() protoreflect.Message

In a real generated file, ProtoReflect() would be fully implemented. For this example, we don't need it as the marshallers will use reflection.

func (*PatchError) Reset added in v0.0.17

func (x *PatchError) Reset()

func (*PatchError) String added in v0.0.17

func (x *PatchError) String() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL