1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-04 12:52:28 +08:00

feat: add IsZipFile

This commit is contained in:
dudaodong
2023-04-24 11:00:58 +08:00
parent aaf45012e4
commit 5e79eaa9dd
6 changed files with 95 additions and 3 deletions

View File

@@ -7,6 +7,7 @@ package fileutil
import (
"archive/zip"
"bufio"
"bytes"
"errors"
"fmt"
"io"
@@ -174,6 +175,23 @@ func ListFileNames(path string) ([]string, error) {
return result, nil
}
// IsZipFile checks if file is zip or not.
// Play: todo
func IsZipFile(filepath string) bool {
f, err := os.Open(filepath)
if err != nil {
return false
}
defer f.Close()
buf := make([]byte, 4)
if n, err := f.Read(buf); err != nil || n < 4 {
return false
}
return bytes.Equal(buf, []byte("PK\x03\x04"))
}
// Zip create zip file, fpath could be a single file or a directory.
// Play: https://go.dev/play/p/j-3sWBp8ik_P
func Zip(fpath string, destPath string) error {
@@ -276,6 +294,7 @@ func UnZip(zipFile string, destPath string) error {
}
}
}
return nil
}

View File

@@ -223,3 +223,15 @@ func ExampleUnZip() {
// Output:
// application/octet-stream
}
func ExampleIsZipFile() {
result1 := IsZipFile("./file.go")
result2 := IsZipFile("./test/file.go.zip")
fmt.Println(result1)
fmt.Println(result2)
// Output:
// false
// true
}

View File

@@ -246,3 +246,10 @@ func TestCurrentPath(t *testing.T) {
absPath := CurrentPath()
t.Log(absPath)
}
func TestIsZipFile(t *testing.T) {
assert := internal.NewAssert(t, "TestIsZipFile")
assert.Equal(false, IsZipFile("./file.go"))
assert.Equal(true, IsZipFile("./test/file.go.zip"))
}