ruby_raider 4.0.1 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. checksums.yaml +4 -4
  2. data/.github/workflows/e2e_tests.yml +3 -0
  3. data/README.md +58 -1
  4. data/RELEASE.md +25 -0
  5. data/lib/commands/schedule_commands.rb +84 -0
  6. data/lib/generators/templates/common/git_ignore.tt +1 -0
  7. data/lib/ruby_raider/runtime/retry_reset.rb +32 -0
  8. data/lib/ruby_raider/runtime/rspec.rb +1 -0
  9. data/lib/ruby_raider/runtime/show_browser.rb +53 -0
  10. data/lib/ruby_raider/runtime.rb +2 -0
  11. data/lib/ruby_raider.rb +31 -0
  12. data/lib/utilities/schedules/adapter.rb +22 -0
  13. data/lib/utilities/schedules/base.rb +27 -0
  14. data/lib/utilities/schedules/kind.rb +74 -0
  15. data/lib/utilities/schedules/legacy.rb +196 -0
  16. data/lib/utilities/schedules/legacy_stub.rb +62 -0
  17. data/lib/utilities/schedules/next_run.rb +61 -0
  18. data/lib/utilities/schedules/notifier.rb +76 -0
  19. data/lib/utilities/schedules/os/command_runner.rb +73 -0
  20. data/lib/utilities/schedules/os/cron.rb +147 -0
  21. data/lib/utilities/schedules/os/launchd.rb +182 -0
  22. data/lib/utilities/schedules/os/linux.rb +81 -0
  23. data/lib/utilities/schedules/os/systemd.rb +194 -0
  24. data/lib/utilities/schedules/os/task_scheduler.rb +195 -0
  25. data/lib/utilities/schedules/os_enumerator.rb +30 -0
  26. data/lib/utilities/schedules/project.rb +70 -0
  27. data/lib/utilities/schedules/rule.rb +162 -0
  28. data/lib/utilities/schedules/run_lock.rb +160 -0
  29. data/lib/utilities/schedules/run_log.rb +122 -0
  30. data/lib/utilities/schedules/run_report.rb +139 -0
  31. data/lib/utilities/schedules/run_wrapper.rb +216 -0
  32. data/lib/utilities/schedules/schedule.rb +89 -0
  33. data/lib/utilities/schedules/schedule_store.rb +53 -0
  34. data/lib/utilities/schedules/scheduler.rb +178 -0
  35. data/lib/utilities/schedules/scheduler_steps.rb +69 -0
  36. data/lib/utilities/schedules/selection.rb +133 -0
  37. data/lib/utilities/schedules/spawn.rb +68 -0
  38. data/lib/utilities/schedules/store.rb +139 -0
  39. data/lib/version +1 -1
  40. data/ruby_raider.gemspec +1 -0
  41. data/sig/commands/schedule_commands.rbs +12 -0
  42. data/sig/ruby_raider/runtime/retry_reset.rbs +7 -0
  43. data/sig/ruby_raider/runtime/show_browser.rbs +27 -0
  44. data/sig/ruby_raider.rbs +6 -0
  45. data/sig/utilities/schedules/adapter.rbs +5 -0
  46. data/sig/utilities/schedules/base.rbs +15 -0
  47. data/sig/utilities/schedules/kind.rbs +32 -0
  48. data/sig/utilities/schedules/legacy.rbs +45 -0
  49. data/sig/utilities/schedules/legacy_stub.rbs +15 -0
  50. data/sig/utilities/schedules/next_run.rbs +15 -0
  51. data/sig/utilities/schedules/notifier.rbs +29 -0
  52. data/sig/utilities/schedules/os/command_runner.rbs +27 -0
  53. data/sig/utilities/schedules/os/cron.rbs +34 -0
  54. data/sig/utilities/schedules/os/launchd.rbs +46 -0
  55. data/sig/utilities/schedules/os/linux.rbs +33 -0
  56. data/sig/utilities/schedules/os/systemd.rbs +44 -0
  57. data/sig/utilities/schedules/os/task_scheduler.rbs +56 -0
  58. data/sig/utilities/schedules/os_enumerator.rbs +12 -0
  59. data/sig/utilities/schedules/project.rbs +22 -0
  60. data/sig/utilities/schedules/rule.rbs +72 -0
  61. data/sig/utilities/schedules/run_lock.rbs +29 -0
  62. data/sig/utilities/schedules/run_log.rbs +33 -0
  63. data/sig/utilities/schedules/run_report.rbs +34 -0
  64. data/sig/utilities/schedules/run_wrapper.rbs +45 -0
  65. data/sig/utilities/schedules/schedule.rbs +27 -0
  66. data/sig/utilities/schedules/schedule_store.rbs +21 -0
  67. data/sig/utilities/schedules/scheduler.rbs +49 -0
  68. data/sig/utilities/schedules/scheduler_steps.rbs +22 -0
  69. data/sig/utilities/schedules/selection.rbs +36 -0
  70. data/sig/utilities/schedules/spawn.rbs +10 -0
  71. data/sig/utilities/schedules/store.rbs +39 -0
  72. data/spec/commands/schedule_commands_spec.rb +284 -0
  73. data/spec/integration/content/common_content_spec.rb +8 -2
  74. data/spec/integration/content/gemfile_content_spec.rb +2 -2
  75. data/spec/runtime/retry_reset_spec.rb +112 -0
  76. data/spec/runtime/show_browser_project_spec.rb +70 -0
  77. data/spec/runtime/show_browser_spec.rb +101 -0
  78. data/spec/utilities/schedules/kind_spec.rb +81 -0
  79. data/spec/utilities/schedules/legacy_spec.rb +433 -0
  80. data/spec/utilities/schedules/legacy_stub_spec.rb +144 -0
  81. data/spec/utilities/schedules/next_run_spec.rb +119 -0
  82. data/spec/utilities/schedules/notifier_spec.rb +120 -0
  83. data/spec/utilities/schedules/os/command_runner_spec.rb +55 -0
  84. data/spec/utilities/schedules/os/cron_spec.rb +292 -0
  85. data/spec/utilities/schedules/os/launchd_spec.rb +306 -0
  86. data/spec/utilities/schedules/os/linux_spec.rb +163 -0
  87. data/spec/utilities/schedules/os/list_ids_spec.rb +202 -0
  88. data/spec/utilities/schedules/os/systemd_spec.rb +333 -0
  89. data/spec/utilities/schedules/os/task_scheduler_spec.rb +511 -0
  90. data/spec/utilities/schedules/os_entry_spec.rb +54 -0
  91. data/spec/utilities/schedules/os_enumerator_spec.rb +57 -0
  92. data/spec/utilities/schedules/project_spec.rb +125 -0
  93. data/spec/utilities/schedules/run_lock_spec.rb +143 -0
  94. data/spec/utilities/schedules/run_log_spec.rb +83 -0
  95. data/spec/utilities/schedules/run_report_spec.rb +150 -0
  96. data/spec/utilities/schedules/run_wrapper_integration_spec.rb +166 -0
  97. data/spec/utilities/schedules/run_wrapper_spec.rb +430 -0
  98. data/spec/utilities/schedules/schedule_spec.rb +120 -0
  99. data/spec/utilities/schedules/schedule_store_spec.rb +151 -0
  100. data/spec/utilities/schedules/scheduler_launchd_spec.rb +77 -0
  101. data/spec/utilities/schedules/scheduler_spec.rb +445 -0
  102. data/spec/utilities/schedules/selection_spec.rb +176 -0
  103. data/spec/utilities/schedules/spawn_spec.rb +104 -0
  104. metadata +106 -2
