gitee.com/h79/goutils@v1.22.10/build/7z.go (about)

     1  package build
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"gitee.com/h79/goutils/common/archive"
     7  	"gitee.com/h79/goutils/common/archive/e7z"
     8  	fileconfig "gitee.com/h79/goutils/common/file/config"
     9  	"io"
    10  	"os"
    11  	"path/filepath"
    12  	"runtime"
    13  )
    14  
    15  type e7zBuilder struct {
    16  }
    17  
    18  func (t *e7zBuilder) Ext() string {
    19  	return ".7z"
    20  }
    21  
    22  func (*e7zBuilder) New(target io.WriteCloser, conf archive.Config) archive.Archive {
    23  	return &e7zArchive{Archive: e7z.New(target, conf.Path, conf.File), closed: false}
    24  }
    25  
    26  func (*e7zBuilder) Coping(r *os.File, w io.Writer, conf archive.Config) (archive.Archive, error) {
    27  	return nil, fmt.Errorf("not support")
    28  }
    29  
    30  type e7zArchive struct {
    31  	e7z.Archive
    32  	closed bool
    33  }
    34  
    35  func (c *e7zArchive) Close() error {
    36  	if c.closed {
    37  		return nil
    38  	}
    39  	c.closed = true //防止重复close
    40  	cmd := "7z"
    41  	switch runtime.GOOS {
    42  	case "windows":
    43  		cmd = "7z.exe"
    44  	}
    45  	// for 7z 命令
    46  	src := filepath.Join(c.Path, "*")
    47  	if len(src) >= 2 && filepath.VolumeName(src) == "" && !os.IsPathSeparator(src[0]) {
    48  		if src[0] != '.' && !os.IsPathSeparator(src[1]) {
    49  			src = "." + string(filepath.Separator) + src
    50  		}
    51  	}
    52  	return run(context.Background(), []string{cmd, "a", c.Filename, src}, nil, "")
    53  }
    54  
    55  func (c *e7zArchive) Add(f fileconfig.File, stream ...fileconfig.ReaderStream) error {
    56  	err := c.Stream(f, stream...)
    57  	if err != nil {
    58  		c.closed = true
    59  	}
    60  	return err
    61  }