The following pull request was submitted through Github. It can be accessed and reviewed at: https://github.com/lxc/lxd/pull/8025
This e-mail was sent by the LXC bot, direct replies will not reach the author unless they happen to be subscribed to this list. === Description (from pull-request) === This patch fixes a call to defer inside of a loop and instead uses an anonymous function to ensure proper behavior.
From 601d274f2d6fc935ac73d1e741c1ce2a570ab207 Mon Sep 17 00:00:00 2001 From: Garrett Squire <git...@garrettsquire.com> Date: Mon, 12 Oct 2020 22:21:36 -0700 Subject: [PATCH] Fix defer in for loop This patch fixes a call to defer inside of a loop and instead uses an anonymous function to ensure proper behavior. --- lxd-agent/templates.go | 70 ++++++++++++++++++++++-------------------- 1 file changed, 36 insertions(+), 34 deletions(-) diff --git a/lxd-agent/templates.go b/lxd-agent/templates.go index 8a2833d892..2ce6a6a252 100644 --- a/lxd-agent/templates.go +++ b/lxd-agent/templates.go @@ -35,51 +35,53 @@ func templatesApply(path string) ([]string, error) { // Go through the files and copy them into place. files := []string{} for tplPath, tpl := range metadata.Templates { - filePath := filepath.Join(path, fmt.Sprintf("%s.out", tpl.Template)) + func() { + filePath := filepath.Join(path, fmt.Sprintf("%s.out", tpl.Template)) - if !shared.PathExists(filePath) { - continue - } - - var w *os.File - if shared.PathExists(tplPath) { - if tpl.CreateOnly { + if !shared.PathExists(filePath) { continue } - // Open the existing file. - w, err = os.Create(tplPath) - if err != nil { - return nil, errors.Wrap(err, "Failed to create template file") + var w *os.File + if shared.PathExists(tplPath) { + if tpl.CreateOnly { + continue + } + + // Open the existing file. + w, err = os.Create(tplPath) + if err != nil { + return nil, errors.Wrap(err, "Failed to create template file") + } + } else { + // Create the directories leading to the file. + os.MkdirAll(filepath.Dir(tplPath), 0755) + + // Create the file itself. + w, err = os.Create(tplPath) + if err != nil { + return nil, err + } + + // Fix mode. + w.Chmod(0644) } - } else { - // Create the directories leading to the file. - os.MkdirAll(filepath.Dir(tplPath), 0755) + defer w.Close() - // Create the file itself. - w, err = os.Create(tplPath) + // Do the copy. + src, err := os.Open(filePath) if err != nil { return nil, err } + defer src.Close() - // Fix mode. - w.Chmod(0644) - } - defer w.Close() - - // Do the copy. - src, err := os.Open(filePath) - if err != nil { - return nil, err - } - defer src.Close() - - _, err = io.Copy(w, src) - if err != nil { - return nil, err - } + _, err = io.Copy(w, src) + if err != nil { + return nil, err + } - files = append(files, tplPath) + files = append(files, tplPath) + }() } return files, nil
_______________________________________________ lxc-devel mailing list lxc-devel@lists.linuxcontainers.org http://lists.linuxcontainers.org/listinfo/lxc-devel