@@ -0,0 +1,119 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'tmpdir'
4
+ require_relative '../../../lib/utilities/schedules/next_run'
5
+ require_relative '../../../lib/utilities/schedules/schedule'
6
+
7
+ RSpec.describe RubyRaider::Schedules::NextRun do # rubocop:disable RSpec/FilePath
8
+ let(:dir) { File.realpath(Dir.mktmpdir('flows-next-run')) }
9
+ let(:project) { RubyRaider::Schedules::Project.new(dir) }
10
+
11
+ around do |example|
12
+ zone = ENV.fetch('TZ', nil)
13
+ ENV['TZ'] = 'Europe/Copenhagen'
14
+ example.run
15
+ ensure
16
+ ENV['TZ'] = zone
17
+ end
18
+
19
+ after { FileUtils.rm_rf(dir) }
20
+
21
+ def rule(every, at = '08:00', on: nil)
22
+ RubyRaider::Schedules::Schedule.build(project: project, name: 'report', every: every, at: at, on: on)
23
+ end
24
+
25
+ def next_after(schedule, *local)
26
+ described_class.after(schedule, Time.local(*local))
27
+ end
28
+
29
+ # [wall clock, UTC offset in hours] of a local time
30
+ def wall(time)
31
+ [time.strftime('%F %R'), time.utc_offset / 3600]
32
+ end
33
+
34
+ describe 'every day' do
35
+ it 'runs later today, or tomorrow once the time has passed' do
36
+ expect([wall(next_after(rule('day'), 2026, 11, 9, 7, 59)), wall(next_after(rule('day'), 2026, 11, 9, 8, 0))]).to eq(
37
+ [['2026-11-09 08:00', 1], ['2026-11-10 08:00', 1]]
38
+ )
39
+ end
40
+
41
+ it 'is strictly after now, by seconds too' do
42
+ expect(wall(next_after(rule('day'), 2026, 11, 9, 8, 0, 1))).to eq(['2026-11-10 08:00', 1])
43
+ end
44
+
45
+ it 'crosses a month and a year' do
46
+ expect(wall(next_after(rule('day'), 2026, 12, 31, 9, 0))).to eq(['2027-01-01 08:00', 1])
47
+ end
48
+ end
49
+
50
+ describe 'every weekday' do
51
+ it 'skips the weekend' do
52
+ # 2026-11-13 is a Friday
53
+ expect(wall(next_after(rule('weekday'), 2026, 11, 13, 9, 0))).to eq(['2026-11-16 08:00', 1])
54
+ end
55
+ end
56
+
57
+ describe 'every week' do
58
+ it 'runs on its day, a week later once that has passed' do
59
+ # 2026-11-09 is a Monday
60
+ expect([wall(next_after(rule('week', on: 'wed'), 2026, 11, 9, 9, 0)), wall(next_after(rule('week', on: 'mon'), 2026, 11, 9, 8, 0))]).to eq(
61
+ [['2026-11-11 08:00', 1], ['2026-11-16 08:00', 1]]
62
+ )
63
+ end
64
+ end
65
+
66
+ describe 'every hour' do
67
+ it 'runs at the next matching minute' do
68
+ expect([wall(next_after(rule('hour', ':15'), 2026, 11, 9, 10, 20)), wall(next_after(rule('hour', ':15'), 2026, 11, 9, 10, 14, 59))]).to eq(
69
+ [['2026-11-09 11:15', 1], ['2026-11-09 10:15', 1]]
70
+ )
71
+ end
72
+
73
+ it 'crosses midnight' do
74
+ expect(wall(next_after(rule('hour', ':00'), 2026, 11, 9, 23, 30))).to eq(['2026-11-10 00:00', 1])
75
+ end
76
+ end
77
+
78
+ # Copenhagen: 2026-03-29 02:00 CET jumps to 03:00 CEST; 2026-10-25 03:00 CEST falls back to 02:00 CET
79
+ describe 'the last Sunday of March' do
80
+ it 'runs a time in the skipped hour at the first minute after the gap' do
81
+ expect(wall(next_after(rule('day', '02:30'), 2026, 3, 29, 0, 0))).to eq(['2026-03-29 03:00', 2])
82
+ end
83
+
84
+ it 'goes back to the normal time the next day' do
85
+ expect(wall(next_after(rule('day', '02:30'), 2026, 3, 29, 3, 0))).to eq(['2026-03-30 02:30', 2])
86
+ end
87
+
88
+ it 'keeps a time outside the gap' do
89
+ expect(wall(next_after(rule('day'), 2026, 3, 29, 0, 0))).to eq(['2026-03-29 08:00', 2])
90
+ end
91
+
92
+ it 'runs every hour at the next real matching minute' do
93
+ expect(wall(next_after(rule('hour', ':30'), 2026, 3, 29, 1, 45))).to eq(['2026-03-29 03:30', 2])
94
+ end
95
+ end
96
+
97
+ describe 'the last Sunday of October' do
98
+ it 'runs a repeated time at its first occurrence' do
99
+ expect(wall(next_after(rule('day', '02:30'), 2026, 10, 25, 0, 0))).to eq(['2026-10-25 02:30', 2])
100
+ end
101
+
102
+ it 'does not run again at the second occurrence' do
103
+ first = next_after(rule('day', '02:30'), 2026, 10, 25, 0, 0)
104
+
105
+ expect(wall(described_class.after(rule('day', '02:30'), first))).to eq(['2026-10-26 02:30', 1])
106
+ end
107
+
108
+ it 'runs every hour in both repeated hours' do
109
+ first = next_after(rule('hour', ':30'), 2026, 10, 25, 1, 45)
110
+ second = described_class.after(rule('hour', ':30'), first)
111
+
112
+ expect([wall(first), wall(second), second - first]).to eq([['2026-10-25 02:30', 2], ['2026-10-25 02:30', 1], 3600.0])
113
+ end
114
+
115
+ it 'runs a week rule on the changeover day' do
116
+ expect(wall(next_after(rule('week', '02:30', on: 'sun'), 2026, 10, 20, 12, 0))).to eq(['2026-10-25 02:30', 2])
117
+ end
118
+ end
119
+ end
@@ -0,0 +1,120 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'stringio'
4
+ require_relative '../../../lib/utilities/schedules/notifier'
5
+
6
+ RSpec.describe RubyRaider::Schedules::Notifier do # rubocop:disable RSpec/FilePath
7
+ # Records each command instead of running it: no real osascript, notify-send or PowerShell
8
+ let(:runner) do
9
+ Class.new do
10
+ attr_reader :calls
11
+ attr_accessor :exitstatus
12
+
13
+ def initialize
14
+ @calls = []
15
+ @exitstatus = 0
16
+ end
17
+
18
+ def call(*argv, env: {}, timeout: nil, **)
19
+ @calls << { argv: argv, env: env, timeout: timeout }
20
+ RubyRaider::Schedules::Os::CommandRunner::Result.new(stdout: '', stderr: 'no notification server', exitstatus: exitstatus)
21
+ end
22
+ end.new
23
+ end
24
+
25
+ let(:err) { StringIO.new }
26
+ let(:hostile) do
27
+ ["'; rm -rf ~; '", '" & do shell script "id" & "', '$(id)', '</text>', '-u critical', '$env:USERPROFILE', '`whoami`']
28
+ end
29
+
30
+ let(:powershell) { 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe' }
31
+
32
+ def notifier(host_os) = described_class.new(runner: runner, host_os: host_os, err: err, powershell: powershell)
33
+
34
+ it 'passes the title and message to osascript as argv items of a fixed script on macOS' do
35
+ expect(notifier('darwin25').notify('Ruby Raider flow report', 'Failed at step 3 (Open report)')).to be(true)
36
+
37
+ expect(runner.calls).to eq([{ argv: ['/usr/bin/osascript', '-e', 'on run argv', '-e',
38
+ 'display notification (item 2 of argv) with title (item 1 of argv)', '-e', 'end run', '--',
39
+ 'Ruby Raider flow report', 'Failed at step 3 (Open report)'], env: {}, timeout: 15 }])
40
+ end
41
+
42
+ it 'ends osascript option parsing before the title, so -e in a title is not a script' do
43
+ notifier('darwin25').notify('-e', 'property p : (1 + 2)')
44
+
45
+ expect(runner.calls.first[:argv].last(3)).to eq(['--', '-e', 'property p : (1 + 2)'])
46
+ end
47
+
48
+ it 'keeps hostile text out of the script on every OS' do
49
+ hosts = %w[darwin25 linux-gnu mingw32]
50
+ scripts = hosts.to_h do |host|
51
+ hostile.each { |text| notifier(host).notify(text, text) }
52
+ calls = runner.calls.pop(hostile.size)
53
+ [host, calls.map { |call| host == 'mingw32' ? call[:argv] : call[:argv][0...-2] }.uniq]
54
+ end
55
+
56
+ expect(scripts.values.map(&:size)).to eq([1, 1, 1])
57
+ expect(scripts.values.flatten.join("\n")).not_to include(*hostile)
58
+ end
59
+
60
+ it 'passes hostile text unchanged as the last argv items on macOS' do
61
+ hostile.each { |text| notifier('darwin25').notify(text, text) }
62
+
63
+ expect(runner.calls.map { |call| call[:argv].last(2) }).to eq(hostile.map { |text| [text, text] })
64
+ end
65
+
66
+ it 'stops notify-send option parsing before the title and escapes markup in the message on Linux' do
67
+ notifier('linux-gnu').notify('-u critical', 'a < b & c > d')
68
+
69
+ expect(runner.calls.first[:argv]).to eq(['notify-send', '--app-name=Ruby Raider', '--', '-u critical', 'a &lt; b &amp; c &gt; d'])
70
+ end
71
+
72
+ it 'passes the title and message to a fixed PowerShell script through the environment on Windows' do
73
+ notifier('mswin64').notify('$env:USERPROFILE', '`whoami`')
74
+
75
+ expect(runner.calls.first).to eq(
76
+ argv: [powershell, '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', described_class::TOAST_SCRIPT],
77
+ env: { 'RAIDER_NOTIFY_TITLE' => '$env:USERPROFILE', 'RAIDER_NOTIFY_MESSAGE' => '`whoami`' }, timeout: 15
78
+ )
79
+ end
80
+
81
+ it 'finds PowerShell under SystemRoot by default' do
82
+ allow(ENV).to receive(:fetch).and_call_original
83
+ allow(ENV).to receive(:fetch).with('SystemRoot', 'C:\\Windows').and_return('D:\\Win')
84
+ described_class.new(runner: runner, host_os: 'mingw32', err: err).notify('t', 'm')
85
+
86
+ expect(runner.calls.first[:argv].first).to eq(File.join('D:\\Win', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'))
87
+ end
88
+
89
+ it 'builds the toast from the environment, never from text joined into XML' do
90
+ script = described_class::TOAST_SCRIPT
91
+
92
+ expect(script).to include('$env:RAIDER_NOTIFY_TITLE', '$env:RAIDER_NOTIFY_MESSAGE', 'CreateTextNode', 'ToastText02')
93
+ expect(script).not_to include('"', "\n", 'EncodedCommand')
94
+ end
95
+
96
+ it 'makes control characters printable and caps the message at 200 characters' do
97
+ notifier('darwin25').notify("flow\e[2J", "#{'x' * 250}\n")
98
+
99
+ expect(runner.calls.first[:argv].last(2)).to eq(['flow?[2J', 'x' * 200])
100
+ end
101
+
102
+ it 'does nothing on another OS' do
103
+ expect([notifier('solaris2').notify('t', 'm'), runner.calls]).to eq([false, []])
104
+ end
105
+
106
+ it 'returns false and warns once when the notification fails, without raising' do
107
+ runner.exitstatus = 1
108
+ sender = notifier('linux-gnu')
109
+
110
+ expect([sender.notify('t', 'm'), sender.notify('t', 'm')]).to eq([false, false])
111
+ expect(err.string).to eq("Could not show a desktop notification: no notification server\n")
112
+ end
113
+
114
+ it 'returns false when the runner raises' do
115
+ allow(runner).to receive(:call).and_raise(IOError, 'closed stream')
116
+
117
+ expect(notifier('darwin25').notify('t', 'm')).to be(false)
118
+ expect(err.string).to include('closed stream')
119
+ end
120
+ end
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'rbconfig'
4
+ require_relative '../../../../lib/utilities/schedules/os/command_runner'
5
+
6
+ RSpec.describe RubyRaider::Schedules::Os::CommandRunner do # rubocop:disable RSpec/FilePath
7
+ let(:runner) { described_class.new }
8
+ let(:ruby) { RbConfig.ruby }
9
+
10
+ it 'captures stdout, stderr and the exit status' do
11
+ result = runner.call(ruby, '-e', '$stdout.print "out"; $stderr.print "err"; exit 3')
12
+
13
+ expect([result.stdout, result.stderr, result.exitstatus, result.success?]).to eq(['out', 'err', 3, false])
14
+ end
15
+
16
+ it 'succeeds on exit 0' do
17
+ expect(runner.call(ruby, '-e', 'exit 0').success?).to be(true)
18
+ end
19
+
20
+ it 'feeds stdin' do
21
+ expect(runner.call(ruby, '-e', 'print $stdin.read.upcase', stdin_data: "a b\n").stdout).to eq("A B\n")
22
+ end
23
+
24
+ it 'adds env values to the command environment' do
25
+ result = runner.call(ruby, '-e', 'print ENV["RAIDER_NOTIFY_TITLE"]', env: { 'RAIDER_NOTIFY_TITLE' => '$(id)' })
26
+
27
+ expect(result.stdout).to eq('$(id)')
28
+ end
29
+
30
+ it 'stops a command that runs past the timeout' do
31
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
32
+ result = runner.call(ruby, '-e', 'sleep 10', timeout: 0.3)
33
+
34
+ expect([result.success?, result.stderr]).to eq([false, "#{ruby} took longer than 0.3 s"])
35
+ expect(Process.clock_gettime(Process::CLOCK_MONOTONIC) - started).to be < 5
36
+ end
37
+
38
+ it 'passes arguments without a shell' do
39
+ hostile = ["'; rm -rf ~; '", '$(id)', '%h', '</string>']
40
+
41
+ expect(runner.call(ruby, '-e', 'print ARGV.join("|")', *hostile).stdout).to eq(hostile.join('|'))
42
+ end
43
+
44
+ it 'never runs a single string through a shell' do
45
+ result = runner.call('echo $(id)')
46
+
47
+ expect([result.success?, result.stdout]).to eq([false, ''])
48
+ end
49
+
50
+ it 'returns a failed result for a missing executable' do
51
+ result = runner.call('/no/such/raider-command', 'x')
52
+
53
+ expect([result.success?, result.exitstatus, result.stderr]).to match([false, 127, /raider-command/])
54
+ end
55
+ end
@@ -0,0 +1,292 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'shellwords'
4
+ require 'tmpdir'
5
+ require_relative '../../../../lib/utilities/schedules/os/cron'
6
+ require_relative '../../../../lib/utilities/schedules/schedule'
7
+
8
+ # The fake runner and project folders sit next to the adapter under test
9
+ # rubocop:disable RSpec/MultipleMemoizedHelpers
10
+ RSpec.describe RubyRaider::Schedules::Os::Cron do # rubocop:disable RSpec/FilePath
11
+ # Plays crontab: -l prints the current table (or fails), - stores stdin; never runs anything
12
+ let(:fake_runner_class) do
13
+ Class.new do
14
+ attr_reader :calls, :answers
15
+ attr_accessor :table
16
+
17
+ def initialize
18
+ @calls = []
19
+ @answers = {}
20
+ @table = nil
21
+ end
22
+
23
+ def call(*argv, stdin_data: nil)
24
+ @calls << [*argv, stdin_data].compact
25
+ verb = argv[1]
26
+ missing = verb == '-l' && table.nil?
27
+ stderr, status = answers.fetch(verb) { missing ? ['no crontab for raider', 1] : ['', 0] }
28
+ stdout = verb == '-l' ? table.to_s : ''
29
+ self.table = stdin_data if verb == '-' && status.zero?
30
+ RubyRaider::Schedules::Os::CommandRunner::Result.new(stdout: stdout, stderr: stderr, exitstatus: status)
31
+ end
32
+ end
33
+ end
34
+
35
+ let(:hostile) { %q('; rm -rf ~; ' </string> %h $(id) " \\ &) }
36
+ let(:tmp) { File.realpath(Dir.mktmpdir('schedules-cron')) }
37
+ let(:project_dir) { File.join(tmp, 'plain') }
38
+ let(:runner) { fake_runner_class.new }
39
+ let(:cron) { described_class.new(kind: RubyRaider::Schedules::Kind::TESTS, runner: runner) }
40
+ let(:now) { Time.utc(2026, 11, 9, 10, 0, 0) }
41
+
42
+ def schedule(dir: project_dir, name: 'report', gem_env: {}, bundle: '/opt/ruby/bin/bundle', **options)
43
+ FileUtils.mkdir_p(dir)
44
+ # Hermetic: the GEM_HOME/GEM_PATH and bundle this spec runs with never reach the entry; a spec passes its own
45
+ allow(RubyRaider::Schedules::Schedule).to receive_messages(captured_gem_env: gem_env, bundle_path: bundle)
46
+ project = RubyRaider::Schedules::Project.new(File.realpath(dir))
47
+ RubyRaider::Schedules::Schedule.build(project: project, name: name, every: 'day', at: '08:00', now: now, **options)
48
+ end
49
+
50
+ # What cron (cronie/vixie do_command.c) hands to /bin/sh: a backslash escapes the next character, an
51
+ # escaped % loses its backslash, any other escaped character keeps it, and an unescaped % would end the
52
+ # command (the rest becomes stdin). Strict: an unescaped % fails the spec.
53
+ def cron_command(text)
54
+ command = +''
55
+ escaped = false
56
+ text.each_char do |char|
57
+ if escaped
58
+ command.chop! if char == '%'
59
+ command << char
60
+ escaped = false
61
+ next
62
+ end
63
+ raise ArgumentError, "unescaped % in #{text.inspect}" if char == '%'
64
+
65
+ escaped = char == '\\'
66
+ command << char
67
+ end
68
+ command
69
+ end
70
+
71
+ def fields_and_words(line)
72
+ fields = line.split(' ', 6)
73
+ [fields.first(5), Shellwords.split(cron_command(fields.last))]
74
+ end
75
+
76
+ def expected_words(item)
77
+ ['cd', item.working_directory, '&&', '/usr/bin/env', *item.env.map { |key, value| "#{key}=#{value}" }, *item.argv,
78
+ '>>', item.log_path, '2>&1']
79
+ end
80
+
81
+ def block(item) = "# raider-schedule #{item.os_id}\n#{cron.line(item)}\n"
82
+
83
+ after { FileUtils.rm_rf(tmp) }
84
+
85
+ it 'is called cron in messages and says missed runs are skipped' do
86
+ expect([cron.label, cron.missed_runs_note]).to eq(['cron', '(cron: missed runs are skipped)'])
87
+ end
88
+
89
+ describe '#line' do
90
+ it 'writes the exact line for a daily schedule' do
91
+ item = schedule
92
+ env = item.env.map { |key, value| Shellwords.escape("#{key}=#{value}") }.join(' ')
93
+ args = item.argv.map { |arg| Shellwords.escape(arg) }.join(' ')
94
+
95
+ expect(cron.line(item)).to eq("0 8 * * * cd #{Shellwords.escape(item.working_directory)} && /usr/bin/env #{env} #{args} " \
96
+ ">> #{Shellwords.escape(item.log_path)} 2>&1")
97
+ end
98
+
99
+ it 'turns each rule into cron fields, Sunday 0' do
100
+ rules = [schedule(every: 'hour', at: ':15'), schedule(every: 'weekday', at: '18:05'),
101
+ schedule(every: 'week', on: 'sun', at: '07:30'), schedule(every: 'week', on: 'sat', at: '23:59')]
102
+
103
+ expect(rules.map { |item| fields_and_words(cron.line(item)).first.join(' ') })
104
+ .to eq(['15 * * * *', '5 18 * * 1-5', '30 7 * * 0', '59 23 * * 6'])
105
+ end
106
+
107
+ it 'keeps GEM_HOME and GEM_PATH in the environment when they were captured' do
108
+ item = schedule(gem_env: { 'GEM_HOME' => '/g/%home', 'GEM_PATH' => '/g/path' })
109
+
110
+ expect(fields_and_words(cron.line(item)).last).to include('GEM_HOME=/g/%home', 'GEM_PATH=/g/path')
111
+ end
112
+
113
+ it 'refuses a ruby path env would read as a variable' do
114
+ plain = schedule
115
+ item = RubyRaider::Schedules::Schedule.from_h(plain.to_h.merge('ruby' => '/opt/a=b/ruby'), plain.project_root)
116
+
117
+ expect { cron.line(item) }.to raise_error(RubyRaider::Schedules::Error, /cron can not run ruby from .*a=b/)
118
+ end
119
+
120
+ describe 'with hostile values in the bundle path, GEM_HOME and the project path' do
121
+ let(:item) do
122
+ schedule(dir: File.join(tmp, "p#{hostile}<", "string> #{hostile} 100%"), bundle: "/opt/#{hostile} 50%/bundle",
123
+ gem_env: { 'GEM_HOME' => "/g/#{hostile} 25%" })
124
+ end
125
+ let(:text) { cron.line(item) }
126
+
127
+ it 'gives back the exact command words after cron and the shell read it' do
128
+ fields, words = fields_and_words(text)
129
+
130
+ expect([fields, words]).to eq([%w[0 8 * * *], expected_words(item)])
131
+ expect(words).to include("/opt/#{hostile} 50%/bundle", "GEM_HOME=/g/#{hostile} 25%")
132
+ expect(item.working_directory).to include('</string>', "'; rm -rf ~; '", '$(id)', '%h', '"', '\\', '&', ' ')
133
+ end
134
+
135
+ it 'writes them only in escaped form' do
136
+ expect(text).to include('\\%h', '\\$\\(id\\)', "\\'\\;\\ rm")
137
+ expect(text).not_to include('$(id)', "'; rm", "\n")
138
+ end
139
+ end
140
+ end
141
+
142
+ describe '#install' do
143
+ it 'starts a crontab when there is none' do
144
+ item = schedule
145
+
146
+ cron.install(item)
147
+
148
+ expect(runner.calls).to eq([%w[crontab -l], ['crontab', '-', block(item)]])
149
+ end
150
+
151
+ it 'puts the block first and keeps every other byte, CRLF and a missing last newline included' do
152
+ item = schedule
153
+ other = "SHELL=/bin/fish\r\nMAILTO=\"\"\r\n# raider-schedule dev.rubyraider.schedule.0123456789.other\n1 2 * * * echo % \\%\n5 5 * * * last"
154
+ runner.table = other
155
+
156
+ cron.install(item)
157
+
158
+ expect(runner.table).to eq(block(item) + other)
159
+ end
160
+
161
+ it 'replaces its own block and nothing else' do
162
+ item = schedule
163
+ daily = block(item)
164
+ runner.table = "1 * * * * a\n#{daily}2 * * * * b\n"
165
+
166
+ cron.install(schedule(every: 'hour', at: ':10'))
167
+
168
+ expect(runner.table).to eq("#{block(schedule(every: 'hour', at: ':10'))}1 * * * * a\n2 * * * * b\n")
169
+ expect(runner.table).not_to include(daily)
170
+ end
171
+
172
+ it "keeps another schedule's block" do
173
+ other = schedule(name: 'nightly')
174
+ runner.table = block(other)
175
+
176
+ cron.install(schedule)
177
+
178
+ expect(runner.table).to eq(block(schedule) + block(other))
179
+ end
180
+
181
+ it 'refuses a line vixie cron would cut short and writes nothing' do
182
+ item = schedule(gem_env: { 'GEM_HOME' => "/g/#{'x' * 900}" })
183
+
184
+ expect { cron.install(item) }.to raise_error(RubyRaider::Schedules::Error, /crontab line is \d{4} bytes, over 990/)
185
+ expect(runner.calls).to be_empty
186
+ end
187
+
188
+ it 'raises with the scheduler error when crontab -l fails for another reason' do
189
+ runner.answers['-l'] = ["crontab: permission denied\e[2J", 1]
190
+
191
+ expect { cron.install(schedule) }.to raise_error(RubyRaider::Schedules::Error, /cron could not read .*permission denied\?\[2J/)
192
+ expect(runner.calls).to eq([%w[crontab -l]])
193
+ end
194
+
195
+ it 'raises with the scheduler error when crontab - fails' do
196
+ runner.table = "1 * * * * a\n"
197
+ runner.answers['-'] = ['crontab: errors in crontab file', 1]
198
+
199
+ expect { cron.install(schedule) }.to raise_error(RubyRaider::Schedules::Error, /cron could not save .*errors in crontab file/)
200
+ expect(runner.table).to eq("1 * * * * a\n")
201
+ end
202
+ end
203
+
204
+ describe '#remove' do
205
+ it 'removes its block and gives back the crontab byte for byte' do
206
+ other = "A=1\r\n1 * * * * a\n2 * * * * b"
207
+ runner.table = other
208
+ cron.install(schedule)
209
+
210
+ expect(cron.remove(schedule.os_id)).to be(true)
211
+ expect(runner.table).to eq(other)
212
+ end
213
+
214
+ it 'removes every copy of its block' do
215
+ item = schedule
216
+ runner.table = "#{block(item)}1 * * * * a\n#{block(item)}"
217
+
218
+ expect(cron.remove(item.os_id)).to be(true)
219
+ expect(runner.table).to eq("1 * * * * a\n")
220
+ end
221
+
222
+ it 'keeps an unrelated line that follows an orphaned tag' do
223
+ item = schedule
224
+ other = schedule(name: 'nightly')
225
+ runner.table = "# raider-schedule #{item.os_id}\n#{cron.line(other)}\n1 * * * * a\n"
226
+
227
+ expect(cron.remove(item.os_id)).to be(true)
228
+ expect(runner.table).to eq("#{cron.line(other)}\n1 * * * * a\n")
229
+ end
230
+
231
+ it 'keeps a line under its tag that is not a schedule run' do
232
+ item = schedule
233
+ manual = cron.line(item).sub(' --trigger schedule', ' --trigger manual')
234
+ runner.table = "# raider-schedule #{item.os_id}\n#{manual}\n"
235
+
236
+ expect(cron.remove(item.os_id)).to be(true)
237
+ expect(runner.table).to eq("#{manual}\n")
238
+ end
239
+
240
+ it 'removes a tag line left without its line' do
241
+ item = schedule
242
+ runner.table = "1 * * * * a\n# raider-schedule #{item.os_id}"
243
+
244
+ expect(cron.remove(item.os_id)).to be(true)
245
+ expect(runner.table).to eq("1 * * * * a\n")
246
+ end
247
+
248
+ it 'is false and writes nothing when its block is not there' do
249
+ runner.table = "1 * * * * a\n# raider-schedule #{schedule.os_id}x\n"
250
+
251
+ expect(cron.remove(schedule.os_id)).to be(false)
252
+ expect(runner.calls).to eq([%w[crontab -l]])
253
+ end
254
+
255
+ it 'is false when there is no crontab' do
256
+ expect(cron.remove(schedule.os_id)).to be(false)
257
+ end
258
+
259
+ it 'refuses an os_id that is not a schedule id' do
260
+ expect { cron.remove("x\n* * * * * evil") }.to raise_error(RubyRaider::Schedules::Error, /Invalid os_id/)
261
+ expect(runner.calls).to be_empty
262
+ end
263
+ end
264
+
265
+ describe '#usable?' do
266
+ it 'is true when crontab -l answers, even with no crontab' do
267
+ expect(cron.usable?).to be(true)
268
+ end
269
+
270
+ it 'is false when crontab -l fails for another reason' do
271
+ runner.answers['-l'] = ['crontab: not found', 127]
272
+
273
+ expect(cron.usable?).to be(false)
274
+ end
275
+ end
276
+
277
+ describe '#present?' do
278
+ it 'is true when the tag line is there' do
279
+ item = schedule
280
+ runner.table = block(item)
281
+
282
+ expect(cron.present?(item.os_id)).to be(true)
283
+ end
284
+
285
+ it 'is false when there is no crontab or no tag line' do
286
+ expect(cron.present?(schedule.os_id)).to be(false)
287
+ runner.table = "1 * * * * a\n"
288
+ expect(cron.present?(schedule.os_id)).to be(false)
289
+ end
290
+ end
291
+ end
292
+ # rubocop:enable RSpec/MultipleMemoizedHelpers