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 |
|---|---|---|---|---|---|---|---|---|
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/spec/input_responders/reset_spec.rb | spec/input_responders/reset_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'puppet-debugger'
require 'puppet-debugger/plugin_test_helper'
describe :reset do
include_examples 'plugin_tests'
let(:args) { [] }
it 'can process a file' do
debugger_output = /Puppet::Type::File/
debugger.handle_input("file{'/tmp/reset': ensure => present}")
expect(output.string).to match(debugger_output)
debugger.handle_input('reset')
expect(output.string).to match(debugger_output)
end
describe 'loglevel' do
it 'has not changed' do
debugger.handle_input(':set loglevel debug')
expect(Puppet::Util::Log.level).to eq(:debug)
expect(Puppet::Util::Log.destinations[:buffer].name).to eq(:buffer)
plugin.run('reset')
expect(Puppet::Util::Log.level).to eq(:debug)
expect(Puppet::Util::Log.destinations[:buffer].name).to eq(:buffer)
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/krt_spec.rb | spec/input_responders/krt_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'puppet-debugger/plugin_test_helper'
describe :krt do
include_examples 'plugin_tests'
let(:args) { [] }
it 'works' do
expect(plugin.run(args)).to match(/hostclasses/)
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/set_spec.rb | spec/input_responders/set_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'puppet-debugger'
require 'puppet-debugger/plugin_test_helper'
describe 'set' do
include_examples 'plugin_tests'
let(:input) do
':set loglevel debug'
end
it 'should set the loglevel' do
debugger_output = /loglevel debug is set/
debugger.handle_input(input)
expect(output.string).to match(debugger_output)
expect(Puppet::Util::Log.level).to eq(:debug)
expect(Puppet::Util::Log.destinations[:buffer].name).to eq(:buffer)
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/play_spec.rb | spec/input_responders/play_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'puppet-debugger/plugin_test_helper'
describe :play do
include_examples 'plugin_tests'
describe 'convert url' do
describe 'unsupported' do
let(:url) { 'https://bitbuck.com/master/lib/log_helper.rb' }
let(:converted) { 'https://bitbuck.com/master/lib/log_helper.rb' }
it do
expect(plugin.convert_to_text(url)).to eq(converted)
end
end
describe 'gitlab' do
describe 'blob' do
let(:url) { 'https://gitlab.com/nwops/pdebugger-web/blob/master/lib/log_helper.rb' }
let(:converted) { 'https://gitlab.com/nwops/pdebugger-web/raw/master/lib/log_helper.rb' }
it do
expect(plugin.convert_to_text(url)).to eq(converted)
end
end
describe 'raw' do
let(:url) { 'https://gitlab.com/nwops/pdebugger-web/raw/master/lib/log_helper.rb' }
let(:converted) { 'https://gitlab.com/nwops/pdebugger-web/raw/master/lib/log_helper.rb' }
it do
expect(plugin.convert_to_text(url)).to eq(converted)
end
end
describe 'snippet' do
describe 'not raw' do
let(:url) { 'https://gitlab.com/snippets/19471' }
let(:converted) { 'https://gitlab.com/snippets/19471/raw' }
it do
expect(plugin.convert_to_text(url)).to eq(converted)
end
end
describe 'raw' do
let(:url) { 'https://gitlab.com/snippets/19471/raw' }
let(:converted) { 'https://gitlab.com/snippets/19471/raw' }
it do
expect(plugin.convert_to_text(url)).to eq(converted)
end
end
end
end
describe 'github' do
describe 'raw' do
let(:url) { 'https://gist.githubusercontent.com/logicminds/f9b1ac65a3a440d562b0/raw' }
let(:converted) { 'https://gist.githubusercontent.com/logicminds/f9b1ac65a3a440d562b0/raw' }
it do
expect(plugin.convert_to_text(url)).to eq(converted)
end
end
describe 'raw' do
let(:url) { 'https://gist.githubusercontent.com/logicminds/f9b1ac65a3a440d562b0' }
let(:converted) { 'https://gist.githubusercontent.com/logicminds/f9b1ac65a3a440d562b0.txt' }
it do
expect(plugin.convert_to_text(url)).to eq(converted)
end
end
describe 'raw gist' do
let(:url) { 'https://gist.githubusercontent.com/logicminds/f9b1ac65a3a440d562b0/raw/c8f6be52da5b2b0eeaabb9aa75832b75793d35d1/controls.pp' }
let(:converted) { 'https://gist.githubusercontent.com/logicminds/f9b1ac65a3a440d562b0/raw/c8f6be52da5b2b0eeaabb9aa75832b75793d35d1/controls.pp' }
it do
expect(plugin.convert_to_text(url)).to eq(converted)
end
end
describe 'raw non gist' do
let(:url) { 'https://raw.githubusercontent.com/nwops/puppet-debugger/master/lib/puppet-debugger.rb' }
let(:converted) { 'https://raw.githubusercontent.com/nwops/puppet-debugger/master/lib/puppet-debugger.rb' }
it do
expect(plugin.convert_to_text(url)).to eq(converted)
end
end
describe 'blob' do
let(:url) { 'https://github.com/nwops/puppet-debugger/blob/master/lib/puppet-debugger.rb' }
let(:converted) { 'https://github.com/nwops/puppet-debugger/raw/master/lib/puppet-debugger.rb' }
it do
expect(plugin.convert_to_text(url)).to eq(converted)
end
end
describe 'gist' do
let(:url) { 'https://gist.github.com/logicminds/f9b1ac65a3a440d562b0' }
let(:converted) { 'https://gist.github.com/logicminds/f9b1ac65a3a440d562b0.txt' }
it do
expect(plugin.convert_to_text(url)).to eq(converted)
end
end
end
end
describe 'multiple lines of input' do
before(:each) do
end
describe '3 lines' do
let(:input) do
"$var1 = 'test'\nfile{\"/tmp/${var1}.txt\": ensure => present, mode => '0755'}\nvars"
end
it do
plugin.play_back_string(input)
expect(output.string).to match(/server_facts/) if Gem::Version.new(Puppet.version) >= Gem::Version.new(4.1)
expect(output.string).to match(/test/)
expect(output.string).to match(/Puppet::Type::File/)
end
end
describe '2 lines' do
let(:input) do
"$var1 = 'test'\n $var2 = 'test2'"
end
it do
plugin.play_back_string(input)
expect(output.string).to include("$var1 = 'test'")
expect(output.string).to include('"test"')
expect(output.string).to include("$var2 = 'test2'")
expect(output.string).to include('"test2"')
end
end
describe '1 lines' do
let(:input) do
"$var1 = 'test'"
end
it do
plugin.play_back_string(input)
expect(output.string).to include("$var1 = 'test'")
expect(output.string).to include('"test"')
end
end
describe 'multiple lines puppet code' do
let(:input) do
<<~OUT
if $osfamily {
$var = '3'
}
$var
OUT
end
end
end
describe 'play' do
let(:fixtures_file) do
File.join(fixtures_dir, 'sample_manifest.pp')
end
let(:file_url) do
'https://gist.github.com/logicminds/f9b1ac65a3a440d562b0'
end
let(:input) do
"play #{file_url}"
end
it 'file' do
debugger.handle_input("play #{fixtures_file}")
expect(output.string).to match(/Puppet::Type::File/)
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/facterdb_filter_spec.rb | spec/input_responders/facterdb_filter_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'puppet-debugger'
require 'puppet-debugger/plugin_test_helper'
describe :facterdb_filter do
include_examples 'plugin_tests'
let(:args) { [] }
it 'outputs filter' do
expect(plugin.run(args)).to match(/facterversion/)
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/facts_spec.rb | spec/input_responders/facts_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'puppet-debugger'
require 'puppet-debugger/plugin_test_helper'
describe :facts do
include_examples 'plugin_tests'
let(:args) { ['$::fqdn', 'facts'] }
it 'should be able to resolve fqdn' do
debugger_output = /foo\.example\.com/
output = plugin.run(args[0])
expect(output).to match(debugger_output)
end
it 'should be able to print facts' do
debugger_output = /kernel/
plugin.run(args[1])
expect(plugin.run(args[1])).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/commands_spec.rb | spec/input_responders/commands_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'puppet-debugger'
require 'puppet-debugger/plugin_test_helper'
describe :commands do
include_examples 'plugin_tests'
let(:args) { [] }
it do
expect(plugin.run(args)).to match(/environment/)
end
it 'run a plugin command' do
debugger.handle_input('help')
expect(output.string).to match(/Type "commands" for a list of debugger commands/)
end
it 'show error when command does not exist' do
debugger.handle_input('helpp')
expect(output.string).to match(/invalid command helpp/)
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/classes_spec.rb | spec/input_responders/classes_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'puppet-debugger'
require 'puppet-debugger/plugin_test_helper'
describe :classes do
include_examples 'plugin_tests'
let(:input) do
'classes'
end
it 'should be able to print classes' do
expect(plugin.run([])).to match(/settings/)
end
it 'should be able to print classes with handle input' do
debugger_output = /settings/
expect(plugin.run(['settings'])).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/help_spec.rb | spec/input_responders/help_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'puppet-debugger/plugin_test_helper'
describe :help do
include_examples 'plugin_tests'
let(:args) { [] }
let(:help_output) do
plugin.run(args)
end
it 'can show the help screen' do
expected_debugger_output = /Type \"commands\" for a list of debugger commands\nor \"help\" to show the help screen.\n\n/
expect(help_output).to match(expected_debugger_output)
end
it 'show puppet version' do
expect(help_output).to match(/Puppet Version: \d.\d\d?.\d+\n/)
end
it 'show ruby version' do
expect(help_output).to match(/Ruby Version: #{RUBY_VERSION}\n/)
end
it 'show debugger version' do
expect(help_output).to match(/Puppet Debugger Version: \d.\d\d?.\d.*+\n/)
end
it 'show created by' do
expect(help_output).to match(/Created by: NWOps <corey@nwops.io>\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/resources_spec.rb | spec/input_responders/resources_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'puppet-debugger'
require 'puppet-debugger/plugin_test_helper'
describe :resources do
include_examples 'plugin_tests'
let(:args) {}
it 'should be able to print resources' do
debugger_output = /main/
expect(plugin.run(args)).to match(debugger_output)
end
it 'filter resources' do
expect(plugin.run(['settings'])).to match(/Settings/)
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/vars_spec.rb | spec/input_responders/vars_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'puppet-debugger'
require 'puppet-debugger/plugin_test_helper'
require 'pluginator'
describe :vars do
include_examples 'plugin_tests'
let(:args) { [] }
it 'display facts variable' do
debugger_output = /facts/
output = plugin.run(args)
expect(output).to match(debugger_output)
end
it 'display server facts variable' do
debugger_output = /server_facts/
expect(plugin.run(args)).to match(debugger_output) if Puppet.version.to_f >= 4.1
end
it 'display serverversion variable' do
debugger_output = /serverversion/
expect(plugin.run(args)).to match(debugger_output) if Puppet.version.to_f >= 4.1
end
it 'display local variable' do
debugger.handle_input("$var1 = 'value1'")
expect(plugin.run(args)).to match(/value1/)
end
describe 'resource' do
let(:input) do
"$service_require = Package['httpd']"
end
it 'can process a resource' do
debugger_output = /Facts/
debugger.handle_input(input)
expect(plugin.run(args)).to match(debugger_output)
end
end
describe 'list variables' do
let(:input) do
<<-OUT
class test( $param1 = "files", $param2 = $param1 ) {}
include test
OUT
end
it 'ls test' do
debugger.handle_input(input)
out = plugin.run(['test'])
expect(out).to include('"param1"')
expect(out).to include('"param2"')
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/benchmark_spec.rb | spec/input_responders/benchmark_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'puppet-debugger'
require 'puppet-debugger/plugin_test_helper'
describe :benchmark do
include_examples 'plugin_tests'
let(:args) { ['benchmark', "md5('12345')"] }
describe 'mode' do
before(:each) do
debugger.handle_input('benchmark') # enable
end
it 'enable' do
debugger.handle_input("md5('12345')")
expect(output.string).to match(/Benchmark\ Mode\ On/)
expect(output.string).to match(/Time\ elapsed/)
end
it 'disable' do
debugger.handle_input('benchmark') # disable
expect(output.string).to match(/Benchmark\ Mode\ Off/)
end
end
describe 'onetime' do
it 'run' do
debugger.handle_input("benchmark md5('12345')")
expect(output.string).to_not match(/Benchmark\ Mode\ On/)
expect(output.string).to_not match(/Benchmark\ Mode\ Off/)
expect(output.string).to match(/Time\ elapsed/)
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/functions_spec.rb | spec/input_responders/functions_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'puppet-debugger'
require 'puppet-debugger/plugin_test_helper'
describe :functions do
include_examples 'plugin_tests'
let(:input) do
"md5('hello')"
end
let(:mod_dir) do
File.join(fixtures_dir, 'modules', 'extlib')
end
it 'runs' do
expect(plugin.run).to be_a String
end
it 'returns functions' do
expect(plugin.function_map).to be_a Hash
end
it 'sorted_list' do
expect(plugin.sorted_list).to be_a Array
expect(plugin.sorted_list.first).to be_a Hash
end
it 'returns function names' do
expect(plugin.func_list).to be_a Array
expect(plugin.func_list.find { |m| m =~ /md5/ }).to eq('md5()')
end
it 'execute md5' do
debugger_output = /5d41402abc4b2a76b9719d911017c592/
debugger.handle_input("md5('hello')")
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
it '#function_obj with native function' do
expect(plugin.function_obj(File.join(mod_dir, 'functions', 'dir_split.pp'))).to eq(
file: File.join(mod_dir, 'functions', 'dir_split.pp'), mod_name: 'extlib',
full_name: 'extlib::dir_split', name: 'extlib::dir_split', namespace: 'extlib',
summary: 'Splits the given directory or directories into individual paths.'
)
end
it '#function_obj ruby v4 without namespace' do
expect(plugin.function_obj(File.join(mod_dir, 'lib', 'puppet', 'functions', 'echo.rb'))).to eq(file: File.join(mod_dir, 'lib', 'puppet', 'functions', 'echo.rb'), mod_name: 'extlib',
full_name: 'echo', name: 'echo', namespace: '', summary: 'DEPRECATED. Use the namespaced function [`extlib::echo`](#extlibecho) instead.')
end
it '#function_obj ruby v4 and namespace' do
expect(plugin.function_obj(File.join(mod_dir, 'lib', 'puppet', 'functions', 'extlib', 'echo.rb'))).to eq(file: File.join(mod_dir, 'lib', 'puppet', 'functions', 'extlib', 'echo.rb'), mod_name: 'extlib',
full_name: 'extlib::echo', name: 'extlib::echo', namespace: 'extlib', summary: nil)
end
it '#function_obj has puppet namespace' do
file, = Puppet::Functions.method(:create_function).source_location
dir = File.dirname(file)
f_obj = plugin.function_obj(File.join(dir, 'functions', 'include.rb'))
expect(f_obj[:mod_name]).to match(/puppet-.*/)
expect(f_obj[:name]).to eq('include')
expect(f_obj[:full_name]).to eq('include')
expect(f_obj[:summary]).to be_nil
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/datatypes_spec.rb | spec/input_responders/datatypes_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'puppet-debugger'
require 'puppet-debugger/plugin_test_helper'
describe :datatypes do
include_examples 'plugin_tests'
let(:args) { [] }
it 'handle datatypes' do
output = plugin.run(args)
if Gem::Version.new(Puppet.version) < Gem::Version.new('4.5.0')
expect(output).to eq('[]')
else
expect(output).to match(/.*Array.*/)
end
end
it 'returns core datatypes' do
if Gem::Version.new(Puppet.version) >= Gem::Version.new('6.0.0')
expect(plugin.all_data_types.count).to be >= 19 if supports_datatypes?
else
expect(plugin.all_data_types.count).to be >= 30 if supports_datatypes?
end
end
it 'returns environment datatypes' do
expect(plugin.environment_data_types.count).to be >= 0
end
it 'search datatypes' do
output = plugin.run(['integer'])
expect(output.split('Integer').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/input_responders/environment_spec.rb | spec/input_responders/environment_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'puppet-debugger'
require 'puppet-debugger/plugin_test_helper'
describe :environment do
include_examples 'plugin_tests'
let(:args) { [''] }
it 'can display itself' do
output = plugin.run(args)
expect(output).to eq("Puppet Environment: #{debugger.puppet_env_name}")
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/spec/awesome_print/ext/awesome_puppet_spec.rb | spec/awesome_print/ext/awesome_puppet_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'awesome_print'
require 'awesome_print/ext/awesome_puppet'
RSpec.describe do
let(:output) do
StringIO.new
end
let(:debugger) do
PuppetDebugger::Cli.new(options)
end
let(:options) do
{
out_buffer: output
}
end
let(:input) do
"notify{'ff:gg': }"
end
let(:resource_type) do
debugger.parser.evaluate_string(debugger.scope, input).first
end
let(:ral_type) do
debugger.scope.catalog.resource(resource_type.type_name, resource_type.title).to_ral
end
it 'outputs awesomely' do
expect(ral_type.ai).to include('ff:gg')
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/application/debugger_spec.rb | spec/puppet/application/debugger_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'puppet/application/debugger'
describe Puppet::Application::Debugger do
let(:debugger) do
Puppet::Application::Debugger.new(command_line)
end
# ideally, we should only be providing args in stead of mocking the options
# however during a text, the options in the puppet application are not merged from
# the command line opts so the args never get passed through to options
let(:args) do
[]
end
let(:command_line) do
Puppet::Util::CommandLine.new('puppet', ['debugger', args].flatten)
end
let(:environment) do
debugger.create_environment(nil)
end
let(:node) do
debugger.create_node(environment)
end
let(:scope) do
debugger.create_node(node)
end
before :each do
debugger.initialize_app_defaults
end
it 'declare a main command' do
expect(debugger).to respond_to(:main)
end
it 'start the debugger' do
expect(PuppetDebugger::Cli).to receive(:start_without_stdin)
debugger.run_command
end
it 'start the debugger' do
expect(PuppetDebugger::Cli).to receive(:start_without_stdin)
debugger.run_command
end
it 'create an environment' do
expect(environment).to be_a(Puppet::Node::Environment)
end
it 'shows describtion' do
expect(debugger.help).to match(/^puppet-debugger\([^\)]+\) -- (.*)$/)
end
describe 'with facterdb' do
before(:each) do
end
it 'run md5 function' do
allow(debugger).to receive(:options).and_return(code: "md5('sdafsd')", quiet: true, run_once: true, use_facterdb: true)
expect { debugger.run_command }.to output(/569ebc3d91672e7d3dce25de1684d0c9/).to_stdout
end
it 'assign variable' do
allow(debugger).to receive(:options).and_return(code: "$var1 = 'blah'", quiet: true, run_once: true, use_facterdb: true)
expect { debugger.run_command }.to output(/"blah"/).to_stdout
end
describe 'can reset correctly' do
let(:input) do
<<~OUT
$var1 = 'dsfasd'
$var1
reset
$var1 = '111111'
$var1
OUT
end
it 'assign variable' do
allow(debugger).to receive(:options).and_return(code: input, quiet: true, run_once: true, use_facterdb: true)
expect { debugger.run_command }.to output(/\"111111\"/).to_stdout
end
end
end
describe 'without facterdb' do
it 'run md5 function' do
allow(debugger).to receive(:options).and_return(code: "md5('sdafsd')", quiet: true, run_once: true, use_facterdb: false)
expect { debugger.run_command }.to output(/569ebc3d91672e7d3dce25de1684d0c9/).to_stdout
end
it 'assign variable' do
allow(debugger).to receive(:options).and_return(code: "$var1 = 'blah'", quiet: true, run_once: true, use_facterdb: false)
expect { debugger.run_command }.to output(/"blah"/).to_stdout
end
describe 'import a catalog' do
let(:args) do
[
'--quiet', '--run_once', "--code='resources'",
"--catalog=#{File.expand_path(File.join(fixtures_dir, 'pe-xl-core-0.puppet.vm.json'))}"
]
end
it 'list resources in catalog' do
allow(debugger).to receive(:options).and_return(code: 'resources',
quiet: true, run_once: true, use_facterdb: true,
catalog: File.expand_path(File.join(fixtures_dir, 'pe-xl-core-0.puppet.vm.json')))
expect { debugger.run_command }.to output(/Puppet_enterprise/).to_stdout
end
end
describe 'can reset correctly' do
let(:input) do
<<~OUT
$var1 = 'dsfasd'
$var1
reset
$var1 = '111111'
$var1
OUT
end
it 'assign variable' do
allow(debugger).to receive(:options).and_return(code: input, quiet: true, run_once: true, use_facterdb: false)
expect { debugger.run_command }.to output(/\"111111\"/).to_stdout
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/lib/puppet-debugger.rb | lib/puppet-debugger.rb | # frozen_string_literal: true
require 'puppet-debugger/cli'
require 'puppet-debugger/version'
require 'awesome_print'
require 'awesome_print/ext/awesome_puppet'
require 'puppet-debugger/trollop'
require 'puppet/util/log'
require 'puppet-debugger/debugger_code'
require 'puppet-debugger/support/errors'
require 'plugins/puppet-debugger/input_responders/commands'
require 'puppet-debugger/monkey_patches'
Puppet::Util::Log.newdesttype :buffer do
require 'puppet/util/colors'
include Puppet::Util::Colors
attr_accessor :err_buffer, :out_buffer
def initialize(err = $stderr, out = $stdout)
@err_buffer = err
@out_buffer = out
end
def handle(msg)
levels = {
emerg: { name: 'Emergency', color: :hred, stream: err_buffer },
alert: { name: 'Alert', color: :hred, stream: err_buffer },
crit: { name: 'Critical', color: :hred, stream: err_buffer },
err: { name: 'Error', color: :hred, stream: err_buffer },
warning: { name: 'Warning', color: :hred, stream: err_buffer },
notice: { name: 'Notice', color: :reset, stream: out_buffer },
info: { name: 'Info', color: :green, stream: out_buffer },
debug: { name: 'Debug', color: :cyan, stream: out_buffer }
}
str = msg.respond_to?(:multiline) ? msg.multiline : msg.to_s
str = msg.source == 'Puppet' ? str : "#{msg.source}: #{str}"
level = levels[msg.level]
level[:stream].puts colorize(level[:color], "#{level[:name]}: #{str}")
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/lib/puppet-debugger/version.rb | lib/puppet-debugger/version.rb | # frozen_string_literal: true
module PuppetDebugger
VERSION = '1.2.0'
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/lib/puppet-debugger/monkey_patches.rb | lib/puppet-debugger/monkey_patches.rb | # frozen_string_literal: true
# monkey patch in some color effects string methods
class String
def red
"\033[31m#{self}\033[0m"
end
def bold
"\033[1m#{self}\033[22m"
end
def black
"\033[30m#{self}\033[0m"
end
def green
"\033[32m#{self}\033[0m"
end
def cyan
"\033[36m#{self}\033[0m"
end
def yellow
"\033[33m#{self}\033[0m"
end
def warning
yellow
end
def fatal
red
end
def info
green
end
def camel_case
return self if self !~ /_/ && self =~ /[A-Z]+.*/
split('_').map(&:capitalize).join
end
end
# Bolt plans utilize the PAL Script Compiler to compile the code and thus
# don't store a catalog with the scope. This is due to not needing the catalog
# in the scope. The debugger relies on the catalog being present in the scope
# and thus uses all the methods to discover various data in the catalog
# We monkey patch in a catalog here instead of changing our API for simplicity.
class Puppet::Parser::ScriptCompiler
def catalog
@catalog ||= Puppet::Resource::Catalog.new(@node_name, @environment, 'bolt')
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/lib/puppet-debugger/hooks.rb | lib/puppet-debugger/hooks.rb | # frozen_string_literal: true
require 'puppet-debugger/support/errors'
module PuppetDebugger
# This code was borrowed from Pry hooks file
# Implements a hooks system for Puppet Debugger. A hook is a callable that is associated
# with an event. A number of events are currently provided by Pry, these
# include: `:when_started`, `:before_session`, `:after_session`. A hook must
# have a name, and is connected with an event by the `PuppetDebugger::Hooks#add_hook`
# method.
#
# @example Adding a hook for the `:before_session` event.
# debugger.hooks.add_hook(:before_session, :say_hi) do
# puts "hello"
# end
class Hooks
def initialize
@hooks = Hash.new { |h, k| h[k] = [] }
end
# Ensure that duplicates have their @hooks object.
def initialize_copy(_orig)
hooks_dup = @hooks.dup
@hooks.each do |k, v|
hooks_dup[k] = v.dup
end
@hooks = hooks_dup
end
def errors
@errors ||= []
end
# Destructively merge the contents of two `PuppetDebugger::Hooks` instances.
#
# @param [PuppetDebugger::Hooks] other The `PuppetDebugger::Hooks` instance to merge
# @return [PuppetDebugger::Hooks] The receiver.
# @see {#merge}
def merge!(other)
@hooks.merge!(other.dup.hooks) do |_key, array, other_array|
temp_hash = {}
output = []
(array + other_array).reverse_each do |pair|
temp_hash[pair.first] ||= output.unshift(pair)
end
output
end
self
end
# @example
# hooks = PuppetDebugger::Hooks.new.add_hook(:before_session, :say_hi) { puts "hi!" }
# PuppetDebugger::Hooks.new.merge(hooks)
# @param [PuppetDebugger::Hooks] other The `PuppetDebugger::Hooks` instance to merge
# @return [PuppetDebugger::Hooks] a new `PuppetDebugger::Hooks` instance containing a merge of the
# contents of two `PuppetDebugger::Hooks` instances.
def merge(other)
dup.tap do |v|
v.merge!(other)
end
end
# Add a new hook to be executed for the `event_name` event.
# @param [Symbol] event_name The name of the event.
# @param [Symbol] hook_name The name of the hook.
# @param [#call] callable The callable.
# @yield The block to use as the callable (if no `callable` provided).
# @return [PuppetDebugger::Hooks] The receiver.
def add_hook(event_name, hook_name, callable = nil, &block)
event_name = event_name.to_s
# do not allow duplicates, but allow multiple `nil` hooks
# (anonymous hooks)
if hook_exists?(event_name, hook_name) && !hook_name.nil?
raise ArgumentError, "Hook with name '#{hook_name}' already defined!"
end
raise ArgumentError, 'Must provide a block or callable.' if !block && !callable
# ensure we only have one anonymous hook
@hooks[event_name].delete_if { |h, _k| h.nil? } if hook_name.nil?
if block
@hooks[event_name] << [hook_name, block]
elsif callable
@hooks[event_name] << [hook_name, callable]
end
self
end
# Execute the list of hooks for the `event_name` event.
# @param [Symbol] event_name The name of the event.
# @param [Array] args The arguments to pass to each hook function.
# @return [Object] The return value of the last executed hook.
def exec_hook(event_name, *args, &block)
@hooks[event_name.to_s].map do |_hook_name, callable|
begin
callable.call(*args, &block)
rescue PuppetDebugger::Exception::Error, ::RuntimeError => e
errors << e
e
end
end.last
end
# @param [Symbol] event_name The name of the event.
# @return [Fixnum] The number of hook functions for `event_name`.
def hook_count(event_name)
@hooks[event_name.to_s].size
end
# @param [Symbol] event_name The name of the event.
# @param [Symbol] hook_name The name of the hook
# @return [#call] a specific hook for a given event.
def get_hook(event_name, hook_name)
hook = @hooks[event_name.to_s].find do |current_hook_name, _callable|
current_hook_name == hook_name
end
hook&.last
end
# @param [Symbol] event_name The name of the event.
# @return [Hash] The hash of hook names / hook functions.
# @note Modifying the returned hash does not alter the hooks, use
# `add_hook`/`delete_hook` for that.
def get_hooks(event_name)
Hash[@hooks[event_name.to_s]]
end
# @param [Symbol] event_name The name of the event.
# @param [Symbol] hook_name The name of the hook.
# to delete.
# @return [#call] The deleted hook.
def delete_hook(event_name, hook_name)
deleted_callable = nil
@hooks[event_name.to_s].delete_if do |current_hook_name, callable|
if current_hook_name == hook_name
deleted_callable = callable
true
else
false
end
end
deleted_callable
end
# Clear all hooks functions for a given event.
#
# @param [String] event_name The name of the event.
# @return [void]
def clear_event_hooks(event_name)
@hooks[event_name.to_s] = []
end
# @param [Symbol] event_name Name of the event.
# @param [Symbol] hook_name Name of the hook.
# @return [Boolean] Whether the hook by the name `hook_name`.
def hook_exists?(event_name, hook_name)
@hooks[event_name.to_s].map(&:first).include?(hook_name)
end
protected
attr_reader :hooks
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/lib/puppet-debugger/trollop.rb | lib/puppet-debugger/trollop.rb | # frozen_string_literal: true
# lib/trollop.rb -- trollop command-line processing library
# Copyright (c) 2008-2014 William Morgan.
# Copyright (c) 2014 Red Hat, Inc.
# trollop is licensed under the MIT license.
require 'date'
module Trollop
# note: this is duplicated in gemspec
# please change over there too
VERSION = '2.1.2'
## Thrown by Parser in the event of a commandline error. Not needed if
## you're using the Trollop::options entry.
class CommandlineError < StandardError
attr_reader :error_code
def initialize(msg, error_code = nil)
super(msg)
@error_code = error_code
end
end
## Thrown by Parser if the user passes in '-h' or '--help'. Handled
## automatically by Trollop#options.
class HelpNeeded < StandardError
end
## Thrown by Parser if the user passes in '-v' or '--version'. Handled
## automatically by Trollop#options.
class VersionNeeded < StandardError
end
## Regex for floating point numbers
FLOAT_RE = /^-?((\d+(\.\d+)?)|(\.\d+))([eE][-+]?[\d]+)?$/.freeze
## Regex for parameters
PARAM_RE = /^-(-|\.$|[^\d\.])/.freeze
## The commandline parser. In typical usage, the methods in this class
## will be handled internally by Trollop::options. In this case, only the
## #opt, #banner and #version, #depends, and #conflicts methods will
## typically be called.
##
## If you want to instantiate this class yourself (for more complicated
## argument-parsing logic), call #parse to actually produce the output hash,
## and consider calling it from within
## Trollop::with_standard_exception_handling.
class Parser
## The set of values that indicate a flag option when passed as the
## +:type+ parameter of #opt.
FLAG_TYPES = %i[flag bool boolean].freeze
## The set of values that indicate a single-parameter (normal) option when
## passed as the +:type+ parameter of #opt.
##
## A value of +io+ corresponds to a readable IO resource, including
## a filename, URI, or the strings 'stdin' or '-'.
SINGLE_ARG_TYPES = %i[int integer string double float io date].freeze
## The set of values that indicate a multiple-parameter option (i.e., that
## takes multiple space-separated values on the commandline) when passed as
## the +:type+ parameter of #opt.
MULTI_ARG_TYPES = %i[ints integers strings doubles floats ios dates].freeze
## The complete set of legal values for the +:type+ parameter of #opt.
TYPES = FLAG_TYPES + SINGLE_ARG_TYPES + MULTI_ARG_TYPES
INVALID_SHORT_ARG_REGEX = /[\d-]/.freeze #:nodoc:
## The values from the commandline that were not interpreted by #parse.
attr_reader :leftovers
## The complete configuration hashes for each option. (Mainly useful
## for testing.)
attr_reader :specs
## A flag that determines whether or not to raise an error if the parser is passed one or more
## options that were not registered ahead of time. If 'true', then the parser will simply
## ignore options that it does not recognize.
attr_accessor :ignore_invalid_options
## Initializes the parser, and instance-evaluates any block given.
def initialize(*a, &b)
@version = nil
@leftovers = []
@specs = {}
@long = {}
@short = {}
@order = []
@constraints = []
@stop_words = []
@stop_on_unknown = false
@educate_on_error = false
# instance_eval(&b) if b # can't take arguments
cloaker(&b).bind(self).call(*a) if b
end
## Define an option. +name+ is the option name, a unique identifier
## for the option that you will use internally, which should be a
## symbol or a string. +desc+ is a string description which will be
## displayed in help messages.
##
## Takes the following optional arguments:
##
## [+:long+] Specify the long form of the argument, i.e. the form with two dashes. If unspecified, will be automatically derived based on the argument name by turning the +name+ option into a string, and replacing any _'s by -'s.
## [+:short+] Specify the short form of the argument, i.e. the form with one dash. If unspecified, will be automatically derived from +name+. Use :none: to not have a short value.
## [+:type+] Require that the argument take a parameter or parameters of type +type+. For a single parameter, the value can be a member of +SINGLE_ARG_TYPES+, or a corresponding Ruby class (e.g. +Integer+ for +:int+). For multiple-argument parameters, the value can be any member of +MULTI_ARG_TYPES+ constant. If unset, the default argument type is +:flag+, meaning that the argument does not take a parameter. The specification of +:type+ is not necessary if a +:default+ is given.
## [+:default+] Set the default value for an argument. Without a default value, the hash returned by #parse (and thus Trollop::options) will have a +nil+ value for this key unless the argument is given on the commandline. The argument type is derived automatically from the class of the default value given, so specifying a +:type+ is not necessary if a +:default+ is given. (But see below for an important caveat when +:multi+: is specified too.) If the argument is a flag, and the default is set to +true+, then if it is specified on the the commandline the value will be +false+.
## [+:required+] If set to +true+, the argument must be provided on the commandline.
## [+:multi+] If set to +true+, allows multiple occurrences of the option on the commandline. Otherwise, only a single instance of the option is allowed. (Note that this is different from taking multiple parameters. See below.)
##
## Note that there are two types of argument multiplicity: an argument
## can take multiple values, e.g. "--arg 1 2 3". An argument can also
## be allowed to occur multiple times, e.g. "--arg 1 --arg 2".
##
## Arguments that take multiple values should have a +:type+ parameter
## drawn from +MULTI_ARG_TYPES+ (e.g. +:strings+), or a +:default:+
## value of an array of the correct type (e.g. [String]). The
## value of this argument will be an array of the parameters on the
## commandline.
##
## Arguments that can occur multiple times should be marked with
## +:multi+ => +true+. The value of this argument will also be an array.
## In contrast with regular non-multi options, if not specified on
## the commandline, the default value will be [], not nil.
##
## These two attributes can be combined (e.g. +:type+ => +:strings+,
## +:multi+ => +true+), in which case the value of the argument will be
## an array of arrays.
##
## There's one ambiguous case to be aware of: when +:multi+: is true and a
## +:default+ is set to an array (of something), it's ambiguous whether this
## is a multi-value argument as well as a multi-occurrence argument.
## In thise case, Trollop assumes that it's not a multi-value argument.
## If you want a multi-value, multi-occurrence argument with a default
## value, you must specify +:type+ as well.
def opt(name, desc = '', opts = {}, &b)
raise ArgumentError, "you already have an argument named '#{name}'" if @specs.member? name
## fill in :type
opts[:type] = # normalize
case opts[:type]
when :boolean, :bool then :flag
when :integer then :int
when :integers then :ints
when :double then :float
when :doubles then :floats
when Class
case opts[:type].name
when 'TrueClass', 'FalseClass' then :flag
when 'String' then :string
when 'Integer' then :int
when 'Float' then :float
when 'IO' then :io
when 'Date' then :date
else
raise ArgumentError, "unsupported argument type '#{opts[:type].class.name}'"
end
when nil then nil
else
raise ArgumentError, "unsupported argument type '#{opts[:type]}'" unless TYPES.include?(opts[:type])
opts[:type]
end
## for options with :multi => true, an array default doesn't imply
## a multi-valued argument. for that you have to specify a :type
## as well. (this is how we disambiguate an ambiguous situation;
## see the docs for Parser#opt for details.)
disambiguated_default = if opts[:multi] && opts[:default].is_a?(Array) && !opts[:type]
opts[:default].first
else
opts[:default]
end
type_from_default =
case disambiguated_default
when Integer then :int
when Numeric then :float
when TrueClass, FalseClass then :flag
when String then :string
when IO then :io
when Date then :date
when Array
if opts[:default].empty?
if opts[:type]
raise ArgumentError, 'multiple argument type must be plural' unless MULTI_ARG_TYPES.include?(opts[:type])
nil
else
raise ArgumentError, "multiple argument type cannot be deduced from an empty array for '#{opts[:default][0].class.name}'"
end
else
case opts[:default][0] # the first element determines the types
when Integer then :ints
when Numeric then :floats
when String then :strings
when IO then :ios
when Date then :dates
else
raise ArgumentError, "unsupported multiple argument type '#{opts[:default][0].class.name}'"
end
end
when nil then nil
else
raise ArgumentError, "unsupported argument type '#{opts[:default].class.name}'"
end
raise ArgumentError, ":type specification and default type don't match (default type is #{type_from_default})" if opts[:type] && type_from_default && opts[:type] != type_from_default
opts[:type] = opts[:type] || type_from_default || :flag
## fill in :long
opts[:long] = opts[:long] ? opts[:long].to_s : name.to_s.tr('_', '-')
opts[:long] = case opts[:long]
when /^--([^-].*)$/ then Regexp.last_match(1)
when /^[^-]/ then opts[:long]
else raise ArgumentError, "invalid long option name #{opts[:long].inspect}"
end
raise ArgumentError, "long option name #{opts[:long].inspect} is already taken; please specify a (different) :long" if @long[opts[:long]]
## fill in :short
opts[:short] = opts[:short].to_s if opts[:short] && opts[:short] != :none
opts[:short] = case opts[:short]
when /^-(.)$/ then Regexp.last_match(1)
when nil, :none, /^.$/ then opts[:short]
else raise ArgumentError, "invalid short option name '#{opts[:short].inspect}'"
end
if opts[:short]
raise ArgumentError, "short option name #{opts[:short].inspect} is already taken; please specify a (different) :short" if @short[opts[:short]]
raise ArgumentError, "a short option name can't be a number or a dash" if opts[:short] =~ INVALID_SHORT_ARG_REGEX
end
## fill in :default for flags
opts[:default] = false if opts[:type] == :flag && opts[:default].nil?
## autobox :default for :multi (multi-occurrence) arguments
opts[:default] = [opts[:default]] if opts[:default] && opts[:multi] && !opts[:default].is_a?(Array)
## fill in :multi
opts[:multi] ||= false
opts[:callback] ||= b if block_given?
opts[:desc] ||= desc
@long[opts[:long]] = name
@short[opts[:short]] = name if opts[:short] && opts[:short] != :none
@specs[name] = opts
@order << [:opt, name]
end
## Sets the version string. If set, the user can request the version
## on the commandline. Should probably be of the form "<program name>
## <version number>".
def version(value = nil)
value ? @version = value : @version
end
## Sets the usage string. If set the message will be printed as the
## first line in the help (educate) output and ending in two new
## lines.
def usage(value = nil)
value ? @usage = value : @usage
end
## Adds a synopsis (command summary description) right below the
## usage line, or as the first line if usage isn't specified.
def synopsis(value = nil)
value ? @synopsis = value : @synopsis
end
## Adds text to the help display. Can be interspersed with calls to
## #opt to build a multi-section help page.
def banner(s)
@order << [:text, s]
end
alias text banner
## Marks two (or more!) options as requiring each other. Only handles
## undirected (i.e., mutual) dependencies. Directed dependencies are
## better modeled with Trollop::die.
def depends(*syms)
syms.each { |sym| raise ArgumentError, "unknown option '#{sym}'" unless @specs[sym] }
@constraints << [:depends, syms]
end
## Marks two (or more!) options as conflicting.
def conflicts(*syms)
syms.each { |sym| raise ArgumentError, "unknown option '#{sym}'" unless @specs[sym] }
@constraints << [:conflicts, syms]
end
## Defines a set of words which cause parsing to terminate when
## encountered, such that any options to the left of the word are
## parsed as usual, and options to the right of the word are left
## intact.
##
## A typical use case would be for subcommand support, where these
## would be set to the list of subcommands. A subsequent Trollop
## invocation would then be used to parse subcommand options, after
## shifting the subcommand off of ARGV.
def stop_on(*words)
@stop_words = [*words].flatten
end
## Similar to #stop_on, but stops on any unknown word when encountered
## (unless it is a parameter for an argument). This is useful for
## cases where you don't know the set of subcommands ahead of time,
## i.e., without first parsing the global options.
def stop_on_unknown
@stop_on_unknown = true
end
## Instead of displaying "Try --help for help." on an error
## display the usage (via educate)
def educate_on_error
@educate_on_error = true
end
## Parses the commandline. Typically called by Trollop::options,
## but you can call it directly if you need more control.
##
## throws CommandlineError, HelpNeeded, and VersionNeeded exceptions.
def parse(cmdline = ARGV)
vals = {}
required = {}
opt :version, 'Print version and exit' if @version && !(@specs[:version] || @long['version'])
opt :help, 'Show this message' unless @specs[:help] || @long['help']
@specs.each do |sym, opts|
required[sym] = true if opts[:required]
vals[sym] = opts[:default]
vals[sym] = [] if opts[:multi] && !opts[:default] # multi arguments default to [], not nil
end
resolve_default_short_options!
## resolve symbols
given_args = {}
@leftovers = each_arg cmdline do |arg, params|
## handle --no- forms
arg, negative_given = if arg =~ /^--no-([^-]\S*)$/
["--#{Regexp.last_match(1)}", true]
else
[arg, false]
end
sym = case arg
when /^-([^-])$/ then @short[Regexp.last_match(1)]
when /^--([^-]\S*)$/ then @long[Regexp.last_match(1)] || @long["no-#{Regexp.last_match(1)}"]
else raise CommandlineError, "invalid argument syntax: '#{arg}'"
end
sym = nil if arg =~ /--no-/ # explicitly invalidate --no-no- arguments
next 0 if ignore_invalid_options && !sym
raise CommandlineError, "unknown argument '#{arg}'" unless sym
raise CommandlineError, "option '#{arg}' specified multiple times" if given_args.include?(sym) && !@specs[sym][:multi]
given_args[sym] ||= {}
given_args[sym][:arg] = arg
given_args[sym][:negative_given] = negative_given
given_args[sym][:params] ||= []
# The block returns the number of parameters taken.
num_params_taken = 0
unless params.nil?
if SINGLE_ARG_TYPES.include?(@specs[sym][:type])
given_args[sym][:params] << params[0, 1] # take the first parameter
num_params_taken = 1
elsif MULTI_ARG_TYPES.include?(@specs[sym][:type])
given_args[sym][:params] << params # take all the parameters
num_params_taken = params.size
end
end
num_params_taken
end
## check for version and help args
raise VersionNeeded if given_args.include? :version
raise HelpNeeded if given_args.include? :help
## check constraint satisfaction
@constraints.each do |type, syms|
constraint_sym = syms.find { |sym| given_args[sym] }
next unless constraint_sym
case type
when :depends
syms.each do |sym|
raise CommandlineError, "--#{@specs[constraint_sym][:long]} requires --#{@specs[sym][:long]}" unless given_args.include? sym
end
when :conflicts
syms.each do |sym|
raise CommandlineError, "--#{@specs[constraint_sym][:long]} conflicts with --#{@specs[sym][:long]}" if given_args.include?(sym) && (sym != constraint_sym)
end
end
end
required.each do |sym, _val|
raise CommandlineError, "option --#{@specs[sym][:long]} must be specified" unless given_args.include? sym
end
## parse parameters
given_args.each do |sym, given_data|
arg, params, negative_given = given_data.values_at :arg, :params, :negative_given
opts = @specs[sym]
if params.empty? && opts[:type] != :flag
raise CommandlineError, "option '#{arg}' needs a parameter" unless opts[:default]
params << (opts[:default].is_a?(Array) ? opts[:default].clone : [opts[:default]])
end
vals["#{sym}_given".intern] = true # mark argument as specified on the commandline
case opts[:type]
when :flag
vals[sym] = (sym.to_s =~ /^no_/ ? negative_given : !negative_given)
when :int, :ints
vals[sym] = params.map { |pg| pg.map { |p| parse_integer_parameter p, arg } }
when :float, :floats
vals[sym] = params.map { |pg| pg.map { |p| parse_float_parameter p, arg } }
when :string, :strings
vals[sym] = params.map { |pg| pg.map(&:to_s) }
when :io, :ios
vals[sym] = params.map { |pg| pg.map { |p| parse_io_parameter p, arg } }
when :date, :dates
vals[sym] = params.map { |pg| pg.map { |p| parse_date_parameter p, arg } }
end
if SINGLE_ARG_TYPES.include?(opts[:type])
vals[sym] = if opts[:multi] # multiple options, each with a single parameter
vals[sym].map { |p| p[0] }
else # single parameter
vals[sym][0][0]
end
elsif MULTI_ARG_TYPES.include?(opts[:type]) && !opts[:multi]
vals[sym] = vals[sym][0] # single option, with multiple parameters
end
# else: multiple options, with multiple parameters
opts[:callback].call(vals[sym]) if opts.key?(:callback)
end
## modify input in place with only those
## arguments we didn't process
cmdline.clear
@leftovers.each { |l| cmdline << l }
## allow openstruct-style accessors
class << vals
def method_missing(m, *_args)
self[m] || self[m.to_s]
end
end
vals
end
def parse_date_parameter(param, arg) #:nodoc:
begin
require 'chronic'
time = Chronic.parse(param)
rescue LoadError
# chronic is not available
end
time ? Date.new(time.year, time.month, time.day) : Date.parse(param)
rescue ArgumentError
raise CommandlineError, "option '#{arg}' needs a date"
end
## Print the help message to +stream+.
def educate(stream = $stdout)
width # HACK: calculate it now; otherwise we have to be careful not to
# call this unless the cursor's at the beginning of a line.
left = {}
@specs.each do |name, spec|
left[name] =
(spec[:short] && spec[:short] != :none ? "-#{spec[:short]}" : '') +
(spec[:short] && spec[:short] != :none ? ', ' : '') + "--#{spec[:long]}" +
case spec[:type]
when :flag then ''
when :int then '=<i>'
when :ints then '=<i+>'
when :string then '=<s>'
when :strings then '=<s+>'
when :float then '=<f>'
when :floats then '=<f+>'
when :io then '=<filename/uri>'
when :ios then '=<filename/uri+>'
when :date then '=<date>'
when :dates then '=<date+>'
end +
(spec[:type] == :flag && spec[:default] ? ", --no-#{spec[:long]}" : '')
end
leftcol_width = left.values.map(&:length).max || 0
rightcol_start = leftcol_width + 6 # spaces
unless !@order.empty? && @order.first.first == :text
command_name = File.basename($PROGRAM_NAME).gsub(/\.[^.]+$/, '')
stream.puts "Usage: #{command_name} #{@usage}\n" if @usage
stream.puts "#{@synopsis}\n" if @synopsis
stream.puts if @usage || @synopsis
stream.puts "#{@version}\n" if @version
stream.puts 'Options:'
end
@order.each do |what, opt|
if what == :text
stream.puts wrap(opt)
next
end
spec = @specs[opt]
stream.printf " %-#{leftcol_width}s ", left[opt]
desc = spec[:desc] + begin
default_s = case spec[:default]
when $stdout then '<stdout>'
when $stdin then '<stdin>'
when $stderr then '<stderr>'
when Array
spec[:default].join(', ')
else
spec[:default].to_s
end
if spec[:default]
if spec[:desc] =~ /\.$/
" (Default: #{default_s})"
else
" (default: #{default_s})"
end
else
''
end
end
stream.puts wrap(desc, width: width - rightcol_start - 1, prefix: rightcol_start)
end
end
def width #:nodoc:
@width ||= if $stdout.tty?
begin
require 'io/console'
IO.console.winsize.last
rescue LoadError, NoMethodError, Errno::ENOTTY, Errno::EBADF, Errno::EINVAL
legacy_width
end
else
80
end
end
def legacy_width
# Support for older Rubies where io/console is not available
`tput cols`.to_i
rescue Errno::ENOENT
80
end
private :legacy_width
def wrap(str, opts = {}) # :nodoc:
if str == ''
['']
else
inner = false
str.split("\n").map do |s|
line = wrap_line s, opts.merge(inner: inner)
inner = true
line
end.flatten
end
end
## The per-parser version of Trollop::die (see that for documentation).
def die(arg, msg = nil, error_code = nil)
if msg
warn "Error: argument --#{@specs[arg][:long]} #{msg}."
else
warn "Error: #{arg}."
end
if @educate_on_error
$stderr.puts
educate $stderr
else
warn 'Try --help for help.'
end
exit(error_code || -1)
end
private
## yield successive arg, parameter pairs
def each_arg(args)
remains = []
i = 0
until i >= args.length
return remains += args[i..-1] if @stop_words.member? args[i]
case args[i]
when /^--$/ # arg terminator
return remains += args[(i + 1)..-1]
when /^--(\S+?)=(.*)$/ # long argument with equals
yield "--#{Regexp.last_match(1)}", [Regexp.last_match(2)]
i += 1
when /^--(\S+)$/ # long argument
params = collect_argument_parameters(args, i + 1)
if params.empty?
yield args[i], nil
i += 1
else
num_params_taken = yield args[i], params
unless num_params_taken
if @stop_on_unknown
return remains += args[i + 1..-1]
else
remains += params
end
end
i += 1 + num_params_taken
end
when /^-(\S+)$/ # one or more short arguments
shortargs = Regexp.last_match(1).split(//)
shortargs.each_with_index do |a, j|
if j == (shortargs.length - 1)
params = collect_argument_parameters(args, i + 1)
if params.empty?
yield "-#{a}", nil
i += 1
else
num_params_taken = yield "-#{a}", params
unless num_params_taken
if @stop_on_unknown
return remains += args[i + 1..-1]
else
remains += params
end
end
i += 1 + num_params_taken
end
else
yield "-#{a}", nil
end
end
else
if @stop_on_unknown
return remains += args[i..-1]
else
remains << args[i]
i += 1
end
end
end
remains
end
def parse_integer_parameter(param, arg)
raise CommandlineError, "option '#{arg}' needs an integer" unless param =~ /^-?[\d_]+$/
param.to_i
end
def parse_float_parameter(param, arg)
raise CommandlineError, "option '#{arg}' needs a floating-point number" unless param =~ FLOAT_RE
param.to_f
end
def parse_io_parameter(param, arg)
if param =~ /^(stdin|-)$/i
$stdin
else
require 'open-uri'
begin
open param
rescue SystemCallError => e
raise CommandlineError, "file or url for option '#{arg}' cannot be opened: #{e.message}"
end
end
end
def collect_argument_parameters(args, start_at)
params = []
pos = start_at
while args[pos] && args[pos] !~ PARAM_RE && !@stop_words.member?(args[pos])
params << args[pos]
pos += 1
end
params
end
def resolve_default_short_options!
@order.each do |type, name|
opts = @specs[name]
next if type != :opt || opts[:short]
c = opts[:long].split(//).find { |d| d !~ INVALID_SHORT_ARG_REGEX && !@short.member?(d) }
if c # found a character to use
opts[:short] = c
@short[c] = name
end
end
end
def wrap_line(str, opts = {})
prefix = opts[:prefix] || 0
width = opts[:width] || (self.width - 1)
start = 0
ret = []
until start > str.length
nextt =
if start + width >= str.length
str.length
else
x = str.rindex(/\s/, start + width)
x = str.index(/\s/, start) if x && x < start
x || str.length
end
ret << (ret.empty? && !opts[:inner] ? '' : ' ' * prefix) + str[start...nextt]
start = nextt + 1
end
ret
end
## instance_eval but with ability to handle block arguments
## thanks to _why: http://redhanded.hobix.com/inspect/aBlockCostume.html
def cloaker(&b)
(class << self; self; end).class_eval do
define_method :cloaker_, &b
meth = instance_method :cloaker_
remove_method :cloaker_
meth
end
end
end
## The easy, syntactic-sugary entry method into Trollop. Creates a Parser,
## passes the block to it, then parses +args+ with it, handling any errors or
## requests for help or version information appropriately (and then exiting).
## Modifies +args+ in place. Returns a hash of option values.
##
## The block passed in should contain zero or more calls to +opt+
## (Parser#opt), zero or more calls to +text+ (Parser#text), and
## probably a call to +version+ (Parser#version).
##
## The returned block contains a value for every option specified with
## +opt+. The value will be the value given on the commandline, or the
## default value if the option was not specified on the commandline. For
## every option specified on the commandline, a key "<option
## name>_given" will also be set in the hash.
##
## Example:
##
## require 'trollop'
## opts = Trollop::options do
## opt :monkey, "Use monkey mode" # a flag --monkey, defaulting to false
## opt :name, "Monkey name", :type => :string # a string --name <s>, defaulting to nil
## opt :num_limbs, "Number of limbs", :default => 4 # an integer --num-limbs <i>, defaulting to 4
## end
##
## ## if called with no arguments
## p opts # => {:monkey=>false, :name=>nil, :num_limbs=>4, :help=>false}
##
## ## if called with --monkey
## p opts # => {:monkey=>true, :name=>nil, :num_limbs=>4, :help=>false, :monkey_given=>true}
##
## See more examples at http://trollop.rubyforge.org.
def options(args = ARGV, *a, &b)
@last_parser = Parser.new(*a, &b)
with_standard_exception_handling(@last_parser) { @last_parser.parse args }
end
## If Trollop::options doesn't do quite what you want, you can create a Parser
## object and call Parser#parse on it. That method will throw CommandlineError,
## HelpNeeded and VersionNeeded exceptions when necessary; if you want to
## have these handled for you in the standard manner (e.g. show the help
## and then exit upon an HelpNeeded exception), call your code from within
## a block passed to this method.
##
## Note that this method will call System#exit after handling an exception!
##
## Usage example:
##
## require 'trollop'
## p = Trollop::Parser.new do
## opt :monkey, "Use monkey mode" # a flag --monkey, defaulting to false
## opt :goat, "Use goat mode", :default => true # a flag --goat, defaulting to true
## end
##
## opts = Trollop::with_standard_exception_handling p do
## o = p.parse ARGV
## raise Trollop::HelpNeeded if ARGV.empty? # show help screen
## o
## end
##
## Requires passing in the parser object.
def with_standard_exception_handling(parser)
yield
rescue CommandlineError => e
parser.die(e.message, nil, e.error_code)
rescue HelpNeeded
parser.educate
exit
rescue VersionNeeded
puts parser.version
exit
end
## Informs the user that their usage of 'arg' was wrong, as detailed by
## 'msg', and dies. Example:
##
## options do
## opt :volume, :default => 0.0
## end
##
## die :volume, "too loud" if opts[:volume] > 10.0
## die :volume, "too soft" if opts[:volume] < 0.1
##
## In the one-argument case, simply print that message, a notice
## about -h, and die. Example:
##
## options do
## opt :whatever # ...
## end
##
## Trollop::die "need at least one filename" if ARGV.empty?
def die(arg, msg = nil, error_code = nil)
if @last_parser
@last_parser.die arg, msg, error_code
else
raise ArgumentError, 'Trollop::die can only be called after Trollop::options'
end
end
## Displays the help message and dies. Example:
##
## options do
## opt :volume, :default => 0.0
## banner <<-EOS
## Usage:
## #$0 [options] <name>
## where [options] are:
## EOS
## end
##
## Trollop::educate if ARGV.empty?
def educate
if @last_parser
@last_parser.educate
exit
else
raise ArgumentError, 'Trollop::educate can only be called after Trollop::options'
end
end
module_function :options, :die, :educate, :with_standard_exception_handling
end # module
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/lib/puppet-debugger/input_responder_plugin.rb | lib/puppet-debugger/input_responder_plugin.rb | # frozen_string_literal: true
require 'singleton'
require 'puppet-debugger/support/errors'
require 'forwardable'
module PuppetDebugger
class InputResponderPlugin
include Singleton
extend Forwardable
attr_accessor :debugger
def_delegators :debugger, :scope, :node, :environment, :loaders, :puppet_environment,
:add_hook, :handle_input, :delete_hook, :puppet_lib_dir
def_delegators :scope, :compiler, :catalog
def_delegators :node, :facts
# @return [Array[String]] an array of words the user can call the command with
def self.command_words
self::COMMAND_WORDS
end
def modules_paths
debugger.puppet_environment.full_modulepath
end
# @return [String] a summary of the plugin
def self.summary
self::SUMMARY
end
# @return [String] the name of the command group the plugin is in
def self.command_group
self::COMMAND_GROUP
end
# @return [Hash] a has of all the details of the plugin
def self.details
{ words: command_words, summary: summary, group: command_group }
end
# @param buffer_words [Array[String]] a array of words the user has typed in
# @return Array[String] - an array of words that will help the user with word completion
# By default this returns an empty array, your plugin can chose to override this method in order to
# provide the user with a list of key words based on the user's input
def self.command_completion(_buffer_words)
[]
end
# @param args [Array[String]] - an array of arguments to pass to the plugin command
# @param debugger PuppetDebugger::Cli - an instance of the PuppetDebugger::Cli object
# @return the output of the plugin command
def self.execute(args = [], debugger)
instance.debugger = debugger
instance.run(args)
end
# @param args [Array[String]] - an array of arguments to pass to the plugin command
# @return the output of the plugin command
def run(args = [])
raise NotImplementedError
end
# this is the lib directory of this gem
# in order to load any puppet functions from this gem we need to add the lib path
# of this gem
def puppet_debugger_lib_dir
File.expand_path(File.join(File.dirname(File.dirname(File.dirname(__FILE__))), 'lib'))
end
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/lib/puppet-debugger/plugin_test_helper.rb | lib/puppet-debugger/plugin_test_helper.rb | # frozen_string_literal: true
# https://relishapp.com/rspec/rspec-core/v/3-6/docs/example-groups/shared-examples
RSpec.shared_examples 'plugin_tests' do |_parameter|
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_error
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/lib/puppet-debugger/debugger_code.rb | lib/puppet-debugger/debugger_code.rb | # frozen_string_literal: true
require 'puppet-debugger/code/loc'
require 'puppet-debugger/code/code_range'
require 'puppet-debugger/code/code_file'
# `Pry::Code` is a class that encapsulates lines of source code and their
# line numbers and formats them for terminal output. It can read from a file
# or method definition or be instantiated with a `String` or an `Array`.
#
# In general, the formatting methods in `Code` return a new `Code` object
# which will format the text as specified when `#to_s` is called. This allows
# arbitrary chaining of formatting methods without mutating the original
# object.
class DebuggerCode
class << self
# include MethodSource::CodeHelpers
# Instantiate a `Code` object containing code loaded from a file or
# Pry's line buffer.
#
# @param [String] filename The name of a file, or "(pry)".
# @param [Symbol] code_type The type of code the file contains.
# @return [Code]
def from_file(filename, code_type = nil)
code_file = CodeFile.new(filename, code_type)
new(code_file.code, 1, code_file.code_type, filename)
end
# Instantiate a `Code` object containing code loaded from a file or
# Pry's line buffer.
#
# @param [String] source code".
# @param [Symbol] code_type The type of code the file contains.
# @return [Code]
def from_string(code, code_type = nil)
new(code, 1, code_type)
end
end
# @return [Symbol] The type of code stored in this wrapper.
attr_accessor :code_type, :filename
# Instantiate a `Code` object containing code from the given `Array`,
# `String`, or `IO`. The first line will be line 1 unless specified
# otherwise. If you need non-contiguous line numbers, you can create an
# empty `Code` object and then use `#push` to insert the lines.
#
# @param [Array<String>, String, IO] lines
# @param [Integer?] start_line
# @param [Symbol?] code_type
def initialize(lines = [], start_line = 1, code_type = :ruby, filename = nil)
lines = lines.lines if lines.is_a? String
@lines = lines.each_with_index.map do |line, lineno|
LOC.new(line, lineno + start_line.to_i)
end
@code_type = code_type
@filename = filename
@with_file_reference = nil
@with_marker = @with_indentation = nil
end
# Append the given line. +lineno+ is one more than the last existing
# line, unless specified otherwise.
#
# @param [String] line
# @param [Integer?] lineno
# @return [String] The inserted line.
def push(line, lineno = nil)
lineno = @lines.last.lineno + 1 if lineno.nil?
@lines.push(LOC.new(line, lineno))
line
end
alias << push
# Filter the lines using the given block.
#
# @yield [LOC]
# @return [Code]
def select(&block)
alter do
@lines = @lines.select(&block)
end
end
# Remove all lines that aren't in the given range, expressed either as a
# `Range` object or a first and last line number (inclusive). Negative
# indices count from the end of the array of lines.
#
# @param [Range, Integer] start_line
# @param [Integer?] end_line
# @return [Code]
def between(start_line, end_line = nil)
return self unless start_line
code_range = CodeRange.new(start_line, end_line)
alter do
@lines = @lines[code_range.indices_range(@lines)] || []
end
end
# Take `num_lines` from `start_line`, forward or backwards.
#
# @param [Integer] start_line
# @param [Integer] num_lines
# @return [Code]
def take_lines(start_line, num_lines)
start_idx =
if start_line >= 0
@lines.index { |loc| loc.lineno >= start_line } || @lines.length
else
[@lines.length + start_line, 0].max
end
alter do
@lines = @lines.slice(start_idx, num_lines)
end
end
# Remove all lines except for the +lines+ up to and excluding +lineno+.
#
# @param [Integer] lineno
# @param [Integer] lines
# @return [Code]
def before(lineno, lines = 1)
return self unless lineno
select do |loc|
loc.lineno >= lineno - lines && loc.lineno < lineno
end
end
# Remove all lines except for the +lines+ on either side of and including
# +lineno+.
#
# @param [Integer] lineno
# @param [Integer] lines
# @return [Code]
def around(lineno, lines = 1)
return self unless lineno
select do |loc|
loc.lineno >= lineno - lines && loc.lineno <= lineno + lines
end
end
# Remove all lines except for the +lines+ after and excluding +lineno+.
#
# @param [Integer] lineno
# @param [Integer] lines
# @return [Code]
def after(lineno, lines = 1)
return self unless lineno
select do |loc|
loc.lineno > lineno && loc.lineno <= lineno + lines
end
end
# Remove all lines that don't match the given `pattern`.
#
# @param [Regexp] pattern
# @return [Code]
def grep(pattern)
return self unless pattern
pattern = Regexp.new(pattern)
select do |loc|
loc.line =~ pattern
end
end
# Format output with line numbers next to it, unless `y_n` is falsy.
#
# @param [Boolean?] y_n
# @return [Code]
def with_line_numbers(y_n = true)
alter do
@with_line_numbers = y_n
end
end
# Format output with line numbers next to it, unless `y_n` is falsy.
#
# @param [Boolean?] y_n
# @return [Code]
def with_file_reference(y_n = true)
alter do
@with_file_reference = y_n
end
end
# Format output with a marker next to the given +lineno+, unless +lineno+ is
# falsy.
#
# @param [Integer?] lineno
# @return [Code]
def with_marker(lineno = 1)
alter do
@with_marker = !!lineno
@marker_lineno = lineno
end
end
# Format output with the specified number of spaces in front of every line,
# unless `spaces` is falsy.
#
# @param [Integer?] spaces
# @return [Code]
def with_indentation(spaces = 0)
alter do
@with_indentation = !!spaces
@indentation_num = spaces
end
end
# @return [String]
def inspect
Object.instance_method(:to_s).bind(self).call
end
# @return [Integer] the number of digits in the last line.
def max_lineno_width
!@lines.empty? ? @lines.last.lineno.to_s.length : 0
end
# @return [String] a formatted representation (based on the configuration of
# the object).
def to_s
print_to_output('', false)
end
# @return [String] a (possibly highlighted) copy of the source code.
def highlighted
print_to_output('', true)
end
def add_file_reference
return "From inline code: \n" unless filename
"From file: #{File.basename(filename)}\n"
end
# Writes a formatted representation (based on the configuration of the
# object) to the given output, which must respond to `#<<`.
def print_to_output(output, _color = false)
print_output = output.dup
print_output << add_file_reference if @with_file_reference
@lines.each do |loc|
loc = loc.dup
loc.add_line_number(max_lineno_width) if @with_line_numbers
loc.add_marker(@marker_lineno) if @with_marker
loc.indent(@indentation_num) if @with_indentation
print_output << loc.line
print_output << "\n"
end
print_output
end
# Get the comment that describes the expression on the given line number.
#
# @param [Integer] line_number (1-based)
# @return [String] the code.
def comment_describing(line_number)
self.class.comment_describing(raw, line_number)
end
# Get the multiline expression that starts on the given line number.
#
# @param [Integer] line_number (1-based)
# @return [String] the code.
def expression_at(line_number, consume = 0)
self.class.expression_at(raw, line_number, consume: consume)
end
# Get the multiline expression that starts on the given line number.
#
# @param [Integer] line_number (1-based)
# @return [String] the code.
def self.expression_at(raw, _line_number, _consume = 0)
# self.class.expression_at(raw, line_number, :consume => consume)
raw
end
# Get the (approximate) Module.nesting at the give line number.
#
# @param [Integer] line_number line number starting from 1
# @param [Module] top_module the module in which this code exists
# @return [Array<Module>] a list of open modules.
def nesting_at(line_number, _top_module = Object)
Indent.nesting_at(raw, line_number)
end
# Return an unformatted String of the code.
#
# @return [String]
def raw
@lines.map(&:line).join("\n") << "\n"
end
# Return the number of lines stored.
#
# @return [Integer]
def length
@lines ? @lines.length : 0
end
# Two `Code` objects are equal if they contain the same lines with the same
# numbers. Otherwise, call `to_s` and `chomp` and compare as Strings.
#
# @param [Code, Object] other
# @return [Boolean]
def ==(other)
if other.is_a?(Code)
other_lines = other.instance_variable_get(:@lines)
@lines.each_with_index.all? { |loc, i| loc == other_lines[i] }
else
to_s.chomp == other.to_s.chomp
end
end
# Forward any missing methods to the output of `#to_s`.
def method_missing(name, *args, &block)
to_s.send(name, *args, &block)
end
undef =~
protected
# An abstraction of the `dup.instance_eval` pattern used throughout this
# class.
def alter(&block)
dup.tap { |o| o.instance_eval(&block) }
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/lib/puppet-debugger/cli.rb | lib/puppet-debugger/cli.rb | # frozen_string_literal: true
require 'puppet'
require 'readline'
require 'json'
require 'puppet-debugger/support'
require 'pluginator'
require 'puppet-debugger/hooks'
require 'forwardable'
require 'plugins/puppet-debugger/input_responders/functions'
require 'plugins/puppet-debugger/input_responders/datatypes'
require 'tty-pager'
module PuppetDebugger
class Cli
include PuppetDebugger::Support
extend Forwardable
attr_accessor :settings, :log_level, :in_buffer, :out_buffer, :html_mode, :extra_prompt, :bench
attr_reader :source_file, :source_line_num, :hooks, :options
def_delegators :hooks, :exec_hook, :add_hook, :delete_hook
OUT_SYMBOL = ' => '
def initialize(options = {})
do_initialize if Puppet[:codedir].nil?
Puppet.settings[:name] = :debugger
@options = options
Puppet[:static_catalogs] = false unless Puppet.settings[:static_catalogs].nil?
set_remote_node_name(options[:node_name])
initialize_from_scope(options[:scope])
set_catalog(options[:catalog])
@log_level = 'notice'
@out_buffer = options[:out_buffer] || $stdout
@html_mode = options[:html_mode] || false
@source_file = options[:source_file] || nil
@source_line_num = options[:source_line] || nil
@in_buffer = options[:in_buffer] || $stdin
Readline.input = @in_buffer
Readline.output = @out_buffer
Readline.completion_append_character = ''
Readline.basic_word_break_characters = ' '
Readline.completion_proc = command_completion
AwesomePrint.defaults = {
html: @html_mode,
sort_keys: true,
indent: 2
}
# Catch control-c sequences
trap('SIGINT') do
# control-d
exit 0
end
trap('INT') do
# control-c
# handle_output('Type exit or use control-d')
end
end
# @return [Proc] the proc used in the command completion for readline
# if a plugin keyword is found lets return keywords using the plugin's command completion
# otherwise return the default set of keywords and filter out based on input
def command_completion
proc do |input|
words = Readline.line_buffer.split(Readline.basic_word_break_characters)
next key_words.grep(/^#{Regexp.escape(input)}/) if words.empty?
first_word = words.shift
plugins = PuppetDebugger::InputResponders::Commands.plugins.find_all do |p|
p::COMMAND_WORDS.find { |word| word.start_with?(first_word) }
end
if (plugins.count == 1) && /\A#{first_word}\s/.match(Readline.line_buffer)
plugins.first.command_completion(words)
else
key_words.grep(/^#{Regexp.escape(input)}/)
end
end
end
def hooks
@hooks ||= PuppetDebugger::Hooks.new
end
# returns a cached list of key words
def key_words
# because dollar signs don't work we can't display a $ sign in the keyword
# list so its not explicitly clear what the keyword
variables = scope.to_hash.keys
# prepend a :: to topscope variables
scoped_vars = variables.map { |k, _v| scope.compiler.topscope.exist?(k) ? "$::#{k}" : "$#{k}" }
PuppetDebugger::InputResponders::Functions.instance.debugger = self
funcs = PuppetDebugger::InputResponders::Functions.instance.func_list
PuppetDebugger::InputResponders::Datatypes.instance.debugger = self
(scoped_vars + funcs + static_responder_list +
PuppetDebugger::InputResponders::Datatypes.instance.all_data_types).uniq.sort
end
# looks up the type in the catalog by using the type and title
# and returns the resource in ral format
def to_resource_declaration(type)
if type.respond_to?(:type_name) && type.respond_to?(:title)
title = type.title
type_name = type.type_name
elsif type_result = /(\w+)\['?(\w+)'?\]/.match(type.to_s)
# not all types have a type_name and title so we
# output to a string and parse the results
title = type_result[2]
type_name = type_result[1]
else
return type
end
res = scope.catalog.resource(type_name, title)
return res.to_ral if res
# don't return anything or returns nil if item is not in the catalog
end
#
# @return [Array] - returns a formatted array
# @param types [Array] - an array or string
def expand_resource_type(types)
Array(types).flatten.map { |t| contains_resources?(t) ? to_resource_declaration(t) : t }
end
def contains_resources?(result)
!Array(result).flatten.find { |r| r.class.to_s =~ /Puppet::Pops::Types::PResourceType/ }.nil?
end
def normalize_output(result)
if contains_resources?(result)
output = expand_resource_type(result)
# the results might be wrapped into an array
# if the only output is a resource then return it
# otherwise it is multiple items or an actually array
return output.first if output.count == 1
return output
end
result
end
def responder_list
Pluginator.find(PuppetDebugger)
end
# @return [TTY::Pager] the pager object, disable if CI or testing is present
def pager
@pager ||= TTY::Pager.new(output: out_buffer, enabled: pager_enabled?)
end
def pager_enabled?
ENV['CI'].nil?
end
# @param output [String] - the content to output
# @summary outputs the output to the output buffer
# uses the pager if the screen height is less than the height of the
# output content
# Disabled if CI or testing is being done
def handle_output(output)
return if output.nil?
if pager_enabled? && output.lines.count >= TTY::Screen.height
output << "\n"
pager.page(output)
else
out_buffer.puts(output) unless output.empty?
end
end
# this method handles all input and expects a string of text.
# @param input [String] - the input content to parse or run
def handle_input(input)
raise ArgumentError unless input.instance_of?(String)
output =
begin
case input.strip
when PuppetDebugger::InputResponders::Commands.command_list_regex
args = input.split(' ')
command = args.shift
plugin = PuppetDebugger::InputResponders::Commands.plugin_from_command(command)
plugin.execute(args, self) || ''
when '_'
" => #{@last_item}"
else
result = puppet_eval(input)
@last_item = result
o = normalize_output(result)
o.nil? ? '' : o.ai
end
rescue PuppetDebugger::Exception::InvalidCommand => e
e.message.fatal
rescue LoadError => e
e.message.fatal
rescue Errno::ETIMEDOUT => e
e.message.fatal
rescue ArgumentError => e
e.message.fatal
rescue Puppet::ResourceError => e
e.message.fatal
rescue Puppet::Error => e
e.message.fatal
rescue Puppet::ParseErrorWithIssue => e
e.message.fatal
rescue PuppetDebugger::Exception::FatalError => e
handle_output(e.message.fatal)
exit 1 # this can sometimes causes tests to fail
rescue PuppetDebugger::Exception::Error => e
e.message.fatal
rescue ::RuntimeError => e
handle_output(e.message.fatal)
exit 1
end
output = OUT_SYMBOL + output unless output.empty?
handle_output(output)
exec_hook :after_output, out_buffer, self, self
end
def self.print_repl_desc
<<~OUT
Ruby Version: #{RUBY_VERSION}
Puppet Version: #{Puppet.version}
Puppet Debugger Version: #{PuppetDebugger::VERSION}
Created by: NWOps <corey@nwops.io>
Type "commands" for a list of debugger commands
or "help" to show the help screen.
OUT
end
# tries to determine if the input is going to be a multiline input
# by reading the parser error message
# @return [Boolean] - return true if this is a multiline input, false otherwise
def multiline_input?(data)
case data.message
when /Syntax error at end of/i
true
else
false
end
end
# reads input from stdin, since readline requires a tty
# we cannot read from other sources as readline requires a file object
# we parse the string after each input to determine if the input is a multiline_input
# entry. If it is multiline we run through the loop again and concatenate the
# input
def read_loop
line_number = 1
full_buffer = ''
while buf = Readline.readline("#{line_number}:#{extra_prompt}>> ", true)
begin
full_buffer += buf
# unless this is puppet code, otherwise skip repl keywords
unless PuppetDebugger::InputResponders::Commands.command_list_regex.match(buf)
line_number = line_number.next
begin
parser.parse_string(full_buffer)
rescue Puppet::ParseErrorWithIssue => e
if multiline_input?(e)
out_buffer.print ' '
full_buffer += "\n"
next
end
end
end
handle_input(full_buffer)
full_buffer = ''
end
end
end
# used to start a debugger session without attempting to read from stdin
# or
# this is primarily used by the debug::break() module function and the puppet debugger face
# @param [Hash] must contain at least the puppet scope object
# @option play [String] - must be a path to a file
# @option content [String] - play back the string content passed in
# @option source_file [String] - the file from which the breakpoint was used
# @option source_line [Integer] - the line in the sourcefile from which the breakpoint was used
# @option in_buffer [IO] - the input buffer to read from
# @option out_buffer [IO] - the output buffer to write to
# @option scope [Scope] - the puppet scope
def self.start_without_stdin(options = { scope: nil })
options[:play] = options[:play].path if options[:play].respond_to?(:path)
repl_obj = PuppetDebugger::Cli.new(options)
repl_obj.out_buffer.puts print_repl_desc unless options[:quiet]
repl_obj.handle_input(options[:content]) if options[:content]
# TODO: make the output optional so we can have different output destinations
repl_obj.handle_input('whereami') if options[:source_file] && options[:source_line]
repl_obj.handle_input("play #{options[:play]}") if options[:play]
repl_obj.read_loop unless options[:run_once]
end
# start reads from stdin or from a file
# if from stdin, the repl will process the input and exit
# if from a file, the repl will process the file and continue to prompt
# @param [Hash] puppet scope object
def self.start(options = { scope: nil })
opts = Trollop.options do
opt :play, 'Url or file to load from', required: false, type: String
opt :run_once, 'Evaluate and quit', required: false, default: false
opt :node_name, 'Remote Node to grab facts from', required: false, type: String
opt :catalog, 'Import a catalog file to inspect', required: false, type: String
opt :quiet, 'Do not display banner', required: false, default: false
end
if !STDIN.tty? && !STDIN.closed?
options[:run_once] = true
options[:quiet] = true
end
options = opts.merge(options)
options[:play] = options[:play].path if options[:play].respond_to?(:path)
repl_obj = PuppetDebugger::Cli.new(options)
repl_obj.out_buffer.puts print_repl_desc unless options[:quiet]
if options[:play]
repl_obj.handle_input("play #{options[:play]}")
elsif (ARGF.filename == '-') && (!STDIN.tty? && !STDIN.closed?)
# when the user supplied a file content using stdin, aka. cat,pipe,echo or redirection
input = ARGF.read
repl_obj.handle_input(input)
elsif ARGF.filename != '-'
# when the user supplied a file name without using the args (stdin)
path = File.expand_path(ARGF.filename)
repl_obj.handle_input("play #{path}")
end
# helper code to make tests exit the loop
repl_obj.read_loop unless options[:run_once]
end
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/lib/puppet-debugger/support.rb | lib/puppet-debugger/support.rb | # frozen_string_literal: true
require 'puppet/pops'
require 'facterdb'
require 'tempfile'
# load all the generators found in the generators directory
Dir.glob(File.join(File.dirname(__FILE__), 'support', '*.rb')).each do |file|
require_relative File.join('support', File.basename(file, '.rb'))
end
module PuppetDebugger
module Support
include PuppetDebugger::Support::Compilier
include PuppetDebugger::Support::Environment
include PuppetDebugger::Support::Facts
include PuppetDebugger::Support::Scope
include PuppetDebugger::Support::Node
include PuppetDebugger::Support::Loader
# parses the error type into a more useful error message defined in errors.rb
# returns new error object or the original if error cannot be parsed
def parse_error(error)
case error
when SocketError
PuppetDebugger::Exception::ConnectError.new(message: "Unknown host: #{Puppet[:server]}")
when Net::HTTPError
PuppetDebugger::Exception::AuthError.new(message: error.message)
when Errno::ECONNREFUSED
PuppetDebugger::Exception::ConnectError.new(message: error.message)
when Puppet::Error
if error.message =~ /could\ not\ find\ class/i
PuppetDebugger::Exception::NoClassError.new(default_modules_paths: default_modules_paths,
message: error.message)
elsif error.message =~ /default\ node/i
PuppetDebugger::Exception::NodeDefinitionError.new(default_site_manifest: default_site_manifest,
message: error.message)
else
error
end
else
error
end
end
def lib_dirs(module_dirs = modules_paths)
dirs = module_dirs.map do |mod_dir|
Dir["#{mod_dir}/*/lib"].entries
end.flatten
dirs + [puppet_debugger_lib_dir]
end
def static_responder_list
PuppetDebugger::InputResponders::Commands.command_list
end
# returns either the module name or puppet version
def mod_finder
@mod_finder ||= Regexp.new('\/([\w\-\.]+)\/lib')
end
# this is the lib directory of this gem
# in order to load any puppet functions from this gem we need to add the lib path
# of this gem
# @deprecated
def puppet_debugger_lib_dir
File.expand_path(File.join(File.dirname(File.dirname(File.dirname(__FILE__))), 'lib'))
end
def initialize_from_scope(value)
set_scope(value)
if value
set_environment(value.environment)
set_node(value.compiler.node) if defined?(value.compiler.node)
set_compiler(value.compiler)
end
end
def known_resource_types
res = {
hostclasses: scope.environment.known_resource_types.hostclasses.keys,
definitions: scope.environment.known_resource_types.definitions.keys,
nodes: scope.environment.known_resource_types.nodes.keys
}
if sites = scope.environment.known_resource_types.instance_variable_get(:@sites)
res[:sites] = sites
end
if apps = scope.environment.known_resource_types.respond_to?(:applications)
res[:applications] = apps
end
# some versions of puppet do not support capabilities
if maps = scope.environment.known_resource_types.respond_to?(:capability_mappings)
res[:capability_mappings] = maps
end
res
end
# this is required in order to load things only when we need them
def do_initialize
Puppet.initialize_settings
Puppet[:parser] = 'future' # this is required in order to work with puppet 3.8
Puppet[:trusted_node_data] = true
rescue ArgumentError
rescue Puppet::DevError
# do nothing otherwise calling init twice raises an error
end
# @param String - any valid puppet language code
# @return Hostclass - a puppet Program object which is considered the main class
def generate_ast(string = nil)
parse_result = parser.parse_string(string, '')
# the parse_result may be
# * empty / nil (no input)
# * a Model::Program
# * a Model::Expression
#
# should return nil or Puppet::Pops::Model::Program
# puppet 5 does not have the method current
model = parse_result.respond_to?(:current) ? parse_result.current : parse_result
args = {}
::Puppet::Pops::Model::AstTransformer.new('').merge_location(args, model)
ast_code =
if model.is_a? ::Puppet::Pops::Model::Program
::Puppet::Parser::AST::PopsBridge::Program.new(model, args)
else
args[:value] = model
::Puppet::Parser::AST::PopsBridge::Expression.new(args)
end
# Create the "main" class for the content - this content will get merged with all other "main" content
::Puppet::Parser::AST::Hostclass.new('', code: ast_code)
end
# @return [String] the path to the manifest file
# @param input [String] the manfiest content
# @summary creates a manifest file unless one already exist
def manifest_file(input)
file = Tempfile.new(['puppet_debugger_input', '.pp'])
File.open(file, 'w') do |f|
f.write(input)
end
file
end
# @return [Bolt::PuppetDB::Client]
def bolt_pdb_client
@bolt_pdb_client ||=
begin
require 'bolt/logger'
require 'bolt/puppetdb'
require 'bolt/puppetdb/client'
require 'bolt/puppetdb/config'
if Bolt::PuppetDB::Config.respond_to?(:default_config)
config = Bolt::PuppetDB::Config.default_config
Bolt::PuppetDB::Client.new(config: config)
else
config = Bolt::PuppetDB::Config.load_config({})
Bolt::PuppetDB::Client.new(config)
end
rescue LoadError
# not puppet 6+
nil
end
end
# @param String - any valid puppet language code
# @return Object - returns either a string of the result or object from puppet evaulation
def puppet_eval(input, file: nil)
# in order to add functions to the scope the loaders must be created
# in order to call native functions we need to set the global_scope
# record the input for puppet to retrieve and reference later
manifest_file = file || manifest_file(input)
manfifest_content = input || File.read(manifest_file)
ast = generate_ast(manfifest_content)
Puppet.override({ current_environment: puppet_environment, manifest: manifest_file,
global_scope: scope, bolt_pdb_client: bolt_pdb_client,
loaders: scope.compiler.loaders }, 'For puppet-debugger') do
# because the debugger is not a module we leave the modname blank
scope.environment.known_resource_types.import_ast(ast, '')
exec_hook :before_eval, '', self, self
if bench
result = nil
time = Benchmark.realtime do
result = parser.evaluate_string(scope, manfifest_content, File.expand_path(manifest_file))
end
out = [result, "Time elapsed #{(time * 1000).round(2)} ms"]
else
out = parser.evaluate_string(scope, manfifest_content, File.expand_path(manifest_file))
end
exec_hook :after_eval, out, self, self
out
end
end
def puppet_lib_dir
# returns something like "/Library/Ruby/Gems/2.0.0/gems/puppet-4.2.2/lib/puppet.rb"
# "/Users/adam/.rbenv/versions/2.2.6/lib/ruby/gems/2.2.0/gems/puppet-4.9.4/lib"
# this is only useful when returning a namespace with the functions
@puppet_lib_dir ||= File.dirname(Puppet.method(:[]).source_location.first)
end
# returns a future parser for evaluating code
def parser
@parser ||= ::Puppet::Pops::Parser::EvaluatingParser.new
end
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/lib/puppet-debugger/support/compiler.rb | lib/puppet-debugger/support/compiler.rb | # frozen_string_literal: true
require 'tempfile'
module PuppetDebugger
module Support
module Compilier
def create_compiler(node)
Puppet::Parser::Compiler.new(node)
end
def compiler
@compiler ||= create_compiler(node)
end
def set_compiler(value)
@compiler = value
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/lib/puppet-debugger/support/environment.rb | lib/puppet-debugger/support/environment.rb | # frozen_string_literal: true
module PuppetDebugger
module Support
module Environment
# creates a puppet environment given a module path and environment name
# this is cached
def puppet_environment
@puppet_environment ||= create_environment
end
alias environment puppet_environment
# returns an array of module directories, generally this is the only place
# to look for puppet code by default. This is read from the puppet configuration
def default_modules_paths
dirs = []
# add the puppet-debugger directory so we can load any defined functions
dirs << File.join(Puppet[:environmentpath], default_puppet_env_name, 'modules') unless Puppet[:environmentpath].empty?
dirs << Puppet.settings[:basemodulepath].split(File::PATH_SEPARATOR)
dirs << Puppet.settings[:vendormoduledir].split(File::PATH_SEPARATOR) if Puppet.settings[:vendormoduledir]
dirs << bolt_modules
dirs.flatten.compact.uniq
end
def bolt_modules
spec = Gem::Specification.latest_specs.find { |s| s.name.eql?('bolt') }
File.join(spec.full_gem_path, 'bolt-modules') if spec
end
# returns all the modules paths defined in the environment
def modules_paths
puppet_environment.full_modulepath
end
def default_manifests_dir
File.join(Puppet[:environmentpath], Puppet[:environment], 'manifests')
end
def default_site_manifest
File.join(default_manifests_dir, 'site.pp')
end
# returns the environment
def create_environment
Puppet::Node::Environment.create(Puppet[:environment],
default_modules_paths,
default_manifests_dir)
end
def create_node_environment(manifest = nil)
env = Puppet.lookup(:current_environment)
manifest ? env.override_with(manifest: manifest) : env
end
def set_environment(value)
@puppet_environment = value
end
def puppet_env_name
puppet_environment.name
end
# the cached name of the environment
def default_puppet_env_name
ENV['PUPPET_ENV'] || Puppet[:environment]
end
# currently this is not being used
def environment_loaders
compiler.loaders.public_environment_loader.loader_name
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/lib/puppet-debugger/support/errors.rb | lib/puppet-debugger/support/errors.rb | # frozen_string_literal: true
module PuppetDebugger
module Exception
class Error < StandardError
attr_accessor :data
def initialize(data = {})
@data = data
end
end
class FatalError < Error
end
class InvalidCommand < Error
def message
data[:message]
end
end
class ConnectError < Error
def message
<<~OUT
#{data[:message]}
OUT
end
end
class BadFilter < FatalError
def message
data[:message]
end
end
class UndefinedNode < FatalError
def message
<<~OUT
Cannot find node with name: #{data[:name]} on remote server
OUT
end
end
class TimeOutError < Error
# Errno::ETIMEDOUT
end
class NoClassError < FatalError
def message
<<~OUT
#{data[:message]}
You are missing puppet classes that are required for compilation.
Please ensure these classes are installed on this machine in any of the following paths:
#{data[:default_modules_paths]}
OUT
end
end
class NodeDefinitionError < FatalError
def message
out = <<~OUT
You are missing a default node definition in your site.pp that is required for compilation.
Please ensure you have at least the following default node definition
node default {
# include classes here
}
in your #{data[:default_site_manifest]} file.
OUT
out.fatal
end
end
class AuthError < FatalError
def message
<<~OUT
#{data[:message]}
You will need to edit your auth.conf or conf.d/auth.conf (puppetserver) to allow node calls.
OUT
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/lib/puppet-debugger/support/node.rb | lib/puppet-debugger/support/node.rb | # frozen_string_literal: true
require 'puppet/indirector/node/rest'
module PuppetDebugger
module Support
module Node
# creates a node object using defaults or gets the remote node
# object if the remote_node_name is defined
def create_node
if remote_node_name
# refetch
node_obj = set_node_from_name(remote_node_name)
end
unless node_obj
options = {}
options[:parameters] = default_facts.values
options[:facts] = default_facts
options[:classes] = []
options[:environment] = puppet_environment
name = default_facts.values['fqdn']
node_obj = Puppet::Node.new(name, options)
node_obj.add_server_facts(server_facts) if node_obj.respond_to?(:add_server_facts)
node_obj
end
node_obj
end
def create_real_node(environment)
node = nil
unless Puppet[:node_name_fact].empty?
# Collect our facts.
facts = Puppet::Node::Facts.indirection.find(Puppet[:node_name_value])
raise "Could not find facts for #{Puppet[:node_name_value]}" unless facts
Puppet[:node_name_value] = facts.values[Puppet[:node_name_fact]]
facts.name = Puppet[:node_name_value]
end
Puppet.override({ current_environment: environment }, 'For puppet debugger') do
# Find our Node
node = Puppet::Node.indirection.find(Puppet[:node_name_value])
raise "Could not find node #{Puppet[:node_name_value]}" unless node
# Merge in the facts.
node.merge(facts.values) if facts
end
node
end
def set_remote_node_name(name)
@remote_node_name = name
end
def remote_node_name=(name)
@remote_node_name = name
end
def remote_node_name
@remote_node_name
end
# @return [node] puppet node object
def node
@node ||= create_node
end
def get_remote_node(name)
indirection = Puppet::Indirector::Indirection.instance(:node)
indirection.terminus_class = 'rest'
indirection.find(name, environment: puppet_environment)
end
# this is a hack to get around that the puppet node fact face does not return
# a proper node object with the facts hash populated
# returns a node object with a proper facts hash
def convert_remote_node(remote_node)
options = {}
# remove trusted data as it will later get populated during compilation
parameters = remote_node.parameters.dup
trusted_data = parameters.delete('trusted')
options[:parameters] = parameters || {}
options[:facts] = Puppet::Node::Facts.new(remote_node.name, remote_node.parameters)
options[:classes] = remote_node.classes
options[:environment] = puppet_environment
node_object = Puppet::Node.new(remote_node.name, options)
node_object.add_server_facts(server_facts) if node_object.respond_to?(:add_server_facts)
node_object.trusted_data = trusted_data
node_object
end
# query the remote puppet server and retrieve the node object
#
def set_node_from_name(name)
out_buffer.puts "Fetching node #{name}"
remote_node = get_remote_node(name)
raise PuppetDebugger::Exception::UndefinedNode, name: remote_node.name if remote_node&.parameters&.empty?
node_object = convert_remote_node(remote_node)
set_node(node_object)
end
def set_node(value)
@node = value
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/lib/puppet-debugger/support/loader.rb | lib/puppet-debugger/support/loader.rb | # frozen_string_literal: true
module PuppetDebugger
module Support
# the Loader module wraps a few puppet loader functions
module Loader
def create_loader(environment)
Puppet::Pops::Loaders.new(environment)
end
def loaders
@loaders ||= create_loader(puppet_environment)
end
# returns an array of module loaders that we may need to use in the future
# in order to parse all types of code (ie. functions) For now this is not
# being used.
# def resolve_paths(loaders)
# mod_resolver = loaders.instance_variable_get(:@module_resolver)
# all_mods = mod_resolver.instance_variable_get(:@all_module_loaders)
# all_mods.last.get_contents
# end
# def functions
# @functions = []
# @functions << compiler.loaders.static_loader.loaded.keys.find_all {|l| l.type == :function}
# returns all the type names, athough we cannot determine the difference between datatype and resource type
# loaders.static_loader.loaded.map { |item| item.first.name}
# loaders.implementation_registry.
# instance_variable_get(:'@implementations_per_type_name').
# keys.find_all { |t| t !~ /::/ }
# Puppet::Pops::Types::TypeFactory.type_map.keys.map(&:capatilize)
# end
# Puppet::Pops::Adapters::LoaderAdapter.loader_for_model_object(generate_ast(''))
end
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/lib/puppet-debugger/support/facts.rb | lib/puppet-debugger/support/facts.rb | # frozen_string_literal: true
module PuppetDebugger
module Support
module Facts
# in the future we will want to grab real facts from real systems via puppetdb
# or enc data
# allow the user to specify the facterdb filter
def dynamic_facterdb_filter
ENV['DEBUGGER_FACTERDB_FILTER'] || default_facterdb_filter
end
def default_facterdb_filter
"operatingsystem=#{facter_os_name} and operatingsystemrelease=#{facter_os_version} and architecture=x86_64 and facterversion=#{facter_version}"
end
def facter_version
ENV['DEBUGGER_FACTER_VERSION'] || default_facter_version
end
# return the correct supported version of facter facts
def default_facter_version
if Gem::Version.new(Puppet.version) >= Gem::Version.new(4.4)
'/^3\.1/'
else
'/^2\.4/'
end
end
def facter_os_name
ENV['DEBUGGER_FACTER_OS_NAME'] || 'Fedora'
end
def facter_os_version
ENV['DEBUGGER_FACTER_OS_VERSION'] || '23'
end
def set_facts(value)
@facts = value
end
# uses facterdb (cached facts) and retrives the facts given a filter
# creates a new facts object
# we could also use fact_merge to get real facts from the real system or puppetdb
def node_facts
node_facts = FacterDB.get_facts(dynamic_facterdb_filter).first
if node_facts.nil?
message = <<~OUT
Using filter: #{dynamic_facterdb_filter}
Bad FacterDB filter, please change the filter so it returns a result set.
See https://github.com/camptocamp/facterdb/#with-a-string-filter
OUT
raise PuppetDebugger::Exception::BadFilter, message: message
end
# fix for when --show-legacy facts are not part of the facter 3 fact set
node_facts[:fqdn] = node_facts[:networking].fetch('fqdn', nil) unless node_facts[:fqdn]
node_facts
end
def default_facts
unless @facts
values = Hash[node_facts.map { |k, v| [k.to_s, v] }]
name = values['fqdn']
@facts ||= Puppet::Node::Facts.new(name, values)
end
@facts
end
def server_facts
data = {}
data['servername'] = Facter.value('fqdn') || Facter.value('networking')['fqdn']
data['serverip'] = Facter.value('ipaddress')
data['serverversion'] = Puppet.version.to_s
data
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/lib/puppet-debugger/support/scope.rb | lib/puppet-debugger/support/scope.rb | # frozen_string_literal: true
module PuppetDebugger
module Support
module Scope
# @param [Puppet::Pops::Scope] - Scope object or nil
def set_scope(value)
@scope = value
end
def catalog
@catalog || scope.compiler.catalog
end
def get_catalog_text(catalog)
return nil unless catalog
Puppet::FileSystem.read(catalog, encoding: 'utf-8')
end
def set_catalog(catalog_file)
return unless catalog_file
catalog_text = get_catalog_text(catalog_file)
scope # required
Puppet.override({ current_environment: environment }, _('For puppet debugger')) do
format = Puppet::Resource::Catalog.default_format
begin
c = Puppet::Resource::Catalog.convert_from(format, catalog_text)
rescue StandardError => e
raise Puppet::Error, format(_('Could not deserialize catalog from %{format}: %{detail}'), format: format, detail: e), e.backtrace
end
# Resolve all deferred values and replace them / mutate the catalog
# Puppet 6 only
Puppet::Pops::Evaluator::DeferredResolver.resolve_and_replace(node.facts, c) if Gem::Version.new(Puppet.version) >= Gem::Version.new('6.0.0')
@catalog = c
end
end
# @return [Puppet::Pops::Scope] - returns a puppet scope object
def scope
@scope ||= create_scope
end
# @return [Puppet::Pops::Scope] - returns a puppet scope object
def create_scope
do_initialize
begin
# creates a new compiler for each scope
scope = Puppet::Parser::Scope.new(compiler)
# creates a node class
scope.source = Puppet::Resource::Type.new(:node, node.name)
scope.parent = compiler.topscope
# compiling will load all the facts into the scope
# without this step facts will not get resolved
scope.compiler.compile # this will load everything into the scope
rescue StandardError => e
err = parse_error(e)
raise err
end
scope
end
# @return [Hash] - returns a hash of variables that are currently in scope
def scope_vars
vars = scope.to_hash.delete_if { |key, _value| node.facts.values.key?(key.to_sym) }
vars['facts'] = 'removed by the puppet-debugger'
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/lib/puppet-debugger/code/code_file.rb | lib/puppet-debugger/code/code_file.rb | # frozen_string_literal: true
class CodeFile
class SourceNotFound < RuntimeError
end
DEFAULT_EXT = '.pp'
# List of all supported languages.
# @return [Hash]
EXTENSIONS = {
%w[.py] => :python,
%w[.js] => :javascript,
%w[.pp] => :puppet,
%w[.css] => :css,
%w[.xml] => :xml,
%w[.php] => :php,
%w[.html] => :html,
%w[.diff] => :diff,
%w[.java] => :java,
%w[.json] => :json,
%w[.c .h] => :c,
%w[.rhtml] => :rhtml,
%w[.yaml .yml] => :yaml,
%w[.cpp .hpp .cc .h cxx] => :cpp,
%w[.rb .ru .irbrc .gemspec .pryrc] => :ruby
}.freeze
# @return [Symbol] The type of code stored in this wrapper.
attr_reader :code_type
# @param [String] filename The name of a file with code to be detected
# @param [Symbol] code_type The type of code the `filename` contains
def initialize(filename, code_type = type_from_filename(filename))
@filename = filename
@code_type = code_type
end
# @return [String] The code contained in the current `@filename`.
def code
path = abs_path
@code_type = type_from_filename(path)
File.read(path)
end
private
# @raise [MethodSource::SourceNotFoundError] if the `filename` is not
# readable for some reason.
# @return [String] absolute path for the given `filename`.
def abs_path
code_path.detect { |path| readable?(path) } ||
raise(SourceNotFound,
"Cannot open #{@filename.inspect} for reading.")
end
# @param [String] path
# @return [Boolean] if the path, with or without the default ext,
# is a readable file then `true`, otherwise `false`.
def readable?(path)
File.readable?(path) && !File.directory?(path) ||
File.readable?(path << DEFAULT_EXT)
end
# @return [Array] All the paths that contain code that Pry can use for its
# API's. Skips directories.
def code_path
[from_pwd, from_pry_init_pwd, *from_load_path]
end
# @param [String] filename
# @param [Symbol] default (:unknown) the file type to assume if none could be
# detected.
# @return [Symbol, nil] The CodeRay type of a file from its extension, or
# `nil` if `:unknown`.
def type_from_filename(filename, default = :unknown)
_, @code_type = EXTENSIONS.find do |k, _|
k.any? { |ext| ext == File.extname(filename) }
end
code_type || default
end
# @return [String]
def from_pwd
File.expand_path(@filename, Dir.pwd)
end
# @return [String]
def from_pry_init_pwd
File.expand_path(@filename, Dir.pwd)
end
# @return [String]
def from_load_path
$LOAD_PATH.map { |path| File.expand_path(@filename, path) }
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/lib/puppet-debugger/code/code_range.rb | lib/puppet-debugger/code/code_range.rb | # frozen_string_literal: true
class DebuggerCode
# Represents a range of lines in a code listing.
#
# @api private
class CodeRange
# @param [Integer] start_line
# @param [Integer?] end_line
def initialize(start_line, end_line = nil)
@start_line = start_line
@end_line = end_line
force_set_end_line
end
# @param [Array<LOC>] lines
# @return [Range]
def indices_range(lines)
Range.new(*indices(lines))
end
private
attr_reader :start_line
attr_reader :end_line
# If `end_line` is equal to `nil`, then calculate it from the first
# parameter, `start_line`. Otherwise, leave it as it is.
# @return [void]
def force_set_end_line
if start_line.is_a?(Range)
set_end_line_from_range
else
@end_line ||= start_line
end
end
# Finds indices of `start_line` and `end_line` in the given Array of
# +lines+.
#
# @param [Array<LOC>] lines
# @return [Array<Integer>]
def indices(lines)
[find_start_index(lines), find_end_index(lines)]
end
# @return [Integer]
def find_start_index(lines)
return start_line if start_line.negative?
lines.index { |loc| loc.lineno >= start_line } || lines.length
end
# @return [Integer]
def find_end_index(lines)
return end_line if end_line.negative?
(lines.index { |loc| loc.lineno > end_line } || 0) - 1
end
# For example, if the range is 4..10, then `start_line` would be equal to
# 4 and `end_line` to 10.
# @return [void]
def set_end_line_from_range
@end_line = start_line.last
@end_line -= 1 if start_line.exclude_end?
@start_line = start_line.first
end
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/lib/puppet-debugger/code/loc.rb | lib/puppet-debugger/code/loc.rb | # frozen_string_literal: true
class DebuggerCode
# Represents a line of code. A line of code is a tuple, which consists of a
# line and a line number. A `LOC` object's state (namely, the line
# parameter) can be changed via instance methods. `Pry::Code` heavily uses
# this class.
#
# @api private
# @example
# loc = LOC.new("def example\n :example\nend", 1)
# puts loc.line
# def example
# :example
# end
# #=> nil
#
# loc.indent(3)
# loc.line #=> " def example\n :example\nend"
class LOC
# @return [Array<String, Integer>]
attr_reader :tuple
# @param [String] line The line of code.
# @param [Integer] lineno The position of the +line+.
def initialize(line, lineno)
@tuple = [line.chomp, lineno.to_i]
end
# @return [Boolean]
def ==(other)
other.tuple == tuple
end
def dup
self.class.new(line, lineno)
end
# @return [String]
def line
tuple.first
end
# @return [Integer]
def lineno
tuple.last
end
# Prepends the line number `lineno` to the `line`.
# @param [Integer] max_width
# @return [void]
def add_line_number(max_width = 0)
padded = lineno.to_s.rjust(max_width)
tuple[0] = "#{padded}: #{line}"
end
# Prepends a marker "=>" or an empty marker to the +line+.
#
# @param [Integer] marker_lineno If it is equal to the `lineno`, then
# prepend a hashrocket. Otherwise, an empty marker.
# @return [void]
def add_marker(marker_lineno)
tuple[0] =
if lineno == marker_lineno
" => #{line}".cyan
else
" #{line}"
end
end
# Indents the `line` with +distance+ spaces.
#
# @param [Integer] distance
# @return [void]
def indent(distance)
tuple[0] = "#{' ' * distance}#{line}"
end
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/lib/plugins/puppet-debugger/input_responders/vars.rb | lib/plugins/puppet-debugger/input_responders/vars.rb | # frozen_string_literal: true
require 'puppet-debugger/input_responder_plugin'
module PuppetDebugger
module InputResponders
class Vars < InputResponderPlugin
COMMAND_WORDS = %w[vars ls].freeze
SUMMARY = 'List all the variables in the current scopes.'
COMMAND_GROUP = :scope
def run(args = [])
filter = args
unless filter.empty?
parameters = resource_parameters(debugger.catalog.resources, filter)
return parameters.ai(sort_keys: true, indent: -1)
end
# remove duplicate variables that are also in the facts hash
variables = debugger.scope.to_hash.delete_if { |key, _value| debugger.node.facts.values.key?(key) }
variables['facts'] = 'removed by the puppet-debugger' if variables.key?('facts')
output = 'Facts were removed for easier viewing'.ai + "\n"
output + variables.ai(sort_keys: true, indent: -1)
end
def resource_parameters(resources, filter = [])
find_resources(resources, filter).each_with_object({}) do |resource, acc|
name = "#{resource.type}[#{resource.name}]"
acc[name] = parameters_to_h(resource)
acc
end
end
def parameters_to_h(resource)
resource.parameters.each_with_object({}) do |param, params|
name = param.first.to_s
params[name] = param.last.respond_to?(:value) ? param.last.value : param.last
params
end
end
def find_resources(resources, filter = [])
filter_string = filter.join(' ').downcase
resources.find_all do |resource|
resource.name.to_s.downcase.include?(filter_string) || resource.type.to_s.downcase.include?(filter_string)
end
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/lib/plugins/puppet-debugger/input_responders/whereami.rb | lib/plugins/puppet-debugger/input_responders/whereami.rb | # frozen_string_literal: true
require 'puppet-debugger/input_responder_plugin'
module PuppetDebugger
module InputResponders
class Whereami < InputResponderPlugin
COMMAND_WORDS = %w[whereami].freeze
SUMMARY = 'Show code surrounding the current context.'
COMMAND_GROUP = :context
# source_file and source_line_num instance variables must be set for this
# method to show the surrounding code
# @return [String] - string output of the code surrounded by the breakpoint or nil if file
# or line_num do not exist
def run(args = [])
num_lines = parse(args.first)
file = debugger.source_file
line_num = debugger.source_line_num
if file && line_num
if file == :code
source_code = Puppet[:code]
code = DebuggerCode.from_string(source_code, :puppet)
else
code = DebuggerCode.from_file(file, :puppet)
end
code.with_marker(line_num).around(line_num, num_lines)
.with_line_numbers.with_indentation(5).with_file_reference.to_s
end
end
# @return [Integer]
# @param num [String,Integer] number of lines
# @param defalt [Integer] - default value to return if supplied is less than 5
def parse(num, default = 7)
value = num.to_i
value >= 5 ? value : default
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/lib/plugins/puppet-debugger/input_responders/stacktrace.rb | lib/plugins/puppet-debugger/input_responders/stacktrace.rb | # frozen_string_literal: true
require 'puppet-debugger/input_responder_plugin'
module PuppetDebugger
module InputResponders
class Stacktrace < InputResponderPlugin
COMMAND_WORDS = %w[stacktrace].freeze
SUMMARY = 'Show the stacktrace for how we got here'
COMMAND_GROUP = :tools
# @return [Array]- returns a array of pp files that are involved in the stacktrace
def run(_args = [])
s = stacktrace
s.empty? ? 'stacktrace not available'.warning : s.ai
end
# @return [Array] - an array of files with line numbers
# @example
# [
# "/nwops/puppetlabs-peadm/spec/fixtures/modules/peadm/plans/status.pp:23",
# "/nwops/puppetlabs-peadm/spec/fixtures/modules/peadm/plans/status.pp:20"
# ]
def stacktrace
stack = Puppet::Pops::PuppetStack.stacktrace.find_all { |line| !line.include?('unknown') }
stack.each_with_object([]) do |item, acc|
acc << item.join(':')
end
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/lib/plugins/puppet-debugger/input_responders/environment.rb | lib/plugins/puppet-debugger/input_responders/environment.rb | # frozen_string_literal: true
require 'puppet-debugger/input_responder_plugin'
module PuppetDebugger
module InputResponders
class Environment < InputResponderPlugin
COMMAND_WORDS = %w[environment].freeze
SUMMARY = 'Show the current environment name'
COMMAND_GROUP = :context
def run(_args = [])
"Puppet Environment: #{debugger.puppet_env_name}"
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/lib/plugins/puppet-debugger/input_responders/datatypes.rb | lib/plugins/puppet-debugger/input_responders/datatypes.rb | # frozen_string_literal: true
require 'puppet-debugger/input_responder_plugin'
module PuppetDebugger
module InputResponders
class Datatypes < InputResponderPlugin
COMMAND_WORDS = %w[datatypes].freeze
SUMMARY = 'List all the datatypes available in the environment.'
COMMAND_GROUP = :environment
def run(args = [])
filter = args
datatypes = find_datatypes(all_data_types.sort, filter)
datatypes.ai
end
def find_datatypes(datatypes, filter = [])
return datatypes if filter.nil? || filter.empty?
filter_string = filter.join(' ').downcase
datatypes.find_all do |datatype|
datatype.downcase.include?(filter_string)
end
end
# @return [Array[String]] - returns a list of all the custom data types found in all the modules in the environment
def environment_data_types
globs = debugger.puppet_environment.instance_variable_get(:@modulepath).map { |m| File.join(m, '**', 'types', '**', '*.pp') }
files = globs.map { |g| Dir.glob(g) }.flatten
files.map do |f|
m = File.read(f).match(/type\s([a-z\d\:_]+)/i)
next if m =~ /type|alias/ # can't figure out the best way to filter type and alias out
m[1] if m && m[1] =~ /::/
end.uniq.compact
end
# loaders.instance_variable_get(:@loaders_by_name)['boltlib']
# [:func_4x, :func_4xpp, :func_3x, :datatype, :type_pp,
# :resource_type_pp, :plan, :task]
# @return [Array[String]] - a list of core data types
def core_datatypes
loaders.implementation_registry.instance_variable_get(:@parent)
.instance_variable_get(:@implementations_per_type_name)
.keys.find_all { |t| t !~ /::/ }
end
# @return [Array[String]] - combined list of core data types and environment data types
def all_data_types
unless loaders.respond_to?(:implementation_registry)
Puppet.info("Data Types Not Available in Puppet: #{Puppet.version}")
return []
end
core_datatypes + environment_data_types
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/lib/plugins/puppet-debugger/input_responders/benchmark.rb | lib/plugins/puppet-debugger/input_responders/benchmark.rb | # frozen_string_literal: true
require 'benchmark'
require 'puppet-debugger/input_responder_plugin'
module PuppetDebugger
module InputResponders
class Benchmark < InputResponderPlugin
COMMAND_WORDS = %w[benchmark bm].freeze
SUMMARY = 'Benchmark your Puppet code.'
COMMAND_GROUP = :tools
def run(args = [])
if args.count.positive?
enable(false)
out = debugger.handle_input(args.first)
disable
out
else
status = debugger.bench ? disable : enable(true)
"Benchmark Mode #{status}"
end
end
private
def disable
debugger.bench = false
debugger.extra_prompt = ''
'Off'
end
def enable(show_status = false)
debugger.bench = true
if show_status
debugger.extra_prompt = 'BM'
'On'
end
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/lib/plugins/puppet-debugger/input_responders/resources.rb | lib/plugins/puppet-debugger/input_responders/resources.rb | # frozen_string_literal: true
require 'puppet-debugger/input_responder_plugin'
module PuppetDebugger
module InputResponders
class Resources < InputResponderPlugin
COMMAND_WORDS = %w[resources].freeze
SUMMARY = 'List all the resources current in the catalog.'
COMMAND_GROUP = :scope
def run(args = [])
filter = args
resources = find_resources(debugger.catalog.resources, filter)
modified = resources.map do |res|
res.to_s.gsub(/\[/, "['").gsub(/\]/, "']") # ensure the title has quotes
end
output = "Resources not shown in any specific order\n".warning
output + modified.ai
end
def find_resources(resources, filter = [])
return resources if filter.nil? || filter.empty?
filter_string = filter.join(' ').downcase
resources.find_all do |resource|
resource.name.to_s.downcase.include?(filter_string) || resource.type.to_s.downcase.include?(filter_string)
end
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/lib/plugins/puppet-debugger/input_responders/set.rb | lib/plugins/puppet-debugger/input_responders/set.rb | # frozen_string_literal: true
require 'puppet-debugger/input_responder_plugin'
module PuppetDebugger
module InputResponders
class Set < InputResponderPlugin
COMMAND_WORDS = %w[set :set].freeze
SUMMARY = 'Set the a puppet debugger config'
COMMAND_GROUP = :scope
KEYWORDS = %w[node loglevel].freeze
LOGLEVELS = %w[debug info].freeze
def self.command_completion(buffer_words)
next_word = buffer_words.shift
case next_word
when 'loglevel'
if buffer_words.count.positive?
LOGLEVELS.grep(/^#{Regexp.escape(buffer_words.first)}/)
else
LOGLEVELS
end
when 'debug', 'info', 'node'
[]
when nil
%w[node loglevel]
else
KEYWORDS.grep(/^#{Regexp.escape(next_word)}/)
end
end
def run(args = [])
handle_set(args)
end
private
def handle_set(input)
output = ''
# args = input.split(' ')
# args.shift # throw away the set
case input.shift
when /node/
if name = input.shift
output = "Resetting to use node #{name}"
debugger.set_scope(nil)
debugger.set_node(nil)
debugger.set_facts(nil)
debugger.set_environment(nil)
debugger.set_compiler(nil)
set_log_level(debugger.log_level)
debugger.set_remote_node_name(name)
else
debugger.out_buffer.puts 'Must supply a valid node name'
end
when /loglevel/
if level = input.shift
set_log_level(level)
output = "loglevel #{Puppet::Util::Log.level} is set"
end
end
output
end
def set_log_level(level)
debugger.log_level = level
Puppet::Util::Log.level = level.to_sym
buffer_log = Puppet::Util::Log.newdestination(:buffer)
if buffer_log
# if this is already set the buffer_log is nil
buffer_log.out_buffer = debugger.out_buffer
buffer_log.err_buffer = debugger.out_buffer
end
nil
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/lib/plugins/puppet-debugger/input_responders/classification.rb | lib/plugins/puppet-debugger/input_responders/classification.rb | # frozen_string_literal: true
require 'puppet-debugger/input_responder_plugin'
module PuppetDebugger
module InputResponders
class Classification < InputResponderPlugin
COMMAND_WORDS = %w[classification].freeze
SUMMARY = 'Show the classification details of the node.'
COMMAND_GROUP = :node
def run(_args = [])
debugger.node.classes.ai
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/lib/plugins/puppet-debugger/input_responders/krt.rb | lib/plugins/puppet-debugger/input_responders/krt.rb | # frozen_string_literal: true
require 'puppet-debugger/input_responder_plugin'
module PuppetDebugger
module InputResponders
class Krt < InputResponderPlugin
COMMAND_WORDS = %w[krt].freeze
SUMMARY = 'List all the known resource types.'
COMMAND_GROUP = :scope
def run(_args = [])
debugger.known_resource_types.ai(sort_keys: true, indent: -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/lib/plugins/puppet-debugger/input_responders/classes.rb | lib/plugins/puppet-debugger/input_responders/classes.rb | # frozen_string_literal: true
require 'puppet-debugger/input_responder_plugin'
module PuppetDebugger
module InputResponders
class Classes < InputResponderPlugin
COMMAND_WORDS = %w[classes].freeze
SUMMARY = 'List all the classes current in the catalog.'
COMMAND_GROUP = :scope
def run(args = [])
filter = args
classes = find_classes(debugger.catalog.classes, filter)
classes.ai
end
def find_classes(classes, filter = [])
return classes if filter.nil? || filter.empty?
filter_string = filter.join(' ').downcase
classes.find_all do |klass|
klass.downcase.include?(filter_string)
end
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/lib/plugins/puppet-debugger/input_responders/help.rb | lib/plugins/puppet-debugger/input_responders/help.rb | # frozen_string_literal: true
require 'puppet-debugger/input_responder_plugin'
module PuppetDebugger
module InputResponders
class Help < InputResponderPlugin
COMMAND_WORDS = %w[help].freeze
SUMMARY = 'Show the help screen with version information.'
COMMAND_GROUP = :help
def run(_args = [])
PuppetDebugger::Cli.print_repl_desc
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/lib/plugins/puppet-debugger/input_responders/play.rb | lib/plugins/puppet-debugger/input_responders/play.rb | # frozen_string_literal: true
require 'puppet-debugger/input_responder_plugin'
module PuppetDebugger
module InputResponders
class Play < InputResponderPlugin
COMMAND_WORDS = %w[play].freeze
SUMMARY = 'Playback a file or URL as input.'
COMMAND_GROUP = :editing
def run(args = [])
config = {}
config[:play] = args.first
play_back(config)
nil # we don't want to return anything
end
def play_back(config = {})
if config[:play]
if config[:play] =~ /^http/
play_back_url(config[:play])
elsif File.exist? config[:play]
play_back_string(File.read(config[:play]))
else config[:play]
debugger.out_buffer.puts "puppet-debugger can't play #{config[:play]}'"
end
end
end
def convert_to_text(url)
require 'uri'
url_data = URI(url)
case url_data.host
when /^gist\.github*/
url = url += '.txt' unless url_data.path =~ /raw/
url
when /^github.com/
url.gsub('blob', 'raw') if url_data.path =~ /blob/
when /^gist.github.com/
url = url += '.txt' unless url_data.path =~ /raw/
url
when /^gitlab.com/
if url_data.path =~ /snippets/
url += '/raw' unless url_data.path =~ /raw/
url
else
url.gsub('blob', 'raw')
end
else
url
end
end
# opens the url and reads the data
def fetch_url_data(url)
URI.open(url).read # open(url).read
end
def play_back_url(url)
require 'open-uri'
require 'net/http'
converted_url = convert_to_text(url)
str = fetch_url_data(converted_url)
play_back_string(str)
rescue SocketError
abort "puppet-debugger can't play `#{converted_url}'"
end
# plays back the string to the output stream
# echos the input and the produced output
def play_back_string(str)
full_buffer = ''
str.split("\n").each do |buf|
begin
full_buffer += buf
# unless this is puppet code, otherwise skip repl keywords
debugger.parser.parse_string(full_buffer) unless PuppetDebugger::InputResponders::Commands.command_list_regex.match(buf)
debugger.out_buffer.write('>> ')
rescue Puppet::ParseErrorWithIssue => e
if debugger.multiline_input?(e)
full_buffer += "\n"
next
end
end
debugger.out_buffer.puts(full_buffer)
debugger.handle_input(full_buffer)
full_buffer = ''
end
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/lib/plugins/puppet-debugger/input_responders/facterdb_filter.rb | lib/plugins/puppet-debugger/input_responders/facterdb_filter.rb | # frozen_string_literal: true
require 'puppet-debugger/input_responder_plugin'
module PuppetDebugger
module InputResponders
class FacterdbFilter < InputResponderPlugin
COMMAND_WORDS = %w[facterdb_filter ff].freeze
SUMMARY = 'Set the facterdb filter'
COMMAND_GROUP = :node
# displays the facterdb filter
# @param [Array] - args is not used
def run(_args = [])
debugger.dynamic_facterdb_filter.ai
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/lib/plugins/puppet-debugger/input_responders/facts.rb | lib/plugins/puppet-debugger/input_responders/facts.rb | # frozen_string_literal: true
require 'puppet-debugger/input_responder_plugin'
module PuppetDebugger
module InputResponders
class Facts < InputResponderPlugin
COMMAND_WORDS = %w[facts].freeze
SUMMARY = 'List all the facts associated with the node.'
COMMAND_GROUP = :node
def run(_args = [])
variables = debugger.node.facts.values
variables.ai(sort_keys: true, indent: -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/lib/plugins/puppet-debugger/input_responders/exit.rb | lib/plugins/puppet-debugger/input_responders/exit.rb | # frozen_string_literal: true
require 'puppet-debugger/input_responder_plugin'
module PuppetDebugger
module InputResponders
class Exit < InputResponderPlugin
COMMAND_WORDS = %w[exit].freeze
SUMMARY = 'Quit Puppet Debugger, or use control-d'
COMMAND_GROUP = :help
def run(_args = [])
exit 0
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/lib/plugins/puppet-debugger/input_responders/types.rb | lib/plugins/puppet-debugger/input_responders/types.rb | # frozen_string_literal: true
require 'puppet-debugger/input_responder_plugin'
module PuppetDebugger
module InputResponders
class Types < InputResponderPlugin
COMMAND_WORDS = %w[types].freeze
SUMMARY = 'List all the types available in the environment.'
COMMAND_GROUP = :environment
# @return - returns a list of types available to the environment
# if a error occurs we we run the types function again
def run(_args = [])
types
end
def types
loaded_types = []
begin
# this loads all the types, if already loaded the file is skipped
Puppet::Type.loadall
Puppet::Type.eachtype do |t|
next if t.name == :component
loaded_types << t.name.to_s
end
loaded_types.ai
rescue Puppet::Error => e
puts e.message.red
Puppet.info(e.message)
# prevent more than two calls and recursive loop
return if caller_locations(1, 10).find_all { |f| f.label == 'types' }.count > 2
types
end
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/lib/plugins/puppet-debugger/input_responders/commands.rb | lib/plugins/puppet-debugger/input_responders/commands.rb | # frozen_string_literal: true
require 'puppet-debugger/input_responder_plugin'
module PuppetDebugger
module InputResponders
class Commands < InputResponderPlugin
COMMAND_WORDS = %w[commands].freeze
SUMMARY = 'List all available commands, aka. this screen'
COMMAND_GROUP = :help
def run(_args = [])
commands_list
end
def commands_list
unless @commands_list
@commands_list = ''
command_groups.sort.each do |command_group|
group_name = command_group[0].to_s.capitalize.bold
commands = command_group[1]
@commands_list += ' ' + group_name + "\n"
commands.sort.each do |command|
command_name = command[0]
command_description = command[1]
@commands_list += format(" %-20s %s\n", command_name, command_description)
end
@commands_list += "\n"
end
end
@commands_list
end
def command_groups
unless @command_groups
@command_groups = {}
self.class.command_output.each do |item|
if @command_groups[item[:group]]
@command_groups[item[:group]].merge!(item[:words].first => item[:summary])
else
@command_groups[item[:group]] = { item[:words].first => item[:summary] }
end
end
end
@command_groups
end
def self.command_list_regex
out = command_list.map { |n| "^#{n}" }.join('|')
/#{out}/
end
def self.command_list
command_output.map { |f| f[:words] }.flatten
end
def self.command_output
plugins.map(&:details)
end
def self.plugins
debug_plugins = Pluginator.find('puppet-debugger')
debug_plugins['input_responders']
rescue NoMethodError
raise PuppetDebugger::Exception::InvalidCommand.new(message: 'Unsupported gem version. Please update with: gem update --system')
end
# @param name [String] - the name of the command that is associated with a plugin
# @return [PuppetDebugger::InputResponders::InputResponderPlugin]
def self.plugin_from_command(name)
plug = plugins.find { |p| p::COMMAND_WORDS.include?(name) }
raise PuppetDebugger::Exception::InvalidCommand.new(message: "invalid command #{name}") unless plug
plug
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/lib/plugins/puppet-debugger/input_responders/functions.rb | lib/plugins/puppet-debugger/input_responders/functions.rb | # frozen_string_literal: true
require 'puppet-debugger/input_responder_plugin'
require 'table_print'
require 'fileutils'
require 'bundler'
module PuppetDebugger
module InputResponders
class Functions < InputResponderPlugin
COMMAND_WORDS = %w[functions].freeze
SUMMARY = 'List all the functions available in the environment.'
COMMAND_GROUP = :environment
FUNC_NATIVE_NAME_REGEX = /\Afunction\s([\w\:]+)/.freeze
FUNC_V4_NAME_REGEX = /Puppet\:\:Functions.create_function\s?\(?\:?\'?([\w\:]+)/.freeze
def run(args = [])
filter = args.first || ''
TablePrint::Printer.table_print(sorted_list(filter), %i[full_name mod_name])
end
def sorted_list(filter = '')
search = /#{Regexp.escape(filter)}/
function_map.values.find_all do |v|
"#{v[:mod_name]}_#{v[:full_name]}" =~ search
end.sort { |a, b| a[:full_name] <=> b[:full_name] }
end
# append a () to functions so we know they are functions
def func_list
# ideally we should get a list of function names via the puppet loader
function_map.map { |_name, metadata| "#{metadata[:full_name]}()" }
end
# @return [Hash] - a map of all the functions
def function_map
functions = {}
function_files.each do |file|
obj = function_obj(file)
# return the last matched in cases where rbenv might be involved
functions[obj[:full_name]] = obj
end
functions
end
# @return [String] - the current module directory or directory that contains a gemfile
def current_module_dir
@current_module_dir ||= begin
File.dirname(::Bundler.default_gemfile)
rescue ::Bundler::GemfileNotFound
Dir.pwd
end
end
def lib_dirs(module_dirs = modules_paths)
dirs = module_dirs.map do |mod_dir|
Dir["#{mod_dir}/*/lib"].entries
end.flatten
dirs + [puppet_debugger_lib_dir, File.join(current_module_dir, 'lib')]
end
# @return [Array] - returns a array of the parentname and function name
def function_obj(file)
namespace = nil
name = nil
if file =~ /\.pp/
File.readlines(file, encoding: 'UTF-8').find do |line|
# TODO: not getting namespace for functio
next unless line.match(FUNC_NATIVE_NAME_REGEX)
namespace, name = Regexp.last_match(1).split('::', 2)
name = namespace if name.nil?
namespace = '' if namespace == name
end
elsif file.include?('lib/puppet/functions')
File.readlines(file, encoding: 'UTF-8').find do |line|
next unless line.match(FUNC_V4_NAME_REGEX)
namespace, name = Regexp.last_match(1).split('::', 2)
name = namespace if name.nil?
namespace = '' if namespace == name
end
end
name ||= File.basename(file, File.extname(file))
match = file.match('\/(?<mod>[\w\-\.]+)\/(lib|functions|manifests)')
summary_match = File.read(file, encoding: 'UTF-8').match(/@summary\s(.*)/)
summary = summary_match[1] if summary_match
# fetch the puppet version if this is a function from puppet gem
captures = file.match(/(puppet-[\d\.]+)/)
file_namespace = captures[1] if captures
mod_name = file_namespace || match[:mod]
full_name = namespace.nil? || namespace.empty? ? name : name.prepend("#{namespace}::")
{ namespace: namespace, summary: summary, mod_name: mod_name, name: name, full_name: full_name, file: file }
end
private
# load all the lib dirs so puppet can find the functions
# at this time, this function is not being used
def load_lib_dirs(module_dirs = modules_paths)
lib_dirs(module_dirs).each do |lib|
$LOAD_PATH << lib
end
end
# returns a array of function files which is only required
# when displaying the function map, puppet will load each function on demand
# in the future we may want to utilize the puppet loaders to find these things
def function_files
search_dirs = lib_dirs.map do |lib_dir|
[File.join(lib_dir, 'puppet', 'functions', '**', '*.rb'),
File.join(lib_dir, 'functions', '**', '*.rb'),
File.join(File.dirname(lib_dir), 'functions', '**', '*.pp'),
File.join(lib_dir, 'puppet', 'parser', 'functions', '*.rb')]
end
# add puppet lib directories
search_dirs << [File.join(puppet_lib_dir, 'puppet', 'functions', '**', '*.rb'),
File.join(puppet_lib_dir, 'puppet', 'parser', 'functions', '*.rb')]
Dir.glob(search_dirs.flatten)
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/lib/plugins/puppet-debugger/input_responders/reset.rb | lib/plugins/puppet-debugger/input_responders/reset.rb | # frozen_string_literal: true
require 'puppet-debugger/input_responder_plugin'
module PuppetDebugger
module InputResponders
class Reset < InputResponderPlugin
COMMAND_WORDS = %w[reset].freeze
SUMMARY = 'Reset the debugger to a clean state.'
COMMAND_GROUP = :context
def run(_args = [])
debugger.set_scope(nil)
debugger.set_remote_node_name(nil)
debugger.set_node(nil)
debugger.set_facts(nil)
debugger.set_environment(nil)
debugger.set_compiler(nil)
# debugger.handle_input(":set loglevel #{debugger.log_level}")
nil
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/lib/awesome_print/ext/awesome_puppet.rb | lib/awesome_print/ext/awesome_puppet.rb | # frozen_string_literal: true
module Kernel
class Hash
def to_h
hash = extra_hash_attributes.dup
self.class.hash_attribute_names.each do |name|
hash[name] = __send__(name)
end
hash
end
end
end
module AwesomePrint
module Puppet
def self.included(base)
base.send :alias_method, :cast_without_puppet_resource, :cast
base.send :alias_method, :cast, :cast_with_puppet_resource
end
# this tells ap how to cast our object so we can be specific
# about printing different puppet objects
def cast_with_puppet_resource(object, type)
cast = cast_without_puppet_resource(object, type)
# check the object to see if it has an acestor (< ) of the specified type
if defined?(::Puppet::Type) && (object.class < ::Puppet::Type)
cast = :puppet_type
elsif defined?(::Puppet::Pops::Types) && (object.class < ::Puppet::Pops::Types)
cast = :puppet_type
elsif defined?(::Puppet::Parser::Resource) && (object.class < ::Puppet::Parser::Resource)
cast = :puppet_resource
elsif /Puppet::Pops::Types/.match(object.class.to_s)
cast = :puppet_type
elsif /Bolt::/.match(object.class.to_s)
cast = :bolt_type
end
cast
end
def awesome_bolt_type(object)
if object.class.to_s.include?('Result')
object.to_data.ai
elsif object.is_a?(::Bolt::Target)
object.to_h.merge(object.detail).ai
else
object.ai
end
end
def awesome_puppet_resource(object)
return '' if object.nil?
resource_object = object.to_ral
awesome_puppet_type(resource_object)
end
def awesome_puppet_type(object)
return '' if object.nil?
return object.to_s unless object.respond_to?(:name) && object.respond_to?(:title) && object.respond_to?(:to_hash)
h = if [].respond_to?(:to_h)
# to_h is only supported in ruby 2.1+
object.to_hash.merge(name: object.name, title: object.title).sort.to_h
else
object.to_hash.merge(name: object.name, title: object.title)
end
res_str = awesome_hash(JSON.parse(h.to_json)) # converting to json removes symbols
"#{object.class} #{res_str}"
end
end
end
AwesomePrint::Formatter.include AwesomePrint::Puppet
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
nwops/puppet-debugger | https://github.com/nwops/puppet-debugger/blob/d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb/lib/puppet/application/debugger.rb | lib/puppet/application/debugger.rb | # frozen_string_literal: true
require 'puppet/application'
require 'optparse'
require 'puppet/util/command_line'
class Puppet::Application::Debugger < Puppet::Application
attr_reader :use_stdin
option('--execute EXECUTE', '-e') do |arg|
options[:code] = arg
end
option('--facterdb-filter FILTER') do |arg|
options[:use_facterdb] = true unless options[:node_name]
ENV['DEBUGGER_FACTERDB_FILTER'] = arg if arg
end
option('--test') do |_arg|
options[:quiet] = true
options[:run_once] = true
@use_stdin = true
end
option('--no-facterdb') { |_arg| options[:use_facterdb] = false }
option('--log-level LEVEL', '-l') do |arg|
Puppet::Util::Log.level = arg.to_sym
end
option('--catalog catalog', '-c catalog') do |arg|
options[:catalog] = arg
end
option('--quiet', '-q') { |_arg| options[:quiet] = true }
option('--play URL', '-p') do |arg|
options[:play] = arg
end
option('--stdin', '-s') { |_arg| @use_stdin = true }
option('--run-once', '-r') { |_arg| options[:run_once] = true }
option('--node-name CERTNAME', '-n') do |arg|
options[:use_facterdb] = false
options[:node_name] = arg
end
def help
<<~HELP
puppet-debugger(8) -- Starts a debugger session using the puppet-debugger tool
========
SYNOPSIS
--------
A interactive command line tool for evaluating the puppet language and debugging
puppet code.
USAGE
-----
puppet debugger [--help] [--version] [-e|--execute CODE] [--facterdb-filter FILTER]
[--test] [--no-facterdb] [-q|--quiet] [-p|--play URL] [-s|--stdin]
[-r|--run-once] [-n|--node-name CERTNAME]
DESCRIPTION
-----------
A interactive command line tool for evaluating the puppet language and debugging
puppet code.
USAGE WITH DEBUG MODULE
-----------------------
Use the puppet debugger in conjunction with the debug::break() puppet function
to pry into your code during compilation. Get immediate insight in how the puppet4
languge works during the execution of your code.
To use the break function install the module via: puppet module install nwops/debug
Now place the debug::break() function anywhere in your code to
Example:
puppet debugger -e '$abs_vars = [-11,-22,-33].map | Integer $num | { debug::break() ; notice($num) }'
See: https://github.com/nwops/puppet-debug
OPTIONS
-------
Note that any setting that's valid in the configuration
file is also a valid long argument. For example, 'server' is a valid
setting, so you can specify '--server <servername>' as
an argument.
See the configuration file documentation at
http://docs.puppetlabs.com/references/stable/configuration.html for the
full list of acceptable parameters. A commented list of all
configuration options can also be generated by running puppet debugger with
'--genconfig'.
* --help:
Print this help message
* --version:
Print the puppet version number and exit.
* --execute:
Execute a specific piece of Puppet code
* --facterdb-filter
Disables the usage of the current node level facts and uses cached facts
from facterdb. Specifying a filter will override the default facterdb filter.
Not specifiying a filter will use the default CentOS based filter.
This will greatly speed up the start time of the debugger since
you are using cached facts. Additionally, using facterdb also allows you
to play with many other operating system facts that you might not have access
to. For example filters please see the facterdb docs.
See https://github.com/camptocamp/facterdb for more info
* --no-facterdb
Use the facts found on this node instead of cached facts from facterdb.
* --log-level
Set the Puppet log level which can be very useful with using the debugger.
* --quiet
Do not display the debugger help script upon startup.
* --play
Plays back the code file supplied into the debugger. Can also supply
any http based url.
* --run-once
Return the result from the debugger and exit
* --stdin
Read from stdin instead of starting the debugger right away. Useful when piping code into the debugger.
* --catalog:
Import a JSON catalog (such as one generated with 'puppet master --compile'). You need to
specify a valid JSON encoded catalog file. Gives you the ability
to inspect the catalog and all the parameter values that make up the resources. Can
specify a file or pipe to stdin with '-'.
* --node-name
Retrieves the node information remotely via the puppet server given the node name.
This is extremely useful when trying to debug classification issues, as this can show
classes and parameters retrieved from the ENC. You can also play around with the real facts
of the remote node as well.
Note: this requires special permission in your puppet server's auth.conf file to allow
access to make remote calls from this node: #{Puppet[:certname]}. If you are running
the debugger from the puppet server as root you do not need any special setup.
You must also have a signed cert and be able to connect to the server from this system.
Mutually exclusive with --facterdb-filter
* --test
Runs the code in the debugger and exit without showing the help screen ( --quiet --run-once, --stdin)
EXAMPLE
-------
$ puppet debugger
$ echo "notice('hello, can you hear me?')" | puppet debugger --test
$ echo "notice('hello, can you hear me?')" | puppet debugger --stdin
$ puppet debugger --execute "notice('hello')"
$ puppet debugger --facterdb-filter 'facterversion=/^2.4\./ and operatingsystem=Debian'
$ puppet debugger --play https://gist.github.com/logicminds/4f6bcfd723c92aad1f01f6a800319fa4
$ puppet debugger --facterdb-filter 'facterversion=/^2.4\./ and operatingsystem=Debian' \\
--play https://gist.github.com/logicminds/4f6bcfd723c92aad1f01f6a800319fa4
$ puppet debugger --node-name
AUTHOR
------
Corey Osman <corey@nwops.io>
COPYRIGHT
---------
Copyright (c) 2019 NWOps
HELP
end
def initialize(command_line = Puppet::Util::CommandLine.new)
@command_line = CommandLineArgs.new(command_line.subcommand_name, command_line.args.dup)
@options = { use_facterdb: true, play: nil, run_once: false,
node_name: nil, quiet: false, help: false, scope: nil,
catalog: nil }
@use_stdin = false
begin
require 'puppet-debugger'
rescue LoadError
Puppet.err('You must install the puppet-debugger: gem install puppet-debugger')
end
end
def main
# if this is a file we don't play back since its part of the environment
# if just the code we put in a file and use the play feature of the debugger
# we could do the same thing with the passed in manifest file but that might be too much code to show
if options[:code]
code_input = options.delete(:code)
file = Tempfile.new(['puppet_debugger_input', '.pp'])
File.open(file, 'w') do |f|
f.write(code_input)
end
options[:play] = file
elsif command_line.args.empty? && use_stdin
code_input = STDIN.read
file = Tempfile.new(['puppet_debugger_input', '.pp'])
File.open(file, 'w') do |f|
f.write(code_input)
end
options[:play] = file
elsif !command_line.args.empty?
manifest = command_line.args.shift
raise "Could not find file #{manifest}" unless Puppet::FileSystem.exist?(manifest)
Puppet.warning("Only one file can be used per run. Skipping #{command_line.args.join(', ')}") unless command_line.args.empty?
options[:play] = manifest
end
begin
if !options[:use_facterdb] && options[:node_name].nil?
debug_environment = create_environment(nil)
Puppet.notice('Gathering node facts...')
node = create_node(debug_environment)
scope = create_scope(node)
# start_debugger(scope)
options[:scope] = scope
end
::PuppetDebugger::Cli.start_without_stdin(options)
rescue Exception => e
case e.class.to_s
when 'SystemExit'
nil
else
puts e.message
puts e.backtrace
end
end
end
def create_environment(manifest)
configured_environment = Puppet.lookup(:current_environment)
if manifest
configured_environment.override_with(manifest: manifest)
else
configured_environment
end
end
def create_node(environment)
node = nil
unless Puppet[:node_name_fact].empty?
# Collect our facts.
unless facts = Puppet::Node::Facts.indirection.find(Puppet[:node_name_value])
raise "Could not find facts for #{Puppet[:node_name_value]}"
end
Puppet[:node_name_value] = facts.values[Puppet[:node_name_fact]]
facts.name = Puppet[:node_name_value]
end
Puppet.override({ current_environment: environment }, 'For puppet debugger') do
# Find our Node
unless node = Puppet::Node.indirection.find(Puppet[:node_name_value])
raise "Could not find node #{Puppet[:node_name_value]}"
end
# Merge in the facts.
node.merge(facts.values) if facts
end
node
end
def create_scope(node)
compiler = Puppet::Parser::Compiler.new(node) # creates a new compiler for each scope
scope = Puppet::Parser::Scope.new(compiler)
# creates a node class
scope.source = Puppet::Resource::Type.new(:node, node.name)
scope.parent = compiler.topscope
# compiling will load all the facts into the scope
# without this step facts will not get resolved
scope.compiler.compile # this will load everything into the scope
scope
end
def start_debugger(scope, options = {})
if $stdout.isatty
options = options.merge(scope: scope)
# required in order to use convert puppet hash into ruby hash with symbols
options = options.each_with_object({}) do |(k, v), data|
data[k.to_sym] = v
data
end
# options[:source_file], options[:source_line] = stacktrace.last
::PuppetRepl::Cli.start(options)
else
Puppet.info 'puppet debug: refusing to start the debugger without a tty'
end
end
# returns a stacktrace of called puppet code
# @return [String] - file path to source code
# @return [Integer] - line number of called function
# This method originally came from the puppet 4.6 codebase and was backported here
# for compatibility with older puppet versions
# The basics behind this are to find the `.pp` file in the list of loaded code
def stacktrace
caller.each_with_object([]) do |loc, memo|
if loc =~ /\A(.*\.pp)?:([0-9]+):in\s(.*)/
# if the file is not found we set to code
# and read from Puppet[:code]
# $3 is reserved for the stacktrace type
memo << [Regexp.last_match(1).nil? ? :code : Regexp.last_match(1), Regexp.last_match(2).to_i]
end
memo
end.reverse
end
end
| ruby | MIT | d2ed9e3cd0b775956d8b0d6ed78e9a4a4b9a9fbb | 2026-01-04T17:57:09.425774Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/app/helpers/messaging/application_helper.rb | app/helpers/messaging/application_helper.rb | module Messaging
module ApplicationHelper
end
end
| ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/app/controllers/messaging/messages_controller.rb | app/controllers/messaging/messages_controller.rb | module Messaging
class MessagesController < Messaging::ApplicationController
def index
@box = params[:box] || 'inbox'
@messages = current_user.mailbox.inbox if @box == 'inbox'
@messages = current_user.mailbox.sentbox if @box == 'sent'
@messages = current_user.mailbox.trash if @box == 'trash'
end
def new
@message = Message.new
end
def create
@message = Message.new params[:message]
if @message.conversation_id
@conversation = Conversation.find(@message.conversation_id)
unless @conversation.is_participant?(current_user)
flash[:alert] = "You do not have permission to view that conversation."
return redirect_to root_path
end
receipt = current_user.reply_to_conversation(@conversation, @message.body, nil, true, true, @message.attachment)
else
unless @message.valid?
return render :new
end
receipt = current_user.send_message(@message.recipients, @message.body, @message.subject, true, @message.attachment)
end
flash[:notice] = "Message sent."
redirect_to message_path(receipt.conversation)
end
def show
@conversation = Conversation.find_by_id(params[:id])
unless @conversation.is_participant?(current_user)
flash[:alert] = "You do not have permission to view that conversation."
return redirect_to root_path
end
@message = Message.new conversation_id: @conversation.id
current_user.read(@conversation)
end
def trash
conversation = Conversation.find_by_id(params[:id])
if conversation
current_user.trash(conversation)
flash[:notice] = "Message sent to trash."
else
conversations = Conversation.find(params[:conversations])
conversations.each { |c| current_user.trash(c) }
flash[:notice] = "Messages sent to trash."
end
redirect_to messages_path(box: params[:current_box])
end
def untrash
conversation = Conversation.find(params[:id])
current_user.untrash(conversation)
flash[:notice] = "Message untrashed."
redirect_to messages_path(box: 'inbox')
end
def search
@search = params[:search]
@messages = current_user.search_messages(@search)
render :index
end
end
end
| ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/app/controllers/messaging/application_controller.rb | app/controllers/messaging/application_controller.rb | module Messaging
class ApplicationController < ActionController::Base
before_filter :authenticate_messaging_user!
def current_user
current_messaging_user
end
end
end
| ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/app/models/messaging/message.rb | app/models/messaging/message.rb | module Messaging
class Message
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
attr_accessor :recipients, :subject, :body, :conversation_id, :attachment
validates :recipients, presence: true
validates :subject, presence: true
validates :body, presence: true
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
end
def persisted?
false
end
def recipients
@recipient_list
end
def recipients=(string='')
@recipient_list = []
string.split(',').each do |s|
@recipient_list << MessagingUser.find_by_email!(s.strip) unless s.blank?
end
end
end
end
| ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/test/test_helper.rb | test/test_helper.rb | # Configure Rails Environment
ENV["RAILS_ENV"] = "test"
require File.expand_path("../dummy/config/environment.rb", __FILE__)
require "rails/test_help"
Rails.backtrace_cleaner.remove_silencers!
# Load support files
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }
| ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/test/messaging_test.rb | test/messaging_test.rb | require 'test_helper'
class MessagingTest < ActiveSupport::TestCase
test "truth" do
assert_kind_of Module, Messaging
end
end
| ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/test/integration/navigation_test.rb | test/integration/navigation_test.rb | require 'test_helper'
class NavigationTest < ActionDispatch::IntegrationTest
fixtures :all
# test "the truth" do
# assert true
# end
end
| ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/test/dummy/app/helpers/application_helper.rb | test/dummy/app/helpers/application_helper.rb | module ApplicationHelper
end
| ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/test/dummy/app/controllers/home_controller.rb | test/dummy/app/controllers/home_controller.rb | class HomeController < ApplicationController
def index
if user_signed_in?
redirect_to messaging_path
else
redirect_to new_user_session_path
end
end
end
| ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/test/dummy/app/controllers/application_controller.rb | test/dummy/app/controllers/application_controller.rb | class ApplicationController < ActionController::Base
protect_from_forgery
end
| ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/test/dummy/app/models/messaging_user.rb | test/dummy/app/models/messaging_user.rb | class MessagingUser < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
acts_as_messageable
def name
self.to_s
end
def mailboxer_email(message)
email
end
def to_s
email
end
end
| ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/test/dummy/app/models/user.rb | test/dummy/app/models/user.rb | class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
acts_as_messageable
def name
self.to_s
end
def mailboxer_email(message)
email
end
def to_s
email
end
end
| ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/test/dummy/db/schema.rb | test/dummy/db/schema.rb | # encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended to check this file into your version control system.
ActiveRecord::Schema.define(:version => 20111213052240) do
create_table "conversations", :force => true do |t|
t.string "subject", :default => ""
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "messaging_message_drafts", :force => true do |t|
t.integer "user_id"
t.string "recipients"
t.string "subject"
t.string "body"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "messaging_users", :force => true do |t|
t.string "email", :default => "", :null => false
t.string "encrypted_password", :limit => 128, :default => "", :null => false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", :default => 0
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "messaging_users", ["email"], :name => "index_messaging_users_on_email", :unique => true
add_index "messaging_users", ["reset_password_token"], :name => "index_messaging_users_on_reset_password_token", :unique => true
create_table "notifications", :force => true do |t|
t.string "type"
t.text "body"
t.string "subject", :default => ""
t.integer "sender_id"
t.string "sender_type"
t.integer "conversation_id"
t.boolean "draft", :default => false
t.datetime "updated_at", :null => false
t.datetime "created_at", :null => false
t.integer "notified_object_id"
t.string "notified_object_type"
t.string "notification_code"
t.string "attachment"
end
add_index "notifications", ["conversation_id"], :name => "index_notifications_on_conversation_id"
create_table "receipts", :force => true do |t|
t.integer "receiver_id"
t.string "receiver_type"
t.integer "notification_id", :null => false
t.boolean "read", :default => false
t.boolean "trashed", :default => false
t.boolean "deleted", :default => false
t.string "mailbox_type", :limit => 25
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
add_index "receipts", ["notification_id"], :name => "index_receipts_on_notification_id"
create_table "users", :force => true do |t|
t.string "email", :default => "", :null => false
t.string "encrypted_password", :limit => 128, :default => "", :null => false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", :default => 0
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "users", ["email"], :name => "index_users_on_email", :unique => true
add_index "users", ["reset_password_token"], :name => "index_users_on_reset_password_token", :unique => true
end
| ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/test/dummy/db/migrate/20111213052240_devise_create_messaging_users.rb | test/dummy/db/migrate/20111213052240_devise_create_messaging_users.rb | class DeviseCreateMessagingUsers < ActiveRecord::Migration
def change
create_table(:messaging_users) do |t|
t.database_authenticatable :null => false
t.recoverable
t.rememberable
t.trackable
# t.encryptable
# t.confirmable
# t.lockable :lock_strategy => :failed_attempts, :unlock_strategy => :both
# t.token_authenticatable
t.timestamps
end
add_index :messaging_users, :email, :unique => true
add_index :messaging_users, :reset_password_token, :unique => true
# add_index :messaging_users, :confirmation_token, :unique => true
# add_index :messaging_users, :unlock_token, :unique => true
# add_index :messaging_users, :authentication_token, :unique => true
end
end
| ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/test/dummy/db/migrate/20111204041734_devise_create_users.rb | test/dummy/db/migrate/20111204041734_devise_create_users.rb | class DeviseCreateUsers < ActiveRecord::Migration
def change
create_table(:users) do |t|
t.database_authenticatable :null => false
t.recoverable
t.rememberable
t.trackable
# t.encryptable
# t.confirmable
# t.lockable :lock_strategy => :failed_attempts, :unlock_strategy => :both
# t.token_authenticatable
t.timestamps
end
add_index :users, :email, :unique => true
add_index :users, :reset_password_token, :unique => true
# add_index :users, :confirmation_token, :unique => true
# add_index :users, :unlock_token, :unique => true
# add_index :users, :authentication_token, :unique => true
end
end
| ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/test/dummy/db/migrate/20111204042609_create_mailboxer.rb | test/dummy/db/migrate/20111204042609_create_mailboxer.rb | class CreateMailboxer < ActiveRecord::Migration
def self.up
#Tables
#Conversations
create_table :conversations do |t|
t.column :subject, :string, :default => ""
t.column :created_at, :datetime, :null => false
t.column :updated_at, :datetime, :null => false
end
#Receipts
create_table :receipts do |t|
t.references :receiver, :polymorphic => true
t.column :notification_id, :integer, :null => false
t.column :read, :boolean, :default => false
t.column :trashed, :boolean, :default => false
t.column :deleted, :boolean, :default => false
t.column :mailbox_type, :string, :limit => 25
t.column :created_at, :datetime, :null => false
t.column :updated_at, :datetime, :null => false
end
#Notifications and Messages
create_table :notifications do |t|
t.column :type, :string
t.column :body, :text
t.column :subject, :string, :default => ""
t.references :sender, :polymorphic => true
t.references :object, :polymorphic => true
t.column :conversation_id, :integer
t.column :draft, :boolean, :default => false
t.column :updated_at, :datetime, :null => false
t.column :created_at, :datetime, :null => false
end
#Indexes
#Conversations
#Receipts
add_index "receipts","notification_id"
#Messages
add_index "notifications","conversation_id"
#Foreign keys
#Conversations
#Receipts
add_foreign_key "receipts", "notifications", :name => "receipts_on_notification_id"
#Messages
add_foreign_key "notifications", "conversations", :name => "notifications_on_conversation_id"
end
def self.down
#Tables
remove_foreign_key "receipts", :name => "receipts_on_notification_id"
remove_foreign_key "notifications", :name => "notifications_on_conversation_id"
#Indexes
drop_table :receipts
drop_table :conversations
drop_table :notifications
end
end
| ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/test/dummy/db/migrate/20111204042610_add_notified_object.rb | test/dummy/db/migrate/20111204042610_add_notified_object.rb | class AddNotifiedObject < ActiveRecord::Migration
def self.up
change_table :notifications do |t|
t.references :notified_object, :polymorphic => true
t.remove :object_id
t.remove :object_type
end
end
def self.down
change_table :notifications do |t|
t.remove :notified_object_id
t.remove :notified_object_type
t.references :object, :polymorphic => true
end
end
end
| ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/test/dummy/db/migrate/20111205020919_add_attachments.rb | test/dummy/db/migrate/20111205020919_add_attachments.rb | class AddAttachments < ActiveRecord::Migration
def change
add_column :notifications, :attachment, :string
end
end
| ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/test/dummy/db/migrate/20111204042611_add_notification_code.rb | test/dummy/db/migrate/20111204042611_add_notification_code.rb | class AddNotificationCode < ActiveRecord::Migration
def self.up
change_table :notifications do |t|
t.string :notification_code, :default => nil
end
end
def self.down
change_table :notifications do |t|
t.remove :notification_code
end
end
end | ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/test/dummy/test/unit/user_test.rb | test/dummy/test/unit/user_test.rb | require 'test_helper'
class UserTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/test/dummy/test/unit/messaging_user_test.rb | test/dummy/test/unit/messaging_user_test.rb | require 'test_helper'
class MessagingUserTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/test/dummy/config/application.rb | test/dummy/config/application.rb | require File.expand_path('../boot', __FILE__)
require 'rails/all'
Bundler.require
require "messaging"
module Dummy
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
end
end
| ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/test/dummy/config/environment.rb | test/dummy/config/environment.rb | # Load the rails application
require File.expand_path('../application', __FILE__)
# Initialize the rails application
Dummy::Application.initialize!
| ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/test/dummy/config/routes.rb | test/dummy/config/routes.rb | Rails.application.routes.draw do
devise_for :messaging_users
devise_for :users
mount Messaging::Engine => "/messaging"
root to: 'home#index'
end
| ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/test/dummy/config/boot.rb | test/dummy/config/boot.rb | require 'rubygems'
gemfile = File.expand_path('../../../../Gemfile', __FILE__)
if File.exist?(gemfile)
ENV['BUNDLE_GEMFILE'] = gemfile
require 'bundler'
Bundler.setup
end
$:.unshift File.expand_path('../../../../lib', __FILE__) | ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/test/dummy/config/initializers/session_store.rb | test/dummy/config/initializers/session_store.rb | # Be sure to restart your server when you modify this file.
Dummy::Application.config.session_store :cookie_store, key: '_dummy_session'
# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with "rails generate session_migration")
# Dummy::Application.config.session_store :active_record_store
| ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/test/dummy/config/initializers/devise.rb | test/dummy/config/initializers/devise.rb | # Use this hook to configure devise mailer, warden hooks and so forth.
# Many of these configuration options can be set straight in your model.
Devise.setup do |config|
# ==> Mailer Configuration
# Configure the e-mail address which will be shown in Devise::Mailer,
# note that it will be overwritten if you use your own mailer class with default "from" parameter.
config.mailer_sender = "please-change-me-at-config-initializers-devise@example.com"
# Configure the class responsible to send e-mails.
# config.mailer = "Devise::Mailer"
# ==> ORM configuration
# Load and configure the ORM. Supports :active_record (default) and
# :mongoid (bson_ext recommended) by default. Other ORMs may be
# available as additional gems.
require 'devise/orm/active_record'
# ==> Configuration for any authentication mechanism
# Configure which keys are used when authenticating a user. The default is
# just :email. You can configure it to use [:username, :subdomain], so for
# authenticating a user, both parameters are required. Remember that those
# parameters are used only when authenticating and not when retrieving from
# session. If you need permissions, you should implement that in a before filter.
# You can also supply a hash where the value is a boolean determining whether
# or not authentication should be aborted when the value is not present.
# config.authentication_keys = [ :email ]
# Configure parameters from the request object used for authentication. Each entry
# given should be a request method and it will automatically be passed to the
# find_for_authentication method and considered in your model lookup. For instance,
# if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
# The same considerations mentioned for authentication_keys also apply to request_keys.
# config.request_keys = []
# Configure which authentication keys should be case-insensitive.
# These keys will be downcased upon creating or modifying a user and when used
# to authenticate or find a user. Default is :email.
config.case_insensitive_keys = [ :email ]
# Configure which authentication keys should have whitespace stripped.
# These keys will have whitespace before and after removed upon creating or
# modifying a user and when used to authenticate or find a user. Default is :email.
config.strip_whitespace_keys = [ :email ]
# Tell if authentication through request.params is enabled. True by default.
# config.params_authenticatable = true
# Tell if authentication through HTTP Basic Auth is enabled. False by default.
# config.http_authenticatable = false
# If http headers should be returned for AJAX requests. True by default.
# config.http_authenticatable_on_xhr = true
# The realm used in Http Basic Authentication. "Application" by default.
# config.http_authentication_realm = "Application"
# It will change confirmation, password recovery and other workflows
# to behave the same regardless if the e-mail provided was right or wrong.
# Does not affect registerable.
# config.paranoid = true
# ==> Configuration for :database_authenticatable
# For bcrypt, this is the cost for hashing the password and defaults to 10. If
# using other encryptors, it sets how many times you want the password re-encrypted.
#
# Limiting the stretches to just one in testing will increase the performance of
# your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
# a value less than 10 in other environments.
config.stretches = Rails.env.test? ? 1 : 10
# Setup a pepper to generate the encrypted password.
# config.pepper = "1405595daf8618bf64a818cfa3fd99452f9fc4af13f77d5b1faa47558ba836f46e156005546c9802b77efa16acbbeb391c0cddc1b992404fa1608fe1b9f51858"
# ==> Configuration for :confirmable
# A period that the user is allowed to access the website even without
# confirming his account. For instance, if set to 2.days, the user will be
# able to access the website for two days without confirming his account,
# access will be blocked just in the third day. Default is 0.days, meaning
# the user cannot access the website without confirming his account.
# config.confirm_within = 2.days
# Defines which key will be used when confirming an account
# config.confirmation_keys = [ :email ]
# ==> Configuration for :rememberable
# The time the user will be remembered without asking for credentials again.
# config.remember_for = 2.weeks
# If true, a valid remember token can be re-used between multiple browsers.
# config.remember_across_browsers = true
# If true, extends the user's remember period when remembered via cookie.
# config.extend_remember_period = false
# If true, uses the password salt as remember token. This should be turned
# to false if you are not using database authenticatable.
config.use_salt_as_remember_token = true
# Options to be passed to the created cookie. For instance, you can set
# :secure => true in order to force SSL only cookies.
# config.cookie_options = {}
# ==> Configuration for :validatable
# Range for password length. Default is 6..128.
# config.password_length = 6..128
# Email regex used to validate email formats. It simply asserts that
# an one (and only one) @ exists in the given string. This is mainly
# to give user feedback and not to assert the e-mail validity.
# config.email_regexp = /\A[^@]+@[^@]+\z/
# ==> Configuration for :timeoutable
# The time you want to timeout the user session without activity. After this
# time the user will be asked for credentials again. Default is 30 minutes.
# config.timeout_in = 30.minutes
# ==> Configuration for :lockable
# Defines which strategy will be used to lock an account.
# :failed_attempts = Locks an account after a number of failed attempts to sign in.
# :none = No lock strategy. You should handle locking by yourself.
# config.lock_strategy = :failed_attempts
# Defines which key will be used when locking and unlocking an account
# config.unlock_keys = [ :email ]
# Defines which strategy will be used to unlock an account.
# :email = Sends an unlock link to the user email
# :time = Re-enables login after a certain amount of time (see :unlock_in below)
# :both = Enables both strategies
# :none = No unlock strategy. You should handle unlocking by yourself.
# config.unlock_strategy = :both
# Number of authentication tries before locking an account if lock_strategy
# is failed attempts.
# config.maximum_attempts = 20
# Time interval to unlock the account if :time is enabled as unlock_strategy.
# config.unlock_in = 1.hour
# ==> Configuration for :recoverable
#
# Defines which key will be used when recovering the password for an account
# config.reset_password_keys = [ :email ]
# Time interval you can reset your password with a reset password key.
# Don't put a too small interval or your users won't have the time to
# change their passwords.
config.reset_password_within = 2.hours
# ==> Configuration for :encryptable
# Allow you to use another encryption algorithm besides bcrypt (default). You can use
# :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1,
# :authlogic_sha512 (then you should set stretches above to 20 for default behavior)
# and :restful_authentication_sha1 (then you should set stretches to 10, and copy
# REST_AUTH_SITE_KEY to pepper)
# config.encryptor = :sha512
# ==> Configuration for :token_authenticatable
# Defines name of the authentication token params key
# config.token_authentication_key = :auth_token
# If true, authentication through token does not store user in session and needs
# to be supplied on each request. Useful if you are using the token as API token.
# config.stateless_token = false
# ==> Scopes configuration
# Turn scoped views on. Before rendering "sessions/new", it will first check for
# "users/sessions/new". It's turned off by default because it's slower if you
# are using only default views.
# config.scoped_views = false
# Configure the default scope given to Warden. By default it's the first
# devise role declared in your routes (usually :user).
# config.default_scope = :user
# Configure sign_out behavior.
# Sign_out action can be scoped (i.e. /users/sign_out affects only :user scope).
# The default is true, which means any logout action will sign out all active scopes.
# config.sign_out_all_scopes = true
# ==> Navigation configuration
# Lists the formats that should be treated as navigational. Formats like
# :html, should redirect to the sign in page when the user does not have
# access, but formats like :xml or :json, should return 401.
#
# If you have any extra navigational formats, like :iphone or :mobile, you
# should add them to the navigational formats lists.
#
# The :"*/*" and "*/*" formats below is required to match Internet
# Explorer requests.
# config.navigational_formats = [:"*/*", "*/*", :html]
# The default HTTP method used to sign out a resource. Default is :delete.
config.sign_out_via = :delete
# ==> OmniAuth
# Add a new OmniAuth provider. Check the wiki for more information on setting
# up on your models and hooks.
# config.omniauth :github, 'APP_ID', 'APP_SECRET', :scope => 'user,public_repo'
# ==> Warden configuration
# If you want to use other strategies, that are not supported by Devise, or
# change the failure app, you can configure them inside the config.warden block.
#
# config.warden do |manager|
# manager.intercept_401 = false
# manager.default_strategies(:scope => :user).unshift :some_external_strategy
# end
end
| ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/test/dummy/config/initializers/wrap_parameters.rb | test/dummy/config/initializers/wrap_parameters.rb | # Be sure to restart your server when you modify this file.
#
# This file contains settings for ActionController::ParamsWrapper which
# is enabled by default.
# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
ActiveSupport.on_load(:action_controller) do
wrap_parameters format: [:json]
end
# Disable root element in JSON by default.
ActiveSupport.on_load(:active_record) do
self.include_root_in_json = false
end
| ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/test/dummy/config/initializers/inflections.rb | test/dummy/config/initializers/inflections.rb | # Be sure to restart your server when you modify this file.
# Add new inflection rules using the following format
# (all these examples are active by default):
# ActiveSupport::Inflector.inflections do |inflect|
# inflect.plural /^(ox)$/i, '\1en'
# inflect.singular /^(ox)en/i, '\1'
# inflect.irregular 'person', 'people'
# inflect.uncountable %w( fish sheep )
# end
| ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/test/dummy/config/initializers/mailboxer.rb | test/dummy/config/initializers/mailboxer.rb | Mailboxer.setup do |config|
#Configures if you applications uses or no the email sending for Notifications and Messages
config.uses_emails = true
#Configures the default from for the email sent for Messages and Notifications of Mailboxer
config.default_from = "no-reply@mailboxer.com"
#Configures the methods needed by mailboxer
#config.email_method = :mailboxer_email
#config.name_method = :name
end | ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/test/dummy/config/initializers/backtrace_silencers.rb | test/dummy/config/initializers/backtrace_silencers.rb | # Be sure to restart your server when you modify this file.
# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
# Rails.backtrace_cleaner.remove_silencers!
| ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/test/dummy/config/initializers/mime_types.rb | test/dummy/config/initializers/mime_types.rb | # Be sure to restart your server when you modify this file.
# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
# Mime::Type.register_alias "text/html", :iphone
| ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/test/dummy/config/initializers/secret_token.rb | test/dummy/config/initializers/secret_token.rb | # Be sure to restart your server when you modify this file.
# Your secret key for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
Dummy::Application.config.secret_token = 'f4d71fce2fcb8506fd567764a5582f2ddf94500b95e093ea8502b814ba3ff15f8f99bcdb265eb4760d175074fea4b95a0d4f2dad8a6acd57b72726812d2e71ad'
| ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/test/dummy/config/environments/test.rb | test/dummy/config/environments/test.rb | Dummy::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Configure static asset server for tests with Cache-Control for performance
config.serve_static_assets = true
config.static_cache_control = "public, max-age=3600"
# Log error messages when you accidentally call methods on nil
config.whiny_nils = true
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Raise exceptions instead of rendering exception templates
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment
config.action_controller.allow_forgery_protection = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
# Use SQL instead of Active Record's schema dumper when creating the test database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Print deprecation notices to the stderr
config.active_support.deprecation = :stderr
end
| ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/test/dummy/config/environments/development.rb | test/dummy/config/environments/development.rb | Dummy::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
# Only use best-standards-support built into browsers
config.action_dispatch.best_standards_support = :builtin
# Do not compress assets
config.assets.compress = false
# Expands the lines which load the assets
config.assets.debug = true
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
end
| ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/test/dummy/config/environments/production.rb | test/dummy/config/environments/production.rb | Dummy::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to Rails.root.join("public/assets")
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Use a different logger for distributed setups
# config.logger = SyslogLogger.new
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
end
| ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/lib/messaging.rb | lib/messaging.rb | require "messaging/engine"
require 'devise'
require 'haml'
require 'carrierwave'
require 'sunspot_rails'
require 'simple_form'
module Messaging
end
| ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/lib/generators/messaging/devise/devise_generator.rb | lib/generators/messaging/devise/devise_generator.rb | module Messaging
module Generators
class DeviseGenerator < Rails::Generators::NamedBase
desc "Uses Devise for authentication"
argument :name, :type => :string, :default => "MessagingUser"
def self.source_root
@_messaging_source_root ||= File.expand_path("../templates", __FILE__)
end
def install_devise
require 'devise'
if File.exists?(File.join(destination_root, "config", "initializers", "devise.rb"))
log :generate, "No need to install devise, already done."
else
log :generate, "devise:install"
invoke "devise:install"
end
end
def create_user
invoke "devise", [name]
end
def copy_model
template 'messaging_user.rb.erb', 'app/models/messaging_user.rb'
end
end
end
end
| ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/lib/generators/messaging/install/install_generator.rb | lib/generators/messaging/install/install_generator.rb | class Messaging::InstallGenerator < Rails::Generators::Base #:nodoc:
hook_for :users, :default => "devise", :desc => "User generator to run. Skip with --skip-users"
def create_migration_file
generate 'mailboxer:install'
end
def add_messaging_routes
route 'mount Messaging::Engine => "/messaging"'
end
end
| ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/lib/messaging/version.rb | lib/messaging/version.rb | module Messaging
VERSION = "0.0.1"
end
| ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
frodefi/rails-messaging | https://github.com/frodefi/rails-messaging/blob/b840f344dbc3af141c124b5f2df0ea9947fe6493/lib/messaging/engine.rb | lib/messaging/engine.rb | module Messaging
class Engine < Rails::Engine
isolate_namespace Messaging
end
end
| ruby | MIT | b840f344dbc3af141c124b5f2df0ea9947fe6493 | 2026-01-04T17:57:44.259159Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.