File: flock.rb

package info (click to toggle)
ruby-with-advisory-lock 5.3.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 244 kB
  • sloc: ruby: 818; makefile: 14
file content (33 lines) | stat: -rw-r--r-- 809 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# frozen_string_literal: true

require 'fileutils'

module WithAdvisoryLock
  class Flock < Base
    def filename
      @filename ||= begin
        safe = lock_str.to_s.gsub(/[^a-z0-9]/i, '')
        fn = ".lock-#{safe}-#{stable_hashcode(lock_str)}"
        # Let the user specify a directory besides CWD.
        ENV['FLOCK_DIR'] ? File.expand_path(fn, ENV['FLOCK_DIR']) : fn
      end
    end

    def file_io
      @file_io ||= begin
        FileUtils.touch(filename)
        File.open(filename, 'r+')
      end
    end

    def try_lock
      raise ArgumentError, 'transaction level locks are not supported on SQLite' if transaction

      0 == file_io.flock((shared ? File::LOCK_SH : File::LOCK_EX) | File::LOCK_NB)
    end

    def release_lock
      0 == file_io.flock(File::LOCK_UN)
    end
  end
end