[lxc-devel] [lxd/master] Fix Defer
gsquire on Github
lxc-bot at linuxcontainers.org
Tue Oct 13 05:22:52 UTC 2020
A non-text attachment was scrubbed...
Name: not available
Type: text/x-mailbox
Size: 416 bytes
Desc: not available
URL: <http://lists.linuxcontainers.org/pipermail/lxc-devel/attachments/20201012/b44345c2/attachment.bin>
-------------- next part --------------
From 601d274f2d6fc935ac73d1e741c1ce2a570ab207 Mon Sep 17 00:00:00 2001
From: Garrett Squire <github at 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
More information about the lxc-devel
mailing list