Skip to content

Commit

Permalink
fix: handle errors returned by Close() in write paths (#1581)
Browse files Browse the repository at this point in the history
Signed-off-by: Xiaoxuan Wang <[email protected]>
  • Loading branch information
wangxiaoxuan273 authored Dec 11, 2024
1 parent 4b55afe commit 0844004
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 6 deletions.
8 changes: 6 additions & 2 deletions cmd/oras/internal/display/content/manifest_fetch.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,18 @@ type manifestFetch struct {
outputPath string
}

func (h *manifestFetch) OnContentFetched(desc ocispec.Descriptor, manifest []byte) error {
func (h *manifestFetch) OnContentFetched(desc ocispec.Descriptor, manifest []byte) (eventErr error) {
out := h.stdout
if h.outputPath != "-" && h.outputPath != "" {
f, err := os.Create(h.outputPath)
if err != nil {
return fmt.Errorf("failed to open %q: %w", h.outputPath, err)
}
defer f.Close()
defer func() {
if err := f.Close(); eventErr == nil {
eventErr = err
}
}()
out = f
}
return output.PrintJSON(out, manifest, h.pretty)
Expand Down
8 changes: 6 additions & 2 deletions cmd/oras/internal/display/content/manifest_index.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,18 @@ func NewManifestIndexCreateHandler(out io.Writer, pretty bool, outputPath string
}

// OnContentCreated is called after index content is created.
func (h *manifestIndexCreate) OnContentCreated(manifest []byte) error {
func (h *manifestIndexCreate) OnContentCreated(manifest []byte) (eventErr error) {
out := h.stdout
if h.outputPath != "" && h.outputPath != "-" {
f, err := os.Create(h.outputPath)
if err != nil {
return fmt.Errorf("failed to open %q: %w", h.outputPath, err)
}
defer f.Close()
defer func() {
if err := f.Close(); eventErr == nil {
eventErr = err
}
}()
out = f
}
return output.PrintJSON(out, manifest, h.pretty)
Expand Down
8 changes: 6 additions & 2 deletions cmd/oras/root/pull.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ Example - Pull artifact files from an OCI layout archive 'layout.tar':
return oerrors.Command(cmd, &opts.Target)
}

func runPull(cmd *cobra.Command, opts *pullOptions) error {
func runPull(cmd *cobra.Command, opts *pullOptions) (pullError error) {
ctx, logger := command.GetLogger(cmd, &opts.Common)
statusHandler, metadataHandler, err := display.NewPullHandler(opts.Printer, opts.Format, opts.Path, opts.TTY)
if err != nil {
Expand All @@ -148,7 +148,11 @@ func runPull(cmd *cobra.Command, opts *pullOptions) error {
if err != nil {
return err
}
defer dst.Close()
defer func() {
if err := dst.Close(); pullError == nil {
pullError = err
}
}()
dst.AllowPathTraversalOnWrite = opts.PathTraversal
dst.DisableOverwrite = opts.KeepOldFiles

Expand Down

0 comments on commit 0844004

Please sign in to comment.