Debian Codegraph @

cache/accessor/file/file.go

raw
1 // Copyright (c) Microsoft Corporation. All rights reserved.
2 // Licensed under the MIT License. See LICENSE in the project root for license information.
3
4 package file
5
6 import (
7 "context"
8 "errors"
9 "os"
10 "path/filepath"
11 "sync"
12
13 "github.com/AzureAD/microsoft-authentication-extensions-for-go/cache/accessor"
14 )
15
16 // Storage stores data in an unencrypted file.
17 type Storage struct {
18 m *sync.RWMutex
19 p string
20 }
21
22 // New is the constructor for Storage. "p" is the path to the file in which to store data.
23 func New(p string) (*Storage, error) {
24 return &Storage{m: &sync.RWMutex{}, p: p}, nil
25 }
26
27 // Delete deletes the file, if it exists.
28 func (s *Storage) Delete(context.Context) error {
29 s.m.Lock()
30 defer s.m.Unlock()
31 err := os.Remove(s.p)
32 if errors.Is(err, os.ErrNotExist) {
33 return nil
34 }
35 return err
36 }
37
38 // Read returns the file's content or, if the file doesn't exist, a nil slice and error.
39 func (s *Storage) Read(context.Context) ([]byte, error) {
40 s.m.RLock()
41 defer s.m.RUnlock()
42 b, err := os.ReadFile(s.p)
43 if errors.Is(err, os.ErrNotExist) {
44 return nil, nil
45 }
46 return b, err
47 }
48
49 // Write stores data in the file, overwriting any content, and creates the file if necessary.
50 func (s *Storage) Write(ctx context.Context, data []byte) error {
51 s.m.Lock()
52 defer s.m.Unlock()
53 err := os.WriteFile(s.p, data, 0600)
54 if errors.Is(err, os.ErrNotExist) {
55 dir := filepath.Dir(s.p)
56 if err = os.MkdirAll(dir, 0700); err == nil {
57 err = os.WriteFile(s.p, data, 0600)
58 }
59 }
60 return err
61 }
62
63 var _ accessor.Accessor = (*Storage)(nil)