Fix temporary directory cleanup for init repository downloading (#760)

## Changes
This PR fixes a bug where the temp directory created to download the
template would not be cleaned up.

## Tests
Tested manually. The exact process is described in a comment below.
This commit is contained in:
shreyas-goenka 2023-09-11 12:22:05 +02:00 committed by GitHub
parent a4e94e1b36
commit ad84abf415
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 7 additions and 8 deletions

View File

@ -74,22 +74,21 @@ func newInitCommand() *cobra.Command {
return template.Materialize(ctx, configFile, templatePath, outputDir) return template.Materialize(ctx, configFile, templatePath, outputDir)
} }
// Download the template in a temporary directory // Create a temporary directory with the name of the repository. The '*'
tmpDir := os.TempDir() // character is replaced by a random string in the generated temporary directory.
templateURL := templatePath repoDir, err := os.MkdirTemp("", repoName(templatePath)+"-*")
repoDir := filepath.Join(tmpDir, repoName(templateURL))
err := os.MkdirAll(repoDir, 0755)
if err != nil { if err != nil {
return err return err
} }
// TODO: Add automated test that the downloaded git repo is cleaned up. // TODO: Add automated test that the downloaded git repo is cleaned up.
err = git.Clone(ctx, templateURL, "", repoDir) // Clone the repository in the temporary directory
err = git.Clone(ctx, templatePath, "", repoDir)
if err != nil { if err != nil {
return err return err
} }
defer os.RemoveAll(templateDir) // Clean up downloaded repository once the template is materialized.
defer os.RemoveAll(repoDir)
return template.Materialize(ctx, configFile, filepath.Join(repoDir, templateDir), outputDir) return template.Materialize(ctx, configFile, filepath.Join(repoDir, templateDir), outputDir)
} }
return cmd return cmd
} }