You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Victorique/vtqe/attach.go

79 lines
2.0 KiB
Go

4 years ago
package main
import (
4 years ago
"io"
"os"
4 years ago
"b612.me/starlog"
"github.com/spf13/cobra"
)
var attachcmd = &cobra.Command{
Use: "attach",
4 years ago
Short: "合并多个文件",
Long: "合并多个文件",
4 years ago
Run: func(this *cobra.Command, args []string) {
4 years ago
src, _ := this.Flags().GetStringArray("src")
out, _ := this.Flags().GetString("out")
if len(src) < 2 || out == "" {
starlog.Criticalln("请输入至少2个输入路径一个输出路径")
os.Exit(1)
4 years ago
}
4 years ago
os.Exit(runAttach(src, out))
},
}
func runAttach(src []string, out string) int {
fpOut, err := os.Create(out)
if err != nil {
starlog.Errorln("Err:无法创建输出文件!", err)
return 2
}
defer fpOut.Close()
for _, file := range src {
fpFile, err := os.OpenFile(file, os.O_RDONLY, 0644)
if err != nil {
starlog.Errorln("Err:Cannot Openfile:", err)
return 3
4 years ago
}
4 years ago
stats, err := fpFile.Stat()
4 years ago
if err != nil {
4 years ago
starlog.Errorln("Err:Cannot Get File Stats:", err)
return 4
4 years ago
}
4 years ago
if stats.Size() == 0 {
starlog.Warningf("文件:%s为空文件跳过\n", stats.Name())
continue
}
buf := make([]byte, 65535)
sumAll := 0
for {
n, err := fpFile.Read(buf)
if err != nil && err != io.EOF {
starlog.Errorln("Err:Error Occured While ReadFile:", err)
fpFile.Close()
return 5
}
sumAll += n
_, errW := fpOut.Write(buf[:n])
if errW != nil {
starlog.Errorln("Error While Write Data to OutFile", errW)
return 6
}
starlog.StdPrintf([]starlog.Attr{starlog.FgGreen}, "文件%s已完成%.2f%%\r", stats.Name(), (float64(sumAll) / float64(stats.Size()) * 100.0000))
if err == io.EOF {
starlog.StdPrintf([]starlog.Attr{starlog.FgGreen}, "文件:%v已完成100.00%% \n", stats.Name())
fpFile.Close()
break
}
}
}
starlog.StdPrintln([]starlog.Attr{starlog.FgGreen}, "Ok!文件合并完成")
return 0
4 years ago
}
func init() {
4 years ago
attachcmd.Flags().StringArrayP("src", "s", []string{}, "源文件路径")
4 years ago
attachcmd.Flags().StringP("out", "o", "", "输出文件路径")
}