Skip to content

Commit

Permalink
Fix Resource output in multihost setups
Browse files Browse the repository at this point in the history
In Hugo 0.46 we made the output of what you get from resources.Get and similar static, i.e. language agnostic. This makes total sense, as it is wasteful and time-consuming to do SASS/SCSS/PostCSS processing for lots of languages when the output is lots of duplicates with different filenames.

But since we now output the result once only, this had a negative side effect for multihost setups: We publish the resource once only to the root folder (i.e. not to the language "domain folder").

This commit removes the language code from the processed image keys. This creates less duplication in the file cache, but it means that you should do a `hugo --gc` to clean up stale files.

Fixes #5058
  • Loading branch information
bep committed Aug 13, 2018
1 parent c09ee78 commit 78f8475
Show file tree
Hide file tree
Showing 12 changed files with 225 additions and 44 deletions.
53 changes: 53 additions & 0 deletions common/hugio/readers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// Copyright 2018 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package hugio

import (
"io"
"strings"
)

// ReadSeeker wraps io.Reader and io.Seeker.
type ReadSeeker interface {
io.Reader
io.Seeker
}

// ReadSeekCloser is implemented by afero.File. We use this as the common type for
// content in Resource objects, even for strings.
type ReadSeekCloser interface {
ReadSeeker
io.Closer
}

// ReadSeekerNoOpCloser implements ReadSeekCloser by doing nothing in Close.
type ReadSeekerNoOpCloser struct {
ReadSeeker
}

// Close does nothing.
func (r ReadSeekerNoOpCloser) Close() error {
return nil
}

// NewReadSeekerNoOpCloser creates a new ReadSeekerNoOpCloser with the given ReadSeeker.
func NewReadSeekerNoOpCloser(r ReadSeeker) ReadSeekerNoOpCloser {
return ReadSeekerNoOpCloser{r}
}

// NewReadSeekerNoOpCloserFromString uses strings.NewReader to create a new ReadSeekerNoOpCloser
// from the given string.
func NewReadSeekerNoOpCloserFromString(content string) ReadSeekerNoOpCloser {
return ReadSeekerNoOpCloser{strings.NewReader(content)}
}
43 changes: 43 additions & 0 deletions common/hugio/writers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// Copyright 2018 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package hugio

import (
"io"
)

type multiWriteCloser struct {
io.Writer
closers []io.WriteCloser
}

func (m multiWriteCloser) Close() error {
var err error
for _, c := range m.closers {
if closeErr := c.Close(); err != nil {
err = closeErr
}
}
return err
}

// NewMultiWriteCloser creates a new io.WriteCloser that duplicates its writes to all the
// provided writers.
func NewMultiWriteCloser(writeClosers ...io.WriteCloser) io.WriteCloser {
writers := make([]io.Writer, len(writeClosers))
for i, w := range writeClosers {
writers[i] = w
}
return multiWriteCloser{Writer: io.MultiWriter(writers...), closers: writeClosers}
}
19 changes: 19 additions & 0 deletions helpers/path.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"strings"
"unicode"

"github.com/gohugoio/hugo/common/hugio"
"github.com/spf13/afero"
"golang.org/x/text/transform"
"golang.org/x/text/unicode/norm"
Expand Down Expand Up @@ -515,6 +516,24 @@ func WriteToDisk(inpath string, r io.Reader, fs afero.Fs) (err error) {
return afero.WriteReader(fs, inpath, r)
}

// OpenFileForWriting opens all the given filenames for writing.
func OpenFilesForWriting(fs afero.Fs, filenames ...string) (io.WriteCloser, error) {
var writeClosers []io.WriteCloser
for _, filename := range filenames {
f, err := OpenFileForWriting(fs, filename)
if err != nil {
for _, wc := range writeClosers {
wc.Close()
}
return nil, err
}
writeClosers = append(writeClosers, f)
}

return hugio.NewMultiWriteCloser(writeClosers...), nil

}

