"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FileLocker = exports.globSync = void 0;
const glob_1 = require("glob");
const promises_1 = require("fs/promises");
const fs_extra_1 = require("fs-extra");
const time_1 = require("./time");
// Wraps glob.sync but with good default options so that it works across
// platforms and with consistent sorting.
const globSync = (pattern, options) => {
    let output = (0, glob_1.sync)(pattern, options);
    output = output.map(f => f.replace(/\\/g, '/'));
    output.sort();
    return output;
};
exports.globSync = globSync;
class FileLocker {
    constructor(filePath, options = null) {
        this.filePath_ = '';
        this.interval_ = null;
        this.options_ = Object.assign({ interval: 10 * time_1.Second }, options);
        this.filePath_ = filePath;
    }
    get options() {
        return this.options_;
    }
    async lock() {
        if (!(await this.canLock()))
            return false;
        await this.updateLock();
        this.interval_ = setInterval(() => {
            void this.updateLock();
        }, this.options_.interval);
        return true;
    }
    async canLock() {
        try {
            const s = await (0, promises_1.stat)(this.filePath_);
            return Date.now() - s.mtime.getTime() > this.options_.interval;
        }
        catch (error) {
            const e = error;
            if (e.code === 'ENOENT')
                return true;
            e.message = `Could not find out if this file can be locked: ${this.filePath_}`;
            return e;
        }
    }
    // We want the unlock operation to be synchronous because it may be performed when the app
    // is closing.
    unlockSync() {
        this.stopMonitoring_();
        (0, fs_extra_1.removeSync)(this.filePath_);
    }
    async updateLock() {
        await (0, fs_extra_1.ensureFile)(this.filePath_);
        const now = new Date();
        await (0, promises_1.utimes)(this.filePath_, now, now);
    }
    stopMonitoring_() {
        if (this.interval_) {
            clearInterval(this.interval_);
            this.interval_ = null;
        }
    }
}
exports.FileLocker = FileLocker;
//# sourceMappingURL=fs.js.map