Skip to content

Commit

Permalink
remove locking
Browse files Browse the repository at this point in the history
  • Loading branch information
taylormonacelli committed Jul 25, 2024
1 parent a38a7d6 commit ba039b9
Showing 1 changed file with 1 addition and 55 deletions.
56 changes: 1 addition & 55 deletions core/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,43 +7,10 @@ import (
"fmt"
"io"
"os"
"runtime"
"syscall"

"github.com/go-logr/logr"
)

var (
lockFile func(*os.File) error
unlockFile func(*os.File) error
)

func init() {
if runtime.GOOS == "windows" {
lockFile = func(f *os.File) error {
return nil
}
unlockFile = func(f *os.File) error {
return nil
}
} else {
lockFile = func(f *os.File) error {
err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
if err != nil {
return fmt.Errorf("failed to lock file: %w", err)
}
return nil
}
unlockFile = func(f *os.File) error {
err := syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
if err != nil {
return fmt.Errorf("failed to unlock file: %w", err)
}
return nil
}
}
}

func ProcessFile(ctx context.Context, path string, transform func(io.Reader, io.Writer) error) error {
logger := logr.FromContextOrDiscard(ctx)
logger = logger.WithValues("file", path)
Expand All @@ -65,32 +32,11 @@ func ProcessFile(ctx context.Context, path string, transform func(io.Reader, io.
return nil
}

originalFile, err := os.OpenFile(path, os.O_RDWR|os.O_TRUNC, 0o644)
if err != nil {
return fmt.Errorf("failed to open original file: %w", err)
}
defer func() {
if err := unlockFile(originalFile); err != nil {
logger.Error(err, "Failed to unlock file")
}
originalFile.Close()
}()

err = lockFile(originalFile)
if err != nil {
return err
}

_, err = originalFile.Write(processedContent.Bytes())
err = os.WriteFile(path, processedContent.Bytes(), 0o644)
if err != nil {
return fmt.Errorf("failed to write processed content to file: %w", err)
}

err = originalFile.Sync()
if err != nil {
return fmt.Errorf("failed to s.V(1)ync file: %w", err)
}

logger.V(1).Info("Successfully processed and updated file")
return nil
}
Expand Down

0 comments on commit ba039b9

Please sign in to comment.