github.com/telepresenceio/telepresence/v2@v2.20.0-pro.6.0.20240517030216-236ea954e789/pkg/client/cache/cache.go (about)

     1  package cache
     2  
     3  import (
     4  	"context"
     5  	"encoding/json"
     6  	"errors"
     7  	"fmt"
     8  	"io/fs"
     9  	"os"
    10  	"path/filepath"
    11  
    12  	"github.com/telepresenceio/telepresence/v2/pkg/dos"
    13  	"github.com/telepresenceio/telepresence/v2/pkg/filelocation"
    14  )
    15  
    16  type Permissions fs.FileMode
    17  
    18  const (
    19  	Public  Permissions = 0o644
    20  	Private Permissions = 0o600
    21  )
    22  
    23  func SaveToUserCache(ctx context.Context, object any, file string, perm Permissions) error {
    24  	ctx = dos.WithLockedFs(ctx)
    25  	jsonContent, err := json.Marshal(object)
    26  	if err != nil {
    27  		return err
    28  	}
    29  
    30  	// add file path (ex. "ispec/00-00-0000.json")
    31  	fullFilePath := filepath.Join(filelocation.AppUserCacheDir(ctx), file)
    32  	// get dir of joined path
    33  	dir := filepath.Dir(fullFilePath)
    34  	if err := dos.MkdirAll(ctx, dir, 0o755); err != nil {
    35  		return err
    36  	}
    37  	return dos.WriteFile(ctx, fullFilePath, jsonContent, (fs.FileMode(perm)))
    38  }
    39  
    40  func LoadFromUserCache(ctx context.Context, dest any, file string) error {
    41  	ctx = dos.WithLockedFs(ctx)
    42  	path := filepath.Join(filelocation.AppUserCacheDir(ctx), file)
    43  	jsonContent, err := dos.ReadFile(ctx, path)
    44  	if err != nil {
    45  		return err
    46  	}
    47  	if err := json.Unmarshal(jsonContent, &dest); err != nil {
    48  		return fmt.Errorf("failed to parse JSON from file %s: %w", path, err)
    49  	}
    50  	return nil
    51  }
    52  
    53  func DeleteFromUserCache(ctx context.Context, file string) error {
    54  	ctx = dos.WithLockedFs(ctx)
    55  	if err := dos.Remove(ctx, filepath.Join(filelocation.AppUserCacheDir(ctx), file)); err != nil && !os.IsNotExist(err) {
    56  		return err
    57  	}
    58  	return nil
    59  }
    60  
    61  func ExistsInCache(ctx context.Context, fileName string) (bool, error) {
    62  	ctx = dos.WithLockedFs(ctx)
    63  	path := filepath.Join(filelocation.AppUserCacheDir(ctx), fileName)
    64  	if _, err := dos.Stat(ctx, path); err != nil {
    65  		if errors.Is(err, os.ErrNotExist) {
    66  			return false, nil
    67  		}
    68  		return false, err
    69  	}
    70  	return true, nil
    71  }