Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

1.0 KB
Raw Blame
// SiYuan - https://github.com/siyuan-note/siyuan
// Copyright (c) 2020-present, b3log.org
// SPDX-License-Identifier: AGPL-3.0-or-later

package util

import (
	"bytes"
	"errors"
	"fmt"
	"os"

	"github.com/88250/gulu"
	"github.com/siyuan-note/filelock"
)

// ErrFileChanged 表示扫描后的源文件已变化,调用方必须保留当前文件并重新读取。
var ErrFileChanged = errors.New("source changed during operation")

// WriteFileIfUnchanged 在同一文件锁内比对扫描源并原子写入;original 为 nil 时要求目标不存在。
func WriteFileIfUnchanged(path string, original, data []byte) error {
	filelock.Lock(path)
	defer filelock.Unlock(path)
	current, err := os.ReadFile(path)
	if original == nil {
		if !os.IsNotExist(err) {
			return fmt.Errorf("target already exists or is unreadable: %s", path)
		}
	} else if err != nil {
		return err
	} else if !bytes.Equal(current, original) {
		return fmt.Errorf("%w: %s", ErrFileChanged, path)
	}
	return gulu.File.WriteFileSafer(path, data, 0644)
}