github.com/matrixorigin/matrixone@v1.2.0/pkg/util/file/file.go (about)

     1  // Copyright 2021 - 2022 Matrix Origin
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package file
    16  
    17  import (
    18  	"context"
    19  	"time"
    20  
    21  	"github.com/matrixorigin/matrixone/pkg/common/moerr"
    22  	"github.com/matrixorigin/matrixone/pkg/fileservice"
    23  )
    24  
    25  // ReadFile read all data from file
    26  func ReadFile(fs fileservice.ReplaceableFileService, file string) ([]byte, error) {
    27  	ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
    28  	defer cancel()
    29  
    30  	vec := &fileservice.IOVector{
    31  		FilePath: file,
    32  		Entries: []fileservice.IOEntry{
    33  			{
    34  				Offset: 0,
    35  				Size:   -1,
    36  			},
    37  		},
    38  	}
    39  	if err := fs.Read(ctx, vec); err != nil {
    40  		if moerr.IsMoErrCode(err, moerr.ErrFileNotFound) {
    41  			return nil, nil
    42  		}
    43  		return nil, err
    44  	}
    45  	return vec.Entries[0].Data, nil
    46  }
    47  
    48  // WriteFile write data to file
    49  func WriteFile(fs fileservice.ReplaceableFileService, file string, data []byte) error {
    50  	ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
    51  	defer cancel()
    52  
    53  	vec := fileservice.IOVector{
    54  		FilePath: file,
    55  		Entries: []fileservice.IOEntry{
    56  			{
    57  				Offset: 0,
    58  				Size:   int64(len(data)),
    59  				Data:   data,
    60  			},
    61  		},
    62  	}
    63  	return fs.Replace(ctx, vec)
    64  }