2023-02-15 19:30:05 +01:00
|
|
|
package io
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2023-03-05 15:00:53 +01:00
|
|
|
"log"
|
2023-02-15 19:30:05 +01:00
|
|
|
"os"
|
|
|
|
|
|
|
|
"gitlab.com/urkob/go-cert-gen/pkg/io"
|
|
|
|
)
|
|
|
|
|
|
|
|
type writer struct {
|
|
|
|
dirPath string
|
|
|
|
}
|
|
|
|
|
2023-03-05 00:05:00 +01:00
|
|
|
// WriteFile writes file into `w writer` directory.
|
|
|
|
// Returns outputPath and error
|
2023-02-15 19:30:05 +01:00
|
|
|
func (w writer) WriteFile(filename string, data []byte) (string, error) {
|
2023-03-05 00:05:00 +01:00
|
|
|
if filename == "" {
|
|
|
|
return "", fmt.Errorf("filename cannot be empty")
|
|
|
|
}
|
2023-02-15 19:30:05 +01:00
|
|
|
if w.dirPath == "" {
|
|
|
|
return "", fmt.Errorf("export directory cannot be empty")
|
|
|
|
}
|
|
|
|
if err := os.MkdirAll(w.dirPath, 0o755); err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
2023-03-05 15:00:53 +01:00
|
|
|
|
|
|
|
log.Println("to write file")
|
2023-02-15 19:30:05 +01:00
|
|
|
outputPath := w.dirPath + "/" + filename
|
|
|
|
if err := os.WriteFile(outputPath, data, 0o600); err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
2023-03-05 15:00:53 +01:00
|
|
|
log.Println("file written")
|
2023-02-15 19:30:05 +01:00
|
|
|
return outputPath, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewWriter(dirPath string) io.WriterIface {
|
2023-03-05 00:05:00 +01:00
|
|
|
return newWriter(dirPath)
|
|
|
|
}
|
|
|
|
|
|
|
|
func newWriter(dirPath string) *writer {
|
2023-02-15 19:30:05 +01:00
|
|
|
return &writer{
|
|
|
|
dirPath: dirPath,
|
|
|
|
}
|
|
|
|
}
|