Skip to content

Commit

Permalink
all: Refactor to non-global logger
Browse files Browse the repository at this point in the history
  • Loading branch information
bep committed Jan 6, 2017
1 parent 3d058a9 commit 363df2c
Show file tree
Hide file tree
Showing 12 changed files with 165 additions and 95 deletions.
67 changes: 36 additions & 31 deletions commands/hugo.go
Original file line number Diff line number Diff line change
Expand Up @@ -333,37 +333,6 @@ func InitializeConfig(subCmdVs ...*cobra.Command) error {
viper.Set("cacheDir", helpers.GetTempDir("hugo_cache", hugofs.Source()))
}

logFile := ioutil.Discard

if verboseLog || logging || (viper.IsSet("logFile") && viper.GetString("logFile") != "") {

var err error
if viper.IsSet("logFile") && viper.GetString("logFile") != "" {
path := viper.GetString("logFile")
logFile, err = os.OpenFile(path, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)
if err != nil {
return newSystemError("Failed to open log file:", path, err)
}
} else {
logFile, err = ioutil.TempFile(os.TempDir(), "hugo")
if err != nil {
return newSystemError(err)
}
}
}

jww.SetLogOutput(logFile)

if quiet {
jww.SetStdoutThreshold(jww.LevelError)
} else if viper.GetBool("verbose") {
jww.SetStdoutThreshold(jww.LevelInfo)
}

if verboseLog {
jww.SetLogThreshold(jww.LevelInfo)
}

jww.INFO.Println("Using config file:", viper.ConfigFileUsed())

// Init file systems. This may be changed at a later point.
Expand All @@ -387,6 +356,42 @@ func InitializeConfig(subCmdVs ...*cobra.Command) error {

}

func createLogger() *jww.NotePad {
var (
logHandle = ioutil.Discard
outHandle = os.Stdout
stdoutThreshold = jww.LevelError
logThreshold = jww.LevelWarn
)

if verboseLog || logging || (viper.IsSet("logFile") && viper.GetString("logFile") != "") {

var err error
if viper.IsSet("logFile") && viper.GetString("logFile") != "" {
path := viper.GetString("logFile")
logHandle, err = os.OpenFile(path, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)
if err != nil {
return newSystemError("Failed to open log file:", path, err)
}
} else {
logHandle, err = ioutil.TempFile(os.TempDir(), "hugo")
if err != nil {
return newSystemError(err)
}
}
}

} else if !quiet && viper.GetBool("verbose") {
stdoutThreshold = jww.LevelInfo
}

if verboseLog {
logThreshold = jww.LevelInfo
}

return jww.NewNotepad(stdoutThreshold, logThreshold, outHandle, logHandle, "", log.Ldate|log.Ltime)
}

