fix: Improve error handling and fix wrong compress dir for windows (#367) (#368)

* fix: Improve error handling and fix wrong compress dir for windows
* refactor: Refactor fileutil package for pass linter
This commit is contained in:
ᴍᴏᴏɴD4ʀᴋ 2024-07-17 22:32:29 +08:00 committed by GitHub
parent c9beee2662
commit 271e052481
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 112 additions and 34 deletions

View File

@ -62,7 +62,7 @@ func Execute() {
if compress { if compress {
if err = fileutil.CompressDir(outputDir); err != nil { if err = fileutil.CompressDir(outputDir); err != nil {
slog.Error("compress error: ", "err", err) slog.Error("compress error", "err", err)
} }
slog.Info("compress success") slog.Info("compress success")
} }

View File

@ -5,7 +5,6 @@ import (
"bytes" "bytes"
"fmt" "fmt"
"os" "os"
"path"
"path/filepath" "path/filepath"
"strings" "strings"
@ -94,40 +93,67 @@ func ParentBaseDir(p string) string {
func CompressDir(dir string) error { func CompressDir(dir string) error {
files, err := os.ReadDir(dir) files, err := os.ReadDir(dir)
if err != nil { if err != nil {
return err return fmt.Errorf("read dir error: %w", err)
} }
b := new(bytes.Buffer) if len(files) == 0 {
zw := zip.NewWriter(b) // Return an error if no files are found in the directory
for _, f := range files { return fmt.Errorf("no files to compress in: %s", dir)
fw, err := zw.Create(f.Name()) }
if err != nil {
return err buffer := new(bytes.Buffer)
} zipWriter := zip.NewWriter(buffer)
name := path.Join(dir, f.Name()) defer func() {
content, err := os.ReadFile(name) _ = zipWriter.Close()
if err != nil { }()
return err
} for _, file := range files {
_, err = fw.Write(content) if err := addFileToZip(zipWriter, filepath.Join(dir, file.Name())); err != nil {
if err != nil { return fmt.Errorf("failed to add file to zip: %w", err)
return err
}
err = os.Remove(name)
if err != nil {
return err
} }
} }
if err := zw.Close(); err != nil {
return err if err := zipWriter.Close(); err != nil {
return fmt.Errorf("error closing zip writer: %w", err)
} }
filename := filepath.Join(dir, fmt.Sprintf("%s.zip", dir))
outFile, err := os.Create(filepath.Clean(filename)) zipFilename := filepath.Join(dir, filepath.Base(dir)+".zip")
if err != nil { return writeFile(buffer, zipFilename)
return err }
}
_, err = b.WriteTo(outFile) func addFileToZip(zw *zip.Writer, filename string) error {
if err != nil { content, err := os.ReadFile(filename)
return err if err != nil {
} return fmt.Errorf("error reading file %s: %w", filename, err)
return outFile.Close() }
fw, err := zw.Create(filepath.Base(filename))
if err != nil {
return fmt.Errorf("error creating zip entry for %s: %w", filename, err)
}
if _, err = fw.Write(content); err != nil {
return fmt.Errorf("error writing content to zip for %s: %w", filename, err)
}
if err = os.Remove(filename); err != nil {
return fmt.Errorf("error removing original file %s: %w", filename, err)
}
return nil
}
func writeFile(buffer *bytes.Buffer, filename string) error {
outFile, err := os.Create(filename)
if err != nil {
return fmt.Errorf("error creating output file %s: %w", filename, err)
}
defer func() {
_ = outFile.Close()
}()
if _, err = buffer.WriteTo(outFile); err != nil {
return fmt.Errorf("error writing data to file %s: %w", filename, err)
}
return nil
} }

View File

@ -0,0 +1,52 @@
package fileutil
import (
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func setupTestDir(t *testing.T, files []string) string {
t.Helper() // Marks the function as a helper function.
tempDir, err := os.MkdirTemp("", "testCompressDir")
require.NoError(t, err, "failed to create a temporary directory")
for _, file := range files {
filePath := filepath.Join(tempDir, file)
err := os.WriteFile(filePath, []byte("test content"), 0o644)
require.NoError(t, err, "failed to create a test file")
}
return tempDir
}
func TestCompressDir(t *testing.T) {
t.Run("Normal Operation", func(t *testing.T) {
tempDir := setupTestDir(t, []string{"file1.txt", "file2.txt", "file3.txt"})
defer os.RemoveAll(tempDir)
err := CompressDir(tempDir)
assert.NoError(t, err, "compressDir should not return an error")
// Check if the zip file exists
zipFile := filepath.Join(tempDir, filepath.Base(tempDir)+".zip")
assert.FileExists(t, zipFile, "zip file should be created")
})
t.Run("Directory Does Not Exist", func(t *testing.T) {
err := CompressDir("/path/to/nonexistent/directory")
assert.Error(t, err, "should return an error for non-existent directory")
})
t.Run("Empty Directory", func(t *testing.T) {
tempDir, err := os.MkdirTemp("", "testEmptyDir")
require.NoError(t, err, "failed to create empty test directory")
defer os.RemoveAll(tempDir)
err = CompressDir(tempDir)
assert.Error(t, err, "should return an error for an empty directory")
})
}