repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
denisdefreyne/cri | https://github.com/denisdefreyne/cri/blob/022de9676b2912b90d3b21f1727680d81ebc1e5d/test/test_base.rb | test/test_base.rb | # frozen_string_literal: true
require 'helper'
module Cri
class BaseTestCase < Cri::TestCase
def test_stub; end
end
end
| ruby | MIT | 022de9676b2912b90d3b21f1727680d81ebc1e5d | 2026-01-04T17:57:35.186613Z | false |
denisdefreyne/cri | https://github.com/denisdefreyne/cri/blob/022de9676b2912b90d3b21f1727680d81ebc1e5d/test/test_argument_list.rb | test/test_argument_list.rb | # frozen_string_literal: true
require 'helper'
module Cri
class ArgumentListTestCase < Cri::TestCase
def test_empty
args = Cri::ArgumentList.new([], false, [])
assert_equal([], args.to_a)
assert(args.empty?)
assert_equal(0, args.size)
assert_equal(nil, args[0])
assert_equal(nil, args[:abc])
end
def test_no_param_defns
args = Cri::ArgumentList.new(%w[a b c], false, [])
assert_equal(%w[a b c], args.to_a)
refute(args.empty?)
assert_equal(3, args.size)
assert_equal('a', args[0])
assert_equal('b', args[1])
assert_equal('c', args[2])
assert_equal(nil, args[3])
assert_equal(nil, args[:abc])
end
def test_enum
args = Cri::ArgumentList.new(%w[a b c], false, [])
assert_equal(%w[A B C], args.map(&:upcase))
end
def test_enum_without_block
args = Cri::ArgumentList.new(%w[a b c], false, [])
assert_equal(%w[A B C], args.each.map(&:upcase))
end
def test_no_method_error
args = Cri::ArgumentList.new(%w[a b c], false, [])
refute args.respond_to?(:oink)
assert_raises(NoMethodError, 'x') do
args.oink
end
end
def test_dash_dash
args = Cri::ArgumentList.new(%w[a -- b -- c], false, [])
assert_equal(%w[a b c], args.to_a)
end
def test_one_param_defn_matched
param_defns = [Cri::ParamDefinition.new(name: 'filename', transform: nil)]
args = Cri::ArgumentList.new(%w[notbad.jpg], false, param_defns)
assert_equal(['notbad.jpg'], args.to_a)
assert_equal(1, args.size)
assert_equal('notbad.jpg', args[0])
assert_equal('notbad.jpg', args[:filename])
end
def test_one_param_defn_too_many
param_defns = [Cri::ParamDefinition.new(name: 'filename', transform: nil)]
exception = assert_raises(Cri::ArgumentList::ArgumentCountMismatchError) do
Cri::ArgumentList.new(%w[notbad.jpg verybad.jpg], false, param_defns)
end
assert_equal('incorrect number of arguments given: expected 1, but got 2', exception.message)
end
def test_one_param_defn_too_few
param_defns = [Cri::ParamDefinition.new(name: 'filename', transform: nil)]
exception = assert_raises(Cri::ArgumentList::ArgumentCountMismatchError) do
Cri::ArgumentList.new(%w[], false, param_defns)
end
assert_equal('incorrect number of arguments given: expected 1, but got 0', exception.message)
end
def test_zero_params_zero_args
args = Cri::ArgumentList.new(%w[], false, [])
assert_equal([], args.to_a)
assert args.empty?
assert_equal(0, args.size)
end
def test_zero_params_one_arg
exception = assert_raises(Cri::ArgumentList::ArgumentCountMismatchError) do
Cri::ArgumentList.new(%w[a], true, [])
end
assert_equal('incorrect number of arguments given: expected 0, but got 1', exception.message)
end
def test_transform
param_defns = [Cri::ParamDefinition.new(name: 'filename', transform: lambda(&:upcase))]
args = Cri::ArgumentList.new(%w[notbad.jpg], false, param_defns)
assert_equal(['NOTBAD.JPG'], args.to_a)
assert_equal(1, args.size)
assert_equal('NOTBAD.JPG', args[0])
assert_equal('NOTBAD.JPG', args[:filename])
end
end
end
| ruby | MIT | 022de9676b2912b90d3b21f1727680d81ebc1e5d | 2026-01-04T17:57:35.186613Z | false |
denisdefreyne/cri | https://github.com/denisdefreyne/cri/blob/022de9676b2912b90d3b21f1727680d81ebc1e5d/test/test_basic_help.rb | test/test_basic_help.rb | # frozen_string_literal: true
require 'helper'
module Cri
class BasicHelpTestCase < Cri::TestCase
def test_run_without_supercommand
cmd = Cri::Command.new_basic_help
assert_raises Cri::NoHelpAvailableError do
cmd.run([])
end
end
def test_run_with_supercommand
cmd = Cri::Command.define do
name 'meh'
end
help_cmd = Cri::Command.new_basic_help
cmd.add_command(help_cmd)
help_cmd.run([])
end
def test_run_with_chain_of_commands
cmd = Cri::Command.define do
name 'root'
summary 'I am root!'
subcommand do
name 'foo'
summary 'I am foo!'
subcommand do
name 'subsubby'
summary 'I am subsubby!'
end
end
end
help_cmd = Cri::Command.new_basic_help
cmd.add_command(help_cmd)
# Simple call
stdout, stderr = capture_io_while do
help_cmd.run(['foo'])
end
assert_match(/I am foo!/m, stdout)
assert_equal('', stderr)
# Subcommand
stdout, stderr = capture_io_while do
help_cmd.run(%w[foo subsubby])
end
assert_match(/I am subsubby!/m, stdout)
assert_equal('', stderr)
# Non-existing subcommand
stdout, stderr = capture_io_while do
assert_raises SystemExit do
help_cmd.run(%w[foo mysterycmd])
end
end
assert_equal '', stdout
assert_match(/foo: unknown command 'mysterycmd'/, stderr)
end
end
end
| ruby | MIT | 022de9676b2912b90d3b21f1727680d81ebc1e5d | 2026-01-04T17:57:35.186613Z | false |
denisdefreyne/cri | https://github.com/denisdefreyne/cri/blob/022de9676b2912b90d3b21f1727680d81ebc1e5d/test/test_command_runner.rb | test/test_command_runner.rb | # frozen_string_literal: true
require 'helper'
module Cri
class CommandRunnerTestCase < Cri::TestCase
def setup
super
@options = { vehicle: 'pig' }
@arguments = %w[baby_monkey]
@command = Cri::Command.new
end
def test_initialize
runner = Cri::CommandRunner.new(@options, @arguments, @command)
assert_equal @options, runner.options
assert_equal @arguments, runner.arguments
assert_equal @command, runner.command
end
def test_call_run
assert_raises(Cri::NotImplementedError) do
Cri::CommandRunner.new(@options, @arguments, @command).call
end
assert_raises(Cri::NotImplementedError) do
Cri::CommandRunner.new(@options, @arguments, @command).run
end
end
end
end
| ruby | MIT | 022de9676b2912b90d3b21f1727680d81ebc1e5d | 2026-01-04T17:57:35.186613Z | false |
denisdefreyne/cri | https://github.com/denisdefreyne/cri/blob/022de9676b2912b90d3b21f1727680d81ebc1e5d/test/test_parser.rb | test/test_parser.rb | # frozen_string_literal: true
require 'helper'
module Cri
class ParserTestCase < Cri::TestCase
def test_parse_without_options
input = %w[foo bar baz]
opt_defns = []
parser = Cri::Parser.new(input, opt_defns, [], false).run
assert_equal({}, parser.options)
assert_equal(%w[foo bar baz], parser.gen_argument_list.to_a)
end
def test_parse_with_invalid_option
input = %w[foo -x]
opt_defns = []
assert_raises(Cri::Parser::IllegalOptionError) do
Cri::Parser.new(input, opt_defns, [], false).run
end
end
def test_parse_with_unused_options
input = %w[foo]
opt_defns = [
{ long: 'aaa', short: 'a', argument: :forbidden },
].map { |hash| make_opt_defn(hash) }
parser = Cri::Parser.new(input, opt_defns, [], false).run
assert(!parser.options[:aaa])
end
def test_parse_with_long_valueless_option
input = %w[foo --aaa bar]
opt_defns = [
{ long: 'aaa', short: 'a', argument: :forbidden },
].map { |hash| make_opt_defn(hash) }
parser = Cri::Parser.new(input, opt_defns, [], false).run
assert(parser.options[:aaa])
assert_equal(%w[foo bar], parser.gen_argument_list.to_a)
end
def test_parse_with_long_valueful_option
input = %w[foo --aaa xxx bar]
opt_defns = [
{ long: 'aaa', short: 'a', argument: :required },
].map { |hash| make_opt_defn(hash) }
parser = Cri::Parser.new(input, opt_defns, [], false).run
assert_equal({ aaa: 'xxx' }, parser.options)
assert_equal(%w[foo bar], parser.gen_argument_list.to_a)
end
def test_parse_with_long_valueful_equalsign_option
input = %w[foo --aaa=xxx bar]
opt_defns = [
{ long: 'aaa', short: 'a', argument: :required },
].map { |hash| make_opt_defn(hash) }
parser = Cri::Parser.new(input, opt_defns, [], false).run
assert_equal({ aaa: 'xxx' }, parser.options)
assert_equal(%w[foo bar], parser.gen_argument_list.to_a)
end
def test_parse_with_long_valueful_option_with_missing_value
input = %w[foo --aaa]
opt_defns = [
{ long: 'aaa', short: 'a', argument: :required },
].map { |hash| make_opt_defn(hash) }
assert_raises(Cri::Parser::OptionRequiresAnArgumentError) do
Cri::Parser.new(input, opt_defns, [], false).run
end
end
def test_parse_with_two_long_valueful_options
input = %w[foo --all --port 2]
opt_defns = [
{ long: 'all', short: 'a', argument: :required },
{ long: 'port', short: 'p', argument: :required },
].map { |hash| make_opt_defn(hash) }
assert_raises(Cri::Parser::OptionRequiresAnArgumentError) do
Cri::Parser.new(input, opt_defns, [], false).run
end
end
def test_parse_with_long_valueless_option_with_optional_value
input = %w[foo --aaa]
opt_defns = [
{ long: 'aaa', short: 'a', argument: :optional },
].map { |hash| make_opt_defn(hash) }
parser = Cri::Parser.new(input, opt_defns, [], false).run
assert(parser.options[:aaa])
assert_equal(['foo'], parser.gen_argument_list.to_a)
end
def test_parse_with_long_valueful_option_with_optional_value
input = %w[foo --aaa xxx]
opt_defns = [
{ long: 'aaa', short: 'a', argument: :optional },
].map { |hash| make_opt_defn(hash) }
parser = Cri::Parser.new(input, opt_defns, [], false).run
assert_equal({ aaa: 'xxx' }, parser.options)
assert_equal(['foo'], parser.gen_argument_list.to_a)
end
def test_parse_with_long_valueless_option_with_optional_value_and_more_options
input = %w[foo --aaa -b -c]
opt_defns = [
{ long: 'aaa', short: 'a', argument: :optional },
{ long: 'bbb', short: 'b', argument: :forbidden },
{ long: 'ccc', short: 'c', argument: :forbidden },
].map { |hash| make_opt_defn(hash) }
parser = Cri::Parser.new(input, opt_defns, [], false).run
assert(parser.options[:aaa])
assert(parser.options[:bbb])
assert(parser.options[:ccc])
assert_equal(['foo'], parser.gen_argument_list.to_a)
end
def test_parse_with_short_valueless_options
input = %w[foo -a bar]
opt_defns = [
{ long: 'aaa', short: 'a', argument: :forbidden },
].map { |hash| make_opt_defn(hash) }
parser = Cri::Parser.new(input, opt_defns, [], false).run
assert(parser.options[:aaa])
assert_equal(%w[foo bar], parser.gen_argument_list.to_a)
end
def test_parse_with_short_valueful_option_with_missing_value
input = %w[foo -a]
opt_defns = [
{ long: 'aaa', short: 'a', argument: :required },
].map { |hash| make_opt_defn(hash) }
assert_raises(Cri::Parser::OptionRequiresAnArgumentError) do
Cri::Parser.new(input, opt_defns, [], false).run
end
end
def test_parse_with_short_combined_valueless_options
input = %w[foo -abc bar]
opt_defns = [
{ long: 'aaa', short: 'a', argument: :forbidden },
{ long: 'bbb', short: 'b', argument: :forbidden },
{ long: 'ccc', short: 'c', argument: :forbidden },
].map { |hash| make_opt_defn(hash) }
parser = Cri::Parser.new(input, opt_defns, [], false).run
assert(parser.options[:aaa])
assert(parser.options[:bbb])
assert(parser.options[:ccc])
assert_equal(%w[foo bar], parser.gen_argument_list.to_a)
end
def test_parse_with_short_combined_valueful_options_with_missing_value
input = %w[foo -abc bar qux]
opt_defns = [
{ long: 'aaa', short: 'a', argument: :required },
{ long: 'bbb', short: 'b', argument: :forbidden },
{ long: 'ccc', short: 'c', argument: :forbidden },
].map { |hash| make_opt_defn(hash) }
parser = Cri::Parser.new(input, opt_defns, [], false).run
assert_equal('bar', parser.options[:aaa])
assert(parser.options[:bbb])
assert(parser.options[:ccc])
assert_equal(%w[foo qux], parser.gen_argument_list.to_a)
end
def test_parse_with_two_short_valueful_options
input = %w[foo -a -p 2]
opt_defns = [
{ long: 'all', short: 'a', argument: :required },
{ long: 'port', short: 'p', argument: :required },
].map { |hash| make_opt_defn(hash) }
assert_raises(Cri::Parser::OptionRequiresAnArgumentError) do
Cri::Parser.new(input, opt_defns, [], false).run
end
end
def test_parse_with_short_valueless_option_with_optional_value
input = %w[foo -a]
opt_defns = [
{ long: 'aaa', short: 'a', argument: :optional },
].map { |hash| make_opt_defn(hash) }
parser = Cri::Parser.new(input, opt_defns, [], false).run
assert(parser.options[:aaa])
assert_equal(['foo'], parser.gen_argument_list.to_a)
end
def test_parse_with_short_valueful_option_with_optional_value
input = %w[foo -a xxx]
opt_defns = [
{ long: 'aaa', short: 'a', argument: :optional },
].map { |hash| make_opt_defn(hash) }
parser = Cri::Parser.new(input, opt_defns, [], false).run
assert_equal({ aaa: 'xxx' }, parser.options)
assert_equal(['foo'], parser.gen_argument_list.to_a)
end
def test_parse_with_short_valueless_option_with_optional_value_and_more_options
input = %w[foo -a -b -c]
opt_defns = [
{ long: 'aaa', short: 'a', argument: :optional },
{ long: 'bbb', short: 'b', argument: :forbidden },
{ long: 'ccc', short: 'c', argument: :forbidden },
].map { |hash| make_opt_defn(hash) }
parser = Cri::Parser.new(input, opt_defns, [], false).run
assert(parser.options[:aaa])
assert(parser.options[:bbb])
assert(parser.options[:ccc])
assert_equal(['foo'], parser.gen_argument_list.to_a)
end
def test_parse_with_single_hyphen
input = %w[foo - bar]
opt_defns = []
parser = Cri::Parser.new(input, opt_defns, [], false).run
assert_equal({}, parser.options)
assert_equal(['foo', '-', 'bar'], parser.gen_argument_list.to_a)
end
def test_parse_with_end_marker
input = %w[foo bar -- -x --yyy -abc]
opt_defns = []
parser = Cri::Parser.new(input, opt_defns, [], false).run
assert_equal({}, parser.options)
assert_equal(['foo', 'bar', '-x', '--yyy', '-abc'], parser.gen_argument_list.to_a)
end
def test_parse_with_end_marker_between_option_key_and_value
input = %w[foo --aaa -- zzz]
opt_defns = [
{ long: 'aaa', short: 'a', argument: :required },
].map { |hash| make_opt_defn(hash) }
assert_raises(Cri::Parser::OptionRequiresAnArgumentError) do
Cri::Parser.new(input, opt_defns, [], false).run
end
end
def test_parse_with_multiple_options
input = %w[foo -o test -o test2 -v -v -v]
opt_defns = [
{ long: 'long', short: 'o', argument: :required, multiple: true },
{ long: 'verbose', short: 'v', multiple: true },
].map { |hash| make_opt_defn(hash) }
parser = Cri::Parser.new(input, opt_defns, [], false).run
assert_equal(%w[test test2], parser.options[:long])
assert_equal(3, parser.options[:verbose].size)
end
def test_parse_with_default_required_no_value
input = %w[foo -a]
opt_defns = [
{ long: 'animal', short: 'a', argument: :required, default: 'donkey' },
].map { |hash| make_opt_defn(hash) }
assert_raises(Cri::Parser::OptionRequiresAnArgumentError) do
Cri::Parser.new(input, opt_defns, [], false).run
end
end
def test_parse_with_default_required_value
input = %w[foo -a giraffe]
opt_defns = [
{ long: 'animal', short: 'a', argument: :required, default: 'donkey' },
].map { |hash| make_opt_defn(hash) }
parser = Cri::Parser.new(input, opt_defns, [], false).run
assert_equal({ animal: 'giraffe' }, parser.options)
assert_equal(['foo'], parser.gen_argument_list.to_a)
end
def test_parse_with_default_optional_no_value
input = %w[foo -a]
opt_defns = [
{ long: 'animal', short: 'a', argument: :optional, default: 'donkey' },
].map { |hash| make_opt_defn(hash) }
parser = Cri::Parser.new(input, opt_defns, [], false).run
assert_equal({ animal: 'donkey' }, parser.options)
assert_equal(['foo'], parser.gen_argument_list.to_a)
end
def test_parse_with_default_optional_value
input = %w[foo -a giraffe]
opt_defns = [
{ long: 'animal', short: 'a', argument: :optional, default: 'donkey' },
].map { |hash| make_opt_defn(hash) }
parser = Cri::Parser.new(input, opt_defns, [], false).run
assert_equal({ animal: 'giraffe' }, parser.options)
assert_equal(['foo'], parser.gen_argument_list.to_a)
end
def test_parse_with_default_optional_value_and_arg
input = %w[foo -a gi raffe]
opt_defns = [
{ long: 'animal', short: 'a', argument: :optional, default: 'donkey' },
].map { |hash| make_opt_defn(hash) }
parser = Cri::Parser.new(input, opt_defns, [], false).run
assert_equal({ animal: 'gi' }, parser.options)
assert_equal(%w[foo raffe], parser.gen_argument_list.to_a)
end
def test_parse_with_combined_required_options
input = %w[foo -abc xxx yyy zzz]
opt_defns = [
{ long: 'aaa', short: 'a', argument: :forbidden },
{ long: 'bbb', short: 'b', argument: :required },
{ long: 'ccc', short: 'c', argument: :required },
].map { |hash| make_opt_defn(hash) }
parser = Cri::Parser.new(input, opt_defns, [], false).run
assert_equal({ aaa: true, bbb: 'xxx', ccc: 'yyy' }, parser.options)
assert_equal(%w[foo zzz], parser.gen_argument_list.to_a)
end
def test_parse_with_combined_optional_options
input = %w[foo -abc xxx yyy zzz]
opt_defns = [
{ long: 'aaa', short: 'a', argument: :forbidden },
{ long: 'bbb', short: 'b', argument: :optional },
{ long: 'ccc', short: 'c', argument: :required },
].map { |hash| make_opt_defn(hash) }
parser = Cri::Parser.new(input, opt_defns, [], false).run
assert_equal({ aaa: true, bbb: 'xxx', ccc: 'yyy' }, parser.options)
assert_equal(%w[foo zzz], parser.gen_argument_list.to_a)
end
def test_parse_with_combined_optional_options_with_missing_value
input = %w[foo -abc xxx]
opt_defns = [
{ long: 'aaa', short: 'a', argument: :forbidden },
{ long: 'bbb', short: 'b', argument: :required },
{ long: 'ccc', short: 'c', argument: :optional, default: 'c default' },
].map { |hash| make_opt_defn(hash) }
parser = Cri::Parser.new(input, opt_defns, [], false).run
assert_equal({ aaa: true, bbb: 'xxx', ccc: 'c default' }, parser.options)
assert_equal(%w[foo], parser.gen_argument_list.to_a)
end
def test_parse_with_transform_proc
input = %w[--port 123]
opt_defns = [
{ long: 'port', short: 'p', argument: :required, transform: ->(x) { Integer(x) } },
].map { |hash| make_opt_defn(hash) }
parser = Cri::Parser.new(input, opt_defns, [], false).run
assert_equal({ port: 123 }, parser.options)
assert_equal([], parser.gen_argument_list.to_a)
end
def test_parse_with_transform_method
input = %w[--port 123]
opt_defns = [
{ long: 'port', short: 'p', argument: :required, transform: method(:Integer) },
].map { |hash| make_opt_defn(hash) }
parser = Cri::Parser.new(input, opt_defns, [], false).run
assert_equal({ port: 123 }, parser.options)
assert_equal([], parser.gen_argument_list.to_a)
end
def test_parse_with_transform_object
port = Class.new do
def call(str)
Integer(str)
end
end.new
input = %w[--port 123]
opt_defns = [
{ long: 'port', short: 'p', argument: :required, transform: port },
].map { |hash| make_opt_defn(hash) }
parser = Cri::Parser.new(input, opt_defns, [], false).run
assert_equal({ port: 123 }, parser.options)
assert_equal([], parser.gen_argument_list.to_a)
end
def test_parse_with_transform_exception
input = %w[--port one_hundred_and_twenty_three]
opt_defns = [
{ long: 'port', short: 'p', argument: :required, transform: method(:Integer) },
].map { |hash| make_opt_defn(hash) }
exception = assert_raises(Cri::Parser::IllegalOptionValueError) do
Cri::Parser.new(input, opt_defns, [], false).run
end
assert_equal('invalid value "one_hundred_and_twenty_three" for --port option', exception.message)
end
def test_parse_with_param_defns
input = %w[localhost]
param_defns = [
{ name: 'host', transform: nil },
].map { |hash| Cri::ParamDefinition.new(**hash) }
parser = Cri::Parser.new(input, [], param_defns, false).run
assert_equal({}, parser.options)
assert_equal('localhost', parser.gen_argument_list[0])
assert_equal('localhost', parser.gen_argument_list[:host])
end
def test_parse_with_param_defns_too_few_args
input = []
param_defns = [
{ name: 'host', transform: nil },
].map { |hash| Cri::ParamDefinition.new(**hash) }
parser = Cri::Parser.new(input, [], param_defns, false).run
exception = assert_raises(Cri::ArgumentList::ArgumentCountMismatchError) do
parser.gen_argument_list
end
assert_equal('incorrect number of arguments given: expected 1, but got 0', exception.message)
end
def test_parse_with_param_defns_too_many_args
input = %w[localhost oink]
param_defns = [
{ name: 'host', transform: nil },
].map { |hash| Cri::ParamDefinition.new(**hash) }
parser = Cri::Parser.new(input, [], param_defns, false).run
exception = assert_raises(Cri::ArgumentList::ArgumentCountMismatchError) do
parser.gen_argument_list
end
assert_equal('incorrect number of arguments given: expected 1, but got 2', exception.message)
end
def test_parse_with_param_defns_invalid_key
input = %w[localhost]
param_defns = [
{ name: 'host', transform: nil },
].map { |hash| Cri::ParamDefinition.new(**hash) }
parser = Cri::Parser.new(input, [], param_defns, false).run
exception = assert_raises(ArgumentError) do
parser.gen_argument_list['oink']
end
assert_equal('argument lists can be indexed using a Symbol or an Integer, but not a String', exception.message)
end
def test_parse_with_param_defns_two_params
input = %w[localhost example.com]
param_defns = [
{ name: 'source', transform: nil },
{ name: 'target', transform: nil },
].map { |hash| Cri::ParamDefinition.new(**hash) }
parser = Cri::Parser.new(input, [], param_defns, false).run
assert_equal({}, parser.options)
assert_equal('localhost', parser.gen_argument_list[0])
assert_equal('localhost', parser.gen_argument_list[:source])
assert_equal('example.com', parser.gen_argument_list[1])
assert_equal('example.com', parser.gen_argument_list[:target])
end
def make_opt_defn(hash)
Cri::OptionDefinition.new(
short: hash.fetch(:short, nil),
long: hash.fetch(:long, nil),
desc: hash.fetch(:desc, nil),
argument: hash.fetch(:argument, nil),
multiple: hash.fetch(:multiple, nil),
block: hash.fetch(:block, nil),
hidden: hash.fetch(:hidden, nil),
default: hash.fetch(:default, nil),
transform: hash.fetch(:transform, nil),
)
end
end
end
| ruby | MIT | 022de9676b2912b90d3b21f1727680d81ebc1e5d | 2026-01-04T17:57:35.186613Z | false |
denisdefreyne/cri | https://github.com/denisdefreyne/cri/blob/022de9676b2912b90d3b21f1727680d81ebc1e5d/test/helper.rb | test/helper.rb | # frozen_string_literal: true
require 'minitest'
require 'minitest/autorun'
require 'cri'
require 'stringio'
module Cri
class TestCase < Minitest::Test
def setup
@orig_io = capture_io
end
def teardown
uncapture_io(*@orig_io)
end
def capture_io_while
orig_io = capture_io
yield
[$stdout.string, $stderr.string]
ensure
uncapture_io(*orig_io)
end
def lines(string)
string.scan(/^.*\n/).map(&:chomp)
end
private
def capture_io
orig_stdout = $stdout
orig_stderr = $stderr
$stdout = StringIO.new
$stderr = StringIO.new
[orig_stdout, orig_stderr]
end
def uncapture_io(orig_stdout, orig_stderr)
$stdout = orig_stdout
$stderr = orig_stderr
end
end
end
# Unexpected system exit is unexpected
::Minitest::Test::PASSTHROUGH_EXCEPTIONS.delete(SystemExit)
| ruby | MIT | 022de9676b2912b90d3b21f1727680d81ebc1e5d | 2026-01-04T17:57:35.186613Z | false |
denisdefreyne/cri | https://github.com/denisdefreyne/cri/blob/022de9676b2912b90d3b21f1727680d81ebc1e5d/test/test_command.rb | test/test_command.rb | # frozen_string_literal: true
require 'helper'
module Cri
class CommandTestCase < Cri::TestCase
def simple_cmd
Cri::Command.define do
name 'moo'
usage 'moo [options] arg1 arg2 ...'
summary 'does stuff'
description 'This command does a lot of stuff.'
option :a, :aaa, 'opt a', argument: :optional do |value, cmd|
$stdout.puts "#{cmd.name}:#{value}"
end
required :b, :bbb, 'opt b'
optional :c, :ccc, 'opt c'
flag :d, :ddd, 'opt d'
forbidden :e, :eee, 'opt e'
required :t, :transform, 'opt t', transform: method(:Integer)
run do |opts, args, c|
$stdout.puts "Awesome #{c.name}!"
$stdout.puts args.join(',')
opts_strings = []
opts.each_pair { |k, v| opts_strings << "#{k}=#{v}" }
$stdout.puts opts_strings.sort.join(',')
end
end
end
def bare_cmd
Cri::Command.define do
name 'moo'
run do |_opts, _args|
end
end
end
def nested_cmd
super_cmd = Cri::Command.define do
name 'super'
usage 'super [command] [options] [arguments]'
summary 'does super stuff'
description 'This command does super stuff.'
option :a, :aaa, 'opt a', argument: :optional do |value, cmd|
$stdout.puts "#{cmd.name}:#{value}"
end
required :b, :bbb, 'opt b'
optional :c, :ccc, 'opt c'
flag :d, :ddd, 'opt d'
forbidden :e, :eee, 'opt e'
end
super_cmd.define_command do
name 'sub'
aliases 'sup'
usage 'sub [options]'
summary 'does subby stuff'
description 'This command does subby stuff.'
option :m, :mmm, 'opt m', argument: :optional
required :n, :nnn, 'opt n'
optional :o, :ooo, 'opt o'
flag :p, :ppp, 'opt p'
forbidden :q, :qqq, 'opt q'
run do |opts, args|
$stdout.puts 'Sub-awesome!'
$stdout.puts args.join(',')
opts_strings = []
opts.each_pair { |k, v| opts_strings << "#{k}=#{v}" }
$stdout.puts opts_strings.join(',')
end
end
super_cmd.define_command do
name 'sink'
usage 'sink thing_to_sink'
summary 'sinks stuff'
description 'Sinks stuff (like ships and the like).'
run do |_opts, _args|
end
end
super_cmd
end
def nested_cmd_with_run_block
super_cmd = Cri::Command.define do
name 'super'
usage 'super [command] [options] [arguments]'
summary 'does super stuff'
description 'This command does super stuff.'
run do |_opts, _args|
$stdout.puts 'super'
end
end
super_cmd.define_command do
name 'sub'
aliases 'sup'
usage 'sub [options]'
summary 'does subby stuff'
description 'This command does subby stuff.'
run do |_opts, _args|
$stdout.puts 'sub'
end
end
super_cmd
end
def test_invoke_simple_without_opts_or_args
out, err = capture_io_while do
simple_cmd.run(%w[])
end
assert_equal ['Awesome moo!', '', ''], lines(out)
assert_equal [], lines(err)
end
def test_invoke_simple_with_args
out, err = capture_io_while do
simple_cmd.run(%w[abc xyz])
end
assert_equal ['Awesome moo!', 'abc,xyz', ''], lines(out)
assert_equal [], lines(err)
end
def test_invoke_simple_with_opts
out, err = capture_io_while do
simple_cmd.run(%w[-c -b x])
end
assert_equal ['Awesome moo!', '', 'bbb=x,ccc=true'], lines(out)
assert_equal [], lines(err)
end
def test_invoke_simple_with_missing_opt_arg
out, err = capture_io_while do
err = assert_raises SystemExit do
simple_cmd.run(%w[-b])
end
assert_equal 1, err.status
end
assert_equal [], lines(out)
assert_equal ['moo: option requires an argument -- b'], lines(err)
end
def test_invoke_simple_with_missing_opt_arg_no_exit
out, err = capture_io_while do
simple_cmd.run(%w[-b], {}, hard_exit: false)
end
assert_equal [], lines(out)
assert_equal ['moo: option requires an argument -- b'], lines(err)
end
def test_invoke_simple_with_illegal_opt
out, err = capture_io_while do
err = assert_raises SystemExit do
simple_cmd.run(%w[-z])
end
assert_equal 1, err.status
end
assert_equal [], lines(out)
assert_equal ['moo: unrecognised option -- z'], lines(err)
end
def test_invoke_simple_with_illegal_opt_no_exit
out, err = capture_io_while do
simple_cmd.run(%w[-z], {}, hard_exit: false)
end
assert_equal [], lines(out)
assert_equal ['moo: unrecognised option -- z'], lines(err)
end
def test_invoke_simple_with_invalid_value_for_opt
out, err = capture_io_while do
err = assert_raises SystemExit do
simple_cmd.run(%w[-t nope])
end
assert_equal 1, err.status
end
assert_equal [], lines(out)
assert_equal ['moo: invalid value "nope" for --transform option'], lines(err)
end
def test_invoke_simple_with_invalid_value_for_opt_no_exit
out, err = capture_io_while do
simple_cmd.run(%w[-t nope], {}, hard_exit: false)
end
assert_equal [], lines(out)
assert_equal ['moo: invalid value "nope" for --transform option'], lines(err)
end
def test_invoke_simple_with_opt_with_block
out, err = capture_io_while do
simple_cmd.run(%w[-a 123])
end
assert_equal ['moo:123', 'Awesome moo!', '', 'aaa=123'], lines(out)
assert_equal [], lines(err)
end
def test_invoke_nested_without_opts_or_args
out, err = capture_io_while do
err = assert_raises SystemExit do
nested_cmd.run(%w[])
end
assert_equal 1, err.status
end
assert_equal [], lines(out)
assert_equal ['super: no command given'], lines(err)
end
def test_invoke_nested_without_opts_or_args_no_exit
out, err = capture_io_while do
nested_cmd.run(%w[], {}, hard_exit: false)
end
assert_equal [], lines(out)
assert_equal ['super: no command given'], lines(err)
end
def test_invoke_nested_with_correct_command_name
out, err = capture_io_while do
nested_cmd.run(%w[sub])
end
assert_equal ['Sub-awesome!', '', ''], lines(out)
assert_equal [], lines(err)
end
def test_invoke_nested_with_incorrect_command_name
out, err = capture_io_while do
err = assert_raises SystemExit do
nested_cmd.run(%w[oogabooga])
end
assert_equal 1, err.status
end
assert_equal [], lines(out)
assert_equal ["super: unknown command 'oogabooga'"], lines(err)
end
def test_invoke_nested_with_incorrect_command_name_no_exit
out, err = capture_io_while do
nested_cmd.run(%w[oogabooga], {}, hard_exit: false)
end
assert_equal [], lines(out)
assert_equal ["super: unknown command 'oogabooga'"], lines(err)
end
def test_invoke_nested_with_ambiguous_command_name
out, err = capture_io_while do
err = assert_raises SystemExit do
nested_cmd.run(%w[s])
end
assert_equal 1, err.status
end
assert_equal [], lines(out)
assert_equal ["super: 's' is ambiguous:", ' sink sub'], lines(err)
end
def test_invoke_nested_with_ambiguous_command_name_no_exit
out, err = capture_io_while do
nested_cmd.run(%w[s], {}, hard_exit: false)
end
assert_equal [], lines(out)
assert_equal ["super: 's' is ambiguous:", ' sink sub'], lines(err)
end
def test_invoke_nested_with_alias
out, err = capture_io_while do
nested_cmd.run(%w[sup])
end
assert_equal ['Sub-awesome!', '', ''], lines(out)
assert_equal [], lines(err)
end
def test_invoke_nested_with_options_before_command
out, err = capture_io_while do
nested_cmd.run(%w[-a 666 sub])
end
assert_equal ['super:666', 'Sub-awesome!', '', 'aaa=666'], lines(out)
assert_equal [], lines(err)
end
def test_invoke_nested_with_run_block
out, err = capture_io_while do
nested_cmd_with_run_block.run(%w[])
end
assert_equal ['super'], lines(out)
assert_equal [], lines(err)
out, err = capture_io_while do
nested_cmd_with_run_block.run(%w[sub])
end
assert_equal ['sub'], lines(out)
assert_equal [], lines(err)
end
def test_help_nested
def $stdout.tty?
true
end
help = nested_cmd.subcommands.find { |cmd| cmd.name == 'sub' }.help
assert help.include?("USAGE\e[0m\e[0m\n \e[32msuper\e[0m \e[32msub\e[0m [options]\n")
end
def test_help_with_and_without_colors
def $stdout.tty?
true
end
help_on_tty = simple_cmd.help
def $stdout.tty?
false
end
help_not_on_tty = simple_cmd.help
assert_includes help_on_tty, "\e[31mUSAGE\e[0m\e[0m\n \e[32mmoo"
assert_includes help_not_on_tty, "USAGE\n moo"
end
def test_help_for_bare_cmd
bare_cmd.help
end
def test_help_with_optional_options
def $stdout.tty?
true
end
cmd = Cri::Command.define do
name 'build'
flag :s, nil, 'short'
flag nil, :long, 'long'
end
help = cmd.help
assert_match(/--long.*-s/m, help)
assert_match(/^ \e\[33m--long\e\[0m long$/, help)
assert_match(/^ \e\[33m-s\e\[0m short$/, help)
end
def test_help_with_different_option_types_short_and_long
def $stdout.tty?
true
end
cmd = Cri::Command.define do
name 'build'
required :r, :required, 'required value'
flag :f, :flag, 'forbidden value'
optional :o, :optional, 'optional value'
end
help = cmd.help
assert_match(/^ \e\[33m-r\e\[0m \e\[33m--required\e\[0m=<value> required value$/, help)
assert_match(/^ \e\[33m-f\e\[0m \e\[33m--flag\e\[0m forbidden value$/, help)
assert_match(/^ \e\[33m-o\e\[0m \e\[33m--optional\e\[0m\[=<value>\] optional value$/, help)
end
def test_help_with_different_option_types_short
def $stdout.tty?
true
end
cmd = Cri::Command.define do
name 'build'
required :r, nil, 'required value'
flag :f, nil, 'forbidden value'
optional :o, nil, 'optional value'
end
help = cmd.help
assert_match(/^ \e\[33m-r\e\[0m <value> required value$/, help)
assert_match(/^ \e\[33m-f\e\[0m forbidden value$/, help)
assert_match(/^ \e\[33m-o\e\[0m \[<value>\] optional value$/, help)
end
def test_help_with_different_option_types_long
def $stdout.tty?
true
end
cmd = Cri::Command.define do
name 'build'
required nil, :required, 'required value'
flag nil, :flag, 'forbidden value'
optional nil, :optional, 'optional value'
end
help = cmd.help
assert_match(/^ \e\[33m--required\e\[0m=<value> required value$/, help)
assert_match(/^ \e\[33m--flag\e\[0m forbidden value$/, help)
assert_match(/^ \e\[33m--optional\e\[0m\[=<value>\] optional value$/, help)
end
def test_help_with_multiple_groups
help = nested_cmd.subcommands.find { |cmd| cmd.name == 'sub' }.help
assert_match(/OPTIONS.*OPTIONS FOR SUPER/m, help)
end
def test_modify_with_block_argument
cmd = Cri::Command.define do |c|
c.name 'build'
end
assert_equal 'build', cmd.name
cmd.modify do |c|
c.name 'compile'
end
assert_equal 'compile', cmd.name
end
def test_help_with_wrapped_options
def $stdout.tty?
true
end
cmd = Cri::Command.define do
name 'build'
flag nil, :longflag, 'This is an option with a very long description that should be wrapped'
end
help = cmd.help
assert_match(/^ \e\[33m--longflag\e\[0m This is an option with a very long description that$/, help)
assert_match(/^ should be wrapped$/, help)
end
def test_modify_without_block_argument
cmd = Cri::Command.define do
name 'build'
end
assert_equal 'build', cmd.name
cmd.modify do
name 'compile'
end
assert_equal 'compile', cmd.name
end
def test_new_basic_root
cmd = Cri::Command.new_basic_root.modify do
name 'mytool'
end
# Check option definitions
assert_equal 1, cmd.option_definitions.size
opt_defn = cmd.option_definitions.to_a[0]
assert_equal 'help', opt_defn.long
# Check subcommand
assert_equal 1, cmd.subcommands.size
assert_equal 'help', cmd.subcommands.to_a[0].name
end
def test_define_with_block_argument
cmd = Cri::Command.define do |c|
c.name 'moo'
end
assert_equal 'moo', cmd.name
end
def test_define_without_block_argument
cmd = Cri::Command.define do
name 'moo'
end
assert_equal 'moo', cmd.name
end
def test_define_subcommand_with_block_argument
cmd = bare_cmd
cmd.define_command do |c|
c.name 'baresub'
end
assert_equal 'baresub', cmd.subcommands.to_a[0].name
end
def test_define_subcommand_without_block_argument
cmd = bare_cmd
cmd.define_command do
name 'baresub'
end
assert_equal 'baresub', cmd.subcommands.to_a[0].name
end
def test_backtrace_includes_filename
error = assert_raises RuntimeError do
Cri::Command.define('raise "boom"', 'mycommand.rb')
end
assert_match(/mycommand.rb/, error.backtrace.join("\n"))
end
def test_hidden_commands_single
cmd = nested_cmd
subcmd = simple_cmd
cmd.add_command subcmd
subcmd.modify do |c|
c.name 'old-and-deprecated'
c.summary 'does stuff the ancient, totally deprecated way'
c.be_hidden
end
refute cmd.help.include?('hidden commands omitted')
assert cmd.help.include?('hidden command omitted')
refute cmd.help.include?('old-and-deprecated')
refute cmd.help(verbose: true).include?('hidden commands omitted')
refute cmd.help(verbose: true).include?('hidden command omitted')
assert cmd.help(verbose: true).include?('old-and-deprecated')
end
def test_hidden_commands_multiple
cmd = nested_cmd
subcmd = simple_cmd
cmd.add_command subcmd
subcmd.modify do |c|
c.name 'first'
c.summary 'does stuff first'
end
subcmd = simple_cmd
cmd.add_command subcmd
subcmd.modify do |c|
c.name 'old-and-deprecated'
c.summary 'does stuff the old, deprecated way'
c.be_hidden
end
subcmd = simple_cmd
cmd.add_command subcmd
subcmd.modify do |c|
c.name 'ancient-and-deprecated'
c.summary 'does stuff the ancient, reallydeprecated way'
c.be_hidden
end
assert cmd.help.include?('hidden commands omitted')
refute cmd.help.include?('hidden command omitted')
refute cmd.help.include?('old-and-deprecated')
refute cmd.help.include?('ancient-and-deprecated')
refute cmd.help(verbose: true).include?('hidden commands omitted')
refute cmd.help(verbose: true).include?('hidden command omitted')
assert cmd.help(verbose: true).include?('old-and-deprecated')
assert cmd.help(verbose: true).include?('ancient-and-deprecated')
pattern = /ancient-and-deprecated.*first.*old-and-deprecated/m
assert_match(pattern, cmd.help(verbose: true))
end
def test_run_with_raw_args
cmd = Cri::Command.define do
name 'moo'
run do |_opts, args|
puts "args=#{args.join(',')}"
end
end
out, _err = capture_io_while do
cmd.run(%w[foo -- bar])
end
assert_equal "args=foo,bar\n", out
end
def test_run_without_block
cmd = Cri::Command.define do
name 'moo'
end
assert_raises(Cri::NotImplementedError) do
cmd.run([])
end
end
def test_runner_with_raw_args
cmd = Cri::Command.define do
name 'moo'
runner(Class.new(Cri::CommandRunner) do
def run
puts "args=#{arguments.join(',')}"
end
end)
end
out, _err = capture_io_while do
cmd.run(%w[foo -- bar])
end
assert_equal "args=foo,bar\n", out
end
def test_compare
foo = Cri::Command.define { name 'foo' }
bar = Cri::Command.define { name 'bar' }
qux = Cri::Command.define { name 'qux' }
assert_equal [bar, foo, qux], [foo, bar, qux].sort
end
def test_default_subcommand
subcommand = Cri::Command.define do
name 'sub'
run do |_opts, _args, _c|
$stdout.puts 'I am the subcommand!'
end
end
cmd = Cri::Command.define do
name 'super'
default_subcommand 'sub'
subcommand subcommand
end
out, _err = capture_io_while do
cmd.run([])
end
assert_equal "I am the subcommand!\n", out
end
def test_skip_option_parsing
command = Cri::Command.define do
name 'super'
skip_option_parsing
run do |_opts, args, _c|
puts "args=#{args.join(',')}"
end
end
out, _err = capture_io_while do
command.run(['--test', '-a', 'arg'])
end
assert_equal "args=--test,-a,arg\n", out
end
def test_subcommand_skip_option_parsing
super_cmd = Cri::Command.define do
name 'super'
option :a, :aaa, 'opt a', argument: :optional
end
super_cmd.define_command do
name 'sub'
skip_option_parsing
run do |opts, args, _c|
puts "opts=#{opts.inspect} args=#{args.join(',')}"
end
end
out, _err = capture_io_while do
super_cmd.run(['--aaa', 'test', 'sub', '--test', 'value'])
end
expected_aaa_test = { aaa: 'test' }.inspect
assert_equal "opts=#{expected_aaa_test} args=--test,value\n", out
end
def test_wrong_number_of_args
cmd = Cri::Command.define do
name 'publish'
param :filename
end
out, err = capture_io_while do
err = assert_raises SystemExit do
cmd.run([])
end
assert_equal 1, err.status
end
assert_equal [], lines(out)
assert_equal ['publish: incorrect number of arguments given: expected 1, but got 0'], lines(err)
end
def test_no_params_zero_args
dsl = Cri::CommandDSL.new
dsl.instance_eval do
name 'moo'
usage 'dunno whatever'
summary 'does stuff'
description 'This command does a lot of stuff.'
no_params
run do |_opts, args|
end
end
command = dsl.command
command.run([])
end
def test_no_params_one_arg
dsl = Cri::CommandDSL.new
dsl.instance_eval do
name 'moo'
usage 'dunno whatever'
summary 'does stuff'
description 'This command does a lot of stuff.'
no_params
run do |_opts, args|
end
end
command = dsl.command
out, err = capture_io_while do
err = assert_raises SystemExit do
command.run(['a'])
end
assert_equal 1, err.status
end
assert_equal [], lines(out)
assert_equal ['moo: incorrect number of arguments given: expected 0, but got 1'], lines(err)
end
def test_load_file
Dir.mktmpdir('foo') do |dir|
filename = "#{dir}/moo.rb"
File.write(filename, <<~CMD)
name 'moo'
usage 'dunno whatever'
summary 'does stuff'
description 'This command does a lot of stuff.'
no_params
run do |_opts, args|
end
CMD
cmd = Cri::Command.load_file(filename)
assert_equal('moo', cmd.name)
end
end
def test_load_file_infer_name_false
Dir.mktmpdir('foo') do |dir|
filename = "#{dir}/moo.rb"
File.write(filename, <<~CMD)
usage 'dunno whatever'
summary 'does stuff'
description 'This command does a lot of stuff.'
no_params
run do |_opts, args|
end
CMD
cmd = Cri::Command.load_file(filename)
assert_equal(nil, cmd.name)
end
end
def test_load_file_infer_name
Dir.mktmpdir('foo') do |dir|
filename = "#{dir}/moo.rb"
File.write(filename, <<~CMD)
usage 'dunno whatever'
summary 'does stuff'
description 'This command does a lot of stuff.'
no_params
run do |_opts, args|
end
CMD
cmd = Cri::Command.load_file(filename, infer_name: true)
assert_equal('moo', cmd.name)
end
end
def test_load_file_infer_name_double
Dir.mktmpdir('foo') do |dir|
filename = "#{dir}/moo.rb"
File.write(filename, <<~CMD)
name 'oink'
usage 'dunno whatever'
summary 'does stuff'
description 'This command does a lot of stuff.'
no_params
run do |_opts, args|
end
CMD
cmd = Cri::Command.load_file(filename, infer_name: true)
assert_equal('moo', cmd.name)
end
end
def test_required_args_with_dash_h
dsl = Cri::CommandDSL.new
dsl.instance_eval do
name 'moo'
usage 'dunno whatever'
summary 'does stuff'
description 'This command does a lot of stuff.'
param :foo
option :h, :help, 'show help' do
$helped = true
exit 0
end
end
command = dsl.command
$helped = false
out, err = capture_io_while do
assert_raises SystemExit do
command.run(['-h'])
end
end
assert $helped
assert_equal [], lines(out)
assert_equal [], lines(err)
end
def test_propagate_options_two_levels_down
cmd_a = Cri::Command.define do
name 'a'
flag :t, :test, 'test'
end
cmd_b = cmd_a.define_command('b') do
end
cmd_b.define_command('c') do
run do |opts, _args|
puts "test? #{opts[:test].inspect}!"
end
end
# test -t last
out, err = capture_io_while do
cmd_a.run(%w[b c -t])
end
assert_equal ['test? true!'], lines(out)
assert_equal [], lines(err)
# test -t mid
out, err = capture_io_while do
cmd_a.run(%w[b -t c])
end
assert_equal ['test? true!'], lines(out)
assert_equal [], lines(err)
# test -t first
out, err = capture_io_while do
cmd_a.run(%w[-t b c])
end
assert_equal ['test? true!'], lines(out)
assert_equal [], lines(err)
end
def test_flag_defaults_to_false
cmd = Cri::Command.define do
name 'a'
option :f, :force2, 'push with force', argument: :forbidden
run do |opts, _args, _cmd|
puts "Force? #{opts[:force2].inspect}! Key present? #{opts.key?(:force2)}!"
end
end
out, err = capture_io_while do
cmd.run(%w[])
end
assert_equal ['Force? false! Key present? false!'], lines(out)
assert_equal [], lines(err)
end
def test_required_option_defaults_to_given_value
cmd = Cri::Command.define do
name 'a'
option :a, :animal, 'specify animal', argument: :required, default: 'cow'
run do |opts, _args, _cmd|
puts "Animal = #{opts[:animal]}! Key present? #{opts.key?(:animal)}!"
end
end
out, err = capture_io_while do
cmd.run(%w[])
end
assert_equal ['Animal = cow! Key present? false!'], lines(out)
assert_equal [], lines(err)
end
def test_optional_option_defaults_to_given_value
cmd = Cri::Command.define do
name 'a'
option :a, :animal, 'specify animal', argument: :optional, default: 'cow'
run do |opts, _args, _cmd|
puts "Animal = #{opts[:animal]}"
end
end
out, err = capture_io_while do
cmd.run(%w[])
end
assert_equal ['Animal = cow'], lines(out)
assert_equal [], lines(err)
end
def test_required_option_defaults_to_given_value_with_transform
cmd = Cri::Command.define do
name 'a'
option :a, :animal, 'specify animal', argument: :required, transform: lambda(&:upcase), default: 'cow'
run do |opts, _args, _cmd|
puts "Animal = #{opts[:animal]}"
end
end
out, err = capture_io_while do
cmd.run(%w[])
end
assert_equal ['Animal = cow'], lines(out)
assert_equal [], lines(err)
end
def test_option_definitions_are_not_shared_across_commands
root_cmd = Cri::Command.define do
name 'root'
option :r, :rrr, 'Rrr!', argument: :required
end
subcmd_a = root_cmd.define_command do
name 'a'
option :a, :aaa, 'Aaa!', argument: :required
run do |_opts, _args, cmd|
puts cmd.all_opt_defns.map(&:long).sort.join(',')
end
end
subcmd_b = root_cmd.define_command do
name 'b'
option :b, :bbb, 'Bbb!', argument: :required
run do |_opts, _args, cmd|
puts cmd.all_opt_defns.map(&:long).sort.join(',')
end
end
out, err = capture_io_while do
subcmd_a.run(%w[])
end
assert_equal ['aaa,rrr'], lines(out)
assert_equal [], lines(err)
out, err = capture_io_while do
subcmd_b.run(%w[])
end
assert_equal ['bbb,rrr'], lines(out)
assert_equal [], lines(err)
end
end
end
| ruby | MIT | 022de9676b2912b90d3b21f1727680d81ebc1e5d | 2026-01-04T17:57:35.186613Z | false |
denisdefreyne/cri | https://github.com/denisdefreyne/cri/blob/022de9676b2912b90d3b21f1727680d81ebc1e5d/test/test_string_formatter.rb | test/test_string_formatter.rb | # frozen_string_literal: true
require 'helper'
module Cri
class CoreExtTestCase < Cri::TestCase
def formatter
Cri::StringFormatter.new
end
def test_string_to_paragraphs
original = "Lorem ipsum dolor sit amet,\nconsectetur adipisicing.\n\n" \
"Sed do eiusmod\ntempor incididunt ut labore."
expected = ['Lorem ipsum dolor sit amet, consectetur adipisicing.',
'Sed do eiusmod tempor incididunt ut labore.']
actual = formatter.to_paragraphs(original)
assert_equal expected, actual
end
def test_string_wrap_and_indent_without_indent
original = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, ' \
'sed do eiusmod tempor incididunt ut labore et dolore ' \
'magna aliqua.'
expected = "Lorem ipsum dolor sit amet, consectetur\n" \
"adipisicing elit, sed do eiusmod tempor\n" \
"incididunt ut labore et dolore magna\n" \
'aliqua.'
actual = formatter.wrap_and_indent(original, 40, 0)
assert_equal expected, actual
end
def test_string_wrap_and_indent_with_indent
original = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, ' \
'sed do eiusmod tempor incididunt ut labore et dolore ' \
'magna aliqua.'
expected = " Lorem ipsum dolor sit amet,\n" \
" consectetur adipisicing elit,\n" \
" sed do eiusmod tempor\n" \
" incididunt ut labore et dolore\n" \
' magna aliqua.'
actual = formatter.wrap_and_indent(original, 36, 4)
assert_equal expected, actual
end
def test_string_wrap_and_indent_excluding_first_line
original = 'Lorem ipsum dolor sit amet, consectetur adipisicing ' \
'elit, sed do eiusmod tempor incididunt ut labore et dolore ' \
'magna aliqua.'
expected = "Lorem ipsum dolor sit amet,\n" \
" consectetur adipisicing elit,\n" \
" sed do eiusmod tempor\n" \
" incididunt ut labore et dolore\n" \
' magna aliqua.'
actual = formatter.wrap_and_indent(original, 36, 4, true)
assert_equal expected, actual
end
def test_string_wrap_and_indent_with_large_indent
original = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, ' \
'sed do eiusmod tempor incididunt ut labore et dolore ' \
'magna aliqua.'
expected = " Lorem ipsum\n" \
" dolor sit\n" \
" amet,\n" \
" consectetur\n" \
" adipisicing\n" \
" elit, sed do\n" \
" eiusmod\n" \
" tempor\n" \
" incididunt ut\n" \
" labore et\n" \
" dolore magna\n" \
' aliqua.'
actual = formatter.wrap_and_indent(original, 44, 30)
assert_equal expected, actual
end
def test_string_wrap_and_indent_with_multiple_lines
original = "Lorem ipsum dolor sit\namet, consectetur adipisicing elit, " \
"sed do\neiusmod tempor incididunt ut\nlabore et dolore " \
"magna\naliqua."
expected = " Lorem ipsum dolor sit amet,\n" \
" consectetur adipisicing elit,\n" \
" sed do eiusmod tempor\n" \
" incididunt ut labore et dolore\n" \
' magna aliqua.'
actual = formatter.wrap_and_indent(original, 36, 4)
assert_equal expected, actual
end
end
end
| ruby | MIT | 022de9676b2912b90d3b21f1727680d81ebc1e5d | 2026-01-04T17:57:35.186613Z | false |
denisdefreyne/cri | https://github.com/denisdefreyne/cri/blob/022de9676b2912b90d3b21f1727680d81ebc1e5d/test/test_help_renderer.rb | test/test_help_renderer.rb | # frozen_string_literal: true
require 'helper'
module Cri
class HelpRendererTestCase < Cri::TestCase
# NOTE: Additional test cases are in test_command.rb
def help_for(cmd)
io = StringIO.new
Cri::HelpRenderer.new(cmd, io: io).render
end
def test_simple
expected = <<~HELP
NAME
help - show help
USAGE
help [command_name]
DESCRIPTION
Show help for the given command, or show general help. When no command is
given, a list of available commands is displayed, as well as a list of
global command-line options. When a command is given, a command
description, as well as command-specific command-line options, are shown.
OPTIONS
-v --verbose show more detailed help
HELP
cmd = Cri::Command.new_basic_help
assert_equal(expected, help_for(cmd))
end
def test_with_defaults
cmd = Cri::Command.define do
name 'build'
optional nil, :'with-animal', 'Add animal', default: 'giraffe'
end
help = help_for(cmd)
assert_match(/^ --with-animal\[=<value>\] Add animal \(default: giraffe\)$/, help)
end
def test_with_summary
cmd = Cri::Command.define do
name 'build'
summary 'do some buildage'
optional nil, :'with-animal', 'Add animal', default: 'giraffe'
end
help = help_for(cmd)
assert_match(/^NAME\n build - do some buildage\n$/, help)
end
def test_without_summary
cmd = Cri::Command.define do
name 'build'
optional nil, :'with-animal', 'Add animal', default: 'giraffe'
end
help = help_for(cmd)
assert_match(/^NAME\n build\n$/, help)
end
end
end
| ruby | MIT | 022de9676b2912b90d3b21f1727680d81ebc1e5d | 2026-01-04T17:57:35.186613Z | false |
denisdefreyne/cri | https://github.com/denisdefreyne/cri/blob/022de9676b2912b90d3b21f1727680d81ebc1e5d/test/test_basic_root.rb | test/test_basic_root.rb | # frozen_string_literal: true
require 'helper'
module Cri
class BasicRootTestCase < Cri::TestCase
def test_run_with_help
cmd = Cri::Command.new_basic_root
stdout, _stderr = capture_io_while do
err = assert_raises SystemExit do
cmd.run(%w[-h])
end
assert_equal 0, err.status
end
assert stdout =~ /COMMANDS.*\n.*help.*show help/
end
def test_run_with_help_no_exit
cmd = Cri::Command.new_basic_root
stdout, _stderr = capture_io_while do
cmd.run(%w[-h], {}, hard_exit: false)
end
assert stdout =~ /COMMANDS.*\n.*help.*show help/
end
end
end
| ruby | MIT | 022de9676b2912b90d3b21f1727680d81ebc1e5d | 2026-01-04T17:57:35.186613Z | false |
denisdefreyne/cri | https://github.com/denisdefreyne/cri/blob/022de9676b2912b90d3b21f1727680d81ebc1e5d/test/test_command_dsl.rb | test/test_command_dsl.rb | # frozen_string_literal: true
require 'helper'
module Cri
class CommandDSLTestCase < Cri::TestCase
def test_create_command
# Define
dsl = Cri::CommandDSL.new
dsl.instance_eval do
name 'moo'
usage 'dunno whatever'
summary 'does stuff'
description 'This command does a lot of stuff.'
option :a, :aaa, 'opt a', argument: :optional, multiple: true
required :b, :bbb, 'opt b'
optional :c, :ccc, 'opt c'
flag :d, :ddd, 'opt d'
forbidden :e, :eee, 'opt e'
flag :f, :fff, 'opt f', hidden: true
run do |_opts, _args|
$did_it_work = :probably
end
end
command = dsl.command
# Run
$did_it_work = :sadly_not
command.run(%w[-a x -b y -c -d -e])
assert_equal :probably, $did_it_work
# Check
assert_equal 'moo', command.name
assert_equal 'dunno whatever', command.usage
assert_equal 'does stuff', command.summary
assert_equal 'This command does a lot of stuff.', command.description
# Check options
expected_option_definitions =
Set.new(
[
{ short: 'a', long: 'aaa', desc: 'opt a', argument: :optional, multiple: true, hidden: false, block: nil, default: nil, transform: nil },
{ short: 'b', long: 'bbb', desc: 'opt b', argument: :required, multiple: false, hidden: false, block: nil, default: nil, transform: nil },
{ short: 'c', long: 'ccc', desc: 'opt c', argument: :optional, multiple: false, hidden: false, block: nil, default: nil, transform: nil },
{ short: 'd', long: 'ddd', desc: 'opt d', argument: :forbidden, multiple: false, hidden: false, block: nil, default: false, transform: nil },
{ short: 'e', long: 'eee', desc: 'opt e', argument: :forbidden, multiple: false, hidden: false, block: nil, default: false, transform: nil },
{ short: 'f', long: 'fff', desc: 'opt f', argument: :forbidden, multiple: false, hidden: true, block: nil, default: false, transform: nil },
],
)
actual_option_definitions = Set.new(command.option_definitions.map(&:to_h))
assert_equal expected_option_definitions, actual_option_definitions
end
def test_optional_options
# Define
dsl = Cri::CommandDSL.new
dsl.instance_eval do
name 'moo'
usage 'dunno whatever'
summary 'does stuff'
description 'This command does a lot of stuff.'
flag :s, nil, 'short'
flag nil, :long, 'long'
run do |_opts, _args|
$did_it_work = :probably
end
end
command = dsl.command
# Run
$did_it_work = :sadly_not
command.run(%w[-s --long])
assert_equal :probably, $did_it_work
# Check options
expected_option_definitions =
Set.new(
[
{ short: 's', long: nil, desc: 'short', argument: :forbidden, multiple: false, hidden: false, block: nil, default: false, transform: nil },
{ short: nil, long: 'long', desc: 'long', argument: :forbidden, multiple: false, hidden: false, block: nil, default: false, transform: nil },
],
)
actual_option_definitions = Set.new(command.option_definitions.map(&:to_h))
assert_equal expected_option_definitions, actual_option_definitions
end
def test_multiple
# Define
dsl = Cri::CommandDSL.new
dsl.instance_eval do
flag :f, :flag, 'flag', multiple: true
required :r, :required, 'req', multiple: true
optional :o, :optional, 'opt', multiple: true
run { |_opts, _args| }
end
command = dsl.command
# Check options
expected_option_definitions =
Set.new(
[
{ short: 'f', long: 'flag', desc: 'flag', argument: :forbidden, multiple: true, hidden: false, block: nil, default: false, transform: nil },
{ short: 'r', long: 'required', desc: 'req', argument: :required, multiple: true, hidden: false, block: nil, default: nil, transform: nil },
{ short: 'o', long: 'optional', desc: 'opt', argument: :optional, multiple: true, hidden: false, block: nil, default: nil, transform: nil },
],
)
actual_option_definitions = Set.new(command.option_definitions.map(&:to_h))
assert_equal expected_option_definitions, actual_option_definitions
end
def test_hidden
# Define
dsl = Cri::CommandDSL.new
dsl.instance_eval do
flag :f, :flag, 'flag', hidden: true
required :r, :required, 'req', hidden: true
optional :o, :optional, 'opt', hidden: true
run { |_opts, _args| }
end
command = dsl.command
# Check options
expected_option_definitions =
Set.new(
[
{ short: 'f', long: 'flag', desc: 'flag', argument: :forbidden, multiple: false, hidden: true, block: nil, default: false, transform: nil },
{ short: 'r', long: 'required', desc: 'req', argument: :required, multiple: false, hidden: true, block: nil, default: nil, transform: nil },
{ short: 'o', long: 'optional', desc: 'opt', argument: :optional, multiple: false, hidden: true, block: nil, default: nil, transform: nil },
],
)
actual_option_definitions = Set.new(command.option_definitions.map(&:to_h))
assert_equal expected_option_definitions, actual_option_definitions
end
def test_raises_on_unrecognized_option
# Define
dsl = Cri::CommandDSL.new
assert_raises ArgumentError do
dsl.option :s, :long, 'desc', unrecognized: true
end
end
def test_required_short_and_long
# Define
dsl = Cri::CommandDSL.new
assert_raises ArgumentError do
dsl.instance_eval do
option nil, nil, 'meh'
end
end
assert_raises ArgumentError do
dsl.instance_eval do
flag nil, nil, 'meh'
end
end
assert_raises ArgumentError do
dsl.instance_eval do
required nil, nil, 'meh'
end
end
assert_raises ArgumentError do
dsl.instance_eval do
optional nil, nil, 'meh'
end
end
end
def test_default_value_with_equiredness_is_required
dsl = Cri::CommandDSL.new
dsl.instance_eval do
required 'a', 'animal', 'Specify animal', default: 'giraffe'
end
end
def test_default_value_errors_when_requiredness_is_forbidden
dsl = Cri::CommandDSL.new
err = assert_raises ArgumentError do
dsl.instance_eval do
flag 'a', 'animal', 'Allow animal', default: 'giraffe'
end
end
assert_equal('a default value cannot be specified for flag options', err.message)
end
def test_subcommand
# Define
dsl = Cri::CommandDSL.new
dsl.instance_eval do
name 'super'
subcommand do |c|
c.name 'sub'
end
end
command = dsl.command
# Check
assert_equal 'super', command.name
assert_equal 1, command.subcommands.size
assert_equal 'sub', command.subcommands.to_a[0].name
end
def test_aliases
# Define
dsl = Cri::CommandDSL.new
dsl.instance_eval do
aliases :moo, :aah
end
command = dsl.command
# Check
assert_equal %w[aah moo], command.aliases.sort
end
def test_run_arity
dsl = Cri::CommandDSL.new
assert_raises ArgumentError do
dsl.instance_eval do
run do |_a, _b, _c, _d, _e|
end
end
end
end
def test_runner
# Define
dsl = Cri::CommandDSL.new
dsl.instance_eval(<<-CMD, __FILE__, __LINE__ + 1)
class Cri::CommandDSLTestCaseCommandRunner < Cri::CommandRunner
def run
$did_it_work = arguments[0]
end
end
runner Cri::CommandDSLTestCaseCommandRunner
CMD
command = dsl.command
# Check
$did_it_work = false
command.run(%w[certainly])
assert_equal 'certainly', $did_it_work
end
def test_params
# Define
dsl = Cri::CommandDSL.new
dsl.instance_eval do
name 'moo'
usage 'dunno whatever'
summary 'does stuff'
description 'This command does a lot of stuff.'
param :foo
param :bar
param :qux
run do |_opts, args|
$args_num = { foo: args[0], bar: args[1], qux: args[2] }
$args_sym = { foo: args[:foo], bar: args[:bar], qux: args[:qux] }
end
end
command = dsl.command
# Run
$args_num = '???'
$args_sym = '???'
command.run(%w[a b c])
assert_equal({ foo: 'a', bar: 'b', qux: 'c' }, $args_num)
assert_equal({ foo: 'a', bar: 'b', qux: 'c' }, $args_sym)
end
def test_params_transform
# Define
dsl = Cri::CommandDSL.new
dsl.instance_eval do
name 'moo'
usage 'dunno whatever'
summary 'does stuff'
description 'This command does a lot of stuff.'
param :foo, transform: lambda(&:upcase)
run do |_opts, args|
$args_num = { foo: args[0] }
$args_sym = { foo: args[:foo] }
end
end
command = dsl.command
# Run
$args_num = '???'
$args_sym = '???'
command.run(%w[abc])
assert_equal({ foo: 'ABC' }, $args_num)
assert_equal({ foo: 'ABC' }, $args_sym)
end
def test_no_params_with_one_param_specified
dsl = Cri::CommandDSL.new
err = assert_raises Cri::CommandDSL::AlreadySpecifiedWithParams do
dsl.instance_eval do
name 'moo'
usage 'dunno whatever'
summary 'does stuff'
description 'This command does a lot of stuff.'
param :oink
no_params
end
end
assert_equal('Attempted to declare the command "moo" as taking no parameters, but some parameters are already declared for this command. Suggestion: remove the #no_params call.', err.message)
end
def test_one_param_with_no_params_specified
dsl = Cri::CommandDSL.new
err = assert_raises Cri::CommandDSL::AlreadySpecifiedAsNoParams do
dsl.instance_eval do
name 'moo'
usage 'dunno whatever'
summary 'does stuff'
description 'This command does a lot of stuff.'
no_params
param :oink
end
end
assert_equal('Attempted to specify a parameter :oink to the command "moo", which is already specified as taking no params. Suggestion: remove the #no_params call.', err.message)
end
end
end
| ruby | MIT | 022de9676b2912b90d3b21f1727680d81ebc1e5d | 2026-01-04T17:57:35.186613Z | false |
denisdefreyne/cri | https://github.com/denisdefreyne/cri/blob/022de9676b2912b90d3b21f1727680d81ebc1e5d/lib/cri.rb | lib/cri.rb | # frozen_string_literal: true
# The namespace for Cri, a library for building easy-to-use command-line tools
# with support for nested commands.
module Cri
# A generic error class for all Cri-specific errors.
class Error < ::StandardError
end
# Error that will be raised when an implementation for a method or command
# is missing. For commands, this may mean that a run block is missing.
class NotImplementedError < Error
end
# Error that will be raised when no help is available because the help
# command has no supercommand for which to show help.
class NoHelpAvailableError < Error
end
end
require 'set'
require_relative 'cri/version'
require_relative 'cri/argument_list'
require_relative 'cri/command'
require_relative 'cri/string_formatter'
require_relative 'cri/command_dsl'
require_relative 'cri/command_runner'
require_relative 'cri/help_renderer'
require_relative 'cri/option_definition'
require_relative 'cri/parser'
require_relative 'cri/param_definition'
require_relative 'cri/platform'
| ruby | MIT | 022de9676b2912b90d3b21f1727680d81ebc1e5d | 2026-01-04T17:57:35.186613Z | false |
denisdefreyne/cri | https://github.com/denisdefreyne/cri/blob/022de9676b2912b90d3b21f1727680d81ebc1e5d/lib/cri/command.rb | lib/cri/command.rb | # frozen_string_literal: true
module Cri
# Cri::Command represents a command that can be executed on the command line.
# It is also used for the command-line tool itself.
class Command
# Delegate used for partitioning the list of arguments and options. This
# delegate will stop the parser as soon as the first argument, i.e. the
# command, is found.
#
# @api private
class ParserPartitioningDelegate
# Returns the last parsed argument, which, in this case, will be the
# first argument, which will be either nil or the command name.
#
# @return [String] The last parsed argument.
attr_reader :last_argument
# Called when an option is parsed.
#
# @param [Symbol] _key The option key (derived from the long format)
#
# @param _value The option value
#
# @param [Cri::Parser] _parser The option parser
#
# @return [void]
def option_added(_key, _value, _parser); end
# Called when an argument is parsed.
#
# @param [String] argument The argument
#
# @param [Cri::Parser] parser The option parser
#
# @return [void]
def argument_added(argument, parser)
@last_argument = argument
parser.stop
end
end
# Signals that Cri should abort execution. Unless otherwise specified using the `hard_exit`
# param, this exception will cause Cri to exit the running process.
#
# @api private
class CriExitException < StandardError
def initialize(is_error:)
super('exit requested')
@is_error = is_error
end
def error?
@is_error
end
end
# @return [Cri::Command, nil] This command’s supercommand, or nil if the
# command has no supercommand
attr_accessor :supercommand
# @return [Set<Cri::Command>] This command’s subcommands
attr_accessor :commands
alias subcommands commands
# @return [Symbol] The name of the default subcommand
attr_accessor :default_subcommand_name
# @return [String] The name
attr_accessor :name
# @return [Array<String>] A list of aliases for this command that can be
# used to invoke this command
attr_accessor :aliases
# @return [String] The short description (“summary”)
attr_accessor :summary
# @return [String] The long description (“description”)
attr_accessor :description
# @return [String] The usage, without the “usage:” prefix and without the
# supercommands’ names.
attr_accessor :usage
# @return [Boolean] true if the command is hidden (e.g. because it is
# deprecated), false otherwise
attr_accessor :hidden
alias hidden? hidden
# @return [Array<Cri::OptionDefinition>] The list of option definitions
attr_accessor :option_definitions
# @return [Array<Hash>] The list of parameter definitions
attr_accessor :parameter_definitions
# @return [Boolean] Whether or not this command has parameters
attr_accessor :explicitly_no_params
alias explicitly_no_params? explicitly_no_params
# @return [Proc] The block that should be executed when invoking this
# command (ignored for commands with subcommands)
attr_accessor :block
# @return [Boolean] true if the command should skip option parsing and
# treat all options as arguments.
attr_accessor :all_opts_as_args
alias all_opts_as_args? all_opts_as_args
# Creates a new command using the DSL. If a string is given, the command
# will be defined using the string; if a block is given, the block will be
# used instead.
#
# If the block has one parameter, the block will be executed in the same
# context with the command DSL as its parameter. If the block has no
# parameters, the block will be executed in the context of the DSL.
#
# @param [String, nil] string The command definition as a string
#
# @param [String, nil] filename The filename corresponding to the string parameter (only useful if a string is given)
#
# @return [Cri::Command] The newly defined command
def self.define(string = nil, filename = nil, &block)
dsl = Cri::CommandDSL.new
if string
args = filename ? [string, filename] : [string]
dsl.instance_eval(*args)
elsif [-1, 0].include? block.arity
dsl.instance_eval(&block)
else
block.call(dsl)
end
dsl.command
end
# Creates a new command using a DSL, from code defined in the given filename.
#
# @param [String] filename The filename that contains the command definition
# as a string
#
# @return [Cri::Command] The newly defined command
def self.load_file(filename, infer_name: false)
code = File.read(filename, encoding: 'UTF-8')
define(code, filename).tap do |cmd|
if infer_name
command_name = File.basename(filename, '.rb')
cmd.modify { name command_name }
end
end
end
# Returns a new command that has support for the `-h`/`--help` option and
# also has a `help` subcommand. It is intended to be modified (adding
# name, summary, description, other subcommands, …)
#
# @return [Cri::Command] A basic root command
def self.new_basic_root
filename = File.dirname(__FILE__) + '/commands/basic_root.rb'
define(File.read(filename))
end
# Returns a new command that implements showing help.
#
# @return [Cri::Command] A basic help command
def self.new_basic_help
filename = File.dirname(__FILE__) + '/commands/basic_help.rb'
define(File.read(filename))
end
def initialize
@aliases = Set.new
@commands = Set.new
@option_definitions = Set.new
@parameter_definitions = []
@explicitly_no_params = false
@default_subcommand_name = nil
end
# Modifies the command using the DSL.
#
# If the block has one parameter, the block will be executed in the same
# context with the command DSL as its parameter. If the block has no
# parameters, the block will be executed in the context of the DSL.
#
# @return [Cri::Command] The command itself
def modify(&block)
dsl = Cri::CommandDSL.new(self)
if [-1, 0].include? block.arity
dsl.instance_eval(&block)
else
yield(dsl)
end
self
end
# @return [Enumerable<Cri::OptionDefinition>] The option definitions for the
# command itself and all its ancestors
def global_option_definitions
res = Set.new
res.merge(option_definitions)
res.merge(supercommand.global_option_definitions) if supercommand
res
end
# Adds the given command as a subcommand to the current command.
#
# @param [Cri::Command] command The command to add as a subcommand
#
# @return [void]
def add_command(command)
@commands << command
command.supercommand = self
end
# Defines a new subcommand for the current command using the DSL.
#
# @param [String, nil] name The name of the subcommand, or nil if no name
# should be set (yet)
#
# @return [Cri::Command] The subcommand
def define_command(name = nil, &block)
# Execute DSL
dsl = Cri::CommandDSL.new
dsl.name name unless name.nil?
if [-1, 0].include? block.arity
dsl.instance_eval(&block)
else
yield(dsl)
end
# Create command
cmd = dsl.command
add_command(cmd)
cmd
end
# Returns the commands that could be referred to with the given name. If
# the result contains more than one command, the name is ambiguous.
#
# @param [String] name The full, partial or aliases name of the command
#
# @return [Array<Cri::Command>] A list of commands matching the given name
def commands_named(name)
# Find by exact name or alias
@commands.each do |cmd|
found = cmd.name == name || cmd.aliases.include?(name)
return [cmd] if found
end
# Find by approximation
@commands.select do |cmd|
cmd.name[0, name.length] == name
end
end
# Returns the command with the given name. This method will display error
# messages and exit in case of an error (unknown or ambiguous command).
#
# The name can be a full command name, a partial command name (e.g. “com”
# for “commit”) or an aliased command name (e.g. “ci” for “commit”).
#
# @param [String] name The full, partial or aliases name of the command
#
# @return [Cri::Command] The command with the given name
def command_named(name, hard_exit: true)
commands = commands_named(name)
if commands.empty?
warn "#{self.name}: unknown command '#{name}'\n"
raise CriExitException.new(is_error: true)
elsif commands.size > 1
warn "#{self.name}: '#{name}' is ambiguous:"
warn " #{commands.map(&:name).sort.join(' ')}"
raise CriExitException.new(is_error: true)
else
commands[0]
end
rescue CriExitException => e
exit(e.error? ? 1 : 0) if hard_exit
end
# Runs the command with the given command-line arguments, possibly invoking
# subcommands and passing on the options and arguments.
#
# @param [Array<String>] opts_and_args A list of unparsed arguments
#
# @param [Hash] parent_opts A hash of options already handled by the
# supercommand
#
# @return [void]
def run(opts_and_args, parent_opts = {}, hard_exit: true)
# Parse up to command name
stuff = partition(opts_and_args)
opts_before_subcmd, subcmd_name, opts_and_args_after_subcmd = *stuff
if subcommands.empty? || (subcmd_name.nil? && !block.nil?)
run_this(opts_and_args, parent_opts)
else
# Handle options
handle_options(opts_before_subcmd)
# Get command
if subcmd_name.nil?
if default_subcommand_name
subcmd_name = default_subcommand_name
else
warn "#{name}: no command given"
raise CriExitException.new(is_error: true)
end
end
subcommand = command_named(subcmd_name, hard_exit: hard_exit)
return if subcommand.nil?
# Run
subcommand.run(opts_and_args_after_subcmd, parent_opts.merge(opts_before_subcmd), hard_exit: hard_exit)
end
rescue CriExitException => e
exit(e.error? ? 1 : 0) if hard_exit
end
# Runs the actual command with the given command-line arguments, not
# invoking any subcommands. If the command does not have an execution
# block, an error ir raised.
#
# @param [Array<String>] opts_and_args A list of unparsed arguments
#
# @param [Hash] parent_opts A hash of options already handled by the
# supercommand
#
# @raise [NotImplementedError] if the command does not have an execution
# block
#
# @return [void]
def run_this(opts_and_args, parent_opts = {})
if all_opts_as_args?
args = opts_and_args
global_opts = parent_opts
else
# Parse
parser = Cri::Parser.new(
opts_and_args,
global_option_definitions,
parameter_definitions,
explicitly_no_params?,
)
handle_errors_while { parser.run }
local_opts = parser.options
global_opts = parent_opts.merge(parser.options)
global_opts = add_defaults(global_opts)
# Handle options
handle_options(local_opts)
args = handle_errors_while { parser.gen_argument_list }
end
# Execute
if block.nil?
raise NotImplementedError,
"No implementation available for '#{name}'"
end
block.call(global_opts, args, self)
end
def all_opt_defns
if supercommand
supercommand.all_opt_defns | option_definitions
else
option_definitions
end
end
# @return [String] The help text for this command
#
# @option params [Boolean] :verbose true if the help output should be
# verbose, false otherwise.
#
# @option params [IO] :io ($stdout) the IO the help text is intended for.
# This influences the decision to enable/disable colored output.
def help(**params)
HelpRenderer.new(self, **params).render
end
# Compares this command's name to the other given command's name.
#
# @param [Cri::Command] other The command to compare with
#
# @return [-1, 0, 1] The result of the comparison between names
#
# @see Object<=>
def <=>(other)
name <=> other.name
end
private
def handle_options(opts)
opts.each_pair do |key, value|
opt_defn = global_option_definitions.find { |o| (o.long || o.short) == key.to_s }
block = opt_defn.block
block&.call(value, self)
end
end
def partition(opts_and_args)
return [{}, opts_and_args.first, opts_and_args] if all_opts_as_args?
# Parse
delegate = Cri::Command::ParserPartitioningDelegate.new
parser = Cri::Parser.new(
opts_and_args,
global_option_definitions,
parameter_definitions,
explicitly_no_params?,
)
parser.delegate = delegate
handle_errors_while { parser.run }
# Extract
[
parser.options,
delegate.last_argument,
parser.unprocessed_arguments_and_options,
]
end
def handle_errors_while
yield
rescue Cri::Parser::IllegalOptionError => e
warn "#{name}: unrecognised option -- #{e}"
raise CriExitException.new(is_error: true)
rescue Cri::Parser::OptionRequiresAnArgumentError => e
warn "#{name}: option requires an argument -- #{e}"
raise CriExitException.new(is_error: true)
rescue Cri::Parser::IllegalOptionValueError => e
warn "#{name}: #{e.message}"
raise CriExitException.new(is_error: true)
rescue Cri::ArgumentList::ArgumentCountMismatchError => e
warn "#{name}: #{e.message}"
raise CriExitException.new(is_error: true)
end
def add_defaults(options)
all_opt_defns_by_key =
all_opt_defns.each_with_object({}) do |opt_defn, hash|
key = (opt_defn.long || opt_defn.short).to_sym
hash[key] = opt_defn
end
new_options = Hash.new do |hash, key|
hash.fetch(key) { all_opt_defns_by_key[key]&.default }
end
options.each do |key, value|
new_options[key] = value
end
new_options
end
end
end
| ruby | MIT | 022de9676b2912b90d3b21f1727680d81ebc1e5d | 2026-01-04T17:57:35.186613Z | false |
denisdefreyne/cri | https://github.com/denisdefreyne/cri/blob/022de9676b2912b90d3b21f1727680d81ebc1e5d/lib/cri/platform.rb | lib/cri/platform.rb | # frozen_string_literal: true
module Cri
# Provides tools to detect platform and environment configuration (e.g. is
# color support available?)
#
# @api private
module Platform
# @return [Boolean] true if the current platform is Windows, false
# otherwise.
def self.windows?
RUBY_PLATFORM =~ /windows|bccwin|cygwin|djgpp|mingw|mswin|wince/i
end
# Checks whether colors can be enabled. For colors to be enabled, the given
# IO should be a TTY, and, when on Windows, ::Win32::Console::ANSI needs to
# be defined.
#
# @return [Boolean] True if colors should be enabled, false otherwise.
def self.color?(io)
if !io.tty?
false
elsif windows?
defined?(::Win32::Console::ANSI)
else
true
end
end
end
end
| ruby | MIT | 022de9676b2912b90d3b21f1727680d81ebc1e5d | 2026-01-04T17:57:35.186613Z | false |
denisdefreyne/cri | https://github.com/denisdefreyne/cri/blob/022de9676b2912b90d3b21f1727680d81ebc1e5d/lib/cri/version.rb | lib/cri/version.rb | # frozen_string_literal: true
module Cri
# The current Cri version.
VERSION = '2.15.12'
end
| ruby | MIT | 022de9676b2912b90d3b21f1727680d81ebc1e5d | 2026-01-04T17:57:35.186613Z | false |
denisdefreyne/cri | https://github.com/denisdefreyne/cri/blob/022de9676b2912b90d3b21f1727680d81ebc1e5d/lib/cri/help_renderer.rb | lib/cri/help_renderer.rb | # frozen_string_literal: true
module Cri
# The {HelpRenderer} class is responsible for generating a string containing
# the help for a given command, intended to be printed on the command line.
class HelpRenderer
# The line width of the help output
LINE_WIDTH = 78
# The indentation of descriptions
DESC_INDENT = 4
# The spacing between an option name and option description
OPT_DESC_SPACING = 6
# Creates a new help renderer for the given command.
#
# @param [Cri::Command] cmd The command to generate the help for
#
# @option params [Boolean] :verbose true if the help output should be
# verbose, false otherwise.
def initialize(cmd, **params)
@cmd = cmd
@is_verbose = params.fetch(:verbose, false)
@io = params.fetch(:io, $stdout)
end
# @return [String] The help text for this command
def render
text = +''
append_summary(text)
append_usage(text)
append_description(text)
append_subcommands(text)
append_options(text)
text
end
private
def fmt
@fmt ||= Cri::StringFormatter.new
end
def append_summary(text)
return if @cmd.name.nil?
text << fmt.format_as_title('name', @io) << "\n"
text << ' ' << fmt.format_as_command(@cmd.name, @io)
if @cmd.summary
text << ' - ' << @cmd.summary
end
text << "\n"
unless @cmd.aliases.empty?
text << ' aliases: ' << @cmd.aliases.map { |a| fmt.format_as_command(a, @io) }.join(' ') << "\n"
end
end
def append_usage(text)
return if @cmd.usage.nil?
path = [@cmd.supercommand]
path.unshift(path[0].supercommand) until path[0].nil?
formatted_usage = @cmd.usage.gsub(/^([^\s]+)/) { |m| fmt.format_as_command(m, @io) }
full_usage = path[1..-1].map { |c| fmt.format_as_command(c.name, @io) + ' ' }.join + formatted_usage
text << "\n"
text << fmt.format_as_title('usage', @io) << "\n"
text << fmt.wrap_and_indent(full_usage, LINE_WIDTH, DESC_INDENT) << "\n"
end
def append_description(text)
return if @cmd.description.nil?
text << "\n"
text << fmt.format_as_title('description', @io) << "\n"
text << (fmt.wrap_and_indent(@cmd.description, LINE_WIDTH, DESC_INDENT) + "\n")
end
def append_subcommands(text)
return if @cmd.subcommands.empty?
text << "\n"
text << fmt.format_as_title(@cmd.supercommand ? 'subcommands' : 'commands', @io)
text << "\n"
shown_subcommands = @cmd.subcommands.select { |c| !c.hidden? || @is_verbose }
length = shown_subcommands.map { |c| fmt.format_as_command(c.name, @io).size }.max
# Command
shown_subcommands.sort_by(&:name).each do |cmd|
text <<
format(
" %<name>-#{length + DESC_INDENT}s %<summary>s\n",
name: fmt.format_as_command(cmd.name, @io),
summary: cmd.summary,
)
end
# Hidden notice
unless @is_verbose
diff = @cmd.subcommands.size - shown_subcommands.size
if diff == 1
text << " (1 hidden command omitted; show it with --verbose)\n"
elsif diff > 1
text << " (#{diff} hidden commands omitted; show them with --verbose)\n"
end
end
end
def length_for_opt_defns(opt_defns)
opt_defns.map do |opt_defn|
string = +''
# Always pretend there is a short option
string << '-X'
if opt_defn.long
string << (' --' + opt_defn.long)
end
case opt_defn.argument
when :required
string << '=<value>'
when :optional
string << '=[<value>]'
end
string.size
end.max
end
def append_options(text)
groups = { 'options' => @cmd.option_definitions }
if @cmd.supercommand
groups["options for #{@cmd.supercommand.name}"] = @cmd.supercommand.global_option_definitions
end
length = length_for_opt_defns(groups.values.inject(&:+))
groups.keys.sort.each do |name|
defs = groups[name]
append_option_group(text, name, defs, length)
end
end
def append_option_group(text, name, defs, length)
return if defs.empty?
text << "\n"
text << fmt.format_as_title(name.to_s, @io)
text << "\n"
ordered_defs = defs.sort_by { |x| x.short || x.long }
ordered_defs.reject(&:hidden).each do |opt_defn|
text << format_opt_defn(opt_defn, length)
desc = opt_defn.desc + (opt_defn.default ? " (default: #{opt_defn.default})" : '')
text << fmt.wrap_and_indent(desc, LINE_WIDTH, length + OPT_DESC_SPACING + DESC_INDENT, true) << "\n"
end
end
def short_value_postfix_for(opt_defn)
value_postfix =
case opt_defn.argument
when :required
'<value>'
when :optional
'[<value>]'
end
if value_postfix
opt_defn.long ? '' : ' ' + value_postfix
else
''
end
end
def long_value_postfix_for(opt_defn)
value_postfix =
case opt_defn.argument
when :required
'=<value>'
when :optional
'[=<value>]'
end
if value_postfix
opt_defn.long ? value_postfix : ''
else
''
end
end
def format_opt_defn(opt_defn, length)
short_value_postfix = short_value_postfix_for(opt_defn)
long_value_postfix = long_value_postfix_for(opt_defn)
opt_text = +''
opt_text_len = 0
if opt_defn.short
opt_text << fmt.format_as_option('-' + opt_defn.short, @io)
opt_text << short_value_postfix
opt_text << ' '
opt_text_len += 1 + opt_defn.short.size + short_value_postfix.size + 1
else
opt_text << ' '
opt_text_len += 3
end
opt_text << fmt.format_as_option('--' + opt_defn.long, @io) if opt_defn.long
opt_text << long_value_postfix
opt_text_len += 2 + opt_defn.long.size if opt_defn.long
opt_text_len += long_value_postfix.size
' ' + opt_text + (' ' * (length + OPT_DESC_SPACING - opt_text_len))
end
end
end
| ruby | MIT | 022de9676b2912b90d3b21f1727680d81ebc1e5d | 2026-01-04T17:57:35.186613Z | false |
denisdefreyne/cri | https://github.com/denisdefreyne/cri/blob/022de9676b2912b90d3b21f1727680d81ebc1e5d/lib/cri/parser.rb | lib/cri/parser.rb | # frozen_string_literal: true
module Cri
# Cri::Parser is used for parsing command-line options and arguments.
class Parser
# Error that will be raised when an unknown option is encountered.
class IllegalOptionError < Cri::Error
end
# Error that will be raised when an option with an invalid or
# non-transformable value is encountered.
class IllegalOptionValueError < Cri::Error
attr_reader :definition
attr_reader :value
def initialize(definition, value)
super("invalid value #{value.inspect} for #{definition.formatted_name} option")
@value = value
@definition = definition
end
end
# Error that will be raised when an option without argument is
# encountered.
class OptionRequiresAnArgumentError < Cri::Error
end
# The delegate to which events will be sent. The following methods will
# be send to the delegate:
#
# * `option_added(key, value, cmd)`
# * `argument_added(argument, cmd)`
#
# @return [#option_added, #argument_added] The delegate
attr_accessor :delegate
# The options that have already been parsed.
#
# If the parser was stopped before it finished, this will not contain all
# options and `unprocessed_arguments_and_options` will contain what is
# left to be processed.
#
# @return [Hash] The already parsed options.
attr_reader :options
# The options and arguments that have not yet been processed. If the
# parser wasn’t stopped (using {#stop}), this list will be empty.
#
# @return [Array] The not yet parsed options and arguments.
attr_reader :unprocessed_arguments_and_options
# Creates a new parser with the given options/arguments and definitions.
#
# @param [Array<String>] arguments_and_options An array containing the
# command-line arguments (will probably be `ARGS` for a root command)
#
# @param [Array<Cri::OptionDefinition>] option_defns An array of option
# definitions
#
# @param [Array<Cri::ParamDefinition>] param_defns An array of parameter
# definitions
def initialize(arguments_and_options, option_defns, param_defns, explicitly_no_params)
@unprocessed_arguments_and_options = arguments_and_options.dup
@option_defns = option_defns
@param_defns = param_defns
@explicitly_no_params = explicitly_no_params
@options = {}
@raw_arguments = []
@running = false
@no_more_options = false
end
# @return [Boolean] true if the parser is running, false otherwise.
def running?
@running
end
# Stops the parser. The parser will finish its current parse cycle but
# will not start parsing new options and/or arguments.
#
# @return [void]
def stop
@running = false
end
# Parses the command-line arguments into options and arguments.
#
# During parsing, two errors can be raised:
#
# @raise IllegalOptionError if an unrecognised option was encountered,
# i.e. an option that is not present in the list of option definitions
#
# @raise OptionRequiresAnArgumentError if an option was found that did not
# have a value, even though this value was required.
#
# @return [Cri::Parser] The option parser self
def run
@running = true
while running?
# Get next item
e = @unprocessed_arguments_and_options.shift
break if e.nil?
if e == '--'
handle_dashdash(e)
elsif e =~ /^--./ && !@no_more_options
handle_dashdash_option(e)
elsif e =~ /^-./ && !@no_more_options
handle_dash_option(e)
else
add_argument(e)
end
end
self
ensure
@running = false
end
# @return [Cri::ArgumentList] The list of arguments that have already been
# parsed, excluding the -- separator.
def gen_argument_list
ArgumentList.new(@raw_arguments, @explicitly_no_params, @param_defns)
end
private
def handle_dashdash(elem)
add_argument(elem)
@no_more_options = true
end
def handle_dashdash_option(elem)
# Get option key, and option value if included
if elem =~ /^--([^=]+)=(.+)$/
option_key = Regexp.last_match[1]
option_value = Regexp.last_match[2]
else
option_key = elem[2..-1]
option_value = nil
end
# Find definition
option_defn = @option_defns.find { |d| d.long == option_key }
raise IllegalOptionError.new(option_key) if option_defn.nil?
if %i[required optional].include?(option_defn.argument)
# Get option value if necessary
if option_value.nil?
option_value = find_option_value(option_defn, option_key)
end
# Store option
add_option(option_defn, option_value)
else
# Store option
add_option(option_defn, true)
end
end
def handle_dash_option(elem)
# Get option keys
option_keys = elem[1..-1].scan(/./)
# For each key
option_keys.each do |option_key|
# Find definition
option_defn = @option_defns.find { |d| d.short == option_key }
raise IllegalOptionError.new(option_key) if option_defn.nil?
if %i[required optional].include?(option_defn.argument)
# Get option value
option_value = find_option_value(option_defn, option_key)
# Store option
add_option(option_defn, option_value)
else
# Store option
add_option(option_defn, true)
end
end
end
def find_option_value(option_defn, option_key)
option_value = @unprocessed_arguments_and_options.shift
if option_value.nil? || option_value =~ /^-/
if option_defn.argument == :optional && option_defn.default
option_value = option_defn.default
elsif option_defn.argument == :required
raise OptionRequiresAnArgumentError.new(option_key)
else
@unprocessed_arguments_and_options.unshift(option_value)
option_value = true
end
end
option_value
end
def add_option(option_defn, value, transform: true)
key = key_for(option_defn)
value = transform ? transform_value(option_defn, value) : value
if option_defn.multiple
options[key] ||= []
options[key] << value
else
options[key] = value
end
delegate&.option_added(key, value, self)
end
def transform_value(option_defn, value)
transformer = option_defn.transform
if transformer
begin
transformer.call(value)
rescue StandardError
raise IllegalOptionValueError.new(option_defn, value)
end
else
value
end
end
def key_for(option_defn)
(option_defn.long || option_defn.short).to_sym
end
def add_argument(value)
@raw_arguments << value
unless value == '--'
delegate&.argument_added(value, self)
end
end
end
end
| ruby | MIT | 022de9676b2912b90d3b21f1727680d81ebc1e5d | 2026-01-04T17:57:35.186613Z | false |
denisdefreyne/cri | https://github.com/denisdefreyne/cri/blob/022de9676b2912b90d3b21f1727680d81ebc1e5d/lib/cri/option_definition.rb | lib/cri/option_definition.rb | # frozen_string_literal: true
module Cri
# The definition of an option.
class OptionDefinition
attr_reader :short
attr_reader :long
attr_reader :desc
attr_reader :argument
attr_reader :multiple
attr_reader :block
attr_reader :hidden
attr_reader :default
attr_reader :transform
def initialize(short:, long:, desc:, argument:, multiple:, block:, hidden:, default:, transform:)
@short = short
@long = long
@desc = desc
@argument = argument
@multiple = multiple
@block = block
@hidden = hidden
@default = default
@transform = transform
if @short.nil? && @long.nil?
raise ArgumentError, 'short and long options cannot both be nil'
end
if @default && @argument == :forbidden
raise ArgumentError, 'a default value cannot be specified for flag options'
end
@default = false if @argument == :forbidden
end
def to_h
{
short: @short,
long: @long,
desc: @desc,
argument: @argument,
multiple: @multiple,
block: @block,
hidden: @hidden,
default: @default,
transform: @transform,
}
end
def formatted_name
@long ? '--' + @long : '-' + @short
end
end
end
| ruby | MIT | 022de9676b2912b90d3b21f1727680d81ebc1e5d | 2026-01-04T17:57:35.186613Z | false |
denisdefreyne/cri | https://github.com/denisdefreyne/cri/blob/022de9676b2912b90d3b21f1727680d81ebc1e5d/lib/cri/param_definition.rb | lib/cri/param_definition.rb | # frozen_string_literal: true
module Cri
# The definition of a parameter.
class ParamDefinition
attr_reader :name
attr_reader :transform
def initialize(name:, transform:)
@name = name
@transform = transform
end
end
end
| ruby | MIT | 022de9676b2912b90d3b21f1727680d81ebc1e5d | 2026-01-04T17:57:35.186613Z | false |
denisdefreyne/cri | https://github.com/denisdefreyne/cri/blob/022de9676b2912b90d3b21f1727680d81ebc1e5d/lib/cri/argument_list.rb | lib/cri/argument_list.rb | # frozen_string_literal: true
module Cri
# A list of arguments, which can be indexed using either a number or a symbol.
class ArgumentList
# Error that will be raised when an incorrect number of arguments is given.
class ArgumentCountMismatchError < Cri::Error
def initialize(expected_count, actual_count)
super("incorrect number of arguments given: expected #{expected_count}, but got #{actual_count}")
end
end
include Enumerable
def initialize(raw_arguments, explicitly_no_params, param_defns)
@raw_arguments = raw_arguments
@explicitly_no_params = explicitly_no_params
@param_defns = param_defns
load
end
def [](key)
case key
when Symbol
@arguments_hash[key]
when Integer
@arguments_array[key]
else
raise ArgumentError, "argument lists can be indexed using a Symbol or an Integer, but not a #{key.class}"
end
end
def each
return to_enum(__method__) unless block_given?
@arguments_array.each { |e| yield(e) }
self
end
def method_missing(sym, *args, &block)
if @arguments_array.respond_to?(sym)
@arguments_array.send(sym, *args, &block)
else
super
end
end
def respond_to_missing?(sym, include_private = false)
@arguments_array.respond_to?(sym) || super
end
def load
@arguments_array = []
@arguments_hash = {}
arguments_array = @raw_arguments.reject { |a| a == '--' }.freeze
if !@explicitly_no_params && @param_defns.empty?
# No parameters defined; ignore
@arguments_array = arguments_array
return
end
if arguments_array.size != @param_defns.size
raise ArgumentCountMismatchError.new(@param_defns.size, arguments_array.size)
end
arguments_array.zip(@param_defns).each do |(arg, param_defn)|
arg = param_defn.transform ? param_defn.transform.call(arg) : arg
@arguments_hash[param_defn.name.to_sym] = arg
@arguments_array << arg
end
end
end
end
| ruby | MIT | 022de9676b2912b90d3b21f1727680d81ebc1e5d | 2026-01-04T17:57:35.186613Z | false |
denisdefreyne/cri | https://github.com/denisdefreyne/cri/blob/022de9676b2912b90d3b21f1727680d81ebc1e5d/lib/cri/command_dsl.rb | lib/cri/command_dsl.rb | # frozen_string_literal: true
module Cri
# The command DSL is a class that is used for building and modifying
# commands.
class CommandDSL
# Error that will be raised when specifying a parameter after the command is
# already declared as taken no params.
class AlreadySpecifiedAsNoParams < Cri::Error
def initialize(param, command)
super("Attempted to specify a parameter #{param.inspect} to the command #{command.name.inspect}, which is already specified as taking no params. Suggestion: remove the #no_params call.")
end
end
# Error that will be raised when declaring the command as taking no
# parameters, when the command is already declared with parameters.
class AlreadySpecifiedWithParams < Cri::Error
def initialize(command)
super("Attempted to declare the command #{command.name.inspect} as taking no parameters, but some parameters are already declared for this command. Suggestion: remove the #no_params call.")
end
end
# @return [Cri::Command] The built command
attr_reader :command
# Creates a new DSL, intended to be used for building a single command. A
# {CommandDSL} instance is not reusable; create a new instance if you want
# to build another command.
#
# @param [Cri::Command, nil] command The command to modify, or nil if a
# new command should be created
def initialize(command = nil)
@command = command || Cri::Command.new
end
# Adds a subcommand to the current command. The command can either be
# given explicitly, or a block can be given that defines the command.
#
# @param [Cri::Command, nil] command The command to add as a subcommand,
# or nil if the block should be used to define the command that will be
# added as a subcommand
#
# @return [void]
def subcommand(command = nil, &block)
if command.nil?
command = Cri::Command.define(&block)
end
@command.add_command(command)
end
# Sets the name of the default subcommand, i.e. the subcommand that will
# be executed if no subcommand is explicitly specified. This is `nil` by
# default, and will typically only be set for the root command.
#
# @param [String, nil] name The name of the default subcommand
#
# @return [void]
def default_subcommand(name)
@command.default_subcommand_name = name
end
# Sets the command name.
#
# @param [String] arg The new command name
#
# @return [void]
def name(arg)
@command.name = arg
end
# Sets the command aliases.
#
# @param [String, Symbol, Array] args The new command aliases
#
# @return [void]
def aliases(*args)
@command.aliases = args.flatten.map(&:to_s)
end
# Sets the command summary.
#
# @param [String] arg The new command summary
#
# @return [void]
def summary(arg)
@command.summary = arg
end
# Sets the command description.
#
# @param [String] arg The new command description
#
# @return [void]
def description(arg)
@command.description = arg
end
# Sets the command usage. The usage should not include the “usage:”
# prefix, nor should it include the command names of the supercommand.
#
# @param [String] arg The new command usage
#
# @return [void]
def usage(arg)
@command.usage = arg
end
# Marks the command as hidden. Hidden commands do not show up in the list of
# subcommands of the parent command, unless --verbose is passed (or
# `:verbose => true` is passed to the {Cri::Command#help} method). This can
# be used to mark commands as deprecated.
#
# @return [void]
def be_hidden
@command.hidden = true
end
# Skips option parsing for the command. Allows option-like arguments to be
# passed in, avoiding the {Cri::Parser} validation.
#
# @return [void]
def skip_option_parsing
@command.all_opts_as_args = true
end
# Adds a new option to the command. If a block is given, it will be
# executed when the option is successfully parsed.
#
# @param [String, Symbol, nil] short The short option name
#
# @param [String, Symbol, nil] long The long option name
#
# @param [String] desc The option description
#
# @option params [:forbidden, :required, :optional] :argument Whether the
# argument is forbidden, required or optional
#
# @option params [Boolean] :multiple Whether or not the option should
# be multi-valued
#
# @option params [Boolean] :hidden Whether or not the option should
# be printed in the help output
#
# @return [void]
def option(short, long, desc,
argument: :forbidden,
multiple: false,
hidden: false,
default: nil,
transform: nil,
&block)
@command.option_definitions << Cri::OptionDefinition.new(
short: short&.to_s,
long: long&.to_s,
desc: desc,
argument: argument,
multiple: multiple,
hidden: hidden,
default: default,
transform: transform,
block: block,
)
end
alias opt option
# Defines a new parameter for the command.
#
# @param [Symbol] name The name of the parameter
def param(name, transform: nil)
if @command.explicitly_no_params?
raise AlreadySpecifiedAsNoParams.new(name, @command)
end
@command.parameter_definitions << Cri::ParamDefinition.new(
name: name,
transform: transform,
)
end
def no_params
if @command.parameter_definitions.any?
raise AlreadySpecifiedWithParams.new(@command)
end
@command.explicitly_no_params = true
end
# Adds a new option with a required argument to the command. If a block is
# given, it will be executed when the option is successfully parsed.
#
# @param [String, Symbol, nil] short The short option name
#
# @param [String, Symbol, nil] long The long option name
#
# @param [String] desc The option description
#
# @option params [Boolean] :multiple Whether or not the option should
# be multi-valued
#
# @option params [Boolean] :hidden Whether or not the option should
# be printed in the help output
#
# @return [void]
#
# @deprecated
#
# @see #option
def required(short, long, desc, **params, &block)
params = params.merge(argument: :required)
option(short, long, desc, **params, &block)
end
# Adds a new option with a forbidden argument to the command. If a block
# is given, it will be executed when the option is successfully parsed.
#
# @param [String, Symbol, nil] short The short option name
#
# @param [String, Symbol, nil] long The long option name
#
# @param [String] desc The option description
#
# @option params [Boolean] :multiple Whether or not the option should
# be multi-valued
#
# @option params [Boolean] :hidden Whether or not the option should
# be printed in the help output
#
# @return [void]
#
# @see #option
def flag(short, long, desc, **params, &block)
params = params.merge(argument: :forbidden)
option(short, long, desc, **params, &block)
end
alias forbidden flag
# Adds a new option with an optional argument to the command. If a block
# is given, it will be executed when the option is successfully parsed.
#
# @param [String, Symbol, nil] short The short option name
#
# @param [String, Symbol, nil] long The long option name
#
# @param [String] desc The option description
#
# @option params [Boolean] :multiple Whether or not the option should
# be multi-valued
#
# @option params [Boolean] :hidden Whether or not the option should
# be printed in the help output
#
# @return [void]
#
# @deprecated
#
# @see #option
def optional(short, long, desc, **params, &block)
params = params.merge(argument: :optional)
option(short, long, desc, **params, &block)
end
# Sets the run block to the given block. The given block should have two
# or three arguments (options, arguments, and optionally the command).
# Calling this will override existing run block or runner declarations
# (using {#run} and {#runner}, respectively).
#
# @yieldparam [Hash<Symbol,Object>] opts A map of option names, as defined
# in the option definitions, onto strings (when single-valued) or arrays
# (when multi-valued)
#
# @yieldparam [Array<String>] args A list of arguments
#
# @return [void]
def run(&block)
unless [2, 3].include?(block.arity)
raise ArgumentError,
'The block given to Cri::Command#run expects two or three args'
end
@command.block = block
end
# Defines the runner class for this command. Calling this will override
# existing run block or runner declarations (using {#run} and {#runner},
# respectively).
#
# @param [Class<CommandRunner>] klass The command runner class (subclass
# of {CommandRunner}) that is used for executing this command.
#
# @return [void]
def runner(klass)
run do |opts, args, cmd|
klass.new(opts, args, cmd).call
end
end
end
end
| ruby | MIT | 022de9676b2912b90d3b21f1727680d81ebc1e5d | 2026-01-04T17:57:35.186613Z | false |
denisdefreyne/cri | https://github.com/denisdefreyne/cri/blob/022de9676b2912b90d3b21f1727680d81ebc1e5d/lib/cri/command_runner.rb | lib/cri/command_runner.rb | # frozen_string_literal: true
module Cri
# A command runner is responsible for the execution of a command. Using it
# is optional, but it is useful for commands whose execution block is large.
class CommandRunner
# @return [Hash] A hash contain the options and their values
attr_reader :options
# @return [Array] The list of arguments
attr_reader :arguments
# @return [Command] The command
attr_reader :command
# Creates a command runner from the given options, arguments and command.
#
# @param [Hash] options A hash contain the options and their values
#
# @param [Array] arguments The list of arguments
#
# @param [Cri::Command] command The Cri command
def initialize(options, arguments, command)
@options = options
@arguments = arguments
@command = command
end
# Runs the command. By default, this simply does the actual execution, but
# subclasses may choose to add error handling around the actual execution.
#
# @return [void]
def call
run
end
# Performs the actual execution of the command.
#
# @return [void]
#
# @abstract
def run
raise NotImplementedError, 'Cri::CommandRunner subclasses must implement #run'
end
end
end
| ruby | MIT | 022de9676b2912b90d3b21f1727680d81ebc1e5d | 2026-01-04T17:57:35.186613Z | false |
denisdefreyne/cri | https://github.com/denisdefreyne/cri/blob/022de9676b2912b90d3b21f1727680d81ebc1e5d/lib/cri/string_formatter.rb | lib/cri/string_formatter.rb | # frozen_string_literal: true
module Cri
# Used for formatting strings (e.g. converting to paragraphs, wrapping,
# formatting as title)
#
# @api private
class StringFormatter
# Extracts individual paragraphs (separated by two newlines).
#
# @param [String] str The string to format
#
# @return [Array<String>] A list of paragraphs in the string
def to_paragraphs(str)
lines = str.scan(/([^\n]+\n|[^\n]*$)/).map { |l| l[0].strip }
paragraphs = [[]]
lines.each do |line|
if line.empty?
paragraphs << []
else
paragraphs.last << line
end
end
paragraphs.reject(&:empty?).map { |p| p.join(' ') }
end
# Word-wraps and indents the string.
#
# @param [String] str The string to format
#
# @param [Number] width The maximal width of each line. This also includes
# indentation, i.e. the actual maximal width of the text is
# `width`-`indentation`.
#
# @param [Number] indentation The number of spaces to indent each line.
#
# @param [Boolean] first_line_already_indented Whether or not the first
# line is already indented
#
# @return [String] The word-wrapped and indented string
def wrap_and_indent(str, width, indentation, first_line_already_indented = false)
indented_width = width - indentation
indent = ' ' * indentation
# Split into paragraphs
paragraphs = to_paragraphs(str)
# Wrap and indent each paragraph
text = paragraphs.map do |paragraph|
# Initialize
lines = []
line = ''
# Split into words
paragraph.split(/\s/).each do |word|
# Begin new line if it's too long
if (line + ' ' + word).length >= indented_width
lines << line
line = ''
end
# Add word to line
line += (line == '' ? '' : ' ') + word
end
lines << line
# Join lines
lines.map { |l| indent + l }.join("\n")
end.join("\n\n")
if first_line_already_indented
text[indentation..-1]
else
text
end
end
# @param [String] str The string to format
#
# @return [String] The string, formatted to be used as a title in a section
# in the help
def format_as_title(str, io)
if Cri::Platform.color?(io)
bold(red(str.upcase))
else
str.upcase
end
end
# @param [String] str The string to format
#
# @return [String] The string, formatted to be used as the name of a command
# in the help
def format_as_command(str, io)
if Cri::Platform.color?(io)
green(str)
else
str
end
end
# @param [String] str The string to format
#
# @return [String] The string, formatted to be used as an option definition
# of a command in the help
def format_as_option(str, io)
if Cri::Platform.color?(io)
yellow(str)
else
str
end
end
def red(str)
"\e[31m#{str}\e[0m"
end
def green(str)
"\e[32m#{str}\e[0m"
end
def yellow(str)
"\e[33m#{str}\e[0m"
end
def bold(str)
"\e[1m#{str}\e[0m"
end
end
end
| ruby | MIT | 022de9676b2912b90d3b21f1727680d81ebc1e5d | 2026-01-04T17:57:35.186613Z | false |
denisdefreyne/cri | https://github.com/denisdefreyne/cri/blob/022de9676b2912b90d3b21f1727680d81ebc1e5d/lib/cri/commands/basic_root.rb | lib/cri/commands/basic_root.rb | # frozen_string_literal: true
flag :h, :help, 'show help for this command' do |_value, cmd|
puts cmd.help
raise CriExitException.new(is_error: false)
end
subcommand Cri::Command.new_basic_help
| ruby | MIT | 022de9676b2912b90d3b21f1727680d81ebc1e5d | 2026-01-04T17:57:35.186613Z | false |
denisdefreyne/cri | https://github.com/denisdefreyne/cri/blob/022de9676b2912b90d3b21f1727680d81ebc1e5d/lib/cri/commands/basic_help.rb | lib/cri/commands/basic_help.rb | # frozen_string_literal: true
name 'help'
usage 'help [command_name]'
summary 'show help'
description <<~DESC
Show help for the given command, or show general help. When no command is
given, a list of available commands is displayed, as well as a list of global
command-line options. When a command is given, a command description, as well
as command-specific command-line options, are shown.
DESC
flag :v, :verbose, 'show more detailed help'
run do |opts, args, cmd|
if cmd.supercommand.nil?
raise NoHelpAvailableError,
'No help available because the help command has no supercommand'
end
is_verbose = opts.fetch(:verbose, false)
resolved_cmd = args.inject(cmd.supercommand) do |acc, name|
acc.command_named(name)
end
puts resolved_cmd.help(verbose: is_verbose, io: $stdout)
end
| ruby | MIT | 022de9676b2912b90d3b21f1727680d81ebc1e5d | 2026-01-04T17:57:35.186613Z | false |
zverok/geo_coord | https://github.com/zverok/geo_coord/blob/659852f524e7524b6d2aa791b1724cecb391aa02/spec/spec_helper.rb | spec/spec_helper.rb | if Object.const_defined?(:RSpec) # otherwise it is mspec
require 'stringio'
require 'simplecov'
require 'coveralls'
require 'rspec/its'
require 'saharspec'
Coveralls.wear!
SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter.new(
[SimpleCov::Formatter::HTMLFormatter,
Coveralls::SimpleCov::Formatter]
)
SimpleCov.start
RSpec.configure do |c|
c.deprecation_stream = StringIO.new # just make it silent
end
end
TOLERANCE = 0.00003 unless Object.const_defined?(:TOLERANCE)
$:.unshift 'lib'
require 'geo/coord'
| ruby | MIT | 659852f524e7524b6d2aa791b1724cecb391aa02 | 2026-01-04T17:57:37.567912Z | false |
zverok/geo_coord | https://github.com/zverok/geo_coord/blob/659852f524e7524b6d2aa791b1724cecb391aa02/spec/geo/coord_spec.rb | spec/geo/coord_spec.rb | # frozen_string_literal: true
RSpec.describe Geo::Coord do
def coord(*args)
Geo::Coord.new(*args)
end
describe '#initialize' do
subject { described_class.method(:new) }
its_call(50.004444, 36.231389) {
is_expected.to ret have_attributes(
lat: 50.004444,
latitude: 50.004444,
phi: BigDecimal('50.004444') * Math::PI / 180,
lng: 36.231389,
lon: 36.231389,
longitude: 36.231389,
la: BigDecimal('36.231389') * Math::PI / 180
)
}
its_call(100, 36.231389) { is_expected.to raise_error(ArgumentError) }
its_call(50, 360) { is_expected.to raise_error(ArgumentError) }
its_call(lat: 50.004444, lng: 36.231389) {
is_expected.to ret have_attributes(lat: 50.004444, lng: 36.231389)
}
its_call(lat: 50.004444) {
is_expected.to ret have_attributes(lat: 50.004444, lng: 0)
}
its_call(lng: 36.231389) {
is_expected.to ret have_attributes(lat: 0, lng: 36.231389)
}
its_call(latd: 50, lngd: 36) { is_expected.to ret coord(50, 36) }
its_call(latd: 50, lath: 'S', lngd: 36, lngh: 'W') { is_expected.to ret coord(-50, -36) }
its_call(latd: 50, latm: 0, lats: 16, lngd: 36, lngm: 13, lngs: 53) {
is_expected.to ret have_attributes(lat: BigDecimal('50.00444444'), lng: BigDecimal('36.23138889'))
}
its_call(latd: 50, latm: 0, lats: 16) {
is_expected.to ret have_attributes(
lat: BigDecimal('50.00444444'),
lng: 0
)
}
its_call(lngd: 36, lngm: 13, lngs: 53) {
is_expected.to ret have_attributes(
lat: 0,
lng: BigDecimal('36.23138889')
)
}
its_call(lngd: 37, lngm: 30, lngs: 11.84) {
is_expected.to ret have_attributes(
lng: BigDecimal('37.50328889')
)
}
its_call { is_expected.to raise_error(ArgumentError) }
end
describe '.from_h' do
subject { described_class.method(:from_h) }
its_call(lat: 50.004444, lng: 36.231389) { is_expected.to ret coord(50.004444, 36.231389) }
its_call(latitude: 50.004444, longitude: 36.231389) { is_expected.to ret coord(50.004444, 36.231389) }
its_call(lat: 50.004444, lon: 36.231389) { is_expected.to ret coord(50.004444, 36.231389) }
its_call('lat' => 50.004444, 'lng' => 36.231389) { is_expected.to ret coord(50.004444, 36.231389) }
its_call('Lat' => 50.004444, 'LNG' => 36.231389) { is_expected.to ret coord(50.004444, 36.231389) }
end
describe '.parse_ll' do
subject { described_class.method(:parse_ll) }
its_call('50.004444, 36.231389') { is_expected.to ret coord(50.004444, 36.231389) }
its_call('50.004444,36.231389') { is_expected.to ret coord(50.004444, 36.231389) }
its_call('50.004444;36.231389') { is_expected.to ret coord(50.004444, 36.231389) }
its_call('50.004444 36.231389') { is_expected.to ret coord(50.004444, 36.231389) }
its_call('-50.004444 +36.231389') { is_expected.to ret coord(-50.004444, 36.231389) }
its_call('50 36') { is_expected.to ret coord(50, 36) }
its_call('50 36 80') { is_expected.to raise_error(ArgumentError) }
its_call('50.04444') { is_expected.to raise_error(ArgumentError) }
end
describe '.parse_dms' do
subject { described_class.method(:parse_dms) }
its_call(%q{50 0' 16" N, 36 13' 53" E}) {
is_expected.to ret coord(latd: 50, latm: 0, lats: 16, lath: 'N',
lngd: 36, lngm: 13, lngs: 53, lngh: 'E')
}
its_call('50°0′16″N 36°13′53″E') {
is_expected.to ret coord(latd: 50, latm: 0, lats: 16, lath: 'N',
lngd: 36, lngm: 13, lngs: 53, lngh: 'E')
}
its_call('50°0’16″N 36°13′53″E') {
is_expected.to ret coord(latd: 50, latm: 0, lats: 16, lath: 'N',
lngd: 36, lngm: 13, lngs: 53, lngh: 'E')
}
# TODO: its_call(%{22°12'00" 33°18'00"}) { is_expected.to ret coord(latd: 22, latm: 12, lngd: 33, lngm: 18) }
its_call('50 36 80') { is_expected.to raise_error(ArgumentError) }
end
describe '.parse' do
subject { described_class.method(:parse) }
its_call('50.004444, 36.231389') { is_expected.to ret coord(50.004444, 36.231389) }
its_call('50 36') { is_expected.to ret coord(50, 36) }
its_call(%q{50 0' 16" N, 36 13' 53" E}) {
is_expected.to ret coord(latd: 50, latm: 0, lats: 16, lath: 'N',
lngd: 36, lngm: 13, lngs: 53, lngh: 'E')
}
its_call('50') { is_expected.to ret nil }
end
describe '#lat*' do
context 'when in nothern hemisphere' do
subject(:point) { coord(50.004444, 36.231389) }
it {
is_expected.to have_attributes(
latd: 50,
latm: 0,
lats: be_within(0.01).of(16),
lath: 'N'
)
}
describe '#latdms' do
subject { point.method(:latdms) }
its_call { is_expected.to ret [point.latd, point.latm, point.lats, point.lath] }
its_call(hemisphere: false) { is_expected.to ret [point.latd, point.latm, point.lats] }
end
end
context 'when in southern hemisphere' do
subject(:point) { coord(-50.004444, 36.231389) }
it {
is_expected.to have_attributes(
latd: 50,
latm: 0,
lats: be_within(0.01).of(16),
lath: 'S'
)
}
describe '#latdms' do
subject { point.method(:latdms) }
its_call { is_expected.to ret [point.latd, point.latm, point.lats, point.lath] }
its_call(hemisphere: false) { is_expected.to ret [-point.latd, point.latm, point.lats] }
end
end
end
describe '#lng*' do
context 'when in eastern hemisphere' do
subject(:point) { coord(50.004444, 36.231389) }
it {
is_expected.to have_attributes(
lngd: 36,
lngm: 13,
lngs: be_within(0.01).of(53),
lngh: 'E'
)
}
describe '#lngdms' do
subject { point.method(:lngdms) }
its_call { is_expected.to ret [point.lngd, point.lngm, point.lngs, point.lngh] }
its_call(hemisphere: false) { is_expected.to ret [point.lngd, point.lngm, point.lngs] }
end
end
context 'when in western hemisphere' do
subject(:point) { coord(50.004444, -36.231389) }
it {
is_expected.to have_attributes(
lngd: 36,
lngm: 13,
lngs: be_within(0.01).of(53),
lngh: 'W'
)
}
describe '#lngdms' do
subject { point.method(:lngdms) }
its_call { is_expected.to ret [point.lngd, point.lngm, point.lngs, point.lngh] }
its_call(hemisphere: false) { is_expected.to ret [-point.lngd, point.lngm, point.lngs] }
end
end
end
describe 'simple conversions' do
subject(:point) { coord(50.004444, 36.231389) }
its(:inspect) { is_expected.to eq %{#<Geo::Coord 50°0'16"N 36°13'53"E>} }
its(:latlng) { is_expected.to eq [50.004444, 36.231389] }
its(:lnglat) { is_expected.to eq [36.231389, 50.004444] }
describe '#to_s' do
subject { point.method(:to_s) }
its_call { is_expected.to ret %{50°0'16"N 36°13'53"E} }
its_call(dms: false) { is_expected.to ret '50.004444,36.231389' }
context 'when negative coordinates' do
let(:point) { coord(-50.004444, -36.231389) }
its_call { is_expected.to ret %{50°0'16"S 36°13'53"W} }
its_call(dms: false) { is_expected.to ret '-50.004444,-36.231389' }
end
end
describe '#to_h' do
subject { point.method(:to_h) }
its_call { is_expected.to ret({lat: 50.004444, lng: 36.231389}) }
its_call(lat: :latitude, lng: :longitude) { is_expected.to ret({latitude: 50.004444, longitude: 36.231389}) }
its_call(lng: :lon) { is_expected.to ret({lat: 50.004444, lon: 36.231389}) }
its_call(lat: 'LAT', lng: 'LNG') { is_expected.to ret({'LAT' => 50.004444, 'LNG' => 36.231389}) }
end
end
describe '#strfcoord' do
subject { point.method(:strfcoord) }
context 'with positive coordinates' do
let(:point) { coord(50.004444, 36.231389) }
its_call('%latd') { is_expected.to ret '50' }
its_call('%latm') { is_expected.to ret '0' }
its_call('%lats') { is_expected.to ret '16' }
its_call('%lath') { is_expected.to ret 'N' }
its_call('%lat') { is_expected.to ret '%f' % point.lat }
its_call('%lngd') { is_expected.to ret '36' }
its_call('%lngm') { is_expected.to ret '13' }
its_call('%lngs') { is_expected.to ret '53' }
its_call('%lngh') { is_expected.to ret 'E' }
its_call('%lng') { is_expected.to ret '%f' % point.lng }
its_call('%+latds') { is_expected.to ret '+50' }
its_call('%.02lats') { is_expected.to ret '%.02f' % point.lats }
its_call('%.04lat') { is_expected.to ret '%.04f' % point.lat }
its_call('%+.04lat') { is_expected.to ret '%+.04f' % point.lat }
its_call('%+lat') { is_expected.to ret '%+f' % point.lat }
its_call('%+lngds') { is_expected.to ret '+36' }
its_call('%.02lngs') { is_expected.to ret '%.02f' % point.lngs }
its_call('%.04lng') { is_expected.to ret '%.04f' % point.lng }
its_call('%+.04lng') { is_expected.to ret '%+.04f' % point.lng }
# Just leave the unknown part
its_call('%latd %foo') { is_expected.to ret '50 %foo' }
# All at once
its_call(%q{%latd %latm' %lats" %lath, %lngd %lngm' %lngs" %lngh}) {
is_expected.to ret %q{50 0' 16" N, 36 13' 53" E}
}
end
context 'with negative coordinates' do
let(:point) { coord(-50.004444, -36.231389) }
its_call('%latd') { is_expected.to ret '50' }
its_call('%latds') { is_expected.to ret '-50' }
its_call('%lath') { is_expected.to ret 'S' }
its_call('%lat') { is_expected.to ret '%f' % point.lat }
its_call('%lngd') { is_expected.to ret '36' }
its_call('%lngds') { is_expected.to ret '-36' }
its_call('%lngh') { is_expected.to ret 'W' }
its_call('%lng') { is_expected.to ret '%f' % point.lng }
its_call('%+latds') { is_expected.to ret '-50' }
its_call('%+lngds') { is_expected.to ret '-36' }
end
context 'when carry-over required' do
let(:point) { coord(0.033333, 91.333333) }
its_call('%latd %latm %lats, %lngd %lngm %lngs') { is_expected.to ret '0 2 0, 91 20 0' }
its_call('%latd %latm %.02lats, %lngd %lngm %.02lngs') { is_expected.to ret '0 2 0.00, 91 20 0.00' }
its_call('%latd %latm %.03lats, %lngd %lngm %.03lngs') { is_expected.to ret '0 1 59.999, 91 19 59.999' }
end
end
describe '#strpcoord' do
subject { described_class.method(:strpcoord) }
its_call('50.004444, 36.231389', '%lat, %lng') {
is_expected.to ret coord(lat: 50.004444, lng: 36.231389)
}
its_call(
%q{50 0' 16" N, 36 13' 53" E},
%q{%latd %latm' %lats" %lath, %lngd %lngm' %lngs" %lngh}
) { is_expected.to ret coord(latd: 50, latm: 0, lats: 16, lngd: 36, lngm: 13, lngs: 53) }
its_call('50.004444', '%lat') { is_expected.to ret coord(lat: 50.004444, lng: 0) }
its_call('36.231389', '%lng') { is_expected.to ret coord(lng: 36.231389) }
its_call('50.004444, 36.231389', '%lat; %lng') {
is_expected.to raise_error ArgumentError, /can't be parsed/
}
its_call('50.004444, 36.231389 is somewhere in Kharkiv', '%lat, %lng') {
is_expected.to ret coord(lat: 50.004444, lng: 36.231389)
}
end
end
| ruby | MIT | 659852f524e7524b6d2aa791b1724cecb391aa02 | 2026-01-04T17:57:37.567912Z | false |
zverok/geo_coord | https://github.com/zverok/geo_coord/blob/659852f524e7524b6d2aa791b1724cecb391aa02/spec/geo/globes_earth_spec.rb | spec/geo/globes_earth_spec.rb | # frozen_string_literal: true
RSpec.describe Geo::Coord::Globes::Earth do
def coord(*args)
Geo::Coord.new(*args)
end
let(:washington_dc) { coord(38.898748, -77.037684) }
let(:chicago) { coord(41.85, -87.65) }
let(:anti_washington) { coord(-38.898748, 102.962316) }
it 'calculates distance (by Vincenty formula)' do # rubocop:disable RSpec/MultipleExpectations
expect(washington_dc.distance(washington_dc)).to eq 0
expect(washington_dc.distance(chicago)).to be_within(1).of(chicago.distance(washington_dc))
expect(washington_dc.distance(chicago)).to be_within(1).of(958_183)
# vincenty by design fails on antipodal points
expect(washington_dc.distance(anti_washington)).to be_within(1).of(20_037_502)
end
describe '#azimuth' do
subject { ->((lat1, lng1), (lat2, lng2)) { coord(lat1, lng1).azimuth(coord(lat2, lng2)) } }
# same point
its_call([38.898748, -77.037684], [38.898748, -77.037684]) { is_expected.to ret 0 }
# straight angles:
its_call([41, -75], [39, -75]) { is_expected.to ret be_within(1).of(180) }
its_call([40, -74], [40, -76]) { is_expected.to ret be_within(1).of(270) }
its_call([39, -75], [41, -75]) { is_expected.to ret be_within(1).of(0) }
its_call([40, -76], [40, -74]) { is_expected.to ret be_within(1).of(90) }
# some direction on map
its_call([38.898748, -77.037684], [41.85, -87.65]) { is_expected.to ret be_within(1).of(293) }
# vincenty by design fails on antipodal points
its_call([38.898748, -77.037684], [-38.898748, 102.962316]) { is_expected.to ret be_within(1).of(90) }
end
it 'calculates endpoint' do
d = washington_dc.distance(chicago)
a = washington_dc.azimuth(chicago)
endpoint = washington_dc.endpoint(d, a)
endpoint.should == chicago
end
end
| ruby | MIT | 659852f524e7524b6d2aa791b1724cecb391aa02 | 2026-01-04T17:57:37.567912Z | false |
zverok/geo_coord | https://github.com/zverok/geo_coord/blob/659852f524e7524b6d2aa791b1724cecb391aa02/lib/geo/coord.rb | lib/geo/coord.rb | # frozen_string_literal: true
require 'bigdecimal'
require 'bigdecimal/util'
# Geo::Coord is Ruby's library for handling [lat, lng] pairs of
# geographical coordinates. It provides most of basic functionality
# you may expect (storing and representing coordinate pair), as well
# as some geodesy math, like distances and azimuth, and comprehensive
# parsing/formatting features.
#
# See +Geo::Coord+ class docs for full description and usage examples.
#
module Geo
# Geo::Coord is main class of Geo module, representing
# +(latitude, longitude)+ pair. It stores coordinates in floating-point
# degrees form, provides access to coordinate components, allows complex
# formatting and parsing of coordinate pairs and performs geodesy
# calculations in standard WGS-84 coordinate reference system.
#
# == Examples of usage
#
# Creation:
#
# # From lat/lng pair:
# g = Geo::Coord.new(50.004444, 36.231389)
# # => #<Geo::Coord 50°0'16"N 36°13'53"E>
#
# # Or using keyword arguments form:
# g = Geo::Coord.new(lat: 50.004444, lng: 36.231389)
# # => #<Geo::Coord 50°0'16"N 36°13'53"E>
#
# # Keyword arguments also allow creation of Coord from components:
# g = Geo::Coord.new(latd: 50, latm: 0, lats: 16, lath: 'N', lngd: 36, lngm: 13, lngs: 53, lngh: 'E')
# # => #<Geo::Coord 50°0'16"N 36°13'53"E>
#
# For parsing API responses you'd like to use +from_h+,
# which accepts String and Symbol keys, any letter case,
# and knows synonyms (lng/lon/longitude):
#
# g = Geo::Coord.from_h('LAT' => 50.004444, 'LON' => 36.231389)
# # => #<Geo::Coord 50°0'16"N 36°13'53"E>
#
# For math, you'd probably like to be able to initialize
# Coord with radians rather than degrees:
#
# g = Geo::Coord.from_rad(0.8727421884291233, 0.6323570306208558)
# # => #<Geo::Coord 50°0'16"N 36°13'53"E>
#
# There's also family of parsing methods, with different applicability:
#
# # Tries to parse (lat, lng) pair:
# g = Geo::Coord.parse_ll('50.004444, 36.231389')
# # => #<Geo::Coord 50°0'16"N 36°13'53"E>
#
# # Tries to parse degrees/minutes/seconds:
# g = Geo::Coord.parse_dms('50° 0′ 16″ N, 36° 13′ 53″ E')
# # => #<Geo::Coord 50°0'16"N 36°13'53"E>
#
# # Tries to do best guess:
# g = Geo::Coord.parse('50.004444, 36.231389')
# # => #<Geo::Coord 50°0'16"N 36°13'53"E>
# g = Geo::Coord.parse('50° 0′ 16″ N, 36° 13′ 53″ E')
# # => #<Geo::Coord 50°0'16"N 36°13'53"E>
#
# # Allows user to provide pattern:
# g = Geo::Coord.strpcoord('50.004444, 36.231389', '%lat, %lng')
# # => #<Geo::Coord 50°0'16"N 36°13'53"E>
#
# Having Coord object, you can get its properties:
#
# g = Geo::Coord.new(50.004444, 36.231389)
# g.lat # => 50.004444
# g.latd # => 50 -- latitude degrees
# g.lath # => N -- latitude hemisphere
# g.lngh # => E -- longitude hemishpere
# g.phi # => 0.8727421884291233 -- longitude in radians
# g.latdms # => [50, 0, 15.998400000011316, "N"]
# # ...and so on
#
# Format and convert it:
#
# g.to_s # => "50.004444,36.231389"
# g.strfcoord('%latd°%latm′%lats″%lath %lngd°%lngm′%lngs″%lngh')
# # => "50°0′16″N 36°13′53″E"
#
# g.to_h(lat: 'LAT', lng: 'LON') # => {'LAT'=>50.004444, 'LON'=>36.231389}
#
# Do simple geodesy math:
#
# kharkiv = Geo::Coord.new(50.004444, 36.231389)
# kyiv = Geo::Coord.new(50.45, 30.523333)
#
# kharkiv.distance(kyiv) # => 410211.22377421556
# kharkiv.azimuth(kyiv) # => 279.12614358262067
# kharkiv.endpoint(410_211, 280) # => #<Geo::Coord 50.505975,30.531283>
#
class Coord
# Latitude, degrees, signed float.
attr_reader :lat
# Longitude, degrees, signed float.
attr_reader :lng
alias latitude lat
alias longitude lng
alias lon lng
class << self
# @private
LAT_KEYS = %i[lat latitude].freeze # :nodoc:
# @private
LNG_KEYS = %i[lng lon long longitude].freeze # :nodoc:
# Creates Coord from hash, containing latitude and longitude.
#
# This methos designed as a way for parsing responses from APIs and
# databases, so, it tries to be pretty liberal on its input:
# - accepts String or Symbol keys;
# - accepts any letter case;
# - accepts several synonyms for latitude ("lat" and "latitude")
# and longitude ("lng", "lon", "long", "longitude").
#
# g = Geo::Coord.from_h('LAT' => 50.004444, longitude: 36.231389)
# # => #<Geo::Coord 50°0'16"N 36°13'53"E>
#
def from_h(hash)
h = hash.map { |k, v| [k.to_s.downcase.to_sym, v] }.to_h
lat = h.values_at(*LAT_KEYS).compact.first or
raise(ArgumentError, "No latitude value found in #{hash}")
lng = h.values_at(*LNG_KEYS).compact.first or
raise(ArgumentError, "No longitude value found in #{hash}")
new(lat, lng)
end
# Creates Coord from φ and λ (latitude and longitude in radians).
#
# g = Geo::Coord.from_rad(0.8727421884291233, 0.6323570306208558)
# # => #<Geo::Coord 50°0'16"N 36°13'53"E>
#
def from_rad(phi, la)
new(phi * 180 / Math::PI, la * 180 / Math::PI)
end
# @private
INT_PATTERN = '[-+]?\d+' # :nodoc:
# @private
UINT_PATTERN = '\d+' # :nodoc:
# @private
FLOAT_PATTERN = '[-+]?\d+(?:\.\d*)?' # :nodoc:
# @private
UFLOAT_PATTERN = '\d+(?:\.\d*)?' # :nodoc:
# @private
DEG_PATTERN = '[ °d]' # :nodoc:
# @private
MIN_PATTERN = "['′’m]" # :nodoc:
# @private
SEC_PATTERN = '["″s]' # :nodoc:
# @private
LL_PATTERN = /^(#{FLOAT_PATTERN})\s*[,; ]\s*(#{FLOAT_PATTERN})$/.freeze # :nodoc:
# @private
DMS_LATD_P = "(?<latd>#{INT_PATTERN})#{DEG_PATTERN}" # :nodoc:
# @private
DMS_LATM_P = "(?<latm>#{UINT_PATTERN})#{MIN_PATTERN}" # :nodoc:
# @private
DMS_LATS_P = "(?<lats>#{UFLOAT_PATTERN})#{SEC_PATTERN}" # :nodoc:
# @private
DMS_LAT_P = "#{DMS_LATD_P}\\s*#{DMS_LATM_P}\\s*#{DMS_LATS_P}\\s*(?<lath>[NS])" # :nodoc:
# @private
DMS_LNGD_P = "(?<lngd>#{INT_PATTERN})#{DEG_PATTERN}" # :nodoc:
# @private
DMS_LNGM_P = "(?<lngm>#{UINT_PATTERN})#{MIN_PATTERN}" # :nodoc:
# @private
DMS_LNGS_P = "(?<lngs>#{UFLOAT_PATTERN})#{SEC_PATTERN}" # :nodoc:
# @private
DMS_LNG_P = "#{DMS_LNGD_P}\\s*#{DMS_LNGM_P}\\s*#{DMS_LNGS_P}\\s*(?<lngh>[EW])" # :nodoc:
# @private
DMS_PATTERN = /^\s*#{DMS_LAT_P}\s*[,; ]\s*#{DMS_LNG_P}\s*$/x.freeze # :nodoc:
# Parses Coord from string containing float latitude and longitude.
# Understands several types of separators/spaces between values.
#
# Geo::Coord.parse_ll('-50.004444 +36.231389')
# # => #<Geo::Coord 50°0'16"S 36°13'53"E>
#
# If parse_ll is not wise enough to understand your data, consider
# using ::strpcoord.
#
def parse_ll(str)
str.match(LL_PATTERN) do |m|
return new(m[1].to_f, m[2].to_f)
end
raise ArgumentError, "Can't parse #{str} as lat, lng"
end
# Parses Coord from string containing latitude and longitude in
# degrees-minutes-seconds-hemisphere format. Understands several
# types of separators, degree, minute, second signs, as well as
# explicit hemisphere and no-hemisphere (signed degrees) formats.
#
# Geo::Coord.parse_dms('50°0′16″N 36°13′53″E')
# # => #<Geo::Coord 50°0'16"N 36°13'53"E>
#
# If parse_dms is not wise enough to understand your data, consider
# using ::strpcoord.
#
def parse_dms(str)
str.match(DMS_PATTERN) do |m|
return new(
latd: m[:latd], latm: m[:latm], lats: m[:lats], lath: m[:lath],
lngd: m[:lngd], lngm: m[:lngm], lngs: m[:lngs], lngh: m[:lngh]
)
end
raise ArgumentError, "Can't parse #{str} as degrees-minutes-seconds"
end
# Tries its best to parse Coord from string containing it (in any
# known form).
#
# Geo::Coord.parse('-50.004444 +36.231389')
# # => #<Geo::Coord 50°0'16"S 36°13'53"E>
# Geo::Coord.parse('50°0′16″N 36°13′53″E')
# # => #<Geo::Coord 50°0'16"N 36°13'53"E>
#
# If you know exact form in which coordinates are
# provided, it may be wider to consider parse_ll, parse_dms or
# even ::strpcoord.
def parse(str)
# rubocop:disable Style/RescueModifier
parse_ll(str) rescue (parse_dms(str) rescue nil)
# rubocop:enable Style/RescueModifier
end
# @private
PARSE_PATTERNS = { # :nodoc:
'%latd' => "(?<latd>#{INT_PATTERN})",
'%latm' => "(?<latm>#{UINT_PATTERN})",
'%lats' => "(?<lats>#{UFLOAT_PATTERN})",
'%lath' => '(?<lath>[NS])',
'%lat' => "(?<lat>#{FLOAT_PATTERN})",
'%lngd' => "(?<lngd>#{INT_PATTERN})",
'%lngm' => "(?<lngm>#{UINT_PATTERN})",
'%lngs' => "(?<lngs>#{UFLOAT_PATTERN})",
'%lngh' => '(?<lngh>[EW])',
'%lng' => "(?<lng>#{FLOAT_PATTERN})"
}.freeze
# Parses +str+ into Coord with provided +pattern+.
#
# Example:
#
# Geo::Coord.strpcoord('-50.004444/+36.231389', '%lat/%lng')
# # => #<Geo::Coord -50.004444,36.231389>
#
# List of parsing flags:
#
# %lat :: Full latitude, float
# %latd :: Latitude degrees, integer, may be signed (instead of
# providing hemisphere info
# %latm :: Latitude minutes, integer, unsigned
# %lats :: Latitude seconds, float, unsigned
# %lath :: Latitude hemisphere, "N" or "S"
# %lng :: Full longitude, float
# %lngd :: Longitude degrees, integer, may be signed (instead of
# providing hemisphere info
# %lngm :: Longitude minutes, integer, unsigned
# %lngs :: Longitude seconds, float, unsigned
# %lngh :: Longitude hemisphere, "N" or "S"
#
def strpcoord(str, pattern)
pattern = PARSE_PATTERNS.inject(pattern) do |memo, (pfrom, pto)|
memo.gsub(pfrom, pto)
end
match = Regexp.new("^#{pattern}").match(str)
raise ArgumentError, "Coordinates str #{str} can't be parsed by pattern #{pattern}" unless match
new(**match.names.map { |n| [n.to_sym, _extract_match(match, n)] }.to_h)
end
private
def _extract_match(match, name)
return nil unless match[name]
val = match[name]
name.end_with?('h') ? val : val.to_f
end
end
# Creates Coord object.
#
# There are three forms of usage:
# - <tt>Coord.new(lat, lng)</tt> with +lat+ and +lng+ being floats;
# - <tt>Coord.new(lat: lat, lng: lng)</tt> -- same as above, but
# with keyword arguments;
# - <tt>Geo::Coord.new(latd: 50, latm: 0, lats: 16, lath: 'N', lngd: 36, lngm: 13, lngs: 53, lngh: 'E')</tt> -- for
# cases when you have coordinates components already parsed;
#
# In keyword arguments form, any argument can be omitted and will be
# replaced with 0. But you can't mix, for example, "whole" latitude
# key +lat+ and partial longitude keys +lngd+, +lngm+ and so on.
#
# g = Geo::Coord.new(50.004444, 36.231389)
# # => #<Geo::Coord 50°0'16"N 36°13'53"E>
#
# # Or using keyword arguments form:
# g = Geo::Coord.new(lat: 50.004444, lng: 36.231389)
# # => #<Geo::Coord 50°0'16"N 36°13'53"E>
#
# # Keyword arguments also allow creation of Coord from components:
# g = Geo::Coord.new(latd: 50, latm: 0, lats: 16, lath: 'N', lngd: 36, lngm: 13, lngs: 53, lngh: 'E')
# # => #<Geo::Coord 50°0'16"N 36°13'53"E>
#
# # Providing defaults:
# g = Geo::Coord.new(lat: 50.004444)
# # => #<Geo::Coord 50°0'16"N 0°0'0"W>
#
def initialize(lat = nil, lng = nil, **kwargs) # rubocop:disable Metrics/CyclomaticComplexity,Metrics/PerceivedComplexity
@globe = Globes::Earth.instance
# It is probably can be clearer with Ruby 2.7+ pattern-matching... or with less permissive
# protocol :)
kwargs = lat if lat.is_a?(Hash) && kwargs.empty? # Ruby 3.0
case
when lat && lng
_init(lat, lng)
when kwargs.key?(:lat) || kwargs.key?(:lng)
_init(*kwargs.values_at(:lat, :lng))
when kwargs.key?(:latd) || kwargs.key?(:lngd)
_init_dms(**kwargs)
else
raise ArgumentError, "Can't create #{self.class} by provided data: (#{lat}, #{lng}, **#{kwargs}"
end
end
# Compares with +other+.
#
# Note that no greater/lower relation is defined on Coord, so,
# for example, you can't just sort an array of Coord.
def ==(other)
other.is_a?(self.class) && other.lat == lat && other.lng == lng
end
# Returns latitude degrees (unsigned integer).
def latd
lat.abs.to_i
end
# Returns latitude minutes (unsigned integer).
def latm
(lat.abs * 60).to_i % 60
end
# Returns latitude seconds (unsigned float).
def lats
(lat.abs * 3600) % 60
end
# Returns latitude hemisphere (upcase letter 'N' or 'S').
def lath
lat.positive? ? 'N' : 'S'
end
# Returns longitude degrees (unsigned integer).
def lngd
lng.abs.to_i
end
# Returns longitude minutes (unsigned integer).
def lngm
(lng.abs * 60).to_i % 60
end
# Returns longitude seconds (unsigned float).
def lngs
(lng.abs * 3600) % 60
end
# Returns longitude hemisphere (upcase letter 'E' or 'W').
def lngh
lng.positive? ? 'E' : 'W'
end
# Returns latitude components: degrees, minutes, seconds and optionally
# a hemisphere:
#
# # Nothern hemisphere:
# g = Geo::Coord.new(50.004444, 36.231389)
#
# g.latdms # => [50, 0, 15.9984, "N"]
# g.latdms(hemisphere: false) # => [50, 0, 15.9984]
#
# # Southern hemisphere:
# g = Geo::Coord.new(-50.004444, 36.231389)
#
# g.latdms # => [50, 0, 15.9984, "S"]
# g.latdms(hemisphere: false) # => [-50, 0, 15.9984]
#
def latdms(hemisphere: true)
hemisphere ? [latd, latm, lats, lath] : [latsign * latd, latm, lats]
end
# Returns longitude components: degrees, minutes, seconds and optionally
# a hemisphere:
#
# # Eastern hemisphere:
# g = Geo::Coord.new(50.004444, 36.231389)
#
# g.lngdms # => [36, 13, 53.0004, "E"]
# g.lngdms(hemisphere: false) # => [36, 13, 53.0004]
#
# # Western hemisphere:
# g = Geo::Coord.new(50.004444, 36.231389)
#
# g.lngdms # => [36, 13, 53.0004, "E"]
# g.lngdms(hemisphere: false) # => [-36, 13, 53.0004]
#
def lngdms(hemisphere: true)
hemisphere ? [lngd, lngm, lngs, lngh] : [lngsign * lngd, lngm, lngs]
end
# Latitude in radians. Geodesy formulae almost alwayse use greek Phi
# for it.
def phi
deg2rad(lat)
end
alias φ phi
# Latitude in radians. Geodesy formulae almost alwayse use greek Lambda
# for it; we are using shorter name for not confuse with Ruby's +lambda+
# keyword.
def la
deg2rad(lng)
end
alias λ la
# Returns a string represent coordinates object.
#
# g.inspect # => "#<Geo::Coord 50.004444,36.231389>"
#
def inspect
strfcoord(%{#<#{self.class.name} %latd°%latm'%lats"%lath %lngd°%lngm'%lngs"%lngh>})
end
# Returns a string representing coordinates.
#
# g.to_s # => "50°0'16\"N 36°13'53\"E"
# g.to_s(dms: false) # => "50.004444,36.231389"
#
def to_s(dms: true)
format = dms ? %{%latd°%latm'%lats"%lath %lngd°%lngm'%lngs"%lngh} : '%lat,%lng'
strfcoord(format)
end
# Returns a two-element array of latitude and longitude.
#
# g.latlng # => [50.004444, 36.231389]
#
def latlng
[lat, lng]
end
# Returns a two-element array of longitude and latitude (reverse order to +latlng+).
#
# g.lnglat # => [36.231389, 50.004444]
#
def lnglat
[lng, lat]
end
# Returns hash of latitude and longitude. You can provide your keys
# if you want:
#
# g.to_h
# # => {:lat=>50.004444, :lng=>36.231389}
# g.to_h(lat: 'LAT', lng: 'LNG')
# # => {'LAT'=>50.004444, 'LNG'=>36.231389}
#
def to_h(lat: :lat, lng: :lng)
{lat => self.lat, lng => self.lng}
end
# @private
INTFLAGS = '\+' # :nodoc:
# @private
FLOATUFLAGS = /\.0\d+/.freeze # :nodoc:
# @private
FLOATFLAGS = /\+?#{FLOATUFLAGS}?/.freeze # :nodoc:
# @private
DIRECTIVES = { # :nodoc:
/%(#{FLOATUFLAGS})?lats/ => proc { |m| "%<lats>#{m[1] || '.0'}f" },
'%latm' => '%<latm>i',
/%(#{INTFLAGS})?latds/ => proc { |m| "%<latds>#{m[1]}i" },
'%latd' => '%<latd>i',
'%lath' => '%<lath>s',
/%(#{FLOATFLAGS})?lat/ => proc { |m| "%<lat>#{m[1]}f" },
/%(#{FLOATUFLAGS})?lngs/ => proc { |m| "%<lngs>#{m[1] || '.0'}f" },
'%lngm' => '%<lngm>i',
/%(#{INTFLAGS})?lngds/ => proc { |m| "%<lngds>#{m[1]}i" },
'%lngd' => '%<lngd>i',
'%lngh' => '%<lngh>s',
/%(#{FLOATFLAGS})?lng/ => proc { |m| "%<lng>#{m[1]}f" }
}.freeze
# Formats coordinates according to directives in +formatstr+.
#
# Each directive starts with +%+ and can contain some modifiers before
# its name.
#
# Acceptable modifiers:
# - unsigned integers: none;
# - signed integers: <tt>+</tt> for mandatory sign printing;
# - floats: same as integers and number of digits modifier, like
# <tt>.03</tt>.
#
# List of directives:
#
# %lat :: Full latitude, floating point, signed
# %latds :: Latitude degrees, integer, signed
# %latd :: Latitude degrees, integer, unsigned
# %latm :: Latitude minutes, integer, unsigned
# %lats :: Latitude seconds, floating point, unsigned
# %lath :: Latitude hemisphere, "N" or "S"
# %lng :: Full longitude, floating point, signed
# %lngds :: Longitude degrees, integer, signed
# %lngd :: Longitude degrees, integer, unsigned
# %lngm :: Longitude minutes, integer, unsigned
# %lngs :: Longitude seconds, floating point, unsigned
# %lngh :: Longitude hemisphere, "E" or "W"
#
# Examples:
#
# g = Geo::Coord.new(50.004444, 36.231389)
# g.strfcoord('%+lat, %+lng')
# # => "+50.004444, +36.231389"
# g.strfcoord("%latd°%latm'%lath -- %lngd°%lngm'%lngh")
# # => "50°0'N -- 36°13'E"
#
# +strfcoord+ handles seconds rounding implicitly:
#
# pos = Geo::Coord.new(0.033333, 91.333333)
# pos.lats # => 0.599988e2
# pos.strfcoord('%latd %latm %.05lats') # => "0 1 59.99880"
# pos.strfcoord('%latd %latm %lats') # => "0 2 0"
#
def strfcoord(formatstr)
h = full_hash
DIRECTIVES.reduce(formatstr) do |memo, (from, to)|
memo.gsub(from) do
to = to.call(Regexp.last_match) if to.is_a?(Proc)
res = to % h
res, carrymin = guard_seconds(to, res)
h[carrymin] += 1 if carrymin
res
end
end
end
# Calculates distance to +other+ in SI units (meters). Vincenty
# formula is used.
#
# kharkiv = Geo::Coord.new(50.004444, 36.231389)
# kyiv = Geo::Coord.new(50.45, 30.523333)
#
# kharkiv.distance(kyiv) # => 410211.22377421556
#
def distance(other)
@globe.inverse(phi, la, other.phi, other.la).first
end
# Calculates azimuth (direction) to +other+ in degrees. Vincenty
# formula is used.
#
# kharkiv = Geo::Coord.new(50.004444, 36.231389)
# kyiv = Geo::Coord.new(50.45, 30.523333)
#
# kharkiv.azimuth(kyiv) # => 279.12614358262067
#
def azimuth(other)
rad2deg(@globe.inverse(phi, la, other.phi, other.la).last)
end
# Given distance in meters and azimuth in degrees, calculates other
# point on globe being on that direction/azimuth from current.
# Vincenty formula is used.
#
# kharkiv = Geo::Coord.new(50.004444, 36.231389)
# kharkiv.endpoint(410_211, 280)
# # => #<Geo::Coord 50°30'22"N 30°31'53"E>
#
def endpoint(distance, azimuth)
phi2, la2 = @globe.direct(phi, la, distance, deg2rad(azimuth))
Coord.from_rad(phi2, la2)
end
private
LAT_RANGE_ERROR = 'Expected latitude to be between -90 and 90, %p received'
LNG_RANGE_ERROR = 'Expected longitude to be between -180 and 180, %p received'
def _init(lat, lng)
lat = BigDecimal(lat.to_f, 10)
lng = BigDecimal(lng.to_f, 10)
raise ArgumentError, LAT_RANGE_ERROR % lat unless (-90..90).cover?(lat)
raise ArgumentError, LNG_RANGE_ERROR % lng unless (-180..180).cover?(lng)
@lat = lat
@lng = lng
end
# @private
LATH = {'N' => 1, 'S' => -1}.freeze # :nodoc:
# @private
LNGH = {'E' => 1, 'W' => -1}.freeze # :nodoc:
def _init_dms(latd: 0, latm: 0, lats: 0, lath: nil, lngd: 0, lngm: 0, lngs: 0, lngh: nil) # rubocop:disable Metrics/AbcSize
lat = (latd.to_d + latm.to_d / 60 + lats.to_d / 3600) * guess_sign(lath, LATH)
lng = (lngd.to_d + lngm.to_d / 60 + lngs.to_d / 3600) * guess_sign(lngh, LNGH)
_init(lat, lng)
end
def guess_sign(h, hemishperes)
return 1 unless h
hemishperes[h] or
raise ArgumentError, "Unidentified hemisphere: #{h}"
end
def guard_seconds(pattern, result)
m = pattern.match(/<(lat|lng)s>/)
return result unless m && result.start_with?('60')
carry = "#{m[1]}m".to_sym
[pattern % {lats: 0, lngs: 0}, carry]
end
def latsign
lat <=> 0
end
def lngsign
lng <=> 0
end
def latds
lat.to_i
end
def lngds
lng.to_i
end
def full_hash
{
latd: latd,
latds: latds,
latm: latm,
lats: lats,
lath: lath,
lat: lat,
lngd: lngd,
lngds: lngds,
lngm: lngm,
lngs: lngs,
lngh: lngh,
lng: lng
}
end
def rad2deg(r)
(r / Math::PI * 180 + 360) % 360
end
def deg2rad(d)
d * Math::PI / 180
end
end
end
require_relative 'coord/globes'
| ruby | MIT | 659852f524e7524b6d2aa791b1724cecb391aa02 | 2026-01-04T17:57:37.567912Z | false |
zverok/geo_coord | https://github.com/zverok/geo_coord/blob/659852f524e7524b6d2aa791b1724cecb391aa02/lib/geo/coord/version.rb | lib/geo/coord/version.rb | # frozen_string_literal: true
module Geo
class Coord
VERSION = '0.2.0'
end
end
| ruby | MIT | 659852f524e7524b6d2aa791b1724cecb391aa02 | 2026-01-04T17:57:37.567912Z | false |
zverok/geo_coord | https://github.com/zverok/geo_coord/blob/659852f524e7524b6d2aa791b1724cecb391aa02/lib/geo/coord/globes.rb | lib/geo/coord/globes.rb | require 'singleton'
module Geo
# @private
module Coord::Globes # :nodoc:all
# Notes on this module
#
# **Credits:**
#
# Most of the initial code/algo, as well as tests were initially borrowed from
# [Graticule](https://github.com/collectiveidea/graticule).
#
# Algo descriptions borrowed from
#
# * http://www.movable-type.co.uk/scripts/latlong.html (simple)
# * http://www.movable-type.co.uk/scripts/latlong-vincenty.html (Vincenty)
#
# **On naming and code style:**
#
# Two main methods (distance/azimuth between two points and endpoint by
# startpoint and distance/azimuth) are named `inverse` & `direct` due
# to solving "two main geodetic problems": https://en.wikipedia.org/wiki/Geodesy#Geodetic_problems
#
# Code for them is pretty "un-Ruby-ish", trying to preserve original
# formulae as much as possible (including use of Greek names and
# inconsistent naming of some things: "simple" solution of direct problem
# names distance `d`, while Vincenty formula uses `s`).
#
class Generic
include Singleton
include Math
def inverse(phi1, la1, phi2, la2)
# See http://www.movable-type.co.uk/scripts/latlong.html
delta_phi = phi2 - phi1
delta_la = la2 - la1
a = sin(delta_phi/2)**2 + cos(phi1)*cos(phi2) * sin(delta_la/2)**2
c = 2 * atan2(sqrt(a), sqrt(1-a))
d = r * c
y = sin(delta_la) * cos(phi1)
x = cos(phi1) * sin(phi2) - sin(phi1) * cos(phi2) * cos(delta_la)
a = atan2(y, x)
[d, a]
end
def direct(phi1, la1, d, alpha1)
phi2 = asin( sin(phi1)*cos(d/r) +
cos(phi1)*sin(d/r)*cos(alpha1) )
la2 = la1 + atan2(sin(alpha1)*sin(d/r)*cos(phi1), cos(d/r)-sin(phi1)*sin(phi2))
[phi2, la2]
end
private
def r
self.class::RADIUS
end
end
class Earth < Generic
# All in SI units (metres)
RADIUS = 6378135
MAJOR_AXIS = 6378137
MINOR_AXIS = 6356752.3142
F = (MAJOR_AXIS - MINOR_AXIS) / MAJOR_AXIS
VINCENTY_MAX_ITERATIONS = 20
VINCENTY_TOLERANCE = 1e-12
def inverse(phi1, la1, phi2, la2)
# Vincenty formula
# See http://www.movable-type.co.uk/scripts/latlong-vincenty.html
l = la2 - la1
u1 = atan((1-F) * tan(phi1))
u2 = atan((1-F) * tan(phi2))
sin_u1 = sin(u1); cos_u1 = cos(u1)
sin_u2 = sin(u2); cos_u2 = cos(u2)
la = l # first approximation
la_, cosSqalpha, sin_sigma, cos_sigma, sigma, cos2sigmaM, sinla, cosla = nil
VINCENTY_MAX_ITERATIONS.times do
sinla = sin(la)
cosla = cos(la)
sin_sigma = sqrt((cos_u2*sinla) * (cos_u2*sinla) +
(cos_u1*sin_u2-sin_u1*cos_u2*cosla) * (cos_u1*sin_u2-sin_u1*cos_u2*cosla))
return [0, 0] if sin_sigma == 0 # co-incident points
cos_sigma = sin_u1*sin_u2 + cos_u1*cos_u2*cosla
sigma = atan2(sin_sigma, cos_sigma)
sinalpha = cos_u1 * cos_u2 * sinla / sin_sigma
cosSqalpha = 1 - sinalpha*sinalpha
cos2sigmaM = cos_sigma - 2*sin_u1*sin_u2/cosSqalpha
cos2sigmaM = 0 if cos2sigmaM.nan? # equatorial line: cosSqalpha=0 (§6)
c = F/16*cosSqalpha*(4+F*(4-3*cosSqalpha))
la_ = la
la = l + (1-c) * F * sinalpha *
(sigma + c*sin_sigma*(cos2sigmaM+c*cos_sigma*(-1+2*cos2sigmaM*cos2sigmaM)))
break if la_ && (la - la_).abs < VINCENTY_TOLERANCE
end
# Formula failed to converge (happens on antipodal points)
# We'll call Haversine formula instead.
return super if (la - la_).abs > VINCENTY_TOLERANCE
uSq = cosSqalpha * (MAJOR_AXIS**2 - MINOR_AXIS**2) / (MINOR_AXIS**2)
a = 1 + uSq/16384*(4096+uSq*(-768+uSq*(320-175*uSq)))
b = uSq/1024 * (256+uSq*(-128+uSq*(74-47*uSq)))
delta_sigma = b*sin_sigma*(cos2sigmaM+b/4*(cos_sigma*(-1+2*cos2sigmaM*cos2sigmaM)-
b/6*cos2sigmaM*(-3+4*sin_sigma*sin_sigma)*(-3+4*cos2sigmaM*cos2sigmaM)))
s = MINOR_AXIS * a * (sigma-delta_sigma)
alpha1 = atan2(cos_u2*sinla, cos_u1*sin_u2 - sin_u1*cos_u2*cosla)
[s, alpha1]
end
def direct(phi1, la1, s, alpha1)
sinalpha1 = sin(alpha1)
cosalpha1 = cos(alpha1)
tanU1 = (1-F) * tan(phi1)
cosU1 = 1 / sqrt(1 + tanU1**2)
sinU1 = tanU1 * cosU1
sigma1 = atan2(tanU1, cosalpha1)
sinalpha = cosU1 * sinalpha1
cosSqalpha = 1 - sinalpha**2
uSq = cosSqalpha * (MAJOR_AXIS**2 - MINOR_AXIS**2) / (MINOR_AXIS**2);
a = 1 + uSq/16384*(4096+uSq*(-768+uSq*(320-175*uSq)))
b = uSq/1024 * (256+uSq*(-128+uSq*(74-47*uSq)))
sigma = s / (MINOR_AXIS*a)
sigma_ = nil
begin
cos2sigmaM = cos(2*sigma1 + sigma);
sinsigma = sin(sigma);
cossigma = cos(sigma);
delta_sigma = b*sinsigma*(cos2sigmaM+b/4*(cossigma*(-1+2*cos2sigmaM**2)-
b/6*cos2sigmaM*(-3+4*sinsigma**2)*(-3+4*cos2sigmaM**2)))
sigma_ = sigma
sigma = s / (MINOR_AXIS*a) + delta_sigma
end while (sigma-sigma_).abs > 1e-12
tmp = sinU1*sinsigma - cosU1*cossigma*cosalpha1
phi2 = atan2(sinU1*cossigma + cosU1*sinsigma*cosalpha1, (1-F)*sqrt(sinalpha**2 + tmp**2))
la = atan2(sinsigma*sinalpha1, cosU1*cossigma - sinU1*sinsigma*cosalpha1)
c = F/16*cosSqalpha*(4+F*(4-3*cosSqalpha))
l = la - (1-c) * F * sinalpha *
(sigma + c*sinsigma*(cos2sigmaM+c*cossigma*(-1+2*cos2sigmaM*cos2sigmaM)))
la2 = (la1+l+3*PI) % (2*PI) - PI # normalise to -PI...+PI
[phi2, la2]
end
end
end
end
| ruby | MIT | 659852f524e7524b6d2aa791b1724cecb391aa02 | 2026-01-04T17:57:37.567912Z | false |
kabel/homebrew-php-ext | https://github.com/kabel/homebrew-php-ext/blob/6f1beba58200ca5652a5507391b30e4ba90ed8e3/Formula/php@8.2-pdo-oci.rb | Formula/php@8.2-pdo-oci.rb | require_relative "../lib/oracle_php_extension_formula"
class PhpAT82PdoOci < OraclePhpExtensionFormula
extension_dsl "PDO Driver OCI"
deprecate! date: "2026-12-31", because: :unsupported
instantclient_options arg: "--with-pdo-oci", with_version: true
end
| ruby | BSD-2-Clause | 6f1beba58200ca5652a5507391b30e4ba90ed8e3 | 2026-01-04T17:57:42.980777Z | false |
kabel/homebrew-php-ext | https://github.com/kabel/homebrew-php-ext/blob/6f1beba58200ca5652a5507391b30e4ba90ed8e3/Formula/php@8.3-pdo-oci.rb | Formula/php@8.3-pdo-oci.rb | require_relative "../lib/oracle_php_extension_formula"
class PhpAT83PdoOci < OraclePhpExtensionFormula
extension_dsl "PDO Driver OCI"
deprecate! date: "2027-12-31", because: :unsupported
instantclient_options arg: "--with-pdo-oci", with_version: true
end
| ruby | BSD-2-Clause | 6f1beba58200ca5652a5507391b30e4ba90ed8e3 | 2026-01-04T17:57:42.980777Z | false |
kabel/homebrew-php-ext | https://github.com/kabel/homebrew-php-ext/blob/6f1beba58200ca5652a5507391b30e4ba90ed8e3/Formula/php@8.2-snmp.rb | Formula/php@8.2-snmp.rb | require_relative "../lib/php_extension_formula"
class PhpAT82Snmp < PhpExtensionFormula
extension_dsl "SNMP Extension"
deprecate! date: "2026-12-31", because: :unsupported
depends_on "net-snmp"
depends_on "openssl@3"
configure_arg "--with-snmp=#{Formula["net-snmp"].opt_prefix}"
end
| ruby | BSD-2-Clause | 6f1beba58200ca5652a5507391b30e4ba90ed8e3 | 2026-01-04T17:57:42.980777Z | false |
kabel/homebrew-php-ext | https://github.com/kabel/homebrew-php-ext/blob/6f1beba58200ca5652a5507391b30e4ba90ed8e3/Formula/php@8.3-imap.rb | Formula/php@8.3-imap.rb | require_relative "../lib/php_extension_formula"
class PhpAT83Imap < PhpExtensionFormula
extension_dsl "IMAP Extension"
deprecate! date: "2027-12-31", because: :unsupported
depends_on "imap-uw"
depends_on "openssl@3"
depends_on "krb5"
configure_arg %W[
--with-imap=#{Formula["imap-uw"].opt_prefix}
--with-imap-ssl=#{Formula["openssl@3"].opt_prefix}
--with-kerberos
]
def install
ENV["PHP_OPENSSL"] = "yes"
super
end
end
| ruby | BSD-2-Clause | 6f1beba58200ca5652a5507391b30e4ba90ed8e3 | 2026-01-04T17:57:42.980777Z | false |
kabel/homebrew-php-ext | https://github.com/kabel/homebrew-php-ext/blob/6f1beba58200ca5652a5507391b30e4ba90ed8e3/Formula/php@8.3-snmp.rb | Formula/php@8.3-snmp.rb | require_relative "../lib/php_extension_formula"
class PhpAT83Snmp < PhpExtensionFormula
extension_dsl "SNMP Extension"
deprecate! date: "2027-12-31", because: :unsupported
depends_on "net-snmp"
depends_on "openssl@3"
configure_arg "--with-snmp=#{Formula["net-snmp"].opt_prefix}"
end
| ruby | BSD-2-Clause | 6f1beba58200ca5652a5507391b30e4ba90ed8e3 | 2026-01-04T17:57:42.980777Z | false |
kabel/homebrew-php-ext | https://github.com/kabel/homebrew-php-ext/blob/6f1beba58200ca5652a5507391b30e4ba90ed8e3/Formula/php@8.1-pdo-oci.rb | Formula/php@8.1-pdo-oci.rb | require_relative "../lib/oracle_php_extension_formula"
class PhpAT81PdoOci < OraclePhpExtensionFormula
extension_dsl "PDO Driver OCI"
deprecate! date: "2025-12-31", because: :unsupported
instantclient_options arg: "--with-pdo-oci", with_version: true
end
| ruby | BSD-2-Clause | 6f1beba58200ca5652a5507391b30e4ba90ed8e3 | 2026-01-04T17:57:42.980777Z | false |
kabel/homebrew-php-ext | https://github.com/kabel/homebrew-php-ext/blob/6f1beba58200ca5652a5507391b30e4ba90ed8e3/Formula/php@8.1-imap.rb | Formula/php@8.1-imap.rb | require_relative "../lib/php_extension_formula"
class PhpAT81Imap < PhpExtensionFormula
extension_dsl "IMAP Extension"
deprecate! date: "2025-12-31", because: :unsupported
depends_on "imap-uw"
depends_on "openssl@3"
depends_on "krb5"
configure_arg %W[
--with-imap=#{Formula["imap-uw"].opt_prefix}
--with-imap-ssl=#{Formula["openssl@3"].opt_prefix}
--with-kerberos
]
def install
ENV["PHP_OPENSSL"] = "yes"
super
end
end
| ruby | BSD-2-Clause | 6f1beba58200ca5652a5507391b30e4ba90ed8e3 | 2026-01-04T17:57:42.980777Z | false |
kabel/homebrew-php-ext | https://github.com/kabel/homebrew-php-ext/blob/6f1beba58200ca5652a5507391b30e4ba90ed8e3/Formula/php@8.2-enchant.rb | Formula/php@8.2-enchant.rb | require_relative "../lib/php_extension_formula"
class PhpAT82Enchant < PhpExtensionFormula
extension_dsl "Enchant Extension"
deprecate! date: "2026-12-31", because: :unsupported
depends_on "enchant"
end
| ruby | BSD-2-Clause | 6f1beba58200ca5652a5507391b30e4ba90ed8e3 | 2026-01-04T17:57:42.980777Z | false |
kabel/homebrew-php-ext | https://github.com/kabel/homebrew-php-ext/blob/6f1beba58200ca5652a5507391b30e4ba90ed8e3/Formula/php@8.1-oci8.rb | Formula/php@8.1-oci8.rb | require_relative "../lib/oracle_php_extension_formula"
class PhpAT81Oci8 < OraclePhpExtensionFormula
extension_dsl "OCI8 Extension"
deprecate! date: "2025-12-31", because: :unsupported
instantclient_options arg: "--with-oci8"
end
| ruby | BSD-2-Clause | 6f1beba58200ca5652a5507391b30e4ba90ed8e3 | 2026-01-04T17:57:42.980777Z | false |
kabel/homebrew-php-ext | https://github.com/kabel/homebrew-php-ext/blob/6f1beba58200ca5652a5507391b30e4ba90ed8e3/Formula/php@8.2-imap.rb | Formula/php@8.2-imap.rb | require_relative "../lib/php_extension_formula"
class PhpAT82Imap < PhpExtensionFormula
extension_dsl "IMAP Extension"
deprecate! date: "2026-12-31", because: :unsupported
depends_on "imap-uw"
depends_on "openssl@3"
depends_on "krb5"
configure_arg %W[
--with-imap=#{Formula["imap-uw"].opt_prefix}
--with-imap-ssl=#{Formula["openssl@3"].opt_prefix}
--with-kerberos
]
def install
ENV["PHP_OPENSSL"] = "yes"
super
end
end
| ruby | BSD-2-Clause | 6f1beba58200ca5652a5507391b30e4ba90ed8e3 | 2026-01-04T17:57:42.980777Z | false |
kabel/homebrew-php-ext | https://github.com/kabel/homebrew-php-ext/blob/6f1beba58200ca5652a5507391b30e4ba90ed8e3/Formula/php@8.3-oci8.rb | Formula/php@8.3-oci8.rb | require_relative "../lib/oracle_php_extension_formula"
class PhpAT83Oci8 < OraclePhpExtensionFormula
extension_dsl "OCI8 Extension"
deprecate! date: "2027-12-31", because: :unsupported
instantclient_options arg: "--with-oci8"
end
| ruby | BSD-2-Clause | 6f1beba58200ca5652a5507391b30e4ba90ed8e3 | 2026-01-04T17:57:42.980777Z | false |
kabel/homebrew-php-ext | https://github.com/kabel/homebrew-php-ext/blob/6f1beba58200ca5652a5507391b30e4ba90ed8e3/Formula/php-enchant.rb | Formula/php-enchant.rb | require_relative "../lib/php_extension_formula"
class PhpEnchant < PhpExtensionFormula
extension_dsl "Enchant Extension"
depends_on "enchant"
end
| ruby | BSD-2-Clause | 6f1beba58200ca5652a5507391b30e4ba90ed8e3 | 2026-01-04T17:57:42.980777Z | false |
kabel/homebrew-php-ext | https://github.com/kabel/homebrew-php-ext/blob/6f1beba58200ca5652a5507391b30e4ba90ed8e3/Formula/php@8.1-snmp.rb | Formula/php@8.1-snmp.rb | require_relative "../lib/php_extension_formula"
class PhpAT81Snmp < PhpExtensionFormula
extension_dsl "SNMP Extension"
deprecate! date: "2025-12-31", because: :unsupported
depends_on "net-snmp"
depends_on "openssl@3"
configure_arg "--with-snmp=#{Formula["net-snmp"].opt_prefix}"
end
| ruby | BSD-2-Clause | 6f1beba58200ca5652a5507391b30e4ba90ed8e3 | 2026-01-04T17:57:42.980777Z | false |
kabel/homebrew-php-ext | https://github.com/kabel/homebrew-php-ext/blob/6f1beba58200ca5652a5507391b30e4ba90ed8e3/Formula/php@8.3-enchant.rb | Formula/php@8.3-enchant.rb | require_relative "../lib/php_extension_formula"
class PhpAT83Enchant < PhpExtensionFormula
extension_dsl "Enchant Extension"
deprecate! date: "2027-12-31", because: :unsupported
depends_on "enchant"
end
| ruby | BSD-2-Clause | 6f1beba58200ca5652a5507391b30e4ba90ed8e3 | 2026-01-04T17:57:42.980777Z | false |
kabel/homebrew-php-ext | https://github.com/kabel/homebrew-php-ext/blob/6f1beba58200ca5652a5507391b30e4ba90ed8e3/Formula/php@8.1-enchant.rb | Formula/php@8.1-enchant.rb | require_relative "../lib/php_extension_formula"
class PhpAT81Enchant < PhpExtensionFormula
extension_dsl "Enchant Extension"
deprecate! date: "2025-12-31", because: :unsupported
depends_on "enchant"
end
| ruby | BSD-2-Clause | 6f1beba58200ca5652a5507391b30e4ba90ed8e3 | 2026-01-04T17:57:42.980777Z | false |
kabel/homebrew-php-ext | https://github.com/kabel/homebrew-php-ext/blob/6f1beba58200ca5652a5507391b30e4ba90ed8e3/Formula/php@8.2-oci8.rb | Formula/php@8.2-oci8.rb | require_relative "../lib/oracle_php_extension_formula"
class PhpAT82Oci8 < OraclePhpExtensionFormula
extension_dsl "OCI8 Extension"
deprecate! date: "2026-12-31", because: :unsupported
instantclient_options arg: "--with-oci8"
end
| ruby | BSD-2-Clause | 6f1beba58200ca5652a5507391b30e4ba90ed8e3 | 2026-01-04T17:57:42.980777Z | false |
kabel/homebrew-php-ext | https://github.com/kabel/homebrew-php-ext/blob/6f1beba58200ca5652a5507391b30e4ba90ed8e3/lib/oracle_php_extension_formula.rb | lib/oracle_php_extension_formula.rb | # frozen_string_literal: true
require_relative "../lib/php_extension_formula"
class OraclePhpExtensionFormula < PhpExtensionFormula
def install
(prefix/"instantclient").install resource("instantclient-basic")
(prefix/"instantclient").install resource("instantclient-sdk")
instantclient_version = resource("instantclient-basic")
.version
.to_s
.split("-")[0]
arg = "#{self.class.instantclient_arg}=instantclient,#{prefix}/instantclient"
arg += ",#{instantclient_version}" if self.class.instantclient_with_version
configure_args << arg
super
end
def caveats
<<~EOS
Installing this Formula means you have AGREED to the Oracle Technology Network License Agreement at
http://www.oracle.com/technetwork/licenses/instant-client-lic-152016.html
You must also have an Oracle Account. You can register for a free account at
https://profile.oracle.com/myprofile/account/create-account.jspx
EOS
end
class << self
attr_reader :instantclient_arg, :instantclient_with_version
def instantclient_options(options)
@instantclient_arg = options[:arg]
@instantclient_with_version = options[:with_version]
end
def extension_dsl(*)
super
resource "instantclient-basic" do
url "https://download.oracle.com/otn_software/mac/instantclient/198000/instantclient-basic-macos.x64-19.8.0.0.0dbru.zip"
sha256 "57ed4198f3a10d83cd5ddc2472c058d4c3b0b786246baebf6bbfc7391cc12087"
end
resource "instantclient-sdk" do
url "https://download.oracle.com/otn_software/mac/instantclient/198000/instantclient-sdk-macos.x64-19.8.0.0.0dbru.zip"
sha256 "0fa8ae4c4418aa66ce875cf92e728dd7a81aeaf2e68e7926e102b5e52fc8ba4c"
end
end
end
end
| ruby | BSD-2-Clause | 6f1beba58200ca5652a5507391b30e4ba90ed8e3 | 2026-01-04T17:57:42.980777Z | false |
kabel/homebrew-php-ext | https://github.com/kabel/homebrew-php-ext/blob/6f1beba58200ca5652a5507391b30e4ba90ed8e3/lib/php_extension_formula.rb | lib/php_extension_formula.rb | # frozen_string_literal: true
class PhpExtensionFormula < Formula
desc "PHP Extension"
homepage "https://www.php.net/"
def initialize(name, path, spec, alias_path: nil, tap: nil, force_bottle: false)
super
active_spec.owner = php_parent.stable.owner
end
def install
cd "ext/#{extension}"
system php_parent.bin/"phpize"
inreplace "configure",
"EXTENSION_DIR=`$PHP_CONFIG --extension-dir 2>/dev/null`",
"EXTENSION_DIR=#{lib/module_path}"
system "./configure", *configure_args
system "make", "phpincludedir=#{include}/php", "install"
end
def post_install
ext_config_path = etc/"php"/php_parent.version.major_minor/"conf.d"/"ext-#{extension}.ini"
if ext_config_path.exist?
inreplace ext_config_path,
/#{extension_type}=.*$/,
"#{extension_type}=#{opt_lib/module_path}/#{extension}.so"
else
ext_config_path.write <<~EOS
[#{extension}]
#{extension_type}=#{opt_lib/module_path}/#{extension}.so
EOS
end
end
test do
assert_match(/^#{extension}$/i,
shell_output("#{php_parent.opt_bin}/php -m"),
"failed to find extension in php -m output")
end
private
delegate [:php_parent, :extension, :configure_args] => :"self.class"
def extension_type
# extension or zend_extension
"extension"
end
def module_path
extension_dir = Utils.safe_popen_read(php_parent.opt_bin/"php-config", "--extension-dir").chomp
php_basename = File.basename(extension_dir)
"php/#{php_basename}"
end
class << self
NAME_PATTERN = /^Php(?:AT([578])(\d+))?(.+)/
attr_reader :configure_args, :php_parent, :extension
def configure_arg(args)
@configure_args ||= []
@configure_args.concat(Array(args))
end
def extension_dsl(description = nil)
class_name = name.split("::").last
m = NAME_PATTERN.match(class_name)
raise "Bad PHP Extension name for #{class_name}" if m.nil?
if m[1].nil?
parent_name = "php"
else
parent_name = "php@#{m.captures[0..1].join(".")}"
keg_only :versioned_formula
end
@php_parent = Formula[parent_name]
@extension = m[3].gsub(/([a-z])([A-Z])/) do
"#{Regexp.last_match(1)}_#{Regexp.last_match(2)}"
end.downcase
@configure_args = %W[
--with-php-config=#{php_parent.opt_bin/"php-config"}
]
desc "#{description} for PHP #{php_parent.version.major_minor}" unless description.nil?
homepage php_parent.homepage + extension
url php_parent.stable.url
sha256 php_parent.stable.checksum.hexdigest
depends_on "autoconf" => :build
depends_on "pkg-config" => :build
depends_on parent_name
end
end
end
| ruby | BSD-2-Clause | 6f1beba58200ca5652a5507391b30e4ba90ed8e3 | 2026-01-04T17:57:42.980777Z | false |
ryanza/stateflow | https://github.com/ryanza/stateflow/blob/8abeef6440154b0313a186f5872cb0b19f803641/init.rb | init.rb | require 'stateflow' | ruby | MIT | 8abeef6440154b0313a186f5872cb0b19f803641 | 2026-01-04T17:57:40.152738Z | false |
ryanza/stateflow | https://github.com/ryanza/stateflow/blob/8abeef6440154b0313a186f5872cb0b19f803641/benchmark/compare_state_machines.rb | benchmark/compare_state_machines.rb | require 'benchmark'
require 'active_record'
require 'stateflow'
require 'aasm'
# change this if sqlite is unavailable
dbconfig = {
:adapter => 'sqlite3',
:database => ':memory:'
}
ActiveRecord::Base.establish_connection(dbconfig)
ActiveRecord::Migration.verbose = false
class TestMigration < ActiveRecord::Migration
STATE_MACHINES = ['stateflow', 'aasm']
def self.up
STATE_MACHINES.each do |name|
create_table "#{name}_tests", :force => true do |t|
t.column :state, :string
end
end
end
def self.down
STATE_MACHINES.each do |name|
drop_table "#{name}_tests"
end
end
end
Stateflow.persistence = :active_record
class StateflowTest < ActiveRecord::Base
include Stateflow
stateflow do
initial :green
state :green, :yellow, :red
event :change_color do
transitions :from => :green, :to => :yellow
transitions :from => :yellow, :to => :red
transitions :from => :red, :to => :green
end
end
end
class AasmTest < ActiveRecord::Base
include AASM
aasm_column :state # defaults to aasm_state
aasm_initial_state :green
aasm_state :green
aasm_state :yellow
aasm_state :red
aasm_event :change_color do
transitions :from => :green, :to => :yellow
transitions :from => :yellow, :to => :red
transitions :from => :red, :to => :green
end
end
n = 1000
TestMigration.up
Benchmark.bm(7) do |x|
x.report('stateflow') do
n.times do
stateflow = StateflowTest.new
3.times { stateflow.change_color! }
end
end
x.report('aasm') do
n.times do
aasm = AasmTest.new
3.times { aasm.change_color! }
end
end
end
TestMigration.down
| ruby | MIT | 8abeef6440154b0313a186f5872cb0b19f803641 | 2026-01-04T17:57:40.152738Z | false |
ryanza/stateflow | https://github.com/ryanza/stateflow/blob/8abeef6440154b0313a186f5872cb0b19f803641/spec/stateflow_spec.rb | spec/stateflow_spec.rb | require 'spec_helper'
Stateflow.persistence = :none
class Robot
include Stateflow
stateflow do
initial :green
state :green, :yellow, :red
event :change_color do
transitions :from => :green, :to => :yellow
transitions :from => :yellow, :to => :red
transitions :from => :red, :to => :green
end
end
end
class Car
include Stateflow
stateflow do
initial :parked
state :parked do
enter do
"Entering parked"
end
exit do
"Exiting parked"
end
end
state :driving do
enter do
"Entering parked"
end
end
event :drive do
transitions :from => :parked, :to => :driving
end
event :park do
transitions :from => :driving, :to => :parked
end
end
end
class Bob
include Stateflow
stateflow do
state :yellow, :red, :purple
event :change_hair_color do
transitions :from => :purple, :to => :yellow
transitions :from => :yellow, :to => :red
transitions :from => :red, :to => :purple
end
end
end
class Dater
include Stateflow
stateflow do
state :single, :dating, :married
event :take_out do
transitions :from => :single, :to => :dating
end
event :gift do
transitions :from => :dating, :to => [:single, :married], :decide => :girls_mood?
end
event :blank_decision do
transitions :from => :single, :to => [:single, :married], :decide => :girls_mood?
end
event :fail do
transitions :from => :dating, :to => [:single, :married]
end
end
def girls_mood?
end
end
class Priority
include Stateflow
stateflow do
initial :medium
state :low, :medium, :high
event :low do
transitions :from => any, :to => :low
end
event :medium do
transitions :from => any, :to => :medium
end
event :high do
transitions :from => any, :to => :high
end
end
end
class Stater
include Stateflow
stateflow do
initial :bill
state :bob, :bill
event :lolcats do
transitions :from => :bill, :to => :bob
end
end
end
class Excepting
include Stateflow
stateflow do
initial :working
state :working, :failed
event :fail do
transition_missing do |from_state|
raise "Don't know how to fail when in state #{from_state}. Ironically failing anyway."
end
end
end
end
describe Stateflow do
describe "class methods" do
it "should respond to stateflow block to setup the intial stateflow" do
Robot.should respond_to(:stateflow)
end
it "should respond to the machine attr accessor" do
Robot.should respond_to(:machine)
end
it "should return all active persistence layers" do
Stateflow::Persistence.active.should =~ [:active_record, :mongo_mapper, :mongoid, :none]
end
end
describe "instance methods" do
before(:each) do
@r = Robot.new
end
it "should respond to current state" do
@r.should respond_to(:current_state)
end
it "should respond to the current state setter" do
@r.should respond_to(:set_current_state)
end
it "should respond to the current machine" do
@r.should respond_to(:machine)
end
it "should respond to available states" do
@r.should respond_to(:available_states)
end
it "should respond to load from persistence" do
@r.should respond_to(:load_from_persistence)
end
it "should respond to save to persistence" do
@r.should respond_to(:save_to_persistence)
end
end
describe "initial state" do
it "should set the initial state" do
robot = Robot.new
robot.current_state.name.should == :green
end
it "should return true for green?" do
robot = Robot.new
robot.green?.should be_truthy
end
it "should return false for yellow?" do
robot = Robot.new
robot.yellow?.should be_falsey
end
it "should return false for red?" do
robot = Robot.new
robot.red?.should be_falsey
end
it "should set the initial state to the first state set" do
bob = Bob.new
bob.current_state.name.should == :yellow
bob.yellow?.should be_truthy
end
end
it "robot class should contain red, yellow and green states" do
robot = Robot.new
robot.machine.states.keys.should include(:red, :yellow, :green)
end
describe "firing events" do
let(:robot) { Robot.new }
let(:event) { :change_color }
subject { robot }
it "should raise an exception if the event does not exist" do
lambda { robot.send(:fire_event, :fake) }.should raise_error(Stateflow::NoEventFound)
end
shared_examples_for "an entity supporting state changes" do
context "when firing" do
after(:each) { subject.send(event_method) }
it "should call the fire method on event" do
subject.machine.events[event].should_receive(:fire)
end
it "should call the fire_event method" do
subject.should_receive(:fire_event).with(event, {:save=>persisted})
end
end
it "should update the current state" do
subject.current_state.name.should == :green
subject.send(event_method)
subject.current_state.name.should == :yellow
end
end
describe "bang event" do
let(:event_method) { :change_color! }
let(:persisted) { true }
it_should_behave_like "an entity supporting state changes"
end
describe "non-bang event" do
let(:event_method) { :change_color }
let(:persisted) { false }
it_should_behave_like "an entity supporting state changes"
end
describe "before filters" do
before(:each) do
@car = Car.new
end
it "should call the exit state before filter on the exiting old state" do
@car.machine.states[:parked].should_receive(:execute_action).with(:exit, @car)
@car.drive!
end
it "should call the enter state before filter on the entering new state" do
@car.machine.states[:driving].should_receive(:execute_action).with(:enter, @car)
@car.drive!
end
end
end
describe "persistence" do
it "should attempt to persist the new state and the name should be a string" do
robot = Robot.new
robot.should_receive(:save_to_persistence).with("yellow", {:save=>true})
robot.change_color!
end
it "should attempt to read the initial state from the persistence" do
robot = Robot.new
def robot.load_from_persistence
:red
end
robot.current_state.name.should == :red
end
end
describe "dynamic to transitions" do
it "should raise an error without any decide argument" do
date = Dater.new
def date.load_from_persistence
:dating
end
lambda { date.fail! }.should raise_error(Stateflow::IncorrectTransition)
end
it "should raise an error if the decision method does not return a valid state" do
date = Dater.new
def date.girls_mood?
:lol
end
lambda { date.blank_decision! }.should raise_error(Stateflow::NoStateFound, "Decision did not return a state that was set in the 'to' argument")
end
it "should raise an error if the decision method returns blank/nil" do
date = Dater.new
def date.girls_mood?
end
lambda { date.blank_decision! }.should raise_error(Stateflow::NoStateFound, "Decision did not return a state that was set in the 'to' argument")
end
it "should calculate the decide block or method and transition to the correct state" do
date = Dater.new
def date.load_from_persistence
:dating
end
date.current_state.name.should == :dating
def date.girls_mood?
:single
end
date.gift!
date.current_state.name.should == :single
end
end
describe "transitions from any" do
it "should properly change state" do
priority = Priority.new
priority.low!
priority.should be_low
priority.medium!
priority.should be_medium
priority.high!
priority.should be_high
end
end
describe "previous state" do
it "should display the previous state" do
stater = Stater.new
stater.lolcats!
stater._previous_state.should == "bill"
stater.current_state == "bob"
end
end
describe "available states" do
it "should return the available states" do
robot = Robot.new
robot.available_states.should include(:red, :yellow, :green)
end
end
describe 'sub-classes of Stateflow\'d classes' do
subject { Class.new(Stater) }
it 'shouldn\'t raise an exception' do
expect { subject.new.lolcats! }.not_to raise_exception
end
end
describe 'missing transitions' do
subject { proc { Excepting.new.fail } }
it { should raise_error(/Don't know how to fail when in state working./) }
end
end
| ruby | MIT | 8abeef6440154b0313a186f5872cb0b19f803641 | 2026-01-04T17:57:40.152738Z | false |
ryanza/stateflow | https://github.com/ryanza/stateflow/blob/8abeef6440154b0313a186f5872cb0b19f803641/spec/spec_helper.rb | spec/spec_helper.rb | $LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'stateflow'
| ruby | MIT | 8abeef6440154b0313a186f5872cb0b19f803641 | 2026-01-04T17:57:40.152738Z | false |
ryanza/stateflow | https://github.com/ryanza/stateflow/blob/8abeef6440154b0313a186f5872cb0b19f803641/spec/orm/activerecord_spec.rb | spec/orm/activerecord_spec.rb | require 'spec_helper'
require 'active_record'
Stateflow.persistence = :active_record
# change this if sqlite is unavailable
dbconfig = {
:adapter => 'sqlite3',
:database => ':memory:'
}
ActiveRecord::Base.establish_connection(dbconfig)
ActiveRecord::Migration.verbose = false
class TestMigration < ActiveRecord::Migration[4.2]
def self.up
create_table :active_record_robots, :force => true do |t|
t.column :state, :string
t.column :name, :string
end
create_table :active_record_no_scope_robots, :force => true do |t|
t.column :state, :string
t.column :name, :string
end
end
def self.down
drop_table :active_record_robots
drop_table :active_record_no_scope_robots
end
end
class ActiveRecordRobot < ActiveRecord::Base
include Stateflow
stateflow do
initial :red
state :red, :green
event :change do
transitions :from => :red, :to => :green
end
end
end
class ActiveRecordNoScopeRobot < ActiveRecord::Base
include Stateflow
attr_reader :state
stateflow do
create_scopes false
initial :red
state :red, :green
event :change do
transitions :from => :red, :to => :green
end
end
end
class ActiveRecordStateColumnSetRobot < ActiveRecord::Base
include Stateflow
stateflow do
state_column :status
initial :red
state :red, :green
event :change do
transitions :from => :red, :to => :green
end
end
end
describe Stateflow::Persistence::ActiveRecord do
before(:all) { TestMigration.up }
after(:all) { TestMigration.down }
after { ActiveRecordRobot.delete_all }
let(:robot) { ActiveRecordRobot.new }
describe "includes" do
it "should include current_state" do
robot.respond_to?(:current_state).should be_truthy
end
it "should include current_state=" do
robot.respond_to?(:set_current_state).should be_truthy
end
it "should include save_to_persistence" do
robot.respond_to?(:save_to_persistence).should be_truthy
end
it "should include load_from_persistence" do
robot.respond_to?(:load_from_persistence).should be_truthy
end
end
describe "bang method" do
before do
@robot = robot
@robot.state = "red"
end
it "should call the set_current_state with save being true" do
@robot.should_receive(:set_current_state).with(@robot.machine.states[:green], {:save=>true})
@robot.change!
end
it "should call the setter method for the state column" do
@robot.should_receive(:state=).with("green")
@robot.change!
end
it "should call save after setting the state column" do
@robot.should_receive(:save)
@robot.change!
end
it "should save the record" do
@robot.new_record?.should be_truthy
@robot.change!
@robot.new_record?.should be_falsey
@robot.reload.state.should == "green"
end
end
describe "non bang method" do
before do
@robot = robot
@robot.state = "red"
end
it "should call the set_current_state with save being false" do
@robot.should_receive(:set_current_state).with(@robot.machine.states[:green], {:save=>false})
@robot.change
end
it "should call the setter method for the state column" do
@robot.should_receive(:state=).with("green")
@robot.change
end
it "should call save after setting the state column" do
@robot.should_not_receive(:save)
@robot.change
end
it "should not save the record" do
@robot.new_record?.should be_truthy
@robot.change
@robot.new_record?.should be_truthy
@robot.state.should == "green"
end
end
it "Make sure stateflow saves the initial state if no state is set" do
@robot3 = robot
@robot3.save
@robot3.reload
@robot3.state.should == "red"
end
describe "load from persistence" do
before do
@robot = robot
@robot.state = "green"
@robot.name = "Bottie"
@robot.save
end
it "should call the load_from_persistence method" do
@robot.reload
@robot.should_receive(:load_from_persistence)
@robot.current_state
end
end
describe "scopes" do
it "should be added for each state" do
ActiveRecordRobot.should respond_to(:red)
ActiveRecordRobot.should respond_to(:green)
end
it "should be added for each state when the state column is not 'state'" do
ActiveRecordStateColumnSetRobot.should respond_to(:red)
ActiveRecordStateColumnSetRobot.should respond_to(:green)
end
it "should not be added for each state" do
ActiveRecordNoScopeRobot.should_not respond_to(:red)
ActiveRecordNoScopeRobot.should_not respond_to(:green)
end
it "should behave like Mongoid scopes" do
2.times { ActiveRecordRobot.create(:state => "red") }
3.times { ActiveRecordRobot.create(:state => "green") }
ActiveRecordRobot.red.count.should == 2
ActiveRecordRobot.green.count.should == 3
end
end
end
| ruby | MIT | 8abeef6440154b0313a186f5872cb0b19f803641 | 2026-01-04T17:57:40.152738Z | false |
ryanza/stateflow | https://github.com/ryanza/stateflow/blob/8abeef6440154b0313a186f5872cb0b19f803641/spec/orm/mongoid_spec.rb | spec/orm/mongoid_spec.rb | require 'spec_helper'
require 'mongoid'
Stateflow.persistence = :mongoid
Mongoid.load!(File.expand_path("../../mongoid.yml", __FILE__), :test)
class MongoRobot
include Mongoid::Document
include Stateflow
field :state
field :name
stateflow do
initial :red
state :red, :green
event :change do
transitions :from => :red, :to => :green
end
end
end
class MongoNoScopeRobot
include Mongoid::Document
include Stateflow
field :state
field :name
stateflow do
create_scopes false
initial :red
state :red, :green
event :change do
transitions :from => :red, :to => :green
end
end
end
describe Stateflow::Persistence::Mongoid do
after do
MongoRobot.collection.drop
MongoNoScopeRobot.collection.drop
end
let(:robot) { MongoRobot.new }
describe "includes" do
it "should include current_state" do
robot.respond_to?(:current_state).should be_truthy
end
it "should include current_state=" do
robot.respond_to?(:set_current_state).should be_truthy
end
it "should include save_to_persistence" do
robot.respond_to?(:save_to_persistence).should be_truthy
end
it "should include load_from_persistence" do
robot.respond_to?(:load_from_persistence).should be_truthy
end
end
describe "bang method" do
before do
@robot = robot
@robot.state = "red"
end
it "should call the set_current_state with save being true" do
@robot.should_receive(:set_current_state).with(@robot.machine.states[:green], {:save=>true})
@robot.change!
end
it "should call the setter method for the state column" do
@robot.should_receive(:state=).with("green")
@robot.change!
end
it "should call save after setting the state column" do
@robot.should_receive(:save)
@robot.change!
end
it "should save the record" do
@robot.new_record?.should be_truthy
@robot.change!
@robot.new_record?.should be_falsey
@robot.reload.state.should == "green"
end
end
describe "non bang method" do
before do
@robot = robot
@robot.state = "red"
end
it "should call the set_current_state with save being false" do
@robot.should_receive(:set_current_state).with(@robot.machine.states[:green], {:save=>false})
@robot.change
end
it "should call the setter method for the state column" do
@robot.should_receive(:state=).with("green")
@robot.change
end
it "should call save after setting the state column" do
@robot.should_not_receive(:save)
@robot.change
end
it "should not save the record" do
@robot.new_record?.should be_truthy
@robot.change
@robot.new_record?.should be_truthy
@robot.state.should == "green"
end
end
it "Make sure stateflow saves the initial state if no state is set" do
@robot = robot
@robot.save
@robot.reload
@robot.state.should == "red"
end
describe "load from persistence" do
before do
@robot = robot
@robot.state = "green"
@robot.name = "Bottie"
@robot.save
end
it "should call the load_from_persistence method" do
@robot.reload
@robot.should_receive(:load_from_persistence)
@robot.current_state
end
end
describe "scopes" do
it "should be added for each state" do
MongoRobot.should respond_to(:red)
MongoRobot.should respond_to(:green)
end
it "should be not added for each state" do
MongoNoScopeRobot.should_not respond_to(:red)
MongoNoScopeRobot.should_not respond_to(:green)
end
it "should behave like Mongoid scopes" do
2.times { MongoRobot.create(:state => "red") }
3.times { MongoRobot.create(:state => "green") }
MongoRobot.red.count.should == 2
MongoRobot.green.count.should == 3
end
end
end
| ruby | MIT | 8abeef6440154b0313a186f5872cb0b19f803641 | 2026-01-04T17:57:40.152738Z | false |
ryanza/stateflow | https://github.com/ryanza/stateflow/blob/8abeef6440154b0313a186f5872cb0b19f803641/examples/test.rb | examples/test.rb | require 'rubygems'
require 'stateflow'
class Test
include Stateflow
stateflow do
initial :love
state :love do
enter lambda { |t| p "Entering love" }
exit :exit_love
end
state :hate do
enter lambda { |t| p "Entering hate" }
exit lambda { |t| p "Exiting hate" }
end
state :mixed do
enter lambda { |t| p "Entering mixed" }
exit lambda { |t| p "Exiting mixed" }
end
event :b do
transitions :from => :love, :to => :hate, :if => :no_ice_cream
transitions :from => :hate, :to => :love
end
event :a do
transitions :from => :love, :to => [:hate, :mixed], :decide => :likes_ice_cream?
transitions :from => [:hate, :mixed], :to => :love
end
end
def likes_ice_cream?
rand(10) > 5 ? :mixed : :hate
end
def exit_love
p "Exiting love"
end
def no_ice_cream
rand(4) > 2 ? true : false
end
end
| ruby | MIT | 8abeef6440154b0313a186f5872cb0b19f803641 | 2026-01-04T17:57:40.152738Z | false |
ryanza/stateflow | https://github.com/ryanza/stateflow/blob/8abeef6440154b0313a186f5872cb0b19f803641/examples/robot.rb | examples/robot.rb | require 'rubygems'
require 'stateflow'
class Robot
include Stateflow
stateflow do
initial :green
state :green, :yellow, :red
event :change_color do
transitions :from => :green, :to => :yellow
transitions :from => :yellow, :to => :red
transitions :from => :red, :to => :green
end
end
end
| ruby | MIT | 8abeef6440154b0313a186f5872cb0b19f803641 | 2026-01-04T17:57:40.152738Z | false |
ryanza/stateflow | https://github.com/ryanza/stateflow/blob/8abeef6440154b0313a186f5872cb0b19f803641/lib/stateflow.rb | lib/stateflow.rb | require 'active_support'
require 'active_support/inflector'
module Stateflow
extend ActiveSupport::Concern
included do
Stateflow::Persistence.load!(self)
end
def self.persistence
@@persistence ||= nil
end
def self.persistence=(persistence)
@@persistence = persistence
end
module ClassMethods
attr_reader :machine
def stateflow(&block)
@machine = Stateflow::Machine.new(&block)
@machine.states.values.each do |state|
state_name = state.name
define_method "#{state_name}?" do
state_name == current_state.name
end
add_scope state if @machine.create_scopes?
end
@machine.events.keys.each do |key|
define_method "#{key}" do
fire_event(key, :save => false)
end
define_method "#{key}!" do
fire_event(key, :save => true)
end
end
end
end
attr_accessor :_previous_state
def current_state
@current_state ||= load_from_persistence.nil? ? machine.initial_state : machine.states[load_from_persistence.to_sym]
end
def set_current_state(new_state, options = {})
save_to_persistence(new_state.name.to_s, options)
@current_state = new_state
end
def machine
self.class.ancestors.select { |k| k.machine if k.respond_to? :machine }.first.machine
end
def available_states
machine.states.keys
end
private
def fire_event(event_name, options = {})
event = machine.events[event_name.to_sym]
raise Stateflow::NoEventFound.new("No event matches #{event_name}") if event.nil?
event.fire(current_state, self, options)
end
autoload :Machine, 'stateflow/machine'
autoload :State, 'stateflow/state'
autoload :Event, 'stateflow/event'
autoload :Transition, 'stateflow/transition'
autoload :Persistence, 'stateflow/persistence'
autoload :Exception, 'stateflow/exception'
end
require 'stateflow/railtie' if defined?(Rails)
| ruby | MIT | 8abeef6440154b0313a186f5872cb0b19f803641 | 2026-01-04T17:57:40.152738Z | false |
ryanza/stateflow | https://github.com/ryanza/stateflow/blob/8abeef6440154b0313a186f5872cb0b19f803641/lib/stateflow/persistence.rb | lib/stateflow/persistence.rb | module Stateflow
module Persistence
def self.active
persistences = Array.new
Dir[File.dirname(__FILE__) + '/persistence/*.rb'].each do |file|
persistences << File.basename(file, File.extname(file)).underscore.to_sym
end
persistences
end
def self.load!(base)
begin
base.send :include, "Stateflow::Persistence::#{Stateflow.persistence.to_s.camelize}".constantize
rescue NameError
puts "[Stateflow] The ORM you are using does not have a Persistence layer. Defaulting to ActiveRecord."
puts "[Stateflow] You can overwrite the persistence with Stateflow.persistence = :new_persistence_layer"
Stateflow.persistence = :active_record
base.send :include, "Stateflow::Persistence::ActiveRecord".constantize
end
end
Stateflow::Persistence.active.each do |p|
autoload p.to_s.camelize.to_sym, "stateflow/persistence/#{p.to_s}"
end
end
end | ruby | MIT | 8abeef6440154b0313a186f5872cb0b19f803641 | 2026-01-04T17:57:40.152738Z | false |
ryanza/stateflow | https://github.com/ryanza/stateflow/blob/8abeef6440154b0313a186f5872cb0b19f803641/lib/stateflow/event.rb | lib/stateflow/event.rb | module Stateflow
class Event
attr_accessor :name, :transitions, :machine
def initialize(name, machine=nil, &transitions)
@name = name
@machine = machine
@transitions = Array.new
instance_eval(&transitions)
end
def fire(current_state, klass, options)
transition = @transitions.select{ |t| t.from.include? current_state.name }.first
no_transition_found(current_state.name) if transition.nil?
return false unless transition.can_transition?(klass)
new_state = klass.machine.states[transition.find_to_state(klass)]
no_state_found(transition.to) if new_state.nil?
current_state.execute_action(:exit, klass)
klass._previous_state = current_state.name.to_s
new_state.execute_action(:enter, klass)
klass.set_current_state(new_state, options)
true
end
private
def transition_missing(&block)
@transition_missing = block
end
def no_transition_found(from_state)
raise NoTransitionFound.new("No transition found for event #{@name}") unless @transition_missing
@transition_missing.call(from_state)
end
def no_state_found(target_state)
NoStateFound.new("Invalid state #{target_state.to_s} for transition.")
end
def transitions(args = {})
transition = Stateflow::Transition.new(args)
@transitions << transition
end
def any
@machine.states.keys
end
end
end
| ruby | MIT | 8abeef6440154b0313a186f5872cb0b19f803641 | 2026-01-04T17:57:40.152738Z | false |
ryanza/stateflow | https://github.com/ryanza/stateflow/blob/8abeef6440154b0313a186f5872cb0b19f803641/lib/stateflow/transition.rb | lib/stateflow/transition.rb | module Stateflow
class IncorrectTransition < Exception; end
class Transition
attr_reader :from, :to, :if, :decide
def initialize(args)
@from = [args[:from]].flatten
@to = args[:to]
@if = args[:if]
@decide = args[:decide]
end
def can_transition?(base)
return true unless @if
execute_action(@if, base)
end
def find_to_state(base)
raise IncorrectTransition.new("Array of destinations and no decision") if @to.is_a?(Array) && @decide.nil?
return @to unless @to.is_a?(Array)
to = execute_action(@decide, base)
raise NoStateFound.new("Decision did not return a state that was set in the 'to' argument") unless @to.include?(to)
to
end
private
def execute_action(action, base)
case action
when Symbol, String
base.send(action)
when Proc
action.call(base)
end
end
end
end | ruby | MIT | 8abeef6440154b0313a186f5872cb0b19f803641 | 2026-01-04T17:57:40.152738Z | false |
ryanza/stateflow | https://github.com/ryanza/stateflow/blob/8abeef6440154b0313a186f5872cb0b19f803641/lib/stateflow/state.rb | lib/stateflow/state.rb | module Stateflow
class State
attr_accessor :name, :options
def initialize(name, &options)
@name = name
@options = Hash.new
instance_eval(&options) if block_given?
end
def enter(method = nil, &block)
@options[:enter] = method.nil? ? block : method
end
def exit(method = nil, &block)
@options[:exit] = method.nil? ? block : method
end
def execute_action(action, base)
action = @options[action.to_sym]
case action
when Symbol, String
base.send(action)
when Proc
action.call(base)
end
end
end
end
| ruby | MIT | 8abeef6440154b0313a186f5872cb0b19f803641 | 2026-01-04T17:57:40.152738Z | false |
ryanza/stateflow | https://github.com/ryanza/stateflow/blob/8abeef6440154b0313a186f5872cb0b19f803641/lib/stateflow/railtie.rb | lib/stateflow/railtie.rb | module Stateflow
class Railtie < Rails::Railtie
def default_orm
generators = config.respond_to?(:app_generators) ? :app_generators : :generators
config.send(generators).options[:rails][:orm]
end
initializer "stateflow.set_persistence" do
Stateflow.persistence = default_orm if Stateflow.persistence.blank?
end
end
end | ruby | MIT | 8abeef6440154b0313a186f5872cb0b19f803641 | 2026-01-04T17:57:40.152738Z | false |
ryanza/stateflow | https://github.com/ryanza/stateflow/blob/8abeef6440154b0313a186f5872cb0b19f803641/lib/stateflow/exception.rb | lib/stateflow/exception.rb | module Stateflow
class NoTransitionFound < Exception; end
class NoStateFound < Exception; end
class NoEventFound < Exception; end
end | ruby | MIT | 8abeef6440154b0313a186f5872cb0b19f803641 | 2026-01-04T17:57:40.152738Z | false |
ryanza/stateflow | https://github.com/ryanza/stateflow/blob/8abeef6440154b0313a186f5872cb0b19f803641/lib/stateflow/machine.rb | lib/stateflow/machine.rb | module Stateflow
class Machine
attr_accessor :states, :initial_state, :events
def initialize(&machine)
@states, @events, @create_scopes = Hash.new, Hash.new, true
instance_eval(&machine)
end
def state_column(name = :state)
@state_column ||= name
end
def create_scopes(bool = false)
@create_scopes = bool
end
def create_scopes?
@create_scopes
end
private
def initial(name)
@initial_state_name = name
end
def state(*names, &options)
names.each do |name|
state = Stateflow::State.new(name, &options)
@initial_state = state if @states.empty? || @initial_state_name == name
@states[name.to_sym] = state
end
end
def event(name, &transitions)
event = Stateflow::Event.new(name, self, &transitions)
@events[name.to_sym] = event
end
end
end
| ruby | MIT | 8abeef6440154b0313a186f5872cb0b19f803641 | 2026-01-04T17:57:40.152738Z | false |
ryanza/stateflow | https://github.com/ryanza/stateflow/blob/8abeef6440154b0313a186f5872cb0b19f803641/lib/stateflow/persistence/active_record.rb | lib/stateflow/persistence/active_record.rb | module Stateflow
module Persistence
module ActiveRecord
extend ActiveSupport::Concern
included do
before_validation(:ensure_initial_state, :on => :create)
end
module ClassMethods
def add_scope(state)
scope state.name, proc { where("#{machine.state_column}".to_sym => state.name.to_s) }
end
end
def load_from_persistence
send machine.state_column.to_sym
end
def save_to_persistence(new_state, options = {})
send("#{machine.state_column}=".to_sym, new_state)
save if options[:save]
end
def ensure_initial_state
send("#{machine.state_column.to_s}=", current_state.name.to_s) if send(machine.state_column.to_s).blank?
end
end
end
end
| ruby | MIT | 8abeef6440154b0313a186f5872cb0b19f803641 | 2026-01-04T17:57:40.152738Z | false |
ryanza/stateflow | https://github.com/ryanza/stateflow/blob/8abeef6440154b0313a186f5872cb0b19f803641/lib/stateflow/persistence/mongoid.rb | lib/stateflow/persistence/mongoid.rb | module Stateflow
module Persistence
module Mongoid
extend ActiveSupport::Concern
included do
before_validation(:ensure_initial_state, :on => :create)
end
module ClassMethods
def add_scope(state)
scope state.name, -> { where(:state => state.name.to_s) } unless self.respond_to?(state.name)
end
end
def load_from_persistence
send machine.state_column.to_sym
end
def save_to_persistence(new_state, options = {})
send("#{machine.state_column}=".to_sym, new_state)
save if options[:save]
end
def ensure_initial_state
send("#{machine.state_column.to_s}=", current_state.name.to_s) if send(machine.state_column.to_s).blank?
end
end
end
end
| ruby | MIT | 8abeef6440154b0313a186f5872cb0b19f803641 | 2026-01-04T17:57:40.152738Z | false |
ryanza/stateflow | https://github.com/ryanza/stateflow/blob/8abeef6440154b0313a186f5872cb0b19f803641/lib/stateflow/persistence/none.rb | lib/stateflow/persistence/none.rb | module Stateflow
module Persistence
module None
extend ActiveSupport::Concern
module ClassMethods
def add_scope(state)
# do nothing
end
end
attr_accessor :state
def load_from_persistence
@state
end
def save_to_persistence(new_state, options)
@state = new_state
end
end
end
end
| ruby | MIT | 8abeef6440154b0313a186f5872cb0b19f803641 | 2026-01-04T17:57:40.152738Z | false |
ryanza/stateflow | https://github.com/ryanza/stateflow/blob/8abeef6440154b0313a186f5872cb0b19f803641/lib/stateflow/persistence/mongo_mapper.rb | lib/stateflow/persistence/mongo_mapper.rb | module Stateflow
module Persistence
module MongoMapper
extend ActiveSupport::Concern
included do
before_validation(:ensure_initial_state, :on => :create)
end
module ClassMethods
def add_scope(state)
scope state.name, where(:state => state.name.to_s)
end
end
module InstanceMethods
def load_from_persistence
send machine.state_column.to_sym
end
def save_to_persistence(new_state, options = {})
send("#{machine.state_column}=".to_sym, new_state)
save if options[:save]
end
def ensure_initial_state
send("#{machine.state_column.to_s}=", current_state.name.to_s) if send(machine.state_column.to_s).blank?
end
end
end
end
end
| ruby | MIT | 8abeef6440154b0313a186f5872cb0b19f803641 | 2026-01-04T17:57:40.152738Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/test_matrix.rb | test_matrix.rb | # frozen_string_literal: true
require 'yaml'
require 'fileutils'
require 'English'
@threads = {}
def run_container(image, puppet_version)
pversion = puppet_version.match(/([\d\.]+)/)[0]
ruby_version = image.split(':').last
dir = File.join('.', 'local_test_results', pversion, ruby_version)
real_dir = File.expand_path(dir)
FileUtils.rm_rf(real_dir)
FileUtils.mkdir_p(real_dir)
cmd = "docker run -e OUT_DIR='#{dir}' -e RUBY_VERSION='#{ruby_version}' -e PUPPET_GEM_VERSION='#{puppet_version}' --rm -ti -v ${PWD}:/module --workdir /module #{image} /bin/bash run_container_test.sh"
File.write(File.join(real_dir, 'command.txt'), cmd)
output = `#{cmd}`
if $CHILD_STATUS.success?
File.write(File.join(dir, 'success.txt'), output)
else
File.write(File.join(dir, 'error.txt'), output)
end
end
def ci_data
@ci_data ||= YAML.load_file(File.expand_path('.gitlab-ci.yml'))
end
def matrix
unless @matrix
@matrix = {}
ci_data.each do |id, data|
@matrix[id] = data if id.match?(/^puppet/)
end
end
@matrix
end
matrix.each do |id, item|
@threads[id] = Thread.new do
run_container(item['image'], item['variables']['PUPPET_GEM_VERSION'])
end
end
@threads.each { |_id, thr| thr.join } # wait on thread to finish
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/spec/hooks_spec.rb | spec/hooks_spec.rb | # frozen_string_literal: true
require_relative 'spec_helper'
describe PuppetDebugger::Hooks do
before do
@hooks = PuppetDebugger::Hooks.new
end
let(:output) do
StringIO.new
end
let(:debugger) do
PuppetDebugger::Cli.new(out_buffer: output)
end
describe 'adding a new hook' do
it 'should not execute hook while adding it' do
run = false
@hooks.add_hook(:test_hook, :my_name) { run = true }
expect(run).to eq false
end
it 'should not allow adding of a hook with a duplicate name' do
@hooks.add_hook(:test_hook, :my_name) {}
expect { @hooks.add_hook(:test_hook, :my_name) {} }.to raise_error ArgumentError
end
it 'should create a new hook with a block' do
@hooks.add_hook(:test_hook, :my_name) {}
expect(@hooks.hook_count(:test_hook)).to eq 1
end
it 'should create a new hook with a callable' do
@hooks.add_hook(:test_hook, :my_name, proc {})
expect(@hooks.hook_count(:test_hook)).to eq 1
end
it 'should use block if given both block and callable' do
run = false
foo = false
@hooks.add_hook(:test_hook, :my_name, proc { foo = true }) { run = true }
expect(@hooks.hook_count(:test_hook)).to eq 1
@hooks.exec_hook(:test_hook)
expect(run).to eq true
expect(foo).to eq false
end
it 'should raise if not given a block or any other object' do
expect { @hooks.add_hook(:test_hook, :my_name) }.to raise_error ArgumentError
end
it 'should create multiple hooks for an event' do
@hooks.add_hook(:test_hook, :my_name) {}
@hooks.add_hook(:test_hook, :my_name2) {}
expect(@hooks.hook_count(:test_hook)).to eq 2
end
it 'should return a count of 0 for an empty hook' do
expect(@hooks.hook_count(:test_hook)).to eq 0
end
end
describe 'PuppetDebugger::Hooks#merge' do
describe 'merge!' do
it 'should merge in the PuppetDebugger::Hooks' do
h1 = PuppetDebugger::Hooks.new.add_hook(:test_hook, :testing) {}
h2 = PuppetDebugger::Hooks.new
h2.merge!(h1)
expect(h2.get_hook(:test_hook, :testing)).to eq h1.get_hook(:test_hook, :testing)
end
it 'should not share merged elements with original' do
h1 = PuppetDebugger::Hooks.new.add_hook(:test_hook, :testing) {}
h2 = PuppetDebugger::Hooks.new
h2.merge!(h1)
h2.add_hook(:test_hook, :testing2) {}
expect(h2.get_hook(:test_hook, :testing2)).not_to eq h1.get_hook(:test_hook, :testing2)
end
it 'should NOT overwrite hooks belonging to shared event in receiver' do
h1 = PuppetDebugger::Hooks.new.add_hook(:test_hook, :testing) {}
callable = proc {}
h2 = PuppetDebugger::Hooks.new.add_hook(:test_hook, :testing2, callable)
h2.merge!(h1)
expect(h2.get_hook(:test_hook, :testing2)).to eq callable
end
it 'should overwrite identical hook in receiver' do
callable1 = proc { :one }
h1 = PuppetDebugger::Hooks.new.add_hook(:test_hook, :testing, callable1)
callable2 = proc { :two }
h2 = PuppetDebugger::Hooks.new.add_hook(:test_hook, :testing, callable2)
h2.merge!(h1)
expect(h2.get_hook(:test_hook, :testing)).to eq callable1
expect(h2.hook_count(:test_hook)).to eq 1
end
it 'should preserve hook order' do
test_hook_name = String.new
h1 = PuppetDebugger::Hooks.new
h1.add_hook(:test_hook, :testing3) { test_hook_name << 'h' }
h1.add_hook(:test_hook, :testing4) { test_hook_name << 'n' }
h2 = PuppetDebugger::Hooks.new
h2.add_hook(:test_hook, :testing1) { test_hook_name << 'j' }
h2.add_hook(:test_hook, :testing2) { test_hook_name << 'o' }
h2.merge!(h1)
expect(h2.exec_hook(:test_hook)).to eq 'john'
end
describe 'merge' do
it 'should return a fresh, independent instance' do
h1 = PuppetDebugger::Hooks.new.add_hook(:test_hook, :testing) {}
h2 = PuppetDebugger::Hooks.new
h3 = h2.merge(h1)
expect(h3).not_to eq h1
expect(h3).not_to eq h2
end
it 'should contain hooks from original instance' do
h1 = PuppetDebugger::Hooks.new.add_hook(:test_hook, :testing) {}
h2 = PuppetDebugger::Hooks.new.add_hook(:test_hook2, :testing) {}
h3 = h2.merge(h1)
expect(h3.get_hook(:test_hook, :testing)).to eq h1.get_hook(:test_hook, :testing)
expect(h3.get_hook(:test_hook2, :testing)).to eq h2.get_hook(:test_hook2, :testing)
end
it 'should not affect original instances when new hooks are added' do
h1 = PuppetDebugger::Hooks.new.add_hook(:test_hook, :testing) {}
h2 = PuppetDebugger::Hooks.new.add_hook(:test_hook2, :testing) {}
h3 = h2.merge(h1)
h3.add_hook(:test_hook3, :testing) {}
expect(h1.get_hook(:test_hook3, :testing)).to eq nil
expect(h2.get_hook(:test_hook3, :testing)).to eq nil
end
end
end
end
describe 'dupping a PuppetDebugger::Hooks instance' do
it 'should share hooks with original' do
@hooks.add_hook(:test_hook, :testing) do
:none_such
end
hooks_dup = @hooks.dup
expect(hooks_dup.get_hook(:test_hook, :testing)).to eq @hooks.get_hook(:test_hook, :testing)
end
it 'adding a new event to dupped instance should not affect original' do
@hooks.add_hook(:test_hook, :testing) { :none_such }
hooks_dup = @hooks.dup
hooks_dup.add_hook(:other_test_hook, :testing) { :okay_man }
expect(hooks_dup.get_hook(:other_test_hook, :testing)).not_to eq @hooks.get_hook(:other_test_hook, :testing)
end
it 'adding a new hook to dupped instance should not affect original' do
@hooks.add_hook(:test_hook, :testing) { :none_such }
hooks_dup = @hooks.dup
hooks_dup.add_hook(:test_hook, :testing2) { :okay_man }
expect(hooks_dup.get_hook(:test_hook, :testing2)).not_to eq @hooks.get_hook(:test_hook, :testing2)
end
end
describe 'getting hooks' do
describe 'get_hook' do
it 'should return the correct requested hook' do
run = false
fun = false
@hooks.add_hook(:test_hook, :my_name) { run = true }
@hooks.add_hook(:test_hook, :my_name2) { fun = true }
@hooks.get_hook(:test_hook, :my_name).call
expect(run).to eq true
expect(fun).to eq false
end
it 'should return nil if hook does not exist' do
expect(@hooks.get_hook(:test_hook, :my_name)).to eq nil
end
end
describe 'get_hooks' do
it 'should return a hash of hook names/hook functions for an event' do
hook1 = proc { 1 }
hook2 = proc { 2 }
@hooks.add_hook(:test_hook, :my_name1, hook1)
@hooks.add_hook(:test_hook, :my_name2, hook2)
hash = @hooks.get_hooks(:test_hook)
expect(hash.size).to eq 2
expect(hash[:my_name1]).to eq hook1
expect(hash[:my_name2]).to eq hook2
end
it 'should return an empty hash if no hooks defined' do
expect(@hooks.get_hooks(:test_hook)).to eq({})
end
end
end
describe 'clearing all hooks for an event' do
it 'should clear all hooks' do
@hooks.add_hook(:test_hook, :my_name) {}
@hooks.add_hook(:test_hook, :my_name2) {}
@hooks.add_hook(:test_hook, :my_name3) {}
@hooks.clear_event_hooks(:test_hook)
expect(@hooks.hook_count(:test_hook)).to eq 0
end
end
describe 'deleting a hook' do
it 'should successfully delete a hook' do
@hooks.add_hook(:test_hook, :my_name) {}
@hooks.delete_hook(:test_hook, :my_name)
expect(@hooks.hook_count(:test_hook)).to eq 0
end
it 'should return the deleted hook' do
run = false
@hooks.add_hook(:test_hook, :my_name) { run = true }
@hooks.delete_hook(:test_hook, :my_name).call
expect(run).to eq true
end
it 'should return nil if hook does not exist' do
expect(@hooks.delete_hook(:test_hook, :my_name)).to eq nil
end
end
describe 'executing a hook' do
it 'should execute block hook' do
run = false
@hooks.add_hook(:test_hook, :my_name) { run = true }
@hooks.exec_hook(:test_hook)
expect(run).to eq true
end
it 'should execute proc hook' do
run = false
@hooks.add_hook(:test_hook, :my_name, proc { run = true })
@hooks.exec_hook(:test_hook)
expect(run).to eq true
end
it 'should execute a general callable hook' do
callable = Object.new.tap do |obj|
obj.instance_variable_set(:@test_var, nil)
class << obj
attr_accessor :test_var
def call
@test_var = true
end
end
end
@hooks.add_hook(:test_hook, :my_name, callable)
@hooks.exec_hook(:test_hook)
expect(callable.test_var).to eq true
end
it 'should execute all hooks for an event if more than one is defined' do
x = nil
y = nil
@hooks.add_hook(:test_hook, :my_name1) { y = true }
@hooks.add_hook(:test_hook, :my_name2) { x = true }
@hooks.exec_hook(:test_hook)
expect(x).to eq true
expect(y).to eq true
end
it 'should execute hooks in order' do
array = []
@hooks.add_hook(:test_hook, :my_name1) { array << 1 }
@hooks.add_hook(:test_hook, :my_name2) { array << 2 }
@hooks.add_hook(:test_hook, :my_name3) { array << 3 }
@hooks.exec_hook(:test_hook)
expect(array).to eq [1, 2, 3]
end
it 'return value of exec_hook should be that of last executed hook' do
@hooks.add_hook(:test_hook, :my_name1) { 1 }
@hooks.add_hook(:test_hook, :my_name2) { 2 }
@hooks.add_hook(:test_hook, :my_name3) { 3 }
expect(@hooks.exec_hook(:test_hook)).to eq 3
end
it 'should add exceptions to the errors array' do
@hooks.add_hook(:test_hook, :foo1) { raise 'one' }
@hooks.add_hook(:test_hook, :foo2) { raise 'two' }
@hooks.add_hook(:test_hook, :foo3) { raise 'three' }
@hooks.exec_hook(:test_hook)
expect(@hooks.errors.map(&:message)).to eq %w[one two three]
end
it 'should return the last exception raised as the return value' do
@hooks.add_hook(:test_hook, :foo1) { raise 'one' }
@hooks.add_hook(:test_hook, :foo2) { raise 'two' }
@hooks.add_hook(:test_hook, :foo3) { raise 'three' }
expect(@hooks.exec_hook(:test_hook)).to eq @hooks.errors.last
end
end
describe 'anonymous hooks' do
it 'should allow adding of hook without a name' do
@hooks.add_hook(:test_hook, nil) {}
expect(@hooks.hook_count(:test_hook)).to eq 1
end
it 'should only allow one anonymous hook to exist' do
@hooks.add_hook(:test_hook, nil) {}
@hooks.add_hook(:test_hook, nil) {}
expect(@hooks.hook_count(:test_hook)).to eq 1
end
it 'should execute most recently added anonymous hook' do
x = nil
y = nil
@hooks.add_hook(:test_hook, nil) { y = 1 }
@hooks.add_hook(:test_hook, nil) { x = 2 }
@hooks.exec_hook(:test_hook)
expect(y).to eq nil
expect(x).to eq 2
end
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/spec/support_spec.rb | spec/support_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'tempfile'
describe 'support' do
let(:output) do
StringIO.new
end
let(:debugger) do
PuppetDebugger::Cli.new(out_buffer: output)
end
let(:scope) do
debugger.scope
end
let(:puppet_version) do
debugger.puppet_lib_dir.scan(debugger.mod_finder).flatten.last
end
let(:manifest_file) do
File.open('/tmp/debugger_puppet_manifest.pp', 'w') do |f|
f.write(manifest_code)
end
'/tmp/debugger_puppet_manifest.pp'
end
let(:manifest_code) do
<<-OUT
file{'/tmp/test.txt': ensure => absent } \n
notify{'hello_there':} \n
service{'httpd': ensure => running}\n
OUT
end
after(:each) do
# manifest_file.close
end
it 'should return a puppet version' do
expect(puppet_version).to match(/puppet-\d\.\d+.\d/)
end
it 'should return lib dirs' do
expect(debugger.lib_dirs.count).to be >= 1
end
it 'should return module dirs' do
expect(debugger.modules_paths.count).to be >= 1
end
it 'should return a list of default facts' do
expect(debugger.default_facts.values).to be_instance_of(Hash)
expect(debugger.default_facts.values['fqdn']).to eq('foo.example.com')
end
it 'should return a list of facts' do
expect(debugger.node.facts.values).to be_instance_of(Hash)
expect(debugger.node.facts.values['fqdn']).to eq('foo.example.com')
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/spec/facts_spec.rb | spec/facts_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe 'facts' do
let(:debugger) do
PuppetDebugger::Cli.new(out_buffer: output)
end
let(:puppet_version) do
'4.5.3'
end
let(:facter_version) do
debugger.default_facter_version
end
before(:each) do
allow(Puppet).to receive(:version).and_return(puppet_version)
end
describe '2.4' do
before(:each) do
ENV['DEBUGGER_FACTERDB_FILTER'] = nil
end
let(:puppet_version) do
'4.2.0'
end
it 'returns 2.4' do
expect(facter_version).to eq('/^2\.4/')
end
it 'return default filter' do
expect(debugger.dynamic_facterdb_filter).to eq('operatingsystem=Fedora and operatingsystemrelease=23 and architecture=x86_64 and facterversion=/^2\\.4/')
end
it 'get node_facts' do
expect(debugger.node_facts).to be_instance_of(Hash)
end
it 'has fqdn' do
expect(debugger.node_facts[:fqdn]).to eq('foo.example.com')
end
end
describe '3.1' do
before(:each) do
ENV['DEBUGGER_FACTERDB_FILTER'] = nil
end
let(:puppet_version) do
'4.5.3'
end
it 'get node_facts' do
expect(debugger.node_facts).to be_instance_of(Hash)
end
it 'has networking fqdn' do
expect(debugger.node_facts[:networking]['fqdn']).to eq('foo.example.com')
end
it 'has fqdn' do
expect(debugger.node_facts[:fqdn]).to eq('foo.example.com')
end
it 'returns 3.1' do
expect(facter_version).to eq('/^3\.1/')
end
it 'return default filter' do
expect(debugger.dynamic_facterdb_filter).to eq('operatingsystem=Fedora and operatingsystemrelease=23 and architecture=x86_64 and facterversion=/^3\\.1/')
end
end
describe 'default facts' do
describe 'bad filter' do
before(:each) do
ENV['DEBUGGER_FACTERDB_FILTER'] = 'facterversion=/^6\.5/'
end
it 'return filter' do
expect(debugger.dynamic_facterdb_filter).to eq('facterversion=/^6\\.5/')
end
it 'throws error' do
expect { debugger.default_facts }.to raise_error(PuppetDebugger::Exception::BadFilter)
end
end
describe 'good filter' do
before(:each) do
ENV['DEBUGGER_FACTERDB_FILTER'] = 'facterversion=/^3\.1/'
end
it 'return filter' do
expect(debugger.dynamic_facterdb_filter).to eq('facterversion=/^3\\.1/')
end
end
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/spec/input_responder_plugin_spec.rb | spec/input_responder_plugin_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'puppet-debugger/input_responder_plugin'
describe :input_responder_plugin do
let(:output) do
StringIO.new
end
before(:each) do
allow(plugin).to receive(:run).and_return([])
end
let(:debugger) do
PuppetDebugger::Cli.new({ out_buffer: output }.merge(options))
end
let(:options) do
{}
end
let(:plugin) do
instance = PuppetDebugger::InputResponderPlugin.instance
instance.debugger = debugger
instance
end
it 'works' do
expect(plugin.run([])).to eq([])
end
{ scope: Puppet::Parser::Scope, node: Puppet::Node, facts: Puppet::Node::Facts,
environment: Puppet::Node::Environment,
compiler: Puppet::Parser::Compiler, catalog: Puppet::Resource::Catalog }.each do |name, klass|
it "can access #{name}" do
expect(plugin.send(name).class).to be klass
end
end
%i[add_hook handle_input delete_hook handle_input].each do |name|
it "responds to method #{name}" do
expect(plugin.respond_to?(name)).to eq(true)
end
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/spec/remote_node_spec.rb | spec/remote_node_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'stringio'
describe 'PuppetDebugger' do
let(:resource) do
"service{'httpd': ensure => running}"
end
before(:each) do
debugger.handle_input('reset')
end
let(:output) do
StringIO.new
end
let(:debugger) do
PuppetDebugger::Cli.new(out_buffer: output)
end
let(:input) do
"file{'/tmp/test2.txt': ensure => present, mode => '0755'}"
end
let(:resource_types) do
debugger.parser.evaluate_string(debugger.scope, input)
end
describe 'remote node' do
let(:node_obj) do
YAML.load_file(File.join(fixtures_dir, 'node_obj.yaml'))
end
let(:node_name) do
'puppetdev.localdomain'
end
before :each do
allow(debugger).to receive(:get_remote_node).with(node_name).and_return(node_obj)
debugger.handle_input(":set node #{node_name}")
end
describe 'set' do
it 'sends message about resetting' do
expect(output.string).to eq(" => Resetting to use node puppetdev.localdomain\n")
end
it 'return node name' do
output.reopen # removes previous message
debugger.handle_input('$::hostname')
expect(output.string).to match(/puppetdev.localdomain/)
end
it 'return classification' do
output.reopen # removes previous message
debugger.handle_input('classification')
expect(output.string).to match(/stdlib/)
end
end
describe 'facts' do
let(:input) do
"$::facts['os']['family'].downcase == 'debian'"
end
it 'fact evaulation should return false' do
debugger_output = /false/
debugger.handle_input(input)
expect(output.string).to match(debugger_output)
end
end
describe 'use defaults when invalid' do
let(:node_obj) do
YAML.load_file(File.join(fixtures_dir, 'invalid_node_obj.yaml'))
end
let(:node_name) do
'invalid.localdomain'
end
end
it 'set node name' do
expect(debugger.remote_node_name = 'puppetdev.localdomain').to eq('puppetdev.localdomain')
end
describe 'print classes' do
let(:input) do
'resources'
end
it 'should be able to print classes' do
debugger_output = /Settings/
debugger.handle_input(input)
expect(output.string).to match(debugger_output)
end
end
describe 'vars' do
let(:input) do
'vars'
end
it 'display facts variable' do
debugger_output = /facts/
debugger.handle_input(input)
expect(output.string).to match(debugger_output)
end
it 'display server facts variable' do
debugger_output = /server_facts/
debugger.handle_input(input)
expect(output.string).to match(debugger_output) if Puppet.version.to_f >= 4.1
end
it 'display server facts variable' do
debugger_output = /server_facts/
debugger.handle_input(input)
expect(output.string).to match(debugger_output) if Puppet.version.to_f >= 4.1
end
it 'display local variable' do
debugger.handle_input("$var1 = 'value1'")
expect(output.string).to match(/value1/)
debugger.handle_input('$var1')
expect(output.string).to match(/value1/)
end
it 'display productname variable' do
debugger.handle_input('$productname')
expect(output.string).to match(/VMware Virtual Platform/)
end
end
describe 'execute functions' do
let(:input) do
"md5('hello')"
end
it 'execute md5' do
debugger_output = /5d41402abc4b2a76b9719d911017c592/
debugger.handle_input(input)
expect(output.string).to match(debugger_output)
end
it 'execute swapcase' do
debugger_output = /HELLO/
debugger.handle_input("swapcase('hello')")
expect(output.string).to match(debugger_output)
end
end
describe 'reset' do
let(:input) do
"file{'/tmp/reset': ensure => present}"
end
it 'can process a file' do
debugger_output = /Puppet::Type::File/
debugger.handle_input(input)
expect(output.string).to match(debugger_output)
debugger.handle_input('reset')
debugger.handle_input(input)
expect(output.string).to match(debugger_output)
end
end
describe 'classification' do
let(:input) do
'classification'
end
it 'shows certificate_authority_host' do
debugger.handle_input(input)
expect(output.string).to match(/stdlib/)
end
end
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/spec/pdb_spec.rb | spec/pdb_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe 'pdb' do
let(:fixtures_file) do
File.join(fixtures_dir, 'sample_manifest.pp')
end
before(:each) do
allow(PuppetDebugger).to receive(:fetch_url_data).with(file_url).and_return(File.read(fixtures_file))
end
let(:file_url) do
'https://gist.githubusercontent.com/logicminds/f9b1ac65a3a440d562b0/raw'
end
it do
expect(`echo 'file{"/tmp/test":}'| bundle exec bin/pdb`)
.to match(/Puppet::Type::File/)
end
it do
expect(`bundle exec bin/pdb #{fixtures_file} --run-once`)
.to match(/Puppet::Type::File/)
end
it do
expect(`bundle exec bin/pdb --play #{fixtures_file} --run-once`)
.to match(/Puppet::Type::File/)
end
describe 'remote_node' do
let(:node_obj) do
YAML.load_file(File.join(fixtures_dir, 'node_obj.yaml'))
end
let(:node_name) do
'puppetdev.localdomain'
end
before :each do
allow(PuppetDebugger).to receive(:get_remote_node).with(node_name).and_return(node_obj)
end
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/spec/environment_spec.rb | spec/environment_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'stringio'
describe 'environment' do
let(:output) do
StringIO.new
end
let(:debugger) do
PuppetDebugger::Cli.new(out_buffer: output)
end
it 'environment returns object with properties' do
expect(debugger.puppet_environment).to_not eq nil
expect(debugger.default_site_manifest).to eq(File.join(Puppet[:environmentpath],
Puppet[:environment], 'manifests', 'site.pp'))
end
it 'full module path' do
expect(debugger.modules_paths.count).to be >= 2
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/spec/puppet_debugger_spec.rb | spec/puppet_debugger_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'stringio'
describe 'PuppetDebugger' do
let(:resource) do
"service{'httpd': ensure => running}"
end
before(:each) do
debugger.handle_input('reset')
end
let(:output) do
StringIO.new
end
let(:debugger) do
PuppetDebugger::Cli.new({ out_buffer: output }.merge(options))
end
let(:options) do
{}
end
let(:input) do
"file{'/tmp/test2.txt': ensure => present, mode => '0755'}"
end
let(:resource_types) do
debugger.parser.evaluate_string(debugger.scope, input)
end
describe 'native classes' do
describe 'create' do
let(:input) do
'class testfoo {}'
end
let(:debugger_output) do
" => Puppet::Type::Component {\n loglevel\e[0;37m => \e[0m\e[0;36mnotice\e[0m,\n name\e[0;37m => \e[0m\e[0;33m\"Testfoo\"\e[0m,\n title\e[0;37m => \e[0m\e[0;33m\"Class[Testfoo]\"\e[0m\n}\n"
end
it do
debugger.handle_input(input)
expect(output.string).to eq('')
expect(debugger.known_resource_types[:hostclasses]).to include('testfoo')
end
it do
debugger.handle_input(input)
debugger.handle_input('include testfoo')
expect(debugger.scope.compiler.catalog.classes).to include('testfoo')
end
it do
debugger.handle_input(input)
debugger.handle_input('include testfoo')
expect(debugger.scope.compiler.catalog.resources.map(&:name)).to include('Testfoo')
end
end
end
describe 'native definitions' do
describe 'create' do
let(:input) do
'define testfoodefine {}'
end
let(:debugger_output) do
" => Puppet::Type::Component {\n loglevel\e[0;37m => \e[0m\e[0;36mnotice\e[0m,\n name\e[0;37m => \e[0m\e[0;33m\"some_name\"\e[0m,\n title\e[0;37m => \e[0m\e[0;33m\"Testfoo[some_name]\"\e[0m\n}\n"
end
it do
debugger.handle_input(input)
expect(debugger.scope.environment.known_resource_types.definitions.keys).to include('testfoodefine')
expect(output.string).to eq('')
end
it do
debugger.handle_input(input)
debugger.handle_input("testfoodefine{'some_name':}")
expect(output.string).to include(' => Puppet::Type::Component')
end
end
end
describe 'key_words' do
it do
expect(debugger.key_words.count).to be >= 30 if supports_datatypes?
end
it do
expect(debugger.key_words.count).to be >= 0 unless supports_datatypes?
end
end
describe 'native functions', native_functions: true do
let(:func) do
<<-OUT
function debugger::bool2http($arg) {
case $arg {
false, undef, /(?i:false)/ : { 'Off' }
true, /(?i:true)/ : { 'On' }
default : { "$arg" }
}
}
OUT
end
before(:each) do
debugger.handle_input(func)
end
describe 'create' do
it 'shows function' do
expect(output.string).to eq('')
end
end
describe 'run' do
let(:input) do
<<-OUT
debugger::bool2http(false)
OUT
end
it do
debugger.handle_input(input)
expect(output.string).to include('Off')
end
end
end
describe 'returns a array of resource_types' do
it 'returns resource type' do
expect(resource_types.first.class.to_s).to eq('Puppet::Pops::Types::PResourceType')
end
end
describe 'empty' do
let(:input) do
''
end
it 'can run' do
debugger_output = ''
debugger.handle_input(input)
debugger.handle_input(input)
expect(output.string).to eq(debugger_output)
end
describe 'space' do
let(:input) do
' '
end
it 'can run' do
debugger_output = ''
debugger.handle_input(input)
expect(output.string).to eq(debugger_output)
end
end
end
describe 'variables' do
let(:input) do
"$file_path = '/tmp/test2.txt'"
end
it 'can process a variable' do
debugger.handle_input(input)
expect(output.string).to match(%r{/tmp/test2.txt})
end
end
describe 'resource' do
let(:input) do
"file{'/tmp/test2.txt': ensure => present, mode => '0755'}"
end
it 'can process a resource' do
debugger_output = /Puppet::Type::File/
debugger.handle_input(input)
expect(output.string).to match(debugger_output)
end
end
describe 'bad input' do
let(:input) do
'Service{'
end
it 'can process' do
debugger.handle_input(input)
expect(output.string).to match(/Syntax error at end of/)
end
end
describe 'map block' do
let(:input) do
"['/tmp/test3', '/tmp/test4'].map |String $path| { file{$path: ensure => present} }"
end
it 'can process a each block' do
debugger_output = /Puppet::Type::File/
debugger.handle_input(input)
expect(output.string).to match(debugger_output)
end
end
describe 'each block' do
let(:input) do
"['/tmp/test3', '/tmp/test4'].each |String $path| { file{$path: ensure => present} }"
end
it 'can process a each block' do
debugger.handle_input(input)
expect(output.string).to match(%r{/tmp/test3})
expect(output.string).to match(%r{/tmp/test4})
end
end
describe 'string' do
let(:input) do
'String'
end
it 'shows type' do
debugger.handle_input(input)
expect(output.string).to eq(" => String\n")
end
end
describe 'Array', type_function: true do
let(:input) do
'type([1,2,3,4])'
end
it 'shows type' do
debugger.handle_input(input)
out = " => Tuple[Integer[1, 1], Integer[2, 2], Integer[3, 3], Integer[4, 4]]\n"
expect(output.string).to eq(out)
end
end
describe 'multi diemension array' do
let(:input) do
'[[1, [23,4], [22], [1,[2232]]]]'
end
it 'handles multi array' do
debugger.handle_input(input)
expect(output.string.count('[')).to be >= 17
end
end
describe 'command_completion' do
it 'should complete on tabs' do
allow(Readline).to receive(:line_buffer).and_return("\n")
expect(debugger.command_completion.call('').count).to be >= 200
end
it '#key_words' do
expect(debugger.key_words.count).to be >= 100
end
end
describe 'error message' do
let(:input) do
"file{'/tmp/test': ensure => present, contact => 'blah'}"
end
if Gem::Version.new(Puppet.version) >= Gem::Version.new('4.0')
it 'show error message' do
debugger_output = /no\ parameter\ named\ 'contact'/
debugger.handle_input(input)
expect(output.string).to match(debugger_output)
end
else
it 'show error message' do
debugger_output = /Invalid\ parameter\ contact/
debugger.handle_input(input)
expect(output.string).to match(debugger_output)
end
end
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/spec/spec_helper.rb | spec/spec_helper.rb | # frozen_string_literal: true
require_relative '../lib/puppet-debugger'
require 'yaml'
ENV['CI'] = 'true'
if ENV['COVERAGE']
require 'simplecov'
module SimpleCov::Configuration
def clean_filters
@filters = []
end
end
SimpleCov.configure do
clean_filters
load_profile 'test_frameworks'
end
if ENV['COVERAGE']
SimpleCov.start do
add_filter '/.rvm/'
add_filter 'vendor'
add_filter 'bundler'
end
end
end
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'rspec'
require 'puppet-debugger'
ENV['REPL_FACTERDB_FILTER'] = 'operatingsystem=Fedora and operatingsystemrelease=23 and architecture=x86_64 and facterversion=/^2\\.4/'
# Requires supporting files with custom matchers and macros, etc,
# in ./support/ and its subdirectories.
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].sort.each { |f| require f }
def stdlib_path
File.join(Puppet[:basemodulepath].split(':').first, 'stdlib')
end
def install_stdlib
`bundle exec puppet module install puppetlabs/stdlib` unless File.exist?(stdlib_path)
end
# install_stdlib
def fixtures_dir
File.join(File.dirname(__FILE__), 'fixtures')
end
def environments_dir
File.join(fixtures_dir, 'environments')
end
def supports_native_functions?
Gem::Version.new(Puppet.version) >= Gem::Version.new('4.3')
end
def supports_type_function?
Gem::Version.new(Puppet.version) >= Gem::Version.new('4.0')
end
def supports_datatypes?
Gem::Version.new(Puppet.version) >= Gem::Version.new('4.5')
end
RSpec.configure do |config|
config.filter_run_excluding native_functions: !supports_native_functions?
RSpec::Expectations.configuration.on_potential_false_positives = :nothing
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/spec/fixtures/modules/extlib/lib/puppet/functions/echo.rb | spec/fixtures/modules/extlib/lib/puppet/functions/echo.rb | # @summary DEPRECATED. Use the namespaced function [`extlib::echo`](#extlibecho) instead.
# DEPRECATED. Use the namespaced function [`extlib::echo`](#extlibecho) instead.
Puppet::Functions.create_function(:echo) do
dispatch :deprecation_gen do
repeated_param 'Any', :args
end
def deprecation_gen(*args)
call_function('deprecation', 'echo', 'This method is deprecated, please use extlib::echo instead.')
call_function('extlib::echo', *args)
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/spec/fixtures/modules/extlib/lib/puppet/functions/default_content.rb | spec/fixtures/modules/extlib/lib/puppet/functions/default_content.rb | # @summary DEPRECATED. Use the namespaced function [`extlib::default_content`](#extlibdefault_content) instead.
# DEPRECATED. Use the namespaced function [`extlib::default_content`](#extlibdefault_content) instead.
Puppet::Functions.create_function(:default_content) do
dispatch :deprecation_gen do
repeated_param 'Any', :args
end
def deprecation_gen(*args)
call_function('deprecation', 'default_content', 'This method is deprecated, please use extlib::default_content instead.')
call_function('extlib::default_content', *args)
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/spec/fixtures/modules/extlib/lib/puppet/functions/cache_data.rb | spec/fixtures/modules/extlib/lib/puppet/functions/cache_data.rb | # @summary DEPRECATED. Use the namespaced function [`extlib::cache_data`](#extlibcache_data) instead.
# DEPRECATED. Use the namespaced function [`extlib::cache_data`](#extlibcache_data) instead.
Puppet::Functions.create_function(:cache_data) do
dispatch :deprecation_gen do
repeated_param 'Any', :args
end
def deprecation_gen(*args)
call_function('deprecation', 'cache_data', 'This method is deprecated, please use extlib::cache_data instead.')
call_function('extlib::cache_data', *args)
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/spec/fixtures/modules/extlib/lib/puppet/functions/resources_deep_merge.rb | spec/fixtures/modules/extlib/lib/puppet/functions/resources_deep_merge.rb | # @summary DEPRECATED. Use the namespaced function [`extlib::resources_deep_merge`](#extlibresources_deep_merge) instead.
# DEPRECATED. Use the namespaced function [`extlib::resources_deep_merge`](#extlibresources_deep_merge) instead.
Puppet::Functions.create_function(:resources_deep_merge) do
dispatch :deprecation_gen do
repeated_param 'Any', :args
end
def deprecation_gen(*args)
call_function('deprecation', 'resources_deep_merge', 'This method is deprecated, please use extlib::resources_deep_merge instead.')
call_function('extlib::resources_deep_merge', *args)
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/spec/fixtures/modules/extlib/lib/puppet/functions/random_password.rb | spec/fixtures/modules/extlib/lib/puppet/functions/random_password.rb | # @summary DEPRECATED. Use the namespaced function [`extlib::random_password`](#extlibrandom_password) instead.
# DEPRECATED. Use the namespaced function [`extlib::random_password`](#extlibrandom_password) instead.
Puppet::Functions.create_function(:random_password) do
dispatch :deprecation_gen do
repeated_param 'Any', :args
end
def deprecation_gen(*args)
call_function('deprecation', 'random_password', 'This method is deprecated, please use extlib::random_password instead.')
call_function('extlib::random_password', *args)
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/spec/fixtures/modules/extlib/lib/puppet/functions/dump_args.rb | spec/fixtures/modules/extlib/lib/puppet/functions/dump_args.rb | # @summary DEPRECATED. Use the namespaced function [`extlib::dump_args`](#extlibdump_args) instead.
# DEPRECATED. Use the namespaced function [`extlib::dump_args`](#extlibdump_args) instead.
Puppet::Functions.create_function(:dump_args) do
dispatch :deprecation_gen do
repeated_param 'Any', :args
end
def deprecation_gen(*args)
call_function('deprecation', 'dump_args', 'This method is deprecated, please use extlib::dump_args instead.')
call_function('extlib::dump_args', *args)
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/spec/fixtures/modules/extlib/lib/puppet/functions/ip_to_cron.rb | spec/fixtures/modules/extlib/lib/puppet/functions/ip_to_cron.rb | # @summary DEPRECATED. Use the namespaced function [`extlib::ip_to_cron`](#extlibip_to_cron) instead.
# DEPRECATED. Use the namespaced function [`extlib::ip_to_cron`](#extlibip_to_cron) instead.
Puppet::Functions.create_function(:ip_to_cron) do
dispatch :deprecation_gen do
repeated_param 'Any', :args
end
def deprecation_gen(*args)
call_function('deprecation', 'ip_to_cron', 'This method is deprecated, please use extlib::ip_to_cron instead.')
call_function('extlib::ip_to_cron', *args)
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/spec/fixtures/modules/extlib/lib/puppet/functions/extlib/echo.rb | spec/fixtures/modules/extlib/lib/puppet/functions/extlib/echo.rb | # This function outputs the variable content and its type to the
# debug log. It's similiar to the `notice` function but provides
# a better output format useful to trace variable types and values
# in the manifests.
#
# ```
# $v1 = 'test'
# $v2 = ["1", "2", "3"]
# $v3 = {"a"=>"1", "b"=>"2"}
# $v4 = true
# # $v5 is not defined
# $v6 = { "b" => { "b" => [1,2,3], "c" => true, "d" => { 'x' => 'y' }}, 'x' => 'y', 'z' => [1,2,3,4,5,6]}
# $v7 = 12345
#
# echo($v1, 'My string')
# echo($v2, 'My array')
# echo($v3, 'My hash')
# echo($v4, 'My boolean')
# echo($v5, 'My undef')
# echo($v6, 'My structure')
# echo($v7) # no comment here
# debug log output
# My string (String) "test"
# My array (Array) ["1", "2", "3"]
# My hash (Hash) {"a"=>"1", "b"=>"2"}
# My boolean (TrueClass) true
# My undef (String) ""
# My structure (Hash) {"b"=>{"b"=>["1", "2", "3"], "c"=>true, "d"=>{"x"=>"y"}}, "x"=>"y", "z"=>["1", "2", "3", "4", "5", "6"]}
# (String) "12345"
# ```
Puppet::Functions.create_function(:'extlib::echo') do
# @param value The value you want to inspect.
# @param comment An optional comment to prepend to the debug output.
# @return [Undef] Returns nothing.
dispatch :echo do
param 'Any', :value
optional_param 'String', :comment
end
def echo(value, comment = nil)
message = "(#{value.class}) #{value.inspect}"
message = "#{comment} #{message}" if comment
Puppet.debug message
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/spec/fixtures/modules/extlib/lib/puppet/functions/extlib/default_content.rb | spec/fixtures/modules/extlib/lib/puppet/functions/extlib/default_content.rb | # Takes an optional content and an optional template name and returns the contents of a file.
Puppet::Functions.create_function(:'extlib::default_content') do
# @param content
# @param template_name
# The path to an .erb or .epp template file or `undef`.
# @return
# Returns the value of the content parameter if it's a non empty string.
# Otherwise returns the rendered output from `template_name`.
# Returns `undef` if both `content` and `template_name` are `undef`.
#
# @example Using the function with a file resource.
# $config_file_content = default_content($file_content, $template_location)
# file { '/tmp/x':
# ensure => 'file',
# content => $config_file_content,
# }
dispatch :default_content do
param 'Optional[String]', :content
param 'Optional[String]', :template_name
return_type 'Optional[String]'
end
def emptyish(x)
x.nil? || x.empty? || x == :undef
end
def default_content(content = :undef, template_name = :undef)
return content unless emptyish(content)
unless emptyish(template_name)
return call_function('template', template_name) unless template_name.end_with?('.epp')
return call_function('epp', template_name)
end
:undef
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/spec/fixtures/modules/extlib/lib/puppet/functions/extlib/cache_data.rb | spec/fixtures/modules/extlib/lib/puppet/functions/extlib/cache_data.rb | require 'fileutils'
require 'yaml'
require 'etc'
# @summary Retrieves data from a cache file, or creates it with supplied data if the file doesn't exist
#
# Retrieves data from a cache file, or creates it with supplied data if the
# file doesn't exist
#
# Useful for having data that's randomly generated once on the master side
# (e.g. a password), but then stays the same on subsequent runs. Because it's
# stored on the master on disk, it doesn't work when you use mulitple Puppet
# masters that don't share their vardir.
#
# @example Calling the function
# $password = cache_data('mysql', 'mysql_password', 'this_is_my_password')
#
# @example With a random password
# $password = cache_data('mysql', 'mysql_password', random_password())
Puppet::Functions.create_function(:'extlib::cache_data') do
# @param namespace Namespace for the cache
# @param name Cache key within the namespace
# @param initial_data The data for when there is no cache yet
# @return The cached value when it exists. The initial data when no cache exists
dispatch :cache_data do
param 'String[1]', :namespace
param 'String[1]', :name
param 'Any', :initial_data
return_type 'Any'
end
def cache_data(namespace, name, initial_data)
cache_dir = File.join(Puppet[:vardir], namespace)
cache = File.join(cache_dir, name)
if File.exist? cache
YAML.load(File.read(cache))
else
FileUtils.mkdir_p(cache_dir)
File.open(cache, 'w', 0o600) do |c|
c.write(YAML.dump(initial_data))
end
File.chown(File.stat(Puppet[:vardir]).uid, nil, cache)
File.chown(File.stat(Puppet[:vardir]).uid, nil, cache_dir)
initial_data
end
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/spec/fixtures/modules/extlib/lib/puppet/functions/extlib/sort_by_version.rb | spec/fixtures/modules/extlib/lib/puppet/functions/extlib/sort_by_version.rb | # A function that sorts an array of version numbers.
Puppet::Functions.create_function(:'extlib::sort_by_version') do
# @param versions An array of version strings you want sorted.
# @return Returns the sorted array.
# @example Calling the function
# extlib::sort_by_version(['10.0.0b12', '10.0.0b3', '10.0.0a2', '9.0.10', '9.0.3'])
dispatch :sort_by_version do
param 'Array[String]', :versions
return_type 'Array[String]'
end
def sort_by_version(versions)
versions.sort_by { |v| Gem::Version.new(v) }
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/spec/fixtures/modules/extlib/lib/puppet/functions/extlib/resources_deep_merge.rb | spec/fixtures/modules/extlib/lib/puppet/functions/extlib/resources_deep_merge.rb | # @summary Deeply merge a "defaults" hash into a "resources" hash like the ones expected by `create_resources()`.
#
# Deeply merge a "defaults" hash into a "resources" hash like the ones expected by `create_resources()`.
#
# Internally calls the puppetlabs-stdlib function `deep_merge()`. In case of
# duplicate keys the `resources` hash keys win over the `defaults` hash keys.
#
# Example
# ```puppet
# $defaults_hash = {
# 'one' => '1',
# 'two' => '2',
# 'three' => '3',
# 'four' => {
# 'five' => '5',
# 'six' => '6',
# 'seven' => '7',
# }
# }
#
# $numbers_hash = {
# 'german' => {
# 'one' => 'eins',
# 'three' => 'drei',
# 'four' => {
# 'six' => 'sechs',
# },
# },
# 'french' => {
# 'one' => 'un',
# 'two' => 'deux',
# 'four' => {
# 'five' => 'cinq',
# 'seven' => 'sept',
# },
# }
# }
#
# $result_hash = resources_deep_merge($numbers_hash, $defaults_hash)
# ```
#
# The $result_hash then looks like this:
#
# ```puppet
# $result_hash = {
# 'german' => {
# 'one' => 'eins',
# 'two' => '2',
# 'three' => 'drei',
# 'four' => {
# 'five' => '5',
# 'six' => 'sechs',
# 'seven' => '7',
# }
# },
# 'french' => {
# 'one' => 'un',
# 'two' => 'deux',
# 'three' => '3',
# 'four' => {
# 'five' => 'cinq',
# 'six' => '6',
# 'seven' => 'sept',
# }
# }
# }
# ```
Puppet::Functions.create_function(:'extlib::resources_deep_merge') do
# Deep-merges defaults into a resources hash
# @param resources The hash of resources.
# @param defaults The hash of defaults to merge.
# @return Returns the merged hash.
dispatch :resources_deep_merge do
param 'Hash', :resources
param 'Hash', :defaults
return_type 'Hash'
end
def resources_deep_merge(resources, defaults)
deep_merged_resources = {}
resources.each do |title, params|
deep_merged_resources[title] = call_function('deep_merge', defaults, params)
end
deep_merged_resources
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/spec/fixtures/modules/extlib/lib/puppet/functions/extlib/random_password.rb | spec/fixtures/modules/extlib/lib/puppet/functions/extlib/random_password.rb | # vim: set ts=2 sw=2 et :
# encoding: utf-8
# random_password.rb
#
# Copyright 2012 Krzysztof Wilczynski
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# For example:
# ```
# Given the following statements:
#
# $a = 4
# $b = 8
# $c = 16
#
# notice random_password($a)
# notice random_password($b)
# notice random_password($c)
#
# The result will be as follows:
#
# notice: Scope(Class[main]): fNDC
# notice: Scope(Class[main]): KcKDLrjR
# notice: Scope(Class[main]): FtvfvkS9j9wXLsd6
# ```
# A function to return a string of arbitrary length that contains randomly selected characters.
Puppet::Functions.create_function(:'extlib::random_password') do
# @param length The length of random password you want generated.
# @return [String] The random string returned consists of alphanumeric characters excluding 'look-alike' characters.
# @example Calling the function
# random_password(42)
dispatch :random_password do
param 'Integer[1]', :length
return_type 'String'
end
def random_password(length)
# These are quite often confusing ...
ambiguous_characters = %w[0 1 O I l]
# Get allowed characters set ...
set = ('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a
set -= ambiguous_characters
# Shuffle characters in the set at random and return desired number of them ...
Array.new(length) do |_i|
set[rand(set.length)]
end.join
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/spec/fixtures/modules/extlib/lib/puppet/functions/extlib/dump_args.rb | spec/fixtures/modules/extlib/lib/puppet/functions/extlib/dump_args.rb | require 'json'
# @summary Prints the args to STDOUT in Pretty JSON format.
#
# Prints the args to STDOUT in Pretty JSON format.
#
# Useful for debugging purposes only. Ideally you would use this in
# conjunction with a rspec-puppet unit test. Otherwise the output will
# be shown during a puppet run when verbose/debug options are enabled.
Puppet::Functions.create_function(:'extlib::dump_args') do
# @param args The data you want to dump as pretty JSON.
# @return [Undef] Returns nothing.
dispatch :dump_args do
param 'Any', :args
end
def dump_args(args)
puts JSON.pretty_generate(args)
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/spec/fixtures/modules/extlib/lib/puppet/functions/extlib/ip_to_cron.rb | spec/fixtures/modules/extlib/lib/puppet/functions/extlib/ip_to_cron.rb | # Provides a "random" value to cron based on the last bit of the machine IP address.
# used to avoid starting a certain cron job at the same time on all servers.
# Takes the runinterval in seconds as parameter and returns an array of [hour, minute]
#
# example usage
# ```
# ip_to_cron(3600) - returns [ '*', one value between 0..59 ]
# ip_to_cron(1800) - returns [ '*', an array of two values between 0..59 ]
# ip_to_cron(7200) - returns [ an array of twelve values between 0..23, one value between 0..59 ]
# ```
Puppet::Functions.create_function(:'extlib::ip_to_cron') do
# @param runinterval The number of seconds to use as the run interval
# return [Array] Returns an array of the form `[hour, minute]`
dispatch :ip_to_cron do
optional_param 'Integer[1]', :runinterval
return_type 'Array'
end
def ip_to_cron(runinterval = 1800)
facts = closure_scope['facts']
ip = facts['networking']['ip']
ip_last_octet = ip.to_s.split('.')[3].to_i
if runinterval <= 3600
occurances = 3600 / runinterval
scope = 60
base = ip_last_octet % scope
hour = '*'
minute = (1..occurances).map { |i| (base - (scope / occurances * i)) % scope }.sort
else
occurances = 86_400 / runinterval
scope = 24
base = ip_last_octet % scope
hour = (1..occurances).map { |i| (base - (scope / occurances * i)) % scope }.sort
minute = ip_last_octet % 60
end
[hour, minute]
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/spec/fixtures/modules/extlib/lib/puppet/functions/extlib/has_module.rb | spec/fixtures/modules/extlib/lib/puppet/functions/extlib/has_module.rb | require 'json'
# A function that lets you know whether a specific module is on your modulepath.
Puppet::Functions.create_function(:'extlib::has_module') do
# @param module_name The full name of the module you want to know exists or not.
# Namespace and modulename can be separated with either `-` or `/`.
# @return Returns `true` or `false`.
# @example Calling the function
# extlib::has_module('camptocamp/systemd')
dispatch :has_module do
param 'Pattern[/\A\w+[-\/]\w+\z/]', :module_name
return_type 'Boolean'
end
def has_module(module_name) # rubocop:disable Style/PredicateName
full_module_name = module_name.gsub(%r{/}, '-')
module_name = full_module_name[%r{(?<=-).+}]
begin
module_path = call_function('get_module_path', module_name)
rescue Puppet::ParseError
# stdlib function get_module_path raises Puppet::ParseError if module isn't in your environment
return false
end
metadata_json = File.join(module_path, 'metadata.json')
return false unless File.exist?(metadata_json)
metadata = JSON.parse(File.read(metadata_json))
return true if metadata['name'] == full_module_name
false
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/spec/input_responders/exit_spec.rb | spec/input_responders/exit_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'puppet-debugger'
describe :exit do
let(:args) { [] }
let(:plugin) do
instance = PuppetDebugger::InputResponders::Commands.plugin_from_command(subject.to_s).instance
instance.debugger = debugger
instance
end
let(:output) do
StringIO.new
end
let(:debugger) do
PuppetDebugger::Cli.new({ out_buffer: output }.merge(options))
end
let(:options) do
{}
end
it 'commands contant is an array' do
expect(plugin.class::COMMAND_WORDS).to be_a(Array)
end
it 'commands must contain at least one word' do
expect(plugin.class::COMMAND_WORDS.count).to be > 0
end
it 'summary must be a string' do
expect(plugin.class::SUMMARY).to be_a(String)
end
# it 'implements run' do
# expect { plugin.run([]) }.not_to raise(SystemExit)
# end
it 'be looked up via any command words' do
plugin.class::COMMAND_WORDS.each do |word|
actual = PuppetDebugger::InputResponders::Commands.plugin_from_command(word.to_s).instance.class
expect(actual).to eq(plugin.class)
end
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/spec/input_responders/classification_spec.rb | spec/input_responders/classification_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'puppet-debugger'
require 'puppet-debugger/plugin_test_helper'
describe :classification do
include_examples 'plugin_tests'
let(:args) { [] }
it 'can process a file' do
expect(plugin.run(args)).to eq('[]')
end
it 'can process a file from handle input' do
debugger.handle_input('classification')
expect(output.string).to eq(" => []\n")
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/spec/input_responders/stacktrace_spec.rb | spec/input_responders/stacktrace_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'puppet-debugger'
require 'puppet-debugger/plugin_test_helper'
describe :stacktrace do
include_examples 'plugin_tests'
let(:args) {}
it 'should be able to print stacktrace' do
debugger_output = /stacktrace\snot\savailable/
expect(plugin.run(args)).to match(debugger_output)
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/spec/input_responders/types_spec.rb | spec/input_responders/types_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'puppet-debugger'
require 'puppet-debugger/plugin_test_helper'
describe :types do
include_examples 'plugin_tests'
let(:args) { [] }
it 'runs' do
expect(plugin.run(args)).to match(/service/)
end
describe 'types' do
let(:input) do
'types'
end
it 'runs' do
debugger.handle_input(input)
expect(output.string).to match(/service/)
end
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/spec/input_responders/whereami_spec.rb | spec/input_responders/whereami_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'puppet-debugger'
require 'puppet-debugger/plugin_test_helper'
describe :whereami do
include_examples 'plugin_tests'
let(:input) do
File.expand_path File.join(fixtures_dir, 'sample_start_debugger.pp')
end
let(:options) do
{
source_file: input,
source_line: 10
}
end
before(:each) do
debugger.handle_input('whereami')
end
it 'runs' do
expect(output.string).to match(/\s+5/)
end
it 'contains marker' do
expect(output.string).to match(/\s+=>\s10/)
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.