2022-11-26 20:45:32 +00:00
|
|
|
package file
|
|
|
|
|
|
|
|
import (
|
2022-12-06 21:45:50 +00:00
|
|
|
"io/fs"
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
"time"
|
|
|
|
|
2022-11-26 20:45:32 +00:00
|
|
|
"github.com/asaskevich/govalidator"
|
|
|
|
"github.com/juju/errors"
|
|
|
|
)
|
|
|
|
|
|
|
|
// ConfigStruct is the configuration for File Provider.
|
|
|
|
type ConfigStruct struct {
|
2022-12-06 21:45:50 +00:00
|
|
|
Filename string `yaml:"filename"`
|
|
|
|
Rotate bool `yaml:"rotate"`
|
|
|
|
RotateTime *string `yaml:"rotate_time"`
|
|
|
|
RotateMaxAge *string `yaml:"rotate_max_age"`
|
|
|
|
RotateMaxFile *int `yaml:"rotate_max_file"`
|
2022-11-26 20:45:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// IsValid will check that the File configuration is valid.
|
|
|
|
func (c *ConfigStruct) IsValid() error {
|
|
|
|
|
|
|
|
if c.Filename == "" {
|
|
|
|
return errors.NotValidf("Path is empty in File configuration")
|
|
|
|
} else if isValid, _ := govalidator.IsFilePath(c.Filename); !isValid {
|
|
|
|
return errors.NotValidf("Path is invalid in File configuration")
|
|
|
|
}
|
|
|
|
|
2022-12-06 21:45:50 +00:00
|
|
|
dir := filepath.Dir(c.Filename)
|
2022-11-26 20:45:32 +00:00
|
|
|
|
2022-12-06 21:45:50 +00:00
|
|
|
if _, err := os.Stat(dir); err != nil {
|
|
|
|
if errors.Is(err, fs.ErrPermission) {
|
|
|
|
return errors.NewForbidden(err, "Filename directory is not readeable in File configuration")
|
|
|
|
} else if errors.Is(err, fs.ErrNotExist) {
|
|
|
|
return errors.NewNotFound(err, "Filename directory does not exist in File configuration")
|
|
|
|
} else {
|
|
|
|
return errors.Trace(err)
|
|
|
|
}
|
2022-11-26 20:45:32 +00:00
|
|
|
}
|
|
|
|
|
2022-12-06 21:45:50 +00:00
|
|
|
if c.Rotate {
|
|
|
|
|
|
|
|
if c.RotateTime == nil || *c.RotateTime == "" {
|
|
|
|
return errors.NotValidf("rotate_time cannot be null or an empty string in File configuration")
|
|
|
|
} else if _, err := time.ParseDuration(*c.RotateTime); err != nil {
|
|
|
|
return errors.NewNotValid(err, "rotate_time contain an invalid duration in File configuration")
|
|
|
|
}
|
|
|
|
|
|
|
|
if c.RotateMaxFile != nil && *c.RotateMaxFile <= 0 {
|
|
|
|
return errors.NotValidf("rotate_max_file cannot be negative or 0 in File configuration")
|
|
|
|
}
|
|
|
|
|
|
|
|
if c.RotateMaxAge != nil && *c.RotateMaxAge == "" {
|
|
|
|
return errors.NotValidf("rotate_max_age cannot be an empty string in File configuration")
|
|
|
|
} else if c.RotateMaxAge != nil {
|
|
|
|
if _, err := time.ParseDuration(*c.RotateMaxAge); err != nil {
|
|
|
|
return errors.NewNotValid(err, "rotate_max_age contain an invalid duration in File configuration")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if c.RotateMaxFile != nil && c.RotateMaxAge != nil {
|
|
|
|
return errors.NotValidf("rotate_max_age and rotate_max_file cannot be defined at the same time in File configuration")
|
|
|
|
}
|
2022-11-26 20:45:32 +00:00
|
|
|
}
|
2022-12-06 21:45:50 +00:00
|
|
|
return nil
|
2022-11-26 20:45:32 +00:00
|
|
|
}
|