コード例 #1
0
ファイル: config.go プロジェクト: GuoJing/hugo
func (c *Config) findConfigFile(configFileName string) (string, error) {

	if configFileName == "" { // config not specified, let's search
		if b, _ := helpers.Exists(c.GetAbsPath("config.json")); b {
			return c.GetAbsPath("config.json"), nil
		}

		if b, _ := helpers.Exists(c.GetAbsPath("config.toml")); b {
			return c.GetAbsPath("config.toml"), nil
		}

		if b, _ := helpers.Exists(c.GetAbsPath("config.yaml")); b {
			return c.GetAbsPath("config.yaml"), nil
		}

		return "", fmt.Errorf("config file not found in: %s", c.GetPath())

	} else {
		// If the full path is given, just use that
		if path.IsAbs(configFileName) {
			return configFileName, nil
		}

		// Else check the local directory
		t := c.GetAbsPath(configFileName)
		if b, _ := helpers.Exists(t); b {
			return t, nil
		} else {
			return "", fmt.Errorf("config file not found at: %s", t)
		}
	}
}
コード例 #2
0
ファイル: new.go プロジェクト: CODECOMMUNITY/hugo
func doNewSite(basepath string, force bool) error {
	dirs := []string{
		filepath.Join(basepath, "layouts"),
		filepath.Join(basepath, "content"),
		filepath.Join(basepath, "archetypes"),
		filepath.Join(basepath, "static"),
		filepath.Join(basepath, "data"),
		filepath.Join(basepath, "themes"),
	}

	if exists, _ := helpers.Exists(basepath, hugofs.Source()); exists {
		if isDir, _ := helpers.IsDir(basepath, hugofs.Source()); !isDir {
			return errors.New(basepath + " already exists but not a directory")
		}

		isEmpty, _ := helpers.IsEmpty(basepath, hugofs.Source())

		switch {
		case !isEmpty && !force:
			return errors.New(basepath + " already exists and is not empty")

		case !isEmpty && force:
			all := append(dirs, filepath.Join(basepath, "config."+configFormat))
			for _, path := range all {
				if exists, _ := helpers.Exists(path, hugofs.Source()); exists {
					return errors.New(path + " already exists")
				}
			}
		}
	}

	for _, dir := range dirs {
		hugofs.Source().MkdirAll(dir, 0777)
	}

	createConfig(basepath, configFormat)

	jww.FEEDBACK.Printf("Congratulations! Your new Hugo site is created in %q.\n\n", basepath)
	jww.FEEDBACK.Println(`Just a few more steps and you're ready to go:

1. Download a theme into the same-named folder. Choose a theme from https://themes.gohugo.io or
   create your own with the "hugo new theme <THEMENAME>" command
2. Perhaps you want to add some content. You can add single files with "hugo new <SECTIONNAME>/<FILENAME>.<FORMAT>"
3. Start the built-in live server via "hugo server"

For more information read the documentation at https://gohugo.io.`)

	return nil
}
コード例 #3
0
func loadJekyllConfig(jekyllRoot string) map[string]interface{} {
	fs := hugofs.Source()
	path := filepath.Join(jekyllRoot, "_config.yml")

	exists, err := helpers.Exists(path, fs)

	if err != nil || !exists {
		jww.WARN.Println("_config.yaml not found: Is the specified Jekyll root correct?")
		return nil
	}

	f, err := fs.Open(path)
	if err != nil {
		return nil
	}

	defer f.Close()

	b, err := ioutil.ReadAll(f)

	if err != nil {
		return nil
	}

	c, err := parser.HandleYAMLMetaData(b)

	if err != nil {
		return nil
	}

	return c.(map[string]interface{})
}
コード例 #4
0
ファイル: content.go プロジェクト: hugo-alves/hugo
func FindArchetype(kind string) (outpath string) {
	search := []string{helpers.AbsPathify(viper.GetString("archetypeDir"))}

	if viper.GetString("theme") != "" {
		themeDir := path.Join(helpers.AbsPathify("themes/"+viper.GetString("theme")), "/archetypes/")
		if _, err := os.Stat(themeDir); os.IsNotExist(err) {
			jww.ERROR.Println("Unable to find archetypes directory for theme :", viper.GetString("theme"), "in", themeDir)
		} else {
			search = append(search, themeDir)
		}
	}

	for _, x := range search {
		// If the new content isn't in a subdirectory, kind == "".
		// Therefore it should be excluded otherwise `is a directory`
		// error will occur. github.com/spf13/hugo/issues/411
		var pathsToCheck []string

		if kind == "" {
			pathsToCheck = []string{"default.md", "default"}
		} else {
			pathsToCheck = []string{kind + ".md", kind, "default.md", "default"}
		}
		for _, p := range pathsToCheck {
			curpath := path.Join(x, p)
			jww.DEBUG.Println("checking", curpath, "for archetypes")
			if exists, _ := helpers.Exists(curpath); exists {
				jww.INFO.Println("curpath: " + curpath)
				return curpath
			}
		}
	}

	return ""
}
コード例 #5
0
ファイル: new.go プロジェクト: n2xnot/hugo
// NewSite creates a new hugo site and initializes a structured Hugo directory.
func NewSite(cmd *cobra.Command, args []string) {
	if len(args) < 1 {
		cmd.Usage()
		jww.FATAL.Fatalln("path needs to be provided")
	}

	createpath, err := filepath.Abs(filepath.Clean(args[0]))
	if err != nil {
		cmd.Usage()
		jww.FATAL.Fatalln(err)
	}

	if x, _ := helpers.Exists(createpath, hugofs.SourceFs); x {
		y, _ := helpers.IsDir(createpath, hugofs.SourceFs)
		if z, _ := helpers.IsEmpty(createpath, hugofs.SourceFs); y && z {
			jww.INFO.Println(createpath, "already exists and is empty")
		} else {
			jww.FATAL.Fatalln(createpath, "already exists and is not empty")
		}
	}

	mkdir(createpath, "layouts")
	mkdir(createpath, "content")
	mkdir(createpath, "archetypes")
	mkdir(createpath, "static")
	mkdir(createpath, "data")

	createConfig(createpath, configFormat)
}
コード例 #6
0
func destinationExists(filename string) bool {
	b, err := helpers.Exists(filename, hugofs.Destination())
	if err != nil {
		panic(err)
	}
	return b
}
コード例 #7
0
ファイル: import.go プロジェクト: maruel/hugo
func loadJekyllConfig(jekyllRoot string) map[string]interface{} {
	fs := hugofs.SourceFs
	path := filepath.Join(jekyllRoot, "_config.yml")

	exists, err := helpers.Exists(path, fs)

	if err != nil || !exists {
		return nil
	}

	f, err := fs.Open(path)
	if err != nil {
		return nil
	}

	defer f.Close()

	b, err := ioutil.ReadAll(f)

	if err != nil {
		return nil
	}

	c, err := parser.HandleYAMLMetaData(b)

	if err != nil {
		return nil
	}

	return c.(map[string]interface{})
}
コード例 #8
0
ファイル: content.go プロジェクト: krupakapadia/hugo
func FindArchetype(kind string) (outpath string) {
	search := []string{helpers.AbsPathify(viper.GetString("archetypeDir"))}

	if viper.GetString("theme") != "" {
		themeDir := path.Join(helpers.AbsPathify("themes/"+viper.GetString("theme")), "/archetypes/")
		if _, err := os.Stat(themeDir); os.IsNotExist(err) {
			jww.ERROR.Println("Unable to find archetypes directory for theme :", viper.GetString("theme"), "in", themeDir)
		} else {
			search = append(search, themeDir)
		}
	}

	for _, x := range search {
		pathsToCheck := []string{kind + ".md", kind, "default.md", "default"}
		for _, p := range pathsToCheck {
			curpath := path.Join(x, p)
			jww.DEBUG.Println("checking", curpath, "for archetypes")
			if exists, _ := helpers.Exists(curpath); exists {
				return curpath
			}
		}
	}

	return ""
}
コード例 #9
0
ファイル: new.go プロジェクト: vinchu/hugo
func NewTheme(cmd *cobra.Command, args []string) {
	InitializeConfig()

	if len(args) < 1 {
		cmd.Usage()
		jww.FATAL.Fatalln("theme name needs to be provided")
	}

	createpath := helpers.AbsPathify(path.Join("themes", args[0]))
	jww.INFO.Println("creating theme at", createpath)

	if x, _ := helpers.Exists(createpath); x {
		jww.FATAL.Fatalln(createpath, "already exists")
	}

	mkdir(createpath, "layouts", "_default")
	mkdir(createpath, "layouts", "chrome")

	touchFile(createpath, "layouts", "index.html")
	touchFile(createpath, "layouts", "_default", "list.html")
	touchFile(createpath, "layouts", "_default", "single.html")

	touchFile(createpath, "layouts", "chrome", "header.html")
	touchFile(createpath, "layouts", "chrome", "footer.html")

	mkdir(createpath, "archetypes")
	touchFile(createpath, "archetypes", "default.md")

	mkdir(createpath, "static", "js")
	mkdir(createpath, "static", "css")

	by := []byte(`The MIT License (MIT)

Copyright (c) 2014 YOUR_NAME_HERE

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
`)

	err := helpers.WriteToDisk(path.Join(createpath, "LICENSE.md"), bytes.NewReader(by))
	if err != nil {
		jww.FATAL.Fatalln(err)
	}

	createThemeMD(createpath)
}
コード例 #10
0
// TODO: Consider calling doNewSite() instead?
func createSiteFromJekyll(jekyllRoot, targetDir string, force bool) error {
	fs := hugofs.Source()
	if exists, _ := helpers.Exists(targetDir, fs); exists {
		if isDir, _ := helpers.IsDir(targetDir, fs); !isDir {
			return errors.New("Target path \"" + targetDir + "\" already exists but not a directory")
		}

		isEmpty, _ := helpers.IsEmpty(targetDir, fs)

		if !isEmpty && !force {
			return errors.New("Target path \"" + targetDir + "\" already exists and is not empty")
		}
	}

	jekyllConfig := loadJekyllConfig(jekyllRoot)

	// Crude test to make sure at least one of _drafts/ and _posts/ exists
	// and is not empty.
	hasPostsOrDrafts := false
	postsDir := filepath.Join(jekyllRoot, "_posts")
	draftsDir := filepath.Join(jekyllRoot, "_drafts")
	for _, d := range []string{postsDir, draftsDir} {
		if exists, _ := helpers.Exists(d, fs); exists {
			if isDir, _ := helpers.IsDir(d, fs); isDir {
				if isEmpty, _ := helpers.IsEmpty(d, fs); !isEmpty {
					hasPostsOrDrafts = true
				}
			}
		}
	}
	if !hasPostsOrDrafts {
		return errors.New("Your Jekyll root contains neither posts nor drafts, aborting.")
	}

	mkdir(targetDir, "layouts")
	mkdir(targetDir, "content")
	mkdir(targetDir, "archetypes")
	mkdir(targetDir, "static")
	mkdir(targetDir, "data")
	mkdir(targetDir, "themes")

	createConfigFromJekyll(targetDir, "yaml", jekyllConfig)

	copyJekyllFilesAndFolders(jekyllRoot, filepath.Join(targetDir, "static"))

	return nil
}
コード例 #11
0
// resGetLocal loads the content of a local file
func resGetLocal(url string, fs afero.Fs) ([]byte, error) {
	filename := filepath.Join(viper.GetString("workingDir"), url)
	if e, err := helpers.Exists(filename, fs); !e {
		return nil, err
	}

	return afero.ReadFile(fs, filename)

}
コード例 #12
0
ファイル: new.go プロジェクト: digitalcraftsman/hugo
func doNewSite(basepath string, force bool) error {
	dirs := []string{
		filepath.Join(basepath, "layouts"),
		filepath.Join(basepath, "content"),
		filepath.Join(basepath, "archetypes"),
		filepath.Join(basepath, "static"),
		filepath.Join(basepath, "data"),
		filepath.Join(basepath, "themes"),
	}

	if exists, _ := helpers.Exists(basepath, hugofs.Source()); exists {
		if isDir, _ := helpers.IsDir(basepath, hugofs.Source()); !isDir {
			return errors.New(basepath + " already exists but not a directory")
		}

		isEmpty, _ := helpers.IsEmpty(basepath, hugofs.Source())

		switch {
		case !isEmpty && !force:
			return errors.New(basepath + " already exists and is not empty")

		case !isEmpty && force:
			all := append(dirs, filepath.Join(basepath, "config."+configFormat))
			for _, path := range all {
				if exists, _ := helpers.Exists(path, hugofs.Source()); exists {
					return errors.New(path + " already exists")
				}
			}
		}
	}

	for _, dir := range dirs {
		hugofs.Source().MkdirAll(dir, 0777)
	}

	createConfig(basepath, configFormat)

	jww.FEEDBACK.Printf("Congratulations! Your new Hugo site is created in %s.\n\n", basepath)
	jww.FEEDBACK.Println(nextStepsText())

	return nil
}
コード例 #13
0
// resGetLocal loads the content of a local file
func resGetLocal(url string, fs afero.Fs) ([]byte, error) {
	filename := filepath.Join(viper.GetString("WorkingDir"), url)
	if e, err := helpers.Exists(filename, fs); !e {
		return nil, err
	}

	f, err := fs.Open(filename)
	if err != nil {
		return nil, err
	}
	return ioutil.ReadAll(f)
}
コード例 #14
0
ファイル: hugo.go プロジェクト: nitoyon/hugo
// 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
}
コード例 #15
0
ファイル: new.go プロジェクト: bramp/hugo
func doNewSite(basepath string, force bool) error {
	dirs := []string{
		filepath.Join(basepath, "layouts"),
		filepath.Join(basepath, "content"),
		filepath.Join(basepath, "archetypes"),
		filepath.Join(basepath, "static"),
		filepath.Join(basepath, "data"),
		filepath.Join(basepath, "themes"),
	}

	if exists, _ := helpers.Exists(basepath, hugofs.SourceFs); exists {
		if isDir, _ := helpers.IsDir(basepath, hugofs.SourceFs); !isDir {
			return errors.New(basepath + " already exists but not a directory")
		}

		isEmpty, _ := helpers.IsEmpty(basepath, hugofs.SourceFs)

		switch {
		case !isEmpty && !force:
			return errors.New(basepath + " already exists and is not empty")

		case !isEmpty && force:
			all := append(dirs, filepath.Join(basepath, "config."+configFormat))
			for _, path := range all {
				if exists, _ := helpers.Exists(path, hugofs.SourceFs); exists {
					return errors.New(path + " already exists")
				}
			}
		}
	}

	for _, dir := range dirs {
		hugofs.SourceFs.MkdirAll(dir, 0777)
	}

	createConfig(basepath, configFormat)

	return nil
}
コード例 #16
0
// resGetCache returns the content for an ID from the file cache or an error
// if the file is not found returns nil,nil
func resGetCache(id string, fs afero.Fs, ignoreCache bool) ([]byte, error) {
	if ignoreCache {
		return nil, nil
	}
	fID := getCacheFileID(id)
	isExists, err := helpers.Exists(fID, fs)
	if err != nil {
		return nil, err
	}
	if !isExists {
		return nil, nil
	}

	return afero.ReadFile(fs, fID)

}
コード例 #17
0
// resGetLocal loads the content of a local file
func resGetLocal(url string, fs afero.Fs) ([]byte, error) {
	p := ""
	if viper.GetString("WorkingDir") != "" {
		p = viper.GetString("WorkingDir")
		if helpers.FilePathSeparator != p[len(p)-1:] {
			p = p + helpers.FilePathSeparator
		}
	}
	jFile := p + url
	if e, err := helpers.Exists(jFile, fs); !e {
		return nil, err
	}

	f, err := fs.Open(jFile)
	if err != nil {
		return nil, err
	}
	return ioutil.ReadAll(f)
}
コード例 #18
0
// resGetCache returns the content for an ID from the file cache or an error
// if the file is not found returns nil,nil
func resGetCache(id string, fs afero.Fs, ignoreCache bool) ([]byte, error) {
	if ignoreCache {
		return nil, nil
	}
	fID := getCacheFileID(id)
	isExists, err := helpers.Exists(fID, fs)
	if err != nil {
		return nil, err
	}
	if !isExists {
		return nil, nil
	}

	f, err := fs.Open(fID)
	if err != nil {
		return nil, err
	}

	return ioutil.ReadAll(f)
}
コード例 #19
0
ファイル: new.go プロジェクト: vinchu/hugo
func NewSite(cmd *cobra.Command, args []string) {
	if len(args) < 1 {
		cmd.Usage()
		jww.FATAL.Fatalln("path needs to be provided")
	}

	createpath, err := filepath.Abs(filepath.Clean(args[0]))
	if err != nil {
		cmd.Usage()
		jww.FATAL.Fatalln(err)
	}

	if x, _ := helpers.Exists(createpath); x {
		jww.FATAL.Fatalln(createpath, "already exists")
	}

	mkdir(createpath, "layouts")
	mkdir(createpath, "content")
	mkdir(createpath, "archetypes")
	mkdir(createpath, "static")

	createConfig(createpath, configFormat)
}
コード例 #20
0
ファイル: genman.go プロジェクト: revdave33/hugo
	Use:   "man",
	Short: "Generate man pages for the Hugo CLI",
	Long: `This command automatically generates up-to-date man pages of Hugo's
command-line interface.  By default, it creates the man page files
in the "man" directory under the current directory.`,

	Run: func(cmd *cobra.Command, args []string) {
		header := &cobra.GenManHeader{
			Section: "1",
			Manual:  "Hugo Manual",
			Source:  fmt.Sprintf("Hugo %s", helpers.HugoVersion()),
		}
		if !strings.HasSuffix(genmandir, helpers.FilePathSeparator) {
			genmandir += helpers.FilePathSeparator
		}
		if found, _ := helpers.Exists(genmandir, hugofs.OsFs); !found {
			jww.FEEDBACK.Println("Directory", genmandir, "does not exist, creating...")
			hugofs.OsFs.MkdirAll(genmandir, 0777)
		}
		cmd.Root().DisableAutoGenTag = true

		jww.FEEDBACK.Println("Generating Hugo man pages in", genmandir, "...")
		cmd.Root().GenManTree(header, genmandir)

		jww.FEEDBACK.Println("Done.")
	},
}

