shithub: hugo

Download patch

ref: 214afe4c1bb9c37bc6159e659d66ba9a268a2849
parent: cd830bb0275fc39240861627ef26e146985b5c86
author: Bjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
date: Mon Sep 14 13:09:34 EDT 2020

modules/npm: Preserve the original package.json if it exists

Fixes #7690

--- a/common/hugio/copy.go
+++ b/common/hugio/copy.go
@@ -26,28 +26,29 @@
 
 // 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
 }
 
--- a/hugolib/hugo_modules_test.go
+++ b/hugolib/hugo_modules_test.go
@@ -201,7 +201,7 @@
 		b, clean := newTestBuilder(t, "")
 		defer clean()
 
-		b.WithSourceFile("package.json", `{
+		const origPackageJSON = `{
 		"name": "mypack",
 		"version": "1.2.3",
         "scripts": {},
@@ -208,8 +208,10 @@
           "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)
 
@@ -244,6 +246,10 @@
  "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) {
@@ -281,7 +287,9 @@
  "name": "myhugosite",
  "version": "0.1.0"
 }`
+
 		})
+
 	})
 
 }
--- a/modules/npm/package_builder.go
+++ b/modules/npm/package_builder.go
@@ -18,6 +18,8 @@
 	"fmt"
 	"io"
 
+	"github.com/gohugoio/hugo/common/hugio"
+
 	"github.com/gohugoio/hugo/hugofs/files"
 
 	"github.com/pkg/errors"
@@ -51,7 +53,12 @@
 	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.