// OpenFileForWriting opens or creates the given file. If the target directory
// does not exist, it gets created.
func OpenFileForWriting(fs afero.Fs, filename string) (afero.File, error) {
Expand Down
6 changes: 4 additions & 2 deletions hugolib/hugo_sites_multihost_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,10 @@ languageName = "Nynorsk"
s2h := s2.getPage(KindHome)
assert.Equal("https://example.fr/", s2h.Permalink())

b.AssertFileContent("public/fr/index.html", "French Home Page")
b.AssertFileContent("public/en/index.html", "Default Home Page")
b.AssertFileContent("public/fr/index.html", "French Home Page", "String Resource: /docs/text/pipes.txt")
b.AssertFileContent("public/fr/text/pipes.txt", "Hugo Pipes")
b.AssertFileContent("public/en/index.html", "Default Home Page", "String Resource: /docs/text/pipes.txt")
b.AssertFileContent("public/en/text/pipes.txt", "Hugo Pipes")

// Check paginators
b.AssertFileContent("public/en/page/1/index.html", `refresh" content="0; url=https://example.com/docs/"`)
Expand Down
2 changes: 1 addition & 1 deletion hugolib/page_bundler_handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,7 @@ func (c *contentHandlers) createResource() contentHandler {
SourceFile: ctx.source,
RelTargetFilename: ctx.target,
URLBase: c.s.GetURLLanguageBasePath(),
TargetPathBase: c.s.GetTargetLanguageBasePath(),
TargetBasePaths: []string{c.s.GetTargetLanguageBasePath()},
})

