【问题标题】:Best way to handle OS differences with rake sh command使用 rake sh 命令处理操作系统差异的最佳方法
【发布时间】:2014-12-20 12:27:45
【问题描述】:

我正在尝试使用 rake 编写一个可以在 Windows 和 Linux 上运行的构建脚本。假设我有以下 rake 任务:

task:check do
    sh "dir"
end

这适用于 Windows,但不适用于其他操作系统。使用sh 命令处理操作系统差异的最佳方法是什么?我特别想让以下任务在操作系统之间工作,但它目前在 Windows 上工作:

task:check do
    %w(npm bower kpm gulp).each do |cmd|
        begin sh "#{cmd} --version > NUL" rescue raise "#{cmd} doesn't exists globally" end
    end
end

【问题讨论】:

标签: ruby rake


【解决方案1】:

Ruby 知道它是在什么操作系统上编译的,以及它正在运行什么,因为它必须知道路径分隔符、行结束符等。我们可以使用内置常量和/或模块。

使用RUBY_PLATFORM 常量:

在 Mac OSX 上:

RUBY_PLATFORM # => "x86_64-darwin13.0"

在 Linux 上:

RUBY_PLATFORM # => "x86_64-linux"

你也可以使用 Gem::Platform:

在 Mac OSX 上:

Gem::Platform.local # => #<Gem::Platform:0x3fe859440ef4 @cpu="x86_64", @os="darwin", @version="13">
Gem::Platform.local.os # => "darwin"

在 Linux 上:

Gem::Platform.local # => #<Gem::Platform:0x13e0b60 @cpu="x86_64", @os="linux", @version=nil>
Gem::Platform.local.os # => "linux"

还有 Ruby 自带的 RbConfig 模块:

在 Mac 操作系统上:

RbConfig::CONFIG['target_cpu']   # => "x86_64"
RbConfig::CONFIG['target_os']    # => "darwin13.0"
RbConfig::CONFIG['host_cpu']     # => "x86_64"
RbConfig::CONFIG['host_os']      # => "darwin13.4.0"

在 Linux 上:

 RbConfig::CONFIG['target_cpu'] # => "x86_64"
 RbConfig::CONFIG['target_os']  # => "linux"
 RbConfig::CONFIG['host_cpu']   # => "x86_64"
 RbConfig::CONFIG['host_os']    # => "linux-gnu"

A quick search 为此返回了许多命中,包括 Stack Overflow 上的许多命中。

【讨论】:

    【解决方案2】:

    查看os gem。您可以将任务定义包装在平台检查中,甚至可以使用一些帮助程序来编写更通用的任务。

    这样的东西可能很方便:

    >> OS.dev_null
    => "NUL" # or "/dev/null" depending on which platform
    

    或者只是让它们特定于操作系统:

    if OS.windows?
    
      task :whatever do
        # ...
      end
    
    elsif OS.linux?
    
      task :whatever do
        # ...
      end
    
    end
    

    【讨论】:

    • 太棒了,谢谢!和这个一起去:sh "#{cmd} --version &gt;&gt; #{OS.dev_null}"
    • 请注意这个 gem treats Cygwin as Linux,而不是 Windows!根据您的用例,这可能不是您所期望的。
    猜你喜欢
    • 1970-01-01
    • 2012-11-29
    • 2010-10-02
    • 2014-01-23
    • 2017-05-23
    • 2022-11-10
    • 1970-01-01
    • 2019-05-13
    • 1970-01-01
    相关资源
    最近更新 更多