//go:build !windows12// SPDX-FileCopyrightText: Copyright The Lima Authors3// SPDX-License-Identifier: Apache-2.045// From https://github.com/containerd/nerdctl/blob/v0.13.0/pkg/lockutil/lockutil_unix.go6/*7Copyright The containerd Authors.89Licensed under the Apache License, Version 2.0 (the "License");10you may not use this file except in compliance with the License.11You may obtain a copy of the License at1213http://www.apache.org/licenses/LICENSE-2.01415Unless required by applicable law or agreed to in writing, software16distributed under the License is distributed on an "AS IS" BASIS,17WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.18See the License for the specific language governing permissions and19limitations under the License.20*/2122package lockutil2324import (25"fmt"26"os"2728"github.com/sirupsen/logrus"29"golang.org/x/sys/unix"30)3132func WithDirLock(dir string, fn func() error) error {33dirFile, err := os.Open(dir)34if err != nil {35return err36}37defer dirFile.Close()38if err := Flock(dirFile, unix.LOCK_EX); err != nil {39return fmt.Errorf("failed to lock %q: %w", dir, err)40}41defer func() {42if err := Flock(dirFile, unix.LOCK_UN); err != nil {43logrus.WithError(err).Errorf("failed to unlock %q", dir)44}45}()46return fn()47}4849func Flock(f *os.File, flags int) error {50fd := int(f.Fd())51for {52err := unix.Flock(fd, flags)53if err == nil || err != unix.EINTR {54return err55}56}57}585960