From d5bc1eb525b6767393ccd9b3e9b7be6e96c06bd6 Mon Sep 17 00:00:00 2001 From: Eyal Delarea Date: Mon, 15 Apr 2024 12:05:13 +0300 Subject: [PATCH] Fix npm packed tarball files identification (#1171) --- artifactory/utils/npm/pack.go | 34 +++++++++++++++++++--- tests/testdata/npm-workspaces/package.json | 3 +- 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/artifactory/utils/npm/pack.go b/artifactory/utils/npm/pack.go index 9f9686709..24ff8e289 100644 --- a/artifactory/utils/npm/pack.go +++ b/artifactory/utils/npm/pack.go @@ -1,6 +1,8 @@ package npm import ( + "fmt" + "github.com/jfrog/jfrog-client-go/utils/io/fileutils" "strings" gofrogcmd "github.com/jfrog/gofrog/io" @@ -8,13 +10,17 @@ import ( "github.com/jfrog/jfrog-client-go/utils/errorutils" ) +const ( + npmPackedTarballSuffix = ".tgz" +) + func Pack(npmFlags []string, executablePath string) ([]string, error) { configListCmdConfig := createPackCmdConfig(executablePath, npmFlags) output, err := gofrogcmd.RunCmdOutput(configListCmdConfig) if err != nil { return []string{}, errorutils.CheckError(err) } - return getPackageFileNameFromOutput(output), nil + return getPackageFileNameFromOutput(output) } func createPackCmdConfig(executablePath string, splitFlags []string) *npmutils.NpmConfig { @@ -27,7 +33,27 @@ func createPackCmdConfig(executablePath string, splitFlags []string) *npmutils.N } } -func getPackageFileNameFromOutput(output string) []string { - output = strings.TrimSpace(output) - return strings.Split(output, "\n") +// Extracts packed file names from npm pack command output +// The output can differ when a prePack script exists, +// This function will filter the output and search for the .tgz files +// To avoid misidentifying files, we will verify file exists +func getPackageFileNameFromOutput(output string) (packedTgzFiles []string, err error) { + lines := strings.Split(output, "\n") + var packedFileNamesFromOutput []string + for _, line := range lines { + line = strings.TrimSpace(line) + if strings.HasSuffix(line, npmPackedTarballSuffix) { + packedFileNamesFromOutput = append(packedFileNamesFromOutput, line) + } + } + for _, file := range packedFileNamesFromOutput { + exists, err := fileutils.IsFileExists(file, true) + if err != nil { + return nil, fmt.Errorf("error occurred while checking packed npm tarball exists: %w", err) + } + if exists { + packedTgzFiles = append(packedTgzFiles, file) + } + } + return } diff --git a/tests/testdata/npm-workspaces/package.json b/tests/testdata/npm-workspaces/package.json index 59c936a79..ee7c9c0a6 100644 --- a/tests/testdata/npm-workspaces/package.json +++ b/tests/testdata/npm-workspaces/package.json @@ -4,7 +4,8 @@ "description": "", "main": "index.js", "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" + "test": "echo \"Error: no test specified\" && exit 1", + "prepack": "echo 'prepack script executed'" }, "keywords": [], "author": "",