Skip to content

Commit

Permalink
modules/npm: Preserve the original package.json if it exists
Browse files Browse the repository at this point in the history
Fixes #7690
  • Loading branch information
bep committed Sep 14, 2020
1 parent cd830bb commit 214afe4
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 13 deletions.
21 changes: 11 additions & 10 deletions common/hugio/copy.go
Expand Up @@ -26,28 +26,29 @@ import (

// CopyFile copies a file.
func CopyFile(fs afero.Fs, from, to string) error {
sf, err := os.Open(from)
sf, err := fs.Open(from)
if err != nil {
return err
}
defer sf.Close()
df, err := os.Create(to)
df, err := fs.Create(to)
if err != nil {
return err
}
defer df.Close()
_, err = io.Copy(df, sf)
if err == nil {
si, err := os.Stat(from)
if err != nil {
err = os.Chmod(to, si.Mode())
if err != nil {
return err
}
si, err := fs.Stat(from)
if err != nil {
err = fs.Chmod(to, si.Mode())

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

}

return nil
}

Expand Down
12 changes: 10 additions & 2 deletions hugolib/hugo_modules_test.go
Expand Up @@ -201,14 +201,16 @@ JS imported in module: |
b, clean := newTestBuilder(t, "")
defer clean()

b.WithSourceFile("package.json", `{
const origPackageJSON = `{
"name": "mypack",
"version": "1.2.3",
"scripts": {},
"dependencies": {
"moo": "1.2.3"
}
}`)
}`

b.WithSourceFile("package.json", origPackageJSON)

b.Build(BuildCfg{})
b.Assert(npm.Pack(b.H.BaseFs.SourceFs, b.H.BaseFs.Assets.Dirs), qt.IsNil)
Expand Down Expand Up @@ -244,6 +246,10 @@ JS imported in module: |
"version": "1.2.3"
}`
})

// https://github.com/gohugoio/hugo/issues/7690
b.AssertFileContent("package.hugo.json", origPackageJSON)

})

t.Run("Create package.json, no default, no package.json", func(t *testing.T) {
Expand Down Expand Up @@ -281,7 +287,9 @@ JS imported in module: |
"name": "myhugosite",
"version": "0.1.0"
}`

})

})

}
Expand Down
9 changes: 8 additions & 1 deletion modules/npm/package_builder.go
Expand Up @@ -18,6 +18,8 @@ import (
"fmt"
"io"

"github.com/gohugoio/hugo/common/hugio"

"github.com/gohugoio/hugo/hugofs/files"

"github.com/pkg/errors"
Expand Down Expand Up @@ -51,7 +53,12 @@ func Pack(fs afero.Fs, fis []hugofs.FileMetaInfo) error {
if err != nil {
// Have a package.json?
fi, err = fs.Stat(packageJSONName)
if err != nil {
if err == nil {
// Preserve the original in package.hugo.json.
if err = hugio.CopyFile(fs, packageJSONName, files.FilenamePackageHugoJSON); err != nil {
return errors.Wrap(err, "npm pack: failed to copy package file")
}
} else {
// Create one.
name := "project"
// Use the Hugo site's folder name as the default name.
Expand Down

0 comments on commit 214afe4

Please sign in to comment.