File: pids.rb

package info (click to toggle)
ruby-parallel-tests 5.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 760 kB
  • sloc: ruby: 5,446; javascript: 16; makefile: 4
file content (60 lines) | stat: -rw-r--r-- 837 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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# frozen_string_literal: true
require 'json'

module ParallelTests
  class Pids
    attr_reader :file_path, :mutex

    def initialize(file_path)
      @file_path = file_path
      @mutex = Mutex.new
    end

    def add(pid)
      pids << pid.to_i
      save
    end

    def delete(pid)
      pids.delete(pid.to_i)
      save
    end

    def count
      read
      pids.count
    end

    def all
      read
      pids
    end

    private

    def pids
      @pids ||= []
    end

    def clear
      @pids = []
      save
    end

    def read
      sync do
        contents = File.read(file_path)
        return if contents.empty?
        @pids = JSON.parse(contents)
      end
    end

    def save
      sync { File.write(file_path, pids.to_json) }
    end

    def sync(&block)
      mutex.synchronize(&block)
    end
  end
end