|
| 1 | +package diagnostic |
| 2 | + |
| 3 | +import ( |
| 4 | + "archive/zip" |
| 5 | + "fmt" |
| 6 | + "io" |
| 7 | + "os" |
| 8 | + "path/filepath" |
| 9 | + "strings" |
| 10 | + "time" |
| 11 | +) |
| 12 | + |
| 13 | +// CreateDiagnosticZipFile create a zip file with the contents from the all |
| 14 | +// files paths. The files will be written in the root of the zip file. |
| 15 | +// In case of an error occurs after whilst writing to the zip file |
| 16 | +// this will be removed. |
| 17 | +func CreateDiagnosticZipFile(base string, paths []string) (zipFileName string, err error) { |
| 18 | + // Create a zip file with all files from paths added to the root |
| 19 | + suffix := time.Now().Format(time.RFC3339) |
| 20 | + zipFileName = base + "-" + suffix + ".zip" |
| 21 | + zipFileName = strings.ReplaceAll(zipFileName, ":", "-") |
| 22 | + |
| 23 | + archive, cerr := os.Create(zipFileName) |
| 24 | + if cerr != nil { |
| 25 | + return "", fmt.Errorf("error creating file %s: %w", zipFileName, cerr) |
| 26 | + } |
| 27 | + |
| 28 | + archiveWriter := zip.NewWriter(archive) |
| 29 | + |
| 30 | + defer func() { |
| 31 | + archiveWriter.Close() |
| 32 | + archive.Close() |
| 33 | + |
| 34 | + if err != nil { |
| 35 | + os.Remove(zipFileName) |
| 36 | + } |
| 37 | + }() |
| 38 | + |
| 39 | + for _, file := range paths { |
| 40 | + if file == "" { |
| 41 | + continue |
| 42 | + } |
| 43 | + |
| 44 | + var handle *os.File |
| 45 | + |
| 46 | + handle, err = os.Open(file) |
| 47 | + if err != nil { |
| 48 | + return "", fmt.Errorf("error opening file %s: %w", zipFileName, err) |
| 49 | + } |
| 50 | + |
| 51 | + defer handle.Close() |
| 52 | + |
| 53 | + // Keep the base only to not create sub directories in the |
| 54 | + // zip file. |
| 55 | + var writer io.Writer |
| 56 | + |
| 57 | + writer, err = archiveWriter.Create(filepath.Base(file)) |
| 58 | + if err != nil { |
| 59 | + return "", fmt.Errorf("error creating archive writer from %s: %w", file, err) |
| 60 | + } |
| 61 | + |
| 62 | + if _, err = io.Copy(writer, handle); err != nil { |
| 63 | + return "", fmt.Errorf("error copying file %s: %w", file, err) |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + zipFileName = archive.Name() |
| 68 | + return zipFileName, nil |
| 69 | +} |
0 commit comments