code.vegaprotocol.io/vega@v0.79.0/datanode/utils/file.go (about)

     1  // Copyright (C) 2023 Gobalsky Labs Limited
     2  //
     3  // This program is free software: you can redistribute it and/or modify
     4  // it under the terms of the GNU Affero General Public License as
     5  // published by the Free Software Foundation, either version 3 of the
     6  // License, or (at your option) any later version.
     7  //
     8  // This program is distributed in the hope that it will be useful,
     9  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    10  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    11  // GNU Affero General Public License for more details.
    12  //
    13  // You should have received a copy of the GNU Affero General Public License
    14  // along with this program.  If not, see <http://www.gnu.org/licenses/>.
    15  
    16  package utils
    17  
    18  import (
    19  	"compress/gzip"
    20  	"io"
    21  	"os"
    22  )
    23  
    24  func CompressFile(source string, target string) error {
    25  	sourceFile, err := os.Open(source)
    26  	if err != nil {
    27  		return err
    28  	}
    29  	defer func() {
    30  		_ = sourceFile.Close()
    31  	}()
    32  
    33  	fileToWrite, err := os.Create(target)
    34  	if err != nil {
    35  		return err
    36  	}
    37  
    38  	zw := gzip.NewWriter(fileToWrite)
    39  	if err != nil {
    40  		return err
    41  	}
    42  	defer func() {
    43  		_ = zw.Close()
    44  	}()
    45  
    46  	if _, err = io.Copy(zw, sourceFile); err != nil {
    47  		return err
    48  	}
    49  
    50  	return nil
    51  }
    52  
    53  func DecompressFile(source string, target string) error {
    54  	sourceFile, err := os.Open(source)
    55  	if err != nil {
    56  		return err
    57  	}
    58  	defer func() {
    59  		_ = sourceFile.Close()
    60  	}()
    61  
    62  	fileToWrite, err := os.Create(target)
    63  	if err != nil {
    64  		return err
    65  	}
    66  
    67  	zr, err := gzip.NewReader(sourceFile)
    68  	if err != nil {
    69  		return err
    70  	}
    71  	defer func() {
    72  		_ = zr.Close()
    73  	}()
    74  
    75  	if _, err = io.Copy(fileToWrite, zr); err != nil {
    76  		return err
    77  	}
    78  
    79  	return nil
    80  }