cr-exec 是一个改进的执行库,灵感来自 Crystal 语言。目标是提供一个更好的执行库,更好的用 Ruby 写脚本。
cr-exec 是一个受 Crystal 启发的改进执行库。它提供了一些标准库函数的包装,使得使用 Ruby 执行外部命令变得更加方便和高效。
写 shell 没有方便的功能,也没有方便的文档。ruby 很多符号定义跟 shell 是一脉相承,但标准库执行外部命令的函数和行为却不怎么明晰和方便。 前有 open3 和 python 语法的 subprocess,但我想要更简单的用法,做 shell 的现代替代。
所以自己尝试写了一个 libexec,但实现不怎么优雅,也有想从 go rust 的 std 取经的想法。 但 Crystal 作为 ruby 的正统传人,其标准库 文档 源码 更是非常优雅。将它的标准库反向移植过来,岂不是妙哉?
# frozen_string_literal: true
require "tempfile"
RSpec.describe Cr::Exec do
it "has a version number" do
expect(Cr::Exec::VERSION).not_to be nil
end
it "print lines" do
Cr::Exec.run("sudo apt update")
end
it "return 0" do
expect(Cr::Exec.code("uname")).to eq 0
end
it "accept multi string" do
expect(Cr::Exec.code("uname -s")).to eq 0
end
it "return 127" do
expect(Cr::Exec.code("unamea")).to eq 127
end
it "get Linux" do
expect(Cr::Exec.output("uname")).to eq "Linux"
end
it "get Linux\n" do
expect(Cr::Exec.output("uname", chomp: false)).to eq "Linux\n"
end
it "log to file" do
tempfile = Tempfile.new(["test_", ".log"])
Cr::Exec.run("uname", out: File.open(tempfile.path, "a+"))
expect(tempfile.readlines).to eq ["Linux\n"]
tempfile.delete
end
it "list file" do
expect(Cr::Exec.each_line("ls spec")).to eq ["cr\n", "spec_helper.rb\n"]
end
it "list file with option" do
expect(Cr::Exec.each_line("ls spec", chomp: true)).to eq ["cr", "spec_helper.rb"]
end
it "always return bool" do
p system("unamea")
expect(Cr::Exec.system?("unamea")).to eq false
end
end
https://github.com/initdc/ruby-docker
https://github.com/initdc/gitlab-ci-hello
$ gem install cr-exec
require "cr"
Cr.run("uname")