func init() {
	genmanCmd.PersistentFlags().StringVar(&genmandir, "dir", "man/", "the directory to write the man pages.")
}
コード例 #21
0
ファイル: gendoc.go プロジェクト: XCMer/hugo
var gendocCmd = &cobra.Command{
	Use:   "doc",
	Short: "Generate Markdown documentation for the Hugo CLI.",
	Long: `Generate Markdown documentation for the Hugo CLI.

This command is, mostly, used to create up-to-date documentation
of Hugo's command-line interface for http://gohugo.io/.

It creates one Markdown file per command with front matter suitable
for rendering in Hugo.`,

	RunE: func(cmd *cobra.Command, args []string) error {
		if !strings.HasSuffix(gendocdir, helpers.FilePathSeparator) {
			gendocdir += helpers.FilePathSeparator
		}
		if found, _ := helpers.Exists(gendocdir, hugofs.Os()); !found {
			jww.FEEDBACK.Println("Directory", gendocdir, "does not exist, creating...")
			hugofs.Os().MkdirAll(gendocdir, 0777)
		}
		now := time.Now().Format(time.RFC3339)
		prepender := func(filename string) string {
			name := filepath.Base(filename)
			base := strings.TrimSuffix(name, path.Ext(name))
			url := "/commands/" + strings.ToLower(base) + "/"
			return fmt.Sprintf(gendocFrontmatterTemplate, now, strings.Replace(base, "_", " ", -1), base, url)
		}

		linkHandler := func(name string) string {
			base := strings.TrimSuffix(name, path.Ext(name))
			return "/commands/" + strings.ToLower(base) + "/"
		}
コード例 #22
0
ファイル: template.go プロジェクト: mariuccio/hugo
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)
}
コード例 #23
0
ファイル: template.go プロジェクト: digitalcraftsman/hugo
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)
	}
}