func initializeFlags(cmd *cobra.Command) {
persFlagKeys := []string{"verbose", "logFile"}
flagKeys := []string{
Expand Down
4 changes: 2 additions & 2 deletions hugolib/case_insensitive_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ Site Colors: {{ .Site.Params.COLOR }}|{{ .Site.Params.COLORS.YELLOW }}
t.Fatalf("Failed to load config: %s", err)
}

sites, err := NewHugoSitesFromConfiguration()
sites, err := NewHugoSitesFromConfiguration(DepsCfg{})

if err != nil {
t.Fatalf("Failed to create sites: %s", err)
Expand Down Expand Up @@ -267,7 +267,7 @@ p
t.Fatalf("Failed to load config: %s", err)
}

sites, err := NewHugoSitesFromConfiguration()
sites, err := NewHugoSitesFromConfiguration(DepsCfg{})

if err != nil {
t.Fatalf("Failed to create sites: %s", err)
Expand Down
61 changes: 54 additions & 7 deletions hugolib/hugo_sites.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ package hugolib

import (
"fmt"
"io/ioutil"
"log"
"os"
"strings"
"sync"

Expand All @@ -35,32 +38,64 @@ type HugoSites struct {
runMode runmode

multilingual *Multilingual

*deps
}

// deps holds dependencies used by many.
// TODO(bep) globals a better name.
// There will be normally be only one instance of deps in play
// at a given time.
type deps struct {
// The logger to use.
log *jww.Notepad

// TODO(bep) next in line: Viper, hugofs, template
}

func newDeps(cfg DepsCfg) *deps {
logger := cfg.Logger

if logger == nil {
// TODO(bep) globals default log level
//logger = jww.NewNotepad(jww.LevelError, jww.LevelWarn, os.Stdout, ioutil.Discard, "", log.Ldate|log.Ltime)
logger = jww.NewNotepad(jww.LevelFatal, jww.LevelFatal, os.Stdout, ioutil.Discard, "", log.Ldate|log.Ltime)
}

return &deps{
log: logger,
}
}

// NewHugoSites creates a new collection of sites given the input sites, building
// a language configuration based on those.
func newHugoSites(sites ...*Site) (*HugoSites, error) {
func newHugoSites(cfg DepsCfg, sites ...*Site) (*HugoSites, error) {
langConfig, err := newMultiLingualFromSites(sites...)

if err != nil {
return nil, err
}

h := &HugoSites{multilingual: langConfig, Sites: sites}
h := &HugoSites{
deps: newDeps(cfg),
multilingual: langConfig,
Sites: sites}

for _, s := range sites {
s.owner = h
s.deps = h.deps
}
return h, nil
}

// NewHugoSitesFromConfiguration creates HugoSites from the global Viper config.
func NewHugoSitesFromConfiguration() (*HugoSites, error) {
// TODO(bep) globals rename this when all the globals are gone.
func NewHugoSitesFromConfiguration(cfg DepsCfg) (*HugoSites, error) {
sites, err := createSitesFromConfig()
if err != nil {
return nil, err
}
return newHugoSites(sites...)
return newHugoSites(cfg, sites...)
}

func createSitesFromConfig() ([]*Site, error) {
Expand Down Expand Up @@ -150,6 +185,15 @@ type BuildCfg struct {
whatChanged *whatChanged
}

// DepsCfg contains configuration options that can be used to configure Hugo
// on a global level, i.e. logging etc.
// Nil values will be given default values.
type DepsCfg struct {

// The Logger to use.
Logger *jww.Notepad
}

func (h *HugoSites) renderCrossSitesArtifacts() error {

if !h.multilingual.enabled() {
Expand Down Expand Up @@ -498,7 +542,7 @@ func doBuildSite(s *Site, render bool, additionalTemplates ...string) error {
if s.PageCollections == nil {
s.PageCollections = newPageCollections()
}
sites, err := newHugoSites(s)
sites, err := newHugoSites(DepsCfg{}, s)
if err != nil {
return err
}
Expand All @@ -522,12 +566,15 @@ func newHugoSitesFromSourceAndLanguages(input []source.ByteSource, languages hel
if len(languages) == 0 {
panic("Must provide at least one language")
}

cfg := DepsCfg{}

first := &Site{
Source: &source.InMemorySource{ByteSource: input},
Language: languages[0],
}
if len(languages) == 1 {
return newHugoSites(first)
return newHugoSites(cfg, first)
}

sites := make([]*Site, len(languages))
Expand All @@ -536,7 +583,7 @@ func newHugoSitesFromSourceAndLanguages(input []source.ByteSource, languages hel
sites[i] = &Site{Language: languages[i]}
}

return newHugoSites(sites...)
return newHugoSites(cfg, sites...)

}

Expand Down
3 changes: 1 addition & 2 deletions hugolib/hugo_sites_build.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import (

"github.com/fsnotify/fsnotify"
"github.com/spf13/hugo/helpers"
jww "github.com/spf13/jwalterweatherman"
)

// Build builds all sites. If filesystem events are provided,
Expand Down Expand Up @@ -60,7 +59,7 @@ func (h *HugoSites) Build(config BuildCfg, events ...fsnotify.Event) error {
}

if config.PrintStats {
jww.FEEDBACK.Printf("total in %v ms\n", int(1000*time.Since(t0).Seconds()))
h.log.FEEDBACK.Printf("total in %v ms\n", int(1000*time.Since(t0).Seconds()))
}

return nil
Expand Down
4 changes: 2 additions & 2 deletions hugolib/hugo_sites_build_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ weight = 2
// Add some data
writeSource(t, "data/hugo.toml", "slogan = \"Hugo Rocks!\"")

sites, err := NewHugoSitesFromConfiguration()
sites, err := NewHugoSitesFromConfiguration(DepsCfg{})

if err != nil {
t.Fatalf("Failed to create sites: %s", err)
Expand Down Expand Up @@ -1227,7 +1227,7 @@ lag:
// Add some data
writeSource(t, "data/hugo.toml", "slogan = \"Hugo Rocks!\"")

sites, err := NewHugoSitesFromConfiguration()
sites, err := NewHugoSitesFromConfiguration(DepsCfg{})

if err != nil {
t.Fatalf("Failed to create sites: %s", err)
Expand Down
1 change: 1 addition & 0 deletions hugolib/menu_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -689,6 +689,7 @@ func createTestSite(pageSources []source.ByteSource) *Site {
hugofs.InitMemFs()

return &Site{
deps: newDeps(DepsCfg{}),
Source: &source.InMemorySource{ByteSource: pageSources},
Language: helpers.NewDefaultLanguage(),
}
Expand Down
2 changes: 1 addition & 1 deletion hugolib/node_as_page_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,7 @@ title = "Deutsche Hugo"
t.Fatalf("Failed to load config: %s", err)
}

sites, err := NewHugoSitesFromConfiguration()
sites, err := NewHugoSitesFromConfiguration(DepsCfg{})

if err != nil {
t.Fatalf("Failed to create sites: %s", err)
Expand Down
2 changes: 1 addition & 1 deletion hugolib/shortcode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -578,7 +578,7 @@ tags:

}

sites, err := newHugoSites(s)
sites, err := newHugoSites(DepsCfg{}, s)

if err != nil {
t.Fatalf("Failed to build site: %s", err)
Expand Down
Loading

0 comments on commit 363df2c

Please sign in to comment.