return handlerResult{err: err, handled: true, resource: resource}
Expand Down
20 changes: 17 additions & 3 deletions hugolib/paths/paths.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,10 @@ type Paths struct {

PublishDir string

// When in multihost mode, this returns a list of base paths below PublishDir
// for each language.
MultihostTargetBasePaths []string

DisablePathToLower bool
RemovePathAccents bool
UglyURLs bool
Expand Down Expand Up @@ -135,6 +139,15 @@ func New(fs *hugofs.Fs, cfg config.Provider) (*Paths, error) {
absResourcesDir = FilePathSeparator
}

multilingual := cfg.GetBool("multilingual")

var multihostTargetBasePaths []string
if multilingual {
for _, l := range languages {
multihostTargetBasePaths = append(multihostTargetBasePaths, l.Lang)
}
}

p := &Paths{
Fs: fs,
Cfg: cfg,
Expand All @@ -154,12 +167,13 @@ func New(fs *hugofs.Fs, cfg config.Provider) (*Paths, error) {

themes: config.GetStringSlicePreserveString(cfg, "theme"),

multilingual: cfg.GetBool("multilingual"),
multilingual: multilingual,
defaultContentLanguageInSubdir: cfg.GetBool("defaultContentLanguageInSubdir"),
DefaultContentLanguage: defaultContentLanguage,

Language: language,
Languages: languages,
Language: language,
Languages: languages,
MultihostTargetBasePaths: multihostTargetBasePaths,

PaginatePath: cfg.GetString("paginatePath"),
}
Expand Down
4 changes: 2 additions & 2 deletions hugolib/testhelpers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -403,8 +403,8 @@ date: "2018-02-28"
defaultTemplates = []string{
"_default/single.html", "Single: {{ .Title }}|{{ i18n \"hello\" }}|{{.Lang}}|{{ .Content }}",
"_default/list.html", "{{ $p := .Paginator }}List Page {{ $p.PageNumber }}: {{ .Title }}|{{ i18n \"hello\" }}|{{ .Permalink }}|Pager: {{ template \"_internal/pagination.html\" . }}",
"index.html", "{{ $p := .Paginator }}Default Home Page {{ $p.PageNumber }}: {{ .Title }}|{{ .IsHome }}|{{ i18n \"hello\" }}|{{ .Permalink }}|{{ .Site.Data.hugo.slogan }}",
"index.fr.html", "{{ $p := .Paginator }}French Home Page {{ $p.PageNumber }}: {{ .Title }}|{{ .IsHome }}|{{ i18n \"hello\" }}|{{ .Permalink }}|{{ .Site.Data.hugo.slogan }}",
"index.html", "{{ $p := .Paginator }}Default Home Page {{ $p.PageNumber }}: {{ .Title }}|{{ .IsHome }}|{{ i18n \"hello\" }}|{{ .Permalink }}|{{ .Site.Data.hugo.slogan }}|String Resource: {{ ( \"Hugo Pipes\" | resources.FromString \"text/pipes.txt\").RelPermalink }}",
"index.fr.html", "{{ $p := .Paginator }}French Home Page {{ $p.PageNumber }}: {{ .Title }}|{{ .IsHome }}|{{ i18n \"hello\" }}|{{ .Permalink }}|{{ .Site.Data.hugo.slogan }}|String Resource: {{ ( \"Hugo Pipes\" | resources.FromString \"text/pipes.txt\").RelPermalink }}",

// Shortcodes
"shortcodes/shortcode.html", "Shortcode: {{ i18n \"hello\" }}",
Expand Down
20 changes: 14 additions & 6 deletions resource/image.go
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ func (i *Image) doWithImageConfig(action, spec string, f func(src image.Image, c
ci.config = image.Config{Width: b.Max.X, Height: b.Max.Y}
ci.configLoaded = true

return ci, i.encodeToDestinations(converted, conf, resourceCacheFilename, ci.targetFilename())
return ci, i.encodeToDestinations(converted, conf, resourceCacheFilename, ci.targetFilenames()...)
})

}
Expand Down Expand Up @@ -447,13 +447,21 @@ func (i *Image) decodeSource() (image.Image, error) {
func (i *Image) copyToDestination(src string) error {
var res error
i.copyToDestinationInit.Do(func() {
target := i.targetFilename()
targetFilenames := i.targetFilenames()
var changedFilenames []string

// Fast path:
// This is a processed version of the original.
// If it exists on destination with the same filename and file size, it is
// the same file, so no need to transfer it again.
if fi, err := i.spec.BaseFs.PublishFs.Stat(target); err == nil && fi.Size() == i.osFileInfo.Size() {
for _, targetFilename := range targetFilenames {
if fi, err := i.spec.BaseFs.PublishFs.Stat(targetFilename); err == nil && fi.Size() == i.osFileInfo.Size() {
continue
}
changedFilenames = append(changedFilenames, targetFilename)
}

if len(changedFilenames) == 0 {
return
}

Expand All @@ -464,7 +472,7 @@ func (i *Image) copyToDestination(src string) error {
}
defer in.Close()

out, err := helpers.OpenFileForWriting(i.spec.BaseFs.PublishFs, target)
out, err := helpers.OpenFilesForWriting(i.spec.BaseFs.PublishFs, changedFilenames...)

if err != nil {
res = err
Expand All @@ -485,9 +493,9 @@ func (i *Image) copyToDestination(src string) error {
return nil
}

func (i *Image) encodeToDestinations(img image.Image, conf imageConfig, resourceCacheFilename, targetFilename string) error {
func (i *Image) encodeToDestinations(img image.Image, conf imageConfig, resourceCacheFilename string, targetFilenames ...string) error {

file1, err := helpers.OpenFileForWriting(i.spec.BaseFs.PublishFs, targetFilename)
file1, err := helpers.OpenFilesForWriting(i.spec.BaseFs.PublishFs, targetFilenames...)
if err != nil {
return err
}
Expand Down
2 changes: 1 addition & 1 deletion resource/image_cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ func (c *imageCache) getOrCreate(
parent *Image, conf imageConfig, create func(resourceCacheFilename string) (*Image, error)) (*Image, error) {

relTarget := parent.relTargetPathFromConfig(conf)
key := parent.relTargetPathForRel(relTarget.path(), false)
key := parent.relTargetPathForRel(relTarget.path(), false, false)

// First check the in-memory store, then the disk.
c.mu.RLock()
Expand Down
Loading

0 comments on commit 78f8475

Please sign in to comment.