// isThemeVsHugoVersionMismatch returns whether the current Hugo version is // less than the theme's min_version. func isThemeVsHugoVersionMismatch() (mismatch bool, requiredMinVersion string) { if !helpers.ThemeSet() { return } themeDir := helpers.GetThemeDir() fs := hugofs.SourceFs path := filepath.Join(themeDir, "theme.toml") exists, err := helpers.Exists(path, fs) if err != nil || !exists { return } f, err := fs.Open(path) if err != nil { return } defer f.Close() b, err := ioutil.ReadAll(f) if err != nil { return } c, err := parser.HandleTOMLMetaData(b) if err != nil { return } config := c.(map[string]interface{}) if minVersion, ok := config["min_version"]; ok { switch minVersion.(type) { case float32: return helpers.HugoVersionNumber < minVersion.(float32), fmt.Sprint(minVersion) case float64: return helpers.HugoVersionNumber < minVersion.(float64), fmt.Sprint(minVersion) default: return } } return }
// InitializeConfig initializes a config file with sensible default configuration flags. // A Hugo command that calls initCoreCommonFlags() can pass itself // as an argument to have its command-line flags processed here. func InitializeConfig(subCmdVs ...*cobra.Command) error { viper.SetConfigFile(cfgFile) // See https://github.com/spf13/viper/issues/73#issuecomment-126970794 if source == "" { viper.AddConfigPath(".") } else { viper.AddConfigPath(source) } err := viper.ReadInConfig() if err != nil { if _, ok := err.(viper.ConfigParseError); ok { return newSystemError(err) } else { return newSystemErrorF("Unable to locate Config file. Perhaps you need to create a new site.\n Run `hugo help new` for details. (%s)\n", err) } } viper.RegisterAlias("indexes", "taxonomies") LoadDefaultSettings() for _, cmdV := range append([]*cobra.Command{hugoCmdV}, subCmdVs...) { if flagChanged(cmdV.PersistentFlags(), "verbose") { viper.Set("Verbose", verbose) } if flagChanged(cmdV.PersistentFlags(), "logFile") { viper.Set("LogFile", logFile) } if flagChanged(cmdV.Flags(), "cleanDestinationDir") { viper.Set("cleanDestinationDir", cleanDestination) } if flagChanged(cmdV.Flags(), "buildDrafts") { viper.Set("BuildDrafts", draft) } if flagChanged(cmdV.Flags(), "buildFuture") { viper.Set("BuildFuture", future) } if flagChanged(cmdV.Flags(), "uglyURLs") { viper.Set("UglyURLs", uglyURLs) } if flagChanged(cmdV.Flags(), "canonifyURLs") { viper.Set("CanonifyURLs", canonifyURLs) } if flagChanged(cmdV.Flags(), "disableRSS") { viper.Set("DisableRSS", disableRSS) } if flagChanged(cmdV.Flags(), "disableSitemap") { viper.Set("DisableSitemap", disableSitemap) } if flagChanged(cmdV.Flags(), "disableRobotsTXT") { viper.Set("DisableRobotsTXT", disableRobotsTXT) } if flagChanged(cmdV.Flags(), "pluralizeListTitles") { viper.Set("PluralizeListTitles", pluralizeListTitles) } if flagChanged(cmdV.Flags(), "preserveTaxonomyNames") { viper.Set("PreserveTaxonomyNames", preserveTaxonomyNames) } if flagChanged(cmdV.Flags(), "ignoreCache") { viper.Set("IgnoreCache", ignoreCache) } if flagChanged(cmdV.Flags(), "forceSyncStatic") { viper.Set("ForceSyncStatic", forceSync) } if flagChanged(cmdV.Flags(), "noTimes") { viper.Set("NoTimes", noTimes) } } if baseURL != "" { if !strings.HasSuffix(baseURL, "/") { baseURL = baseURL + "/" } viper.Set("BaseURL", baseURL) } if !viper.GetBool("RelativeURLs") && viper.GetString("BaseURL") == "" { jww.ERROR.Println("No 'baseurl' set in configuration or as a flag. Features like page menus will not work without one.") } if theme != "" { viper.Set("theme", theme) } if destination != "" { viper.Set("PublishDir", destination) } if source != "" { dir, _ := filepath.Abs(source) viper.Set("WorkingDir", dir) } else { dir, _ := os.Getwd() viper.Set("WorkingDir", dir) } if contentDir != "" { viper.Set("ContentDir", contentDir) } if layoutDir != "" { viper.Set("LayoutDir", layoutDir) } if cacheDir != "" { if helpers.FilePathSeparator != cacheDir[len(cacheDir)-1:] { cacheDir = cacheDir + helpers.FilePathSeparator } isDir, err := helpers.DirExists(cacheDir, hugofs.SourceFs) utils.CheckErr(err) if isDir == false { mkdir(cacheDir) } viper.Set("CacheDir", cacheDir) } else { viper.Set("CacheDir", helpers.GetTempDir("hugo_cache", hugofs.SourceFs)) } if verboseLog || logging || (viper.IsSet("LogFile") && viper.GetString("LogFile") != "") { if viper.IsSet("LogFile") && viper.GetString("LogFile") != "" { jww.SetLogFile(viper.GetString("LogFile")) } else { jww.UseTempLogFile("hugo") } } else { jww.DiscardLogging() } if viper.GetBool("verbose") { jww.SetStdoutThreshold(jww.LevelInfo) } if verboseLog { jww.SetLogThreshold(jww.LevelInfo) } jww.INFO.Println("Using config file:", viper.ConfigFileUsed()) themeDir := helpers.GetThemeDir() if themeDir != "" { if _, err := os.Stat(themeDir); os.IsNotExist(err) { return newSystemError("Unable to find theme Directory:", themeDir) } } themeVersionMismatch, minVersion := isThemeVsHugoVersionMismatch() if themeVersionMismatch { jww.ERROR.Printf("Current theme does not support Hugo version %s. Minimum version required is %s\n", helpers.HugoReleaseVersion(), minVersion) } return nil }
// InitializeConfig initializes a config file with sensible default configuration flags. func InitializeConfig() { viper.SetConfigFile(CfgFile) viper.AddConfigPath(Source) err := viper.ReadInConfig() if err != nil { jww.ERROR.Println("Unable to locate Config file. Perhaps you need to create a new site. Run `hugo help new` for details") } viper.RegisterAlias("indexes", "taxonomies") LoadDefaultSettings() if hugoCmdV.PersistentFlags().Lookup("buildDrafts").Changed { viper.Set("BuildDrafts", Draft) } if hugoCmdV.PersistentFlags().Lookup("buildFuture").Changed { viper.Set("BuildFuture", Future) } if hugoCmdV.PersistentFlags().Lookup("uglyUrls").Changed { viper.Set("UglyURLs", UglyURLs) } if hugoCmdV.PersistentFlags().Lookup("disableRSS").Changed { viper.Set("DisableRSS", DisableRSS) } if hugoCmdV.PersistentFlags().Lookup("disableSitemap").Changed { viper.Set("DisableSitemap", DisableSitemap) } if hugoCmdV.PersistentFlags().Lookup("verbose").Changed { viper.Set("Verbose", Verbose) } if hugoCmdV.PersistentFlags().Lookup("pluralizeListTitles").Changed { viper.Set("PluralizeListTitles", PluralizeListTitles) } if hugoCmdV.PersistentFlags().Lookup("preserveTaxonomyNames").Changed { viper.Set("PreserveTaxonomyNames", PreserveTaxonomyNames) } if hugoCmdV.PersistentFlags().Lookup("editor").Changed { viper.Set("NewContentEditor", Editor) } if hugoCmdV.PersistentFlags().Lookup("logFile").Changed { viper.Set("LogFile", LogFile) } if BaseURL != "" { if !strings.HasSuffix(BaseURL, "/") { BaseURL = BaseURL + "/" } viper.Set("BaseURL", BaseURL) } if !viper.GetBool("RelativeURLs") && viper.GetString("BaseURL") == "" { jww.ERROR.Println("No 'baseurl' set in configuration or as a flag. Features like page menus will not work without one.") } if Theme != "" { viper.Set("theme", Theme) } if Destination != "" { viper.Set("PublishDir", Destination) } if Source != "" { viper.Set("WorkingDir", Source) } else { dir, _ := os.Getwd() viper.Set("WorkingDir", dir) } if hugoCmdV.PersistentFlags().Lookup("ignoreCache").Changed { viper.Set("IgnoreCache", IgnoreCache) } if CacheDir != "" { if helpers.FilePathSeparator != CacheDir[len(CacheDir)-1:] { CacheDir = CacheDir + helpers.FilePathSeparator } isDir, err := helpers.DirExists(CacheDir, hugofs.SourceFs) utils.CheckErr(err) if isDir == false { mkdir(CacheDir) } viper.Set("CacheDir", CacheDir) } else { viper.Set("CacheDir", helpers.GetTempDir("hugo_cache", hugofs.SourceFs)) } if VerboseLog || Logging || (viper.IsSet("LogFile") && viper.GetString("LogFile") != "") { if viper.IsSet("LogFile") && viper.GetString("LogFile") != "" { jww.SetLogFile(viper.GetString("LogFile")) } else { jww.UseTempLogFile("hugo") } } else { jww.DiscardLogging() } if viper.GetBool("verbose") { jww.SetStdoutThreshold(jww.LevelInfo) } if VerboseLog { jww.SetLogThreshold(jww.LevelInfo) } jww.INFO.Println("Using config file:", viper.ConfigFileUsed()) themeDir := helpers.GetThemeDir() if themeDir != "" { if _, err := os.Stat(themeDir); os.IsNotExist(err) { jww.FATAL.Fatalln("Unable to find theme Directory:", themeDir) } } themeVersionMismatch, minVersion := helpers.IsThemeVsHugoVersionMismatch() if themeVersionMismatch { jww.ERROR.Printf("Current theme does not support Hugo version %s. Minimum version required is %s\n", helpers.HugoReleaseVersion(), minVersion) } }
// InitializeConfig initializes a config file with sensible default configuration flags. func InitializeConfig(subCmdVs ...*cobra.Command) error { if err := hugolib.LoadGlobalConfig(source, cfgFile); err != nil { return err } for _, cmdV := range append([]*cobra.Command{hugoCmdV}, subCmdVs...) { if flagChanged(cmdV.PersistentFlags(), "verbose") { viper.Set("verbose", verbose) } if flagChanged(cmdV.PersistentFlags(), "logFile") { viper.Set("logFile", logFile) } if flagChanged(cmdV.Flags(), "cleanDestinationDir") { viper.Set("cleanDestinationDir", cleanDestination) } if flagChanged(cmdV.Flags(), "buildDrafts") { viper.Set("buildDrafts", draft) } if flagChanged(cmdV.Flags(), "buildFuture") { viper.Set("buildFuture", future) } if flagChanged(cmdV.Flags(), "buildExpired") { viper.Set("buildExpired", expired) } if flagChanged(cmdV.Flags(), "uglyURLs") { viper.Set("uglyURLs", uglyURLs) } if flagChanged(cmdV.Flags(), "canonifyURLs") { viper.Set("canonifyURLs", canonifyURLs) } if flagChanged(cmdV.Flags(), "disable404") { viper.Set("disable404", disable404) } if flagChanged(cmdV.Flags(), "disableRSS") { viper.Set("disableRSS", disableRSS) } if flagChanged(cmdV.Flags(), "disableSitemap") { viper.Set("disableSitemap", disableSitemap) } if flagChanged(cmdV.Flags(), "enableRobotsTXT") { viper.Set("enableRobotsTXT", enableRobotsTXT) } if flagChanged(cmdV.Flags(), "pluralizeListTitles") { viper.Set("pluralizeListTitles", pluralizeListTitles) } if flagChanged(cmdV.Flags(), "preserveTaxonomyNames") { viper.Set("preserveTaxonomyNames", preserveTaxonomyNames) } if flagChanged(cmdV.Flags(), "ignoreCache") { viper.Set("ignoreCache", ignoreCache) } if flagChanged(cmdV.Flags(), "forceSyncStatic") { viper.Set("forceSyncStatic", forceSync) } if flagChanged(cmdV.Flags(), "noTimes") { viper.Set("noTimes", noTimes) } } if baseURL != "" { if !strings.HasSuffix(baseURL, "/") { baseURL = baseURL + "/" } viper.Set("baseURL", baseURL) } if !viper.GetBool("relativeURLs") && viper.GetString("baseURL") == "" { jww.ERROR.Println("No 'baseurl' set in configuration or as a flag. Features like page menus will not work without one.") } if theme != "" { viper.Set("theme", theme) } if destination != "" { viper.Set("publishDir", destination) } var dir string if source != "" { dir, _ = filepath.Abs(source) } else { dir, _ = os.Getwd() } viper.Set("workingDir", dir) if contentDir != "" { viper.Set("contentDir", contentDir) } if layoutDir != "" { viper.Set("layoutDir", layoutDir) } if cacheDir != "" { viper.Set("cacheDir", cacheDir) } cacheDir = viper.GetString("cacheDir") if cacheDir != "" { if helpers.FilePathSeparator != cacheDir[len(cacheDir)-1:] { cacheDir = cacheDir + helpers.FilePathSeparator } isDir, err := helpers.DirExists(cacheDir, hugofs.Source()) utils.CheckErr(err) if isDir == false { mkdir(cacheDir) } viper.Set("cacheDir", cacheDir) } else { viper.Set("cacheDir", helpers.GetTempDir("hugo_cache", hugofs.Source())) } if verboseLog || logging || (viper.IsSet("logFile") && viper.GetString("logFile") != "") { if viper.IsSet("logFile") && viper.GetString("logFile") != "" { jww.SetLogFile(viper.GetString("logFile")) } else { jww.UseTempLogFile("hugo") } } else { jww.DiscardLogging() } 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. hugofs.InitDefaultFs() themeDir := helpers.GetThemeDir() if themeDir != "" { if _, err := hugofs.Source().Stat(themeDir); os.IsNotExist(err) { return newSystemError("Unable to find theme Directory:", themeDir) } } themeVersionMismatch, minVersion := isThemeVsHugoVersionMismatch() if themeVersionMismatch { jww.ERROR.Printf("Current theme does not support Hugo version %s. Minimum version required is %s\n", helpers.HugoReleaseVersion(), minVersion) } return nil }
func (t *GoHTMLTemplate) loadTemplates(absPath string, prefix string) { jww.DEBUG.Printf("Load templates from path %q prefix %q", absPath, prefix) walker := func(path string, fi os.FileInfo, err error) error { if err != nil { return nil } jww.DEBUG.Println("Template path", path) if fi.Mode()&os.ModeSymlink == os.ModeSymlink { link, err := filepath.EvalSymlinks(absPath) if err != nil { jww.ERROR.Printf("Cannot read symbolic link '%s', error was: %s", absPath, err) return nil } linkfi, err := hugofs.Source().Stat(link) if err != nil { jww.ERROR.Printf("Cannot stat '%s', error was: %s", link, err) return nil } if !linkfi.Mode().IsRegular() { jww.ERROR.Printf("Symbolic links for directories not supported, skipping '%s'", absPath) } return nil } if !fi.IsDir() { if isDotFile(path) || isBackupFile(path) || isBaseTemplate(path) { return nil } tplName := t.GenerateTemplateNameFrom(absPath, path) if prefix != "" { tplName = strings.Trim(prefix, "/") + "/" + tplName } var baseTemplatePath string // Ace and Go templates may have both a base and inner template. pathDir := filepath.Dir(path) if filepath.Ext(path) != ".amber" && !strings.HasSuffix(pathDir, "partials") && !strings.HasSuffix(pathDir, "shortcodes") { innerMarkers := goTemplateInnerMarkers baseFileName := fmt.Sprintf("%s.html", baseFileBase) if filepath.Ext(path) == ".ace" { innerMarkers = aceTemplateInnerMarkers baseFileName = fmt.Sprintf("%s.ace", baseFileBase) } // This may be a view that shouldn't have base template // Have to look inside it to make sure needsBase, err := helpers.FileContainsAny(path, innerMarkers, hugofs.Source()) if err != nil { return err } if needsBase { // Look for base template in the follwing order: // 1. <current-path>/<template-name>-baseof.<suffix>, e.g. list-baseof.<suffix>. // 2. <current-path>/baseof.<suffix> // 3. _default/<template-name>-baseof.<suffix>, e.g. list-baseof.<suffix>. // 4. _default/baseof.<suffix> // 5. <themedir>/layouts/_default/<template-name>-baseof.<suffix> // 6. <themedir>/layouts/_default/baseof.<suffix> currBaseFilename := fmt.Sprintf("%s-%s", helpers.Filename(path), baseFileName) templateDir := filepath.Dir(path) themeDir := helpers.GetThemeDir() pathsToCheck := []string{ filepath.Join(templateDir, currBaseFilename), filepath.Join(templateDir, baseFileName), filepath.Join(absPath, "_default", currBaseFilename), filepath.Join(absPath, "_default", baseFileName), filepath.Join(themeDir, "layouts", "_default", currBaseFilename), filepath.Join(themeDir, "layouts", "_default", baseFileName), } for _, pathToCheck := range pathsToCheck { if ok, err := helpers.Exists(pathToCheck, hugofs.Source()); err == nil && ok { baseTemplatePath = pathToCheck break } } } } if err := t.AddTemplateFile(tplName, baseTemplatePath, path); err != nil { jww.ERROR.Printf("Failed to add template %s: %s", tplName, err) } } return nil } if err := helpers.SymbolicWalk(hugofs.Source(), absPath, walker); err != nil { jww.ERROR.Printf("Failed to load templates: %s", err) } }
func (t *GoHTMLTemplate) loadTemplates(absPath string, prefix string) { walker := func(path string, fi os.FileInfo, err error) error { if err != nil { return nil } if fi.Mode()&os.ModeSymlink == os.ModeSymlink { link, err := filepath.EvalSymlinks(absPath) if err != nil { jww.ERROR.Printf("Cannot read symbolic link '%s', error was: %s", absPath, err) return nil } linkfi, err := os.Stat(link) if err != nil { jww.ERROR.Printf("Cannot stat '%s', error was: %s", link, err) return nil } if !linkfi.Mode().IsRegular() { jww.ERROR.Printf("Symbolic links for directories not supported, skipping '%s'", absPath) } return nil } if !fi.IsDir() { if isDotFile(path) || isBackupFile(path) || isBaseTemplate(path) { return nil } tplName := t.GenerateTemplateNameFrom(absPath, path) if prefix != "" { tplName = strings.Trim(prefix, "/") + "/" + tplName } var baseTemplatePath string // ACE templates may have both a base and inner template. if filepath.Ext(path) == ".ace" && !strings.HasSuffix(filepath.Dir(path), "partials") { // This may be a view that shouldn't have base template // Have to look inside it to make sure needsBase, err := helpers.FileContains(path, aceTemplateInnerMarker, hugofs.OsFs) if err != nil { return err } if needsBase { // Look for base template in the follwing order: // 1. <current-path>/<template-name>-baseof.ace, e.g. list-baseof.ace. // 2. <current-path>/baseof.ace // 3. _default/<template-name>-baseof.ace, e.g. list-baseof.ace. // 4. _default/baseof.ace // 5. <themedir>/layouts/_default/<template-name>-baseof.ace // 6. <themedir>/layouts/_default/baseof.ace currBaseAceFilename := fmt.Sprintf("%s-%s", helpers.Filename(path), baseAceFilename) templateDir := filepath.Dir(path) themeDir := helpers.GetThemeDir() pathsToCheck := []string{ filepath.Join(templateDir, currBaseAceFilename), filepath.Join(templateDir, baseAceFilename), filepath.Join(absPath, "_default", currBaseAceFilename), filepath.Join(absPath, "_default", baseAceFilename), filepath.Join(themeDir, "layouts", "_default", currBaseAceFilename), filepath.Join(themeDir, "layouts", "_default", baseAceFilename), } for _, pathToCheck := range pathsToCheck { if ok, err := helpers.Exists(pathToCheck, hugofs.OsFs); err == nil && ok { baseTemplatePath = pathToCheck break } } } } t.AddTemplateFile(tplName, baseTemplatePath, path) } return nil } filepath.Walk(absPath, walker) }