@@ -135,21 +135,25 @@ func PullAndExtractChartFile(chartRef, version, fileInChart string) (string, fun
135135 if err != nil {
136136 return "" , nil , err
137137 }
138+ success := false
138139 cleanup := func () { os .RemoveAll (tmpDir ) }
140+ defer func () {
141+ if ! success {
142+ cleanup ()
143+ }
144+ }()
139145
140146 // Pull the chart
141147 pullArgs := []string {"pull" , chartRef , "--version" , version , "--destination" , tmpDir }
142148 cmd := exec .Command ("helm" , pullArgs ... )
143149 if out , err := cmd .CombinedOutput (); err != nil {
144- cleanup ()
145150 return "" , nil , fmt .Errorf ("failed to pull chart: %v\n %s" , err , string (out ))
146151 }
147152
148153 // Find the .tgz file
149154 var tgzPath string
150155 dirEntries , err := os .ReadDir (tmpDir )
151156 if err != nil {
152- cleanup ()
153157 return "" , nil , err
154158 }
155159 for _ , entry := range dirEntries {
@@ -159,20 +163,17 @@ func PullAndExtractChartFile(chartRef, version, fileInChart string) (string, fun
159163 }
160164 }
161165 if tgzPath == "" {
162- cleanup ()
163166 return "" , nil , fmt .Errorf ("no chart archive found after helm pull" )
164167 }
165168
166169 // Extract the requested file
167170 tgzFile , err := os .Open (tgzPath )
168171 if err != nil {
169- cleanup ()
170172 return "" , nil , err
171173 }
172174 defer tgzFile .Close ()
173175 gzReader , err := gzip .NewReader (tgzFile )
174176 if err != nil {
175- cleanup ()
176177 return "" , nil , err
177178 }
178179 tarReader := tar .NewReader (gzReader )
@@ -184,29 +185,25 @@ func PullAndExtractChartFile(chartRef, version, fileInChart string) (string, fun
184185 break
185186 }
186187 if err != nil {
187- cleanup ()
188188 return "" , nil , err
189189 }
190190 // Chart files are inside a top-level dir, e.g. united/values-prod.yaml
191191 if filepath .Base (hdr .Name ) == fileInChart {
192192 extractedPath = filepath .Join (tmpDir , fileInChart )
193193 outFile , err := os .Create (extractedPath )
194194 if err != nil {
195- cleanup ()
196195 return "" , nil , err
197196 }
197+ defer outFile .Close ()
198198 if _ , err := io .Copy (outFile , tarReader ); err != nil {
199- outFile .Close ()
200- cleanup ()
201199 return "" , nil , err
202200 }
203- outFile .Close ()
204201 break
205202 }
206203 }
207204 if extractedPath == "" {
208- cleanup ()
209205 return "" , nil , fmt .Errorf ("file %s not found in chart" , fileInChart )
210206 }
207+ success = true
211208 return extractedPath , cleanup , nil
212209}
0 commit comments