pagr

A 'static site generator', built using dati.
Log | Files | Refs | Atom

config.go (1607B)


      1 package main
      2 
      3 import (
      4 	"notabug.org/gearsix/suti"
      5 	"os"
      6 	"path/filepath"
      7 )
      8 
      9 // Config is the data structure containing all key/values to be loaded
     10 // in pagr configuration files
     11 type Config struct {
     12 	Contents        string
     13 	Templates       string
     14 	Assets          []string
     15 	Output          string
     16 	DefaultTemplate string
     17 }
     18 
     19 // relPaths sets all filepath values in `cfg` relative to `dir`
     20 func (cfg *Config) relPaths(dir string) {
     21 	var paths = []string{cfg.Contents, cfg.Templates, cfg.Output}
     22 	paths = append(paths, cfg.Assets...)
     23 	for i, path := range paths {
     24 		if !filepath.IsAbs(path) {
     25 			paths[i] = filepath.Join(dir, path)
     26 		}
     27 	}
     28 	cfg.Contents = paths[0]
     29 	cfg.Templates = paths[1]
     30 	cfg.Output = paths[2]
     31 	cfg.Assets = paths[3:]
     32 	return
     33 }
     34 
     35 // NewConfig returns a Config with default values
     36 func NewConfig() Config {
     37 	return Config{
     38 		Contents:        "./content",
     39 		Templates:       "./templates",
     40 		Assets:          []string{"./assets"},
     41 		Output:          "./out",
     42 		DefaultTemplate: "default",
     43 	}
     44 }
     45 
     46 // NewConfigFromFile returns a Config with values read from the config file found at `fpath`.
     47 // If values from the file are missing, default values are used.
     48 // suti.LoadDataFile() is called to load the file (see notabug.org/gearsix/suti).
     49 // Any relative filepaths in the returned Config are set relative to the parent directory of `fpath`.
     50 func NewConfigFromFile(fpath string) (cfg Config, err error) {
     51 	cfg = NewConfig()
     52 
     53 	if _, err = os.Stat(fpath); err != nil {
     54 		return
     55 	}
     56 
     57 	if err = suti.LoadDataFilepath(fpath, &cfg); err != nil {
     58 		return
     59 	}
     60 
     61 	cfg.relPaths(filepath.Dir(fpath))
     62 	return
     63 }