fix(repo): report the error when creating a missing merge index fails

When the --merge target does not exist, an empty index is created and
written before merging. The error from that write was discarded, so an
unwritable merge target let the command report success while no index
was created there. Propagate the error, matching the final index write
and the LoadIndexFile error handling in the same function.

Signed-off-by: zjncs <18910855655@163.com>
pull/32623/head
zjncs 4 weeks ago
parent fa11636b01
commit 595dd6cffd

@ -101,7 +101,9 @@ func index(dir, url, mergeTo string, json bool) error {
var i2 *repo.IndexFile var i2 *repo.IndexFile
if _, err := os.Stat(mergeTo); errors.Is(err, fs.ErrNotExist) { if _, err := os.Stat(mergeTo); errors.Is(err, fs.ErrNotExist) {
i2 = repo.NewIndexFile() i2 = repo.NewIndexFile()
writeIndexFile(i2, mergeTo, json) if err := writeIndexFile(i2, mergeTo, json); err != nil {
return fmt.Errorf("merge failed: %w", err)
}
} else { } else {
i2, err = repo.LoadIndexFile(mergeTo) i2, err = repo.LoadIndexFile(mergeTo)
if err != nil { if err != nil {

@ -22,6 +22,7 @@ import (
"io" "io"
"os" "os"
"path/filepath" "path/filepath"
"runtime"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -141,3 +142,28 @@ func TestRepoIndexFileCompletion(t *testing.T) {
checkFileCompletion(t, "repo index", true) checkFileCompletion(t, "repo index", true)
checkFileCompletion(t, "repo index mydir", false) checkFileCompletion(t, "repo index mydir", false)
} }
func TestRepoIndexCmdMergeWriteError(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("directory permissions are not enforced on Windows")
}
if os.Geteuid() == 0 {
t.Skip("root bypasses directory permissions")
}
dir := t.TempDir()
require.NoError(t, linkOrCopy("testdata/testcharts/compressedchart-0.1.0.tgz", filepath.Join(dir, "compressedchart-0.1.0.tgz")))
// The merge target does not exist and its directory is read-only, so
// creating it must fail and the error must be reported.
roDir := filepath.Join(t.TempDir(), "ro")
require.NoError(t, os.Mkdir(roDir, 0o500))
mergeTo := filepath.Join(roDir, "index.yaml")
buf := bytes.NewBuffer(nil)
c := newRepoIndexCmd(buf)
require.NoError(t, c.ParseFlags([]string{"--merge", mergeTo}))
err := c.RunE(c, []string{dir})
require.Error(t, err, "expected an error when the missing merge target cannot be written")
}

Loading…
Cancel
Save