Skip to content

Commit

Permalink
support tar.gz .gz compress file
Browse files Browse the repository at this point in the history
  • Loading branch information
yorukot committed Apr 28, 2024
1 parent fbb099b commit b9aed84
Show file tree
Hide file tree
Showing 5 changed files with 127 additions and 84 deletions.
89 changes: 73 additions & 16 deletions src/components/function.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package components

import (
"archive/tar"
"archive/zip"
"compress/gzip"
"encoding/json"
"fmt"
"io"
Expand Down Expand Up @@ -549,16 +551,6 @@ func unzip(src, dest string) error {
total: totalFiles,
done: 0,
}
if _, err := os.Stat(filepath.Join(dest, filepath.Base(src))); os.IsExist(err) {
p.state = failure
p.name = "󰛫 Directory already exist"
channel <- channelMessage{
messageId: id,
processNewState: p,
}
return nil
}
os.MkdirAll(dest, 0755)

// Closure to address file descriptors issue with all the deferred .Close() methods
extractAndWriteFile := func(f *zip.File) error {
Expand Down Expand Up @@ -640,6 +632,77 @@ func unzip(src, dest string) error {
return nil
}

func ungzip(input, output string) error {
var err error
input, err = filepath.Abs(input)
if err != nil {
return err
}
output, err = filepath.Abs(output)
if err != nil {
return err
}

inputFile, err := os.Open(input)
if err != nil {
return err
}
defer inputFile.Close()

gzReader, err := gzip.NewReader(inputFile)
if err != nil {
return err
}
defer gzReader.Close()

err = os.MkdirAll(output, 0755)
if err != nil {
return err
}

tarReader := tar.NewReader(gzReader)
for {
header, err := tarReader.Next()

if err == io.EOF {
break
}
if err != nil {
return err
}

targetPath := filepath.Join(output, header.Name)

fileInfo := header.FileInfo()
if fileInfo.IsDir() {
err = os.MkdirAll(targetPath, fileInfo.Mode())
if err != nil {
return err
}
continue
}

targetFile, err := os.Create(targetPath)
if err != nil {
return err
}

_, err = io.Copy(targetFile, tarReader)
if err != nil {
targetFile.Close()
return err
}

err = targetFile.Close()
if err != nil {
return err
}

}

return nil
}

func zipSource(source, target string) error {
id := shortuuid.New()
prog := progress.New()
Expand Down Expand Up @@ -669,7 +732,6 @@ func zipSource(source, target string) error {
return nil
}

// 1. Create a ZIP file and zip.Writer
f, err := os.Create(target)
if err != nil {
return err
Expand All @@ -679,7 +741,6 @@ func zipSource(source, target string) error {
writer := zip.NewWriter(f)
defer writer.Close()

// 2. Go through all the files of the source
err = filepath.Walk(source, func(path string, info os.FileInfo, err error) error {
p.name = "󰗄 " + filepath.Base(path)
if len(channel) < 5 {
Expand All @@ -693,16 +754,13 @@ func zipSource(source, target string) error {
return err
}

// 3. Create a local file header
header, err := zip.FileInfoHeader(info)
if err != nil {
return err
}

// set compression
header.Method = zip.Deflate

// 4. Set relative path of a file as the header name
header.Name, err = filepath.Rel(filepath.Dir(source), path)
if err != nil {
return err
Expand All @@ -711,7 +769,6 @@ func zipSource(source, target string) error {
header.Name += "/"
}

// 5. Create writer for the file header and save content of the file
headerWriter, err := writer.CreateHeader(header)
if err != nil {
return err
Expand Down
63 changes: 42 additions & 21 deletions src/components/global_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,12 +123,12 @@ func contollerProcessBarListDown(m model) model {
if len(m.processBarModel.processList) == 0 {
return m
}
if m.processBarModel.cursor < len(m.processBarModel.processList)-1 {
if m.processBarModel.cursor < len(m.processBarModel.processList)-1 {
m.processBarModel.cursor++
if m.processBarModel.cursor > m.processBarModel.render+2 {
m.processBarModel.render++
}
} else {
} else {
m.processBarModel.render = 0
m.processBarModel.cursor = 0
}
Expand Down Expand Up @@ -274,7 +274,9 @@ func pasteItem(m model) model {
if len(m.copyItems.items) == 0 {
return m
}

totalFiles := 0

for _, folderPath := range m.copyItems.items {
count, err := countFiles(folderPath)
if err != nil {
Expand All @@ -289,22 +291,17 @@ func pasteItem(m model) model {

newProcess := process{}

prefixIcon := "󰆏 "
if m.copyItems.cut {
newProcess = process{
name: "󰆐 " + filepath.Base(m.copyItems.items[0]),
progress: prog,
state: inOperation,
total: totalFiles,
done: 0,
}
} else {
newProcess = process{
name: "󰆏 " + filepath.Base(m.copyItems.items[0]),
progress: prog,
state: inOperation,
total: totalFiles,
done: 0,
}
prefixIcon = "󰆐 "
}

newProcess = process{
name: prefixIcon + filepath.Base(m.copyItems.items[0]),
progress: prog,
state: inOperation,
total: totalFiles,
done: 0,
}

m.processBarModel.process[id] = newProcess
Expand Down Expand Up @@ -350,7 +347,7 @@ func pasteItem(m model) model {
if m.copyItems.cut {
for _, item := range m.copyItems.items {
if runtime.GOOS == "darwin" {
err := moveElement(item, HomeDir + "/.Trash/" + filepath.Base(item))
err := moveElement(item, HomeDir+"/.Trash/"+filepath.Base(item))
if err != nil {
outPutLog("Delete single item function move file to trash can error", err)
}
Expand Down Expand Up @@ -476,8 +473,26 @@ func toggleDotFileController(m model) model {
}

func extractFile(m model) model {
var err error
panel := m.fileModel.filePanels[m.filePanelFocusIndex]
unzip(panel.element[panel.cursor].location, filepath.Dir(panel.element[panel.cursor].location))
ext := strings.ToLower(filepath.Ext(panel.element[panel.cursor].location))
outputDir := fileNameWithoutExtension(panel.element[panel.cursor].location)
outputDir, err = renameIfDuplicate(outputDir)

if err != nil {
outPutLog("Error extract file when craete new directory", err)
}

switch ext {
case ".zip":
os.MkdirAll(outputDir, 0755)
unzip(panel.element[panel.cursor].location, outputDir)
case ".tar", ".gz":
os.MkdirAll(outputDir, 0755)
ungzip(panel.element[panel.cursor].location, outputDir)
default:
return m
}
m.fileModel.filePanels[m.filePanelFocusIndex] = panel
return m
}
Expand All @@ -487,6 +502,12 @@ func compressFile(m model) model {
fileName := filepath.Base(panel.element[panel.cursor].location)

zipName := strings.TrimSuffix(fileName, filepath.Ext(fileName)) + ".zip"
zipName, err := renameIfDuplicate(zipName)

if err != nil {
outPutLog("Error compress file when rename dublicate", err)
}

zipSource(panel.element[panel.cursor].location, filepath.Join(filepath.Dir(panel.element[panel.cursor].location), zipName))
m.fileModel.filePanels[m.filePanelFocusIndex] = panel
return m
Expand All @@ -501,7 +522,7 @@ func openFileWithEditor(m model) tea.Cmd {
editor = "nano"
}
c := exec.Command(editor, panel.element[panel.cursor].location)

return tea.ExecProcess(c, func(err error) tea.Msg {
return editorFinishedMsg{err}
})
Expand All @@ -527,4 +548,4 @@ func openHelpMenu(m model) model {

m.helpMenu.open = true
return m
}
}
1 change: 1 addition & 0 deletions src/components/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ var forceReloadElement = false
var firstUse = false

var HomeDir = basedir.Home

var SuperFileMainDir = basedir.ConfigHome + "/superfile"
var SuperFileCacheDir = basedir.CacheHome + "/superfile"
var SuperFileDataDir = basedir.DataHome + "/superfile"
Expand Down
52 changes: 11 additions & 41 deletions src/components/string_function.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package components

import (
"strings"
"unicode/utf8"

"github.com/charmbracelet/lipgloss"
Expand Down Expand Up @@ -66,44 +67,13 @@ func clipboardPrettierName(name string, width int, isDir bool, isSelected bool)
}
}

// func placeOverlay(x, y int,background, placeModal string) string {
// lines := strings.Split(placeModal, "\n")
// lines = lines
// re := regexp.MustCompile(`\x1b\[[0-9;]*[mK]`)

// // 示例字符串
// str := "┏A我"

// // 使用 FindAllStringIndex 找出所有匹配的位置
// indexes := re.FindAllStringIndex(str, -1)
// outPutLog(str)
// // 檢查是否找到匹配
// if indexes != nil {
// for _, loc := range indexes {
// loc = mapCoords(str, loc)
// outPutLog(fmt.Sprintf("匹配的開始位置: %d, 結束位置: %d", loc[0], loc[1]))
// }
// } else {
// outPutLog("沒有找到匹配")
// }

// return ""
// }

// func mapCoords(s string, byteCoords []int) (graphemeCoords []int) {
// graphemeCoords = make([]int, 2)
// gr := uniseg.NewGraphemes(s)
// graphemeIndex := -1
// for gr.Next() {
// graphemeIndex++
// a, b := gr.Positions()
// if a == byteCoords[0] {
// graphemeCoords[0] = graphemeIndex
// }
// if b == byteCoords[1] {
// graphemeCoords[1] = graphemeIndex + 1
// break
// }
// }
// return
// }
func fileNameWithoutExtension(fileName string) string {
for {
pos := strings.LastIndexByte(fileName, '.')
if pos == -1 {
break
}
fileName = fileName[:pos]
}
return fileName
}
6 changes: 0 additions & 6 deletions src/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@ github.com/charmbracelet/x/exp/term v0.0.0-20240425164147-ba2a9512b05f h1:1BXkZq
github.com/charmbracelet/x/exp/term v0.0.0-20240425164147-ba2a9512b05f/go.mod h1:yQqGHmheaQfkqiJWjklPHVAq1dKbk8uGbcoS/lcKCJ0=
github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81 h1:q2hJAaP1k2wIvVRd/hEHD7lacgqrCPS+k8g1MndzfWY=
github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81/go.mod h1:YynlIjWYF8myEu6sdkwKIvGQq+cOckRm6So2avqoYAk=
github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w=
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/cpuguy83/go-md2man/v2 v2.0.4 h1:wfIWP927BUkWJb2NmU/kNDYIBTh/ziUX91+lVfRxZq4=
github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
Expand Down Expand Up @@ -76,12 +74,8 @@ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/urfave/cli/v2 v2.27.1 h1:8xSQ6szndafKVRmfyeUMxkNUJQMjL1F2zmsZ+qHpfho=
github.com/urfave/cli/v2 v2.27.1/go.mod h1:8qnjx1vcq5s2/wpsqoZFndg2CE5tNFyrTvS6SinrnYQ=
github.com/urfave/cli/v2 v2.27.2 h1:6e0H+AkS+zDckwPCUrZkKX38mRaau4nL2uipkJpbkcI=
github.com/urfave/cli/v2 v2.27.2/go.mod h1:g0+79LmHHATl7DAcHO99smiR/T7uGLw84w8Y42x+4eM=
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 h1:bAn7/zixMGCfxrRTfdpNzjtPYqr8smhKouy9mxVdGPU=
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673/go.mod h1:N3UwUGtsrSj3ccvlPHLoLsHnpR27oXr4ZE984MbSER8=
github.com/xrash/smetrics v0.0.0-20240312152122-5f08fbb34913 h1:+qGGcbkzsfDQNPPe9UDgpxAWQrhbbBXOYJFQDq/dtJw=
github.com/xrash/smetrics v0.0.0-20240312152122-5f08fbb34913/go.mod h1:4aEEwZQutDLsQv2Deui4iYQ6DWTxR14g6m8Wv88+Xqk=
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
Expand Down

0 comments on commit b9aed84

Please sign in to comment.