summaryrefslogtreecommitdiff
path: root/spec/mspec/lib/mspec/guards/platform.rb
blob: 9543b1dd05221ae2d5a0370bd5a3610d10f811b2 (plain)
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
require 'mspec/guards/guard'

class PlatformGuard < SpecGuard
  def self.implementation?(*args)
    args.any? do |name|
      case name
      when :rubinius
        RUBY_ENGINE.start_with?('rbx')
      when :ruby, :jruby, :truffleruby, :ironruby, :macruby, :maglev, :topaz, :opal
        RUBY_ENGINE.start_with?(name.to_s)
      else
        raise "unknown implementation #{name}"
      end
    end
  end

  def self.standard?
    implementation? :ruby
  end

  HOST_OS = begin
    require 'rbconfig'
    RbConfig::CONFIG['host_os'] || RUBY_PLATFORM
  rescue LoadError
    RUBY_PLATFORM
  end.downcase

  def self.os?(*oses)
    oses.any? do |os|
      raise ":java is not a valid OS" if os == :java
      if os == :windows
        HOST_OS =~ /(mswin|mingw)/
      else
        HOST_OS.include?(os.to_s)
      end
    end
  end

  def self.windows?
    os?(:windows)
  end

  WORD_SIZE = 1.size * 8

  POINTER_SIZE = begin
    require 'rbconfig/sizeof'
    RbConfig::SIZEOF["void*"] * 8
  rescue LoadError
    WORD_SIZE
  end

  def self.wordsize?(size)
    size == WORD_SIZE
  end

  def self.pointer_size?(size)
    size == POINTER_SIZE
  end

  def initialize(*args)
    if args.last.is_a?(Hash)
      @options, @platforms = args.last, args[0..-2]
    else
      @options, @platforms = {}, args
    end
    @parameters = args
  end

  def match?
    match = @platforms.empty? ? true : PlatformGuard.os?(*@platforms)
    @options.each do |key, value|
      case key
      when :os
        match &&= PlatformGuard.os?(*value)
      when :wordsize
        match &&= PlatformGuard.wordsize? value
      when :pointer_size
        match &&= PlatformGuard.pointer_size? value
      end
    end
    match
  end
end

def platform_is(*args, &block)
  PlatformGuard.new(*args).run_if(:platform_is, &block)
end

def platform_is_not(*args, &block)
  PlatformGuard.new(*args).run_unless(:platform_is_not, &block)
end