////
// Simple mutex for concurrent file writes

export class Mutex {
  private queue: (() => void)[] = []
  private locked = false

  async lock(): Promise<() => void> {
    return new Promise(resolve => {
      const unlock = () => {
        const next = this.queue.shift()
        if (next) {
          next()
        } else {
          this.locked = false
        }
      }

      if (this.locked) {
        this.queue.push(() => resolve(unlock))
      } else {
        this.locked = true
        resolve(unlock)
      }
    })
  }
}
