Skip to content

Commit a7f9aee

Browse files
authored
Merge pull request #573 from Earlopain/drop-win32ole
Remove dependency on `win32ole`
2 parents 8b18a1d + 1017f39 commit a7f9aee

File tree

1 file changed

+20
-5
lines changed

1 file changed

+20
-5
lines changed

lib/rake/cpu_counter.rb

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -58,11 +58,20 @@ def count_via_java_runtime
5858
end
5959
6060
def count_via_win32
61-
require 'win32ole'
62-
wmi = WIN32OLE.connect("winmgmts://")
63-
cpu = wmi.ExecQuery("select NumberOfCores from Win32_Processor") # TODO count hyper-threaded in this
64-
cpu.to_enum.first.NumberOfCores
65-
rescue StandardError, LoadError
61+
# Get-CimInstance introduced in PowerShell 3 or earlier: https://learn.microsoft.com/en-us/previous-versions/powershell/module/cimcmdlets/get-ciminstance?view=powershell-3.0
62+
result = run_win32(
63+
'powershell -command "Get-CimInstance -ClassName Win32_Processor -Property NumberOfCores ' \
64+
'| Select-Object -Property NumberOfCores"'
65+
)
66+
if !result || $?.exitstatus != 0
67+
# fallback to deprecated wmic for older systems
68+
result = run_win32("wmic cpu get NumberOfCores")
69+
end
70+
71+
# powershell: "\nNumberOfCores\n-------------\n 4\n\n\n"
72+
# wmic: "NumberOfCores \n\n4 \n\n\n\n"
73+
result.scan(/\d+/).map(&:to_i).reduce(:+) if result
74+
rescue StandardError
6675
nil
6776
end
6877
@@ -87,6 +96,12 @@ def run(command, *args)
8796
end
8897
end
8998
99+
def run_win32(command, *args)
100+
IO.popen(command, &:read)
101+
rescue Errno::ENOENT
102+
nil
103+
end
104+
90105
def resolve_command(command)
91106
look_for_command("/usr/sbin", command) ||
92107
look_for_command("/sbin", command) ||

0 commit comments

Comments
 (0)