github.com/TrueBlocks/trueblocks-core/src/apps/chifra@v0.0.0-20241022031540-b362680128f7/pkg/file/archive.go (about)

     1  package file
     2  
     3  // CreateArchive creates new Writers for gzip and tar. These writers are chained. Writing
     4  // to the tar writer will write to the gzip writer which in turn will write to the "buf" writer
     5  // func CreateArchive(files []string, buf io.Writer, remove bool, relativeTo string) error {
     6  // 	gw := gzip.NewWriter(buf)
     7  //  Note: need to call gw.Flush()
     8  // 	defer gw.Close()
     9  // 	tw := tar.NewWriter(gw)
    10  //  Note: need to call tw.Flush()
    11  // 	defer tw.Close()
    12  
    13  // 	// Iterate over files and add them to the tar archive
    14  // 	for _, fn := range files {
    15  // 		err := addToArchive(tw, fn, relativeTo)
    16  // 		if err != nil {
    17  // 			return err
    18  // 		}
    19  // 	}
    20  
    21  // 	for _, fn := range files {
    22  // 		if remove && !Remove(fn) {
    23  // 			return fmt.Errorf("could not remove file %s", fn)
    24  // 		}
    25  // 	}
    26  
    27  // 	return nil
    28  // }
    29  
    30  // func addToArchive(tw *tar.Writer, filename, relativeTo string) error {
    31  // 	// Open the file which will be written into the archive
    32  // 	file, err := os.OpenFile(filename, os.O_RDONLY, 0)
    33  // 	if err != nil {
    34  // 		return err
    35  // 	}
    36  // 	defer file.Close()
    37  
    38  // 	// Get FileInfo about our file providing file size, mode, etc.
    39  // 	info, err := file.Stat()
    40  // 	if err != nil {
    41  // 		return err
    42  // 	}
    43  
    44  // 	// Create a tar Header from the FileInfo data
    45  // 	header, err := tar.FileInfoHeader(info, info.Name())
    46  // 	if err != nil {
    47  // 		return err
    48  // 	}
    49  
    50  // 	// Use full path as name (FileInfoHeader only takes the basename)
    51  // 	// If we don't do this the directory strucuture would not be preserved
    52  // 	// https://golang.org/src/archive/tar/commo n.go?#L626. If we're told
    53  // 	// where to write it, write it there
    54  // 	header.Name = filename
    55  // 	if len(relativeTo) > 0 {
    56  // 		header.Name = strings.Replace(filename, relativeTo, "", -1)
    57  // 	}
    58  
    59  // 	// Write file header to the tar archive
    60  // 	err = tw.WriteHeader(header)
    61  // 	if err != nil {
    62  // 		return err
    63  // 	}
    64  
    65  // 	// Copy file content to tar archive
    66  // 	_, err = io.Copy(tw, file)
    67  // 	if err != nil {
    68  // 		return err
    69  // 	}
    70  
    71  // 	return nil
    72  // }