ruby_raider 4.0.0 → 4.1.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 (78) hide show
  1. checksums.yaml +4 -4
  2. data/.github/ffmpeg/build.sh +208 -0
  3. data/.github/ffmpeg/check.sh +72 -0
  4. data/.github/ffmpeg/frames.rb +34 -0
  5. data/.github/ffmpeg/probe.sh +17 -0
  6. data/.github/workflows/ffmpeg.yml +160 -0
  7. data/README.md +226 -33
  8. data/RELEASE.md +19 -0
  9. data/lib/commands/flow_commands.rb +104 -0
  10. data/lib/generators/templates/common/read_me.tt +6 -7
  11. data/lib/generators/templates/flows/flow_helper.tt +42 -0
  12. data/lib/generators/templates/flows/run.tt +332 -0
  13. data/lib/generators/templates/helpers/video_helper.tt +1 -2
  14. data/lib/ruby_raider/ffmpeg.rb +38 -11
  15. data/lib/ruby_raider.rb +16 -0
  16. data/lib/utilities/flows/next_run.rb +61 -0
  17. data/lib/utilities/flows/notifier.rb +76 -0
  18. data/lib/utilities/flows/os/command_runner.rb +73 -0
  19. data/lib/utilities/flows/os/cron.rb +137 -0
  20. data/lib/utilities/flows/os/launchd.rb +164 -0
  21. data/lib/utilities/flows/os/linux.rb +63 -0
  22. data/lib/utilities/flows/os/systemd.rb +178 -0
  23. data/lib/utilities/flows/os/task_scheduler.rb +179 -0
  24. data/lib/utilities/flows/project.rb +170 -0
  25. data/lib/utilities/flows/run_log.rb +61 -0
  26. data/lib/utilities/flows/runner.rb +206 -0
  27. data/lib/utilities/flows/schedule.rb +221 -0
  28. data/lib/utilities/flows/schedule_store.rb +135 -0
  29. data/lib/utilities/flows/scheduler.rb +187 -0
  30. data/lib/version +1 -1
  31. data/sig/commands/flow_commands.rbs +13 -0
  32. data/sig/ruby_raider/ffmpeg.rbs +1 -0
  33. data/sig/ruby_raider.rbs +2 -0
  34. data/sig/utilities/flows/next_run.rbs +15 -0
  35. data/sig/utilities/flows/notifier.rbs +29 -0
  36. data/sig/utilities/flows/os/command_runner.rbs +27 -0
  37. data/sig/utilities/flows/os/cron.rbs +34 -0
  38. data/sig/utilities/flows/os/launchd.rbs +45 -0
  39. data/sig/utilities/flows/os/linux.rbs +27 -0
  40. data/sig/utilities/flows/os/systemd.rbs +43 -0
  41. data/sig/utilities/flows/os/task_scheduler.rbs +53 -0
  42. data/sig/utilities/flows/project.rbs +46 -0
  43. data/sig/utilities/flows/run_log.rbs +22 -0
  44. data/sig/utilities/flows/runner.rbs +35 -0
  45. data/sig/utilities/flows/schedule.rbs +61 -0
  46. data/sig/utilities/flows/schedule_store.rbs +34 -0
  47. data/sig/utilities/flows/scheduler.rbs +42 -0
  48. data/spec/commands/flow_commands_spec.rb +128 -0
  49. data/spec/generators/flow_helper_spec.rb +40 -0
  50. data/spec/generators/video_helper_spec.rb +21 -4
  51. data/spec/integration/content/gemfile_content_spec.rb +2 -2
  52. data/spec/integration/content/readme_content_spec.rb +7 -2
  53. data/spec/integration/end_to_end_spec.rb +83 -8
  54. data/spec/integration/flows/flow_project.rb +62 -0
  55. data/spec/integration/flows/run_command_spec.rb +91 -0
  56. data/spec/integration/flows/run_lifecycle_spec.rb +383 -0
  57. data/spec/utilities/ffmpeg_spec.rb +80 -7
  58. data/spec/utilities/flows/next_run_spec.rb +119 -0
  59. data/spec/utilities/flows/notifier_spec.rb +121 -0
  60. data/spec/utilities/flows/os/command_runner_spec.rb +56 -0
  61. data/spec/utilities/flows/os/cron_spec.rb +287 -0
  62. data/spec/utilities/flows/os/launchd_spec.rb +293 -0
  63. data/spec/utilities/flows/os/linux_spec.rb +149 -0
  64. data/spec/utilities/flows/os/systemd_spec.rb +329 -0
  65. data/spec/utilities/flows/os/task_scheduler_spec.rb +505 -0
  66. data/spec/utilities/flows/project_spec.rb +178 -0
  67. data/spec/utilities/flows/run_log_spec.rb +47 -0
  68. data/spec/utilities/flows/runner_spec.rb +313 -0
  69. data/spec/utilities/flows/schedule_spec.rb +233 -0
  70. data/spec/utilities/flows/schedule_store_spec.rb +137 -0
  71. data/spec/utilities/flows/scheduler_spec.rb +329 -0
  72. data/spec/utilities/video_command_spec.rb +13 -0
  73. metadata +58 -7
  74. data/docs/superpowers/plans/2026-10-25-failure-video-replay.md +0 -400
  75. data/docs/superpowers/plans/2026-10-26-parity-cleanup.md +0 -233
  76. data/docs/superpowers/plans/2026-10-28-failure-card.md +0 -295
  77. data/docs/superpowers/specs/2026-10-25-failure-video-replay-design.md +0 -214
  78. data/docs/superpowers/specs/2026-10-28-failure-card-design.md +0 -210
@@ -0,0 +1,137 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'shellwords'
4
+ require_relative 'command_runner'
5
+ require_relative '../schedule'
6
+
7
+ module RubyRaider
8
+ module Flows
9
+ module Os
10
+ # Linux without a systemd user manager: one tagged block per schedule in the user's crontab, read with
11
+ # `crontab -l` and written back with `crontab -`. Every value goes through Shellwords.escape, which also
12
+ # escapes % as \% (cron would turn a bare % into a newline). Lines that are not ours keep every byte.
13
+ class Cron
14
+ CRONTAB = 'crontab'
15
+ TAG = '# raider-flow '
16
+ # Debian's vixie cron cuts a command at MAX_COMMAND (1000) bytes without a word; stay under it
17
+ MAX_LINE = 990
18
+ OS_ID = /\A#{Regexp.escape(Schedule::OS_ID_PREFIX)}\.[0-9a-f]{10}\.([a-z0-9_]{1,60})\z/
19
+
20
+ def initialize(runner: CommandRunner.new)
21
+ @runner = runner
22
+ end
23
+
24
+ def label = 'cron'
25
+
26
+ def missed_runs_note = '(cron: missed runs are skipped)'
27
+
28
+ # Minute hour day-of-month month day-of-week (the system time zone), then the command for /bin/sh
29
+ def line(schedule)
30
+ ruby = schedule.ruby
31
+ raise Error, "cron can not run ruby from #{Flows.printable(ruby)}: env would read the = as a variable" if ruby.include?('=')
32
+
33
+ env = schedule.env.map { |key, value| "#{key}=#{value}" }
34
+ command = ['cd', escape(schedule.working_directory), '&&', '/usr/bin/env', *[*env, *schedule.argv].map { |word| escape(word) },
35
+ '>>', escape(schedule.log_path), '2>&1']
36
+ "#{fields(schedule)} #{command.join(' ')}"
37
+ end
38
+
39
+ # Our block goes first: above any SHELL=, CRON_TZ= or MAILTO= line, and with no byte of the rest changed
40
+ def install(schedule)
41
+ os_id = schedule.os_id
42
+ entry = line(schedule)
43
+ raise Error, "cron can not run #{schedule.name}: its crontab line is #{entry.bytesize} bytes, over #{MAX_LINE}" if entry.bytesize > MAX_LINE
44
+
45
+ rest, = without(read, os_id)
46
+ save("#{TAG}#{os_id}\n#{entry}\n#{rest}")
47
+ true
48
+ end
49
+
50
+ # True when our block was there and is gone, false when it was already gone
51
+ def remove(os_id)
52
+ tag = checked_os_id(os_id)
53
+ rest, found = without(read, tag)
54
+ save(rest) if found
55
+ found
56
+ end
57
+
58
+ def present?(os_id)
59
+ tag = checked_os_id(os_id)
60
+ without(read, tag).last
61
+ end
62
+
63
+ # True when crontab -l answers (an empty crontab counts)
64
+ def usable?
65
+ read
66
+ true
67
+ rescue Error
68
+ false
69
+ end
70
+
71
+ private
72
+
73
+ def fields(schedule)
74
+ minute = schedule.minute
75
+ return "#{minute} * * * *" if schedule.every == 'hour'
76
+
77
+ day = case schedule.every
78
+ when 'weekday' then '1-5'
79
+ when 'week' then weekday(schedule.on.to_s).to_s
80
+ else '*'
81
+ end
82
+ "#{minute} #{schedule.hour} * * #{day}"
83
+ end
84
+
85
+ # cron counts Sunday as 0
86
+ def weekday(day)
87
+ index = Schedule::DAYS.index(day)
88
+ raise Error, "Invalid day #{day.inspect}" unless index
89
+
90
+ (index + 1) % 7
91
+ end
92
+
93
+ def escape(word) = Shellwords.escape(word)
94
+
95
+ # The crontab without any of our tag lines, each with the line after it when that line is our command,
96
+ # and whether a tag was there
97
+ def without(table, os_id)
98
+ tag = "#{TAG}#{os_id}"
99
+ name = OS_ID.match(os_id).to_a[1]
100
+ kept = []
101
+ found = after_tag = false
102
+ table.lines.each do |text|
103
+ ours = text.chomp == tag || (after_tag && our_command?(text, name))
104
+ after_tag = text.chomp == tag
105
+ found ||= after_tag
106
+ kept << text unless ours
107
+ end
108
+ [kept.join, found]
109
+ end
110
+
111
+ # The line under our tag runs `raider flow run <name> --project ... --trigger schedule`
112
+ def our_command?(text, name) = text.include?(" exec raider flow run #{name} --project ") && text.include?(' --trigger schedule')
113
+
114
+ def read
115
+ result = @runner.call(CRONTAB, '-l')
116
+ return result.stdout if result.success?
117
+
118
+ stderr = result.stderr
119
+ return '' if stderr.match?(/no crontab/i)
120
+
121
+ raise Error, "cron could not read the crontab: #{Flows.printable(stderr.strip)}"
122
+ end
123
+
124
+ def save(table)
125
+ result = @runner.call(CRONTAB, '-', stdin_data: table)
126
+ raise Error, "cron could not save the crontab: #{Flows.printable(result.stderr.strip)}" unless result.success?
127
+ end
128
+
129
+ def checked_os_id(os_id)
130
+ return os_id if os_id.is_a?(String) && (match = OS_ID.match(os_id)) && Flows.valid_name?(match[1])
131
+
132
+ raise Error, "Invalid os_id #{Flows.printable(os_id.inspect)}: not a flow schedule"
133
+ end
134
+ end
135
+ end
136
+ end
137
+ end
@@ -0,0 +1,164 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'fileutils'
4
+ require 'securerandom'
5
+ require_relative 'command_runner'
6
+ require_relative '../schedule'
7
+
8
+ module RubyRaider
9
+ module Flows
10
+ module Os
11
+ # macOS: a LaunchAgent plist in ~/Library/LaunchAgents per schedule, loaded into the user's GUI
12
+ # domain with launchctl. Every value in the plist goes through one XML escaper.
13
+ # :reek:TooManyConstants { max_constants: 6 } -- the two tools, NOFOLLOW, the XML escapes and header, the os_id rule
14
+ class Launchd
15
+ LAUNCHCTL = '/bin/launchctl'
16
+ PLUTIL = '/usr/bin/plutil'
17
+ NOFOLLOW = defined?(File::NOFOLLOW) ? File::NOFOLLOW : 0
18
+ ESCAPES = { '&' => '&amp;', '<' => '&lt;', '>' => '&gt;', '"' => '&quot;', "'" => '&apos;' }.freeze
19
+ HEADER = <<~XML
20
+ <?xml version="1.0" encoding="UTF-8"?>
21
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
22
+ <plist version="1.0">
23
+ XML
24
+ OS_ID = /\A#{Regexp.escape(Schedule::OS_ID_PREFIX)}\.[0-9a-f]{10}\.([a-z0-9_]{1,60})\z/
25
+
26
+ def initialize(runner: CommandRunner.new, home: Dir.home, uid: Process.uid)
27
+ @runner = runner
28
+ @home = home
29
+ @uid = uid
30
+ end
31
+
32
+ def label = 'launchd'
33
+
34
+ # The LaunchAgent plist for the schedule (local time, no RunAtLoad)
35
+ def plist(schedule)
36
+ path = schedule.log_path
37
+ entries = [
38
+ ['Label', string(schedule.os_id)],
39
+ ['ProgramArguments', array(schedule.argv.map { |arg| string(arg) })],
40
+ ['WorkingDirectory', string(schedule.working_directory)],
41
+ ['StandardOutPath', string(path)],
42
+ ['StandardErrorPath', string(path)],
43
+ ['EnvironmentVariables', dict(schedule.env.map { |key, value| [key, string(value)] })],
44
+ ['StartCalendarInterval', calendar(schedule)]
45
+ ]
46
+ "#{HEADER}#{dict(entries).join("\n")}\n</plist>\n"
47
+ end
48
+
49
+ def plist_path(os_id) = File.join(agents_dir, "#{checked_os_id(os_id)}.plist")
50
+
51
+ # Writes the plist (linted before it replaces anything), then reloads the service
52
+ def install(schedule)
53
+ os_id = schedule.os_id
54
+ path = plist_path(os_id)
55
+ write(path, plist(schedule))
56
+ launchctl('bootout', service(os_id))
57
+ result = launchctl('bootstrap', domain, path)
58
+ return true if result.success?
59
+
60
+ raise Error, "launchd could not load #{os_id}: #{Flows.printable(result.stderr.strip)}#{discard(path)}"
61
+ end
62
+
63
+ # True when a plist or a loaded service was removed, false when it was already gone
64
+ def remove(os_id)
65
+ path = plist_path(os_id)
66
+ unloaded = launchctl('bootout', service(os_id)).success?
67
+ unlink(path) || unloaded
68
+ end
69
+
70
+ def present?(os_id) = launchctl('print', service(checked_os_id(os_id))).success?
71
+
72
+ private
73
+
74
+ def launchctl(*args) = @runner.call(LAUNCHCTL, *args)
75
+
76
+ def domain = "gui/#{@uid}"
77
+
78
+ def service(os_id) = "#{domain}/#{os_id}"
79
+
80
+ # True when the plist was there; a plist that stays behind is an error, not "already gone"
81
+ def unlink(path)
82
+ File.unlink(path)
83
+ true
84
+ rescue Errno::ENOENT
85
+ false
86
+ rescue SystemCallError => e
87
+ raise Error, "Could not remove #{path}: #{e.message}"
88
+ end
89
+
90
+ def agents_dir = File.join(@home, 'Library', 'LaunchAgents')
91
+
92
+ def checked_os_id(os_id)
93
+ return os_id if os_id.is_a?(String) && (match = OS_ID.match(os_id)) && Flows.valid_name?(match[1])
94
+
95
+ raise Error, "Invalid os_id #{Flows.printable(os_id.inspect)}: not a flow schedule"
96
+ end
97
+
98
+ def escape(text) = text.to_s.gsub(/[&<>"']/, ESCAPES)
99
+
100
+ def string(text) = ["<string>#{escape(text)}</string>"]
101
+
102
+ def integer(number) = ["<integer>#{Integer(number)}</integer>"]
103
+
104
+ def array(items) = ['<array>', *indent(items.flatten), '</array>']
105
+
106
+ def dict(pairs)
107
+ body = pairs.flat_map { |key, value| ["<key>#{escape(key)}</key>", *value] }
108
+ ['<dict>', *indent(body), '</dict>']
109
+ end
110
+
111
+ def indent(lines) = lines.map { |line| "\t#{line}" }
112
+
113
+ # Schedule::DAYS runs mon..sun
114
+ def calendar(schedule)
115
+ time = [['Hour', integer(schedule.hour)], ['Minute', integer(schedule.minute)]]
116
+ case schedule.every
117
+ when 'hour' then dict([['Minute', integer(schedule.minute)]])
118
+ when 'day' then dict(time)
119
+ else
120
+ days = schedule.days.map { |day| dict([['Weekday', integer(weekday(day))], *time]) }
121
+ schedule.every == 'week' ? days.first : array(days)
122
+ end
123
+ end
124
+
125
+ # launchd counts Sunday as 0
126
+ def weekday(day)
127
+ index = Schedule::DAYS.index(day)
128
+ raise Error, "Invalid day #{day.inspect}" unless index
129
+
130
+ (index + 1) % 7
131
+ end
132
+
133
+ # Removes the plist a failed bootstrap left; returns what to add to the error when it stays behind
134
+ def discard(path)
135
+ unlink(path)
136
+ ''
137
+ rescue Error => e
138
+ "; also: #{e.message}"
139
+ end
140
+
141
+ # Temp file in the same folder, checked with plutil, then renamed over the old plist
142
+ def write(path, text)
143
+ dir = File.dirname(path)
144
+ FileUtils.mkdir_p(dir)
145
+ temp = File.join(dir, ".#{File.basename(path)}.#{SecureRandom.hex(6)}.tmp")
146
+ File.open(temp, File::WRONLY | File::CREAT | File::EXCL | NOFOLLOW, 0o644) do |file|
147
+ file.write(text)
148
+ file.flush
149
+ file.fsync
150
+ file.chmod(0o644)
151
+ end
152
+ lint = @runner.call(PLUTIL, '-lint', temp)
153
+ raise Error, "launchd plist for #{File.basename(path)} is invalid: #{Flows.printable("#{lint.stdout} #{lint.stderr}".strip)}" unless lint.success?
154
+
155
+ File.rename(temp, path)
156
+ rescue SystemCallError => e
157
+ raise Error, "Could not write #{path}: #{e.message}"
158
+ ensure
159
+ FileUtils.rm_f(temp) if temp && File.exist?(temp)
160
+ end
161
+ end
162
+ end
163
+ end
164
+ end
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'command_runner'
4
+ require_relative 'systemd'
5
+ require_relative 'cron'
6
+
7
+ module RubyRaider
8
+ module Flows
9
+ module Os
10
+ # Linux: systemd user timers when the user's systemd manager answers, cron otherwise. A schedule made over
11
+ # ssh (no user bus, so cron) must still go when unscheduled from a desktop session, so remove and present?
12
+ # also look in the other scheduler when it answers. The reverse (a systemd timer, unscheduled where no user
13
+ # bus answers) can only be seen from its unit files, and can only be removed where systemctl --user works.
14
+ class Linux
15
+ def self.pick(runner = CommandRunner.new) = new(runner: runner)
16
+
17
+ def initialize(runner: CommandRunner.new, systemd: Systemd.new(runner: runner), cron: Cron.new(runner: runner))
18
+ # systemd is the other one only when it answers, so with cron first there is no other one
19
+ @systemd = systemd
20
+ @primary, @other = systemd.usable? ? [systemd, cron] : [cron, nil]
21
+ end
22
+
23
+ def label = @primary.label
24
+
25
+ def missed_runs_note = @primary.missed_runs_note
26
+
27
+ def install(schedule) = @primary.install(schedule)
28
+
29
+ # True when either scheduler removed something
30
+ def remove(os_id)
31
+ removed = @primary.remove(os_id)
32
+ other = @other
33
+ other_removed = other&.usable? ? other.remove(os_id) : false
34
+ refuse_stranded(os_id)
35
+ removed || other_removed
36
+ end
37
+
38
+ # True when either scheduler has it, or systemd unit files are there though systemd does not answer
39
+ def present?(os_id) = @primary.present?(os_id) || other_present?(os_id) || stranded?(os_id)
40
+
41
+ private
42
+
43
+ def stranded?(os_id) = @primary != @systemd && @systemd.unit_files?(os_id)
44
+
45
+ # Raises so the schedules.yml entry stays until the timer can really go
46
+ def refuse_stranded(os_id)
47
+ return unless stranded?(os_id)
48
+
49
+ raise Error, "This schedule is a systemd timer; run raider flow unschedule #{os_id.split('.').last} " \
50
+ 'from a session where systemctl --user works'
51
+ end
52
+
53
+ # The other scheduler failing counts as not there
54
+ def other_present?(os_id)
55
+ other = @other
56
+ other&.usable? ? other.present?(os_id) : false
57
+ rescue Error
58
+ false
59
+ end
60
+ end
61
+ end
62
+ end
63
+ end
@@ -0,0 +1,178 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'fileutils'
4
+ require 'securerandom'
5
+ require_relative 'command_runner'
6
+ require_relative '../schedule'
7
+
8
+ module RubyRaider
9
+ module Flows
10
+ module Os
11
+ # Linux: a oneshot service and a persistent timer per schedule in the user's systemd folder, enabled
12
+ # with systemctl --user. Words in ExecStart= and Environment= are double-quoted with C escapes; every
13
+ # value has % doubled (specifiers) and ExecStart= also has $ doubled (variable expansion).
14
+ # :reek:TooManyConstants { max_constants: 6 } -- the tool, NOFOLLOW, the escapes, the calendar days, the os_id and path rules
15
+ class Systemd
16
+ SYSTEMCTL = 'systemctl'
17
+ NOFOLLOW = defined?(File::NOFOLLOW) ? File::NOFOLLOW : 0
18
+ QUOTED = { '\\' => '\\\\', '"' => '\\"', '%' => '%%' }.freeze
19
+ CALENDAR = { 'hour' => '', 'day' => '', 'weekday' => 'Mon..Fri ' }.freeze
20
+ OS_ID = /\A#{Regexp.escape(Schedule::OS_ID_PREFIX)}\.[0-9a-f]{10}\.([a-z0-9_]{1,60})\z/
21
+ # The unit parser strips whitespace at the ends of a value and reads a trailing backslash as "continued"
22
+ UNSAFE_PATH = /\s\z|\\\z/
23
+
24
+ def initialize(runner: CommandRunner.new, home: Dir.home, config_home: ENV.fetch('XDG_CONFIG_HOME', nil))
25
+ @runner = runner
26
+ @home = home
27
+ @config_home = config_home
28
+ end
29
+
30
+ def label = 'systemd'
31
+
32
+ def missed_runs_note = nil
33
+
34
+ def service(schedule)
35
+ env = schedule.env.map { |key, value| "Environment=#{quote("#{key}=#{value}")}" }
36
+ exec = schedule.argv.map { |arg| quote(arg.gsub('$', '$$')) }.join(' ')
37
+ log = specifiers(schedule.log_path)
38
+ <<~UNIT
39
+ [Unit]
40
+ Description=raider flow #{schedule.name}
41
+
42
+ [Service]
43
+ Type=oneshot
44
+ WorkingDirectory=#{specifiers(schedule.working_directory)}
45
+ #{env.join("\n")}
46
+ ExecStart=#{exec}
47
+ StandardOutput=append:#{log}
48
+ StandardError=append:#{log}
49
+ UNIT
50
+ end
51
+
52
+ # Local time; Persistent= runs a missed time once the user manager is back
53
+ def timer(schedule)
54
+ every = schedule.every
55
+ day = CALENDAR.fetch(every) { "#{schedule.on.to_s.capitalize} " }
56
+ hour = every == 'hour' ? '*' : format('%02d', schedule.hour)
57
+ <<~UNIT
58
+ [Unit]
59
+ Description=raider flow #{schedule.name} schedule
60
+
61
+ [Timer]
62
+ OnCalendar=#{day}*-*-* #{hour}:#{format('%02d', schedule.minute)}:00
63
+ Persistent=true
64
+
65
+ [Install]
66
+ WantedBy=timers.target
67
+ UNIT
68
+ end
69
+
70
+ def unit_path(os_id, kind) = File.join(units_dir, "#{checked_os_id(os_id)}.#{kind}")
71
+
72
+ # Writes both units (temp files renamed into place), reloads and enables the timer; a failure leaves no unit behind
73
+ def install(schedule)
74
+ os_id = schedule.os_id
75
+ [schedule.working_directory, schedule.log_path].each { |path| checked_path(path) }
76
+ write({ unit_path(os_id, 'service') => service(schedule), unit_path(os_id, 'timer') => timer(schedule) })
77
+ failure = [systemctl('daemon-reload'), systemctl('enable', '--now', "#{os_id}.timer")].find { |result| !result.success? }
78
+ return true unless failure
79
+
80
+ message = "systemd could not enable #{os_id}: #{Flows.printable(failure.stderr.strip)}"
81
+ raise Error, "#{message}#{discard(os_id)}"
82
+ end
83
+
84
+ # True when a unit file was removed, false when it was already gone
85
+ def remove(os_id)
86
+ paths = %w[service timer].map { |kind| unit_path(os_id, kind) }
87
+ systemctl('disable', '--now', "#{os_id}.timer")
88
+ removed = paths.map { |path| unlink(path) }.any?
89
+ reload = systemctl('daemon-reload')
90
+ raise Error, "systemd could not reload after removing #{os_id}: #{Flows.printable(reload.stderr.strip)}" unless reload.success?
91
+
92
+ removed
93
+ end
94
+
95
+ def present?(os_id) = systemctl('is-enabled', "#{checked_os_id(os_id)}.timer").success?
96
+
97
+ # True when a unit file for the schedule is on disk (no user manager needed)
98
+ def unit_files?(os_id) = %w[service timer].any? { |kind| File.exist?(unit_path(os_id, kind)) }
99
+
100
+ # True when the user's systemd manager answers
101
+ def usable? = systemctl('show-environment').success?
102
+
103
+ private
104
+
105
+ def systemctl(*args) = @runner.call(SYSTEMCTL, '--user', *args)
106
+
107
+ def units_dir
108
+ config = @config_home
109
+ base = config.is_a?(String) && File.absolute_path?(config) ? config : File.join(@home, '.config')
110
+ File.join(base, 'systemd', 'user')
111
+ end
112
+
113
+ def checked_os_id(os_id)
114
+ return os_id if os_id.is_a?(String) && (match = OS_ID.match(os_id)) && Flows.valid_name?(match[1])
115
+
116
+ raise Error, "Invalid os_id #{Flows.printable(os_id.inspect)}: not a flow schedule"
117
+ end
118
+
119
+ def checked_path(path)
120
+ raise Error, "systemd can not use the path #{Flows.printable(path.inspect)}: it ends in whitespace or a backslash" if UNSAFE_PATH.match?(path)
121
+ end
122
+
123
+ # A word systemd gives back exactly: double quotes, \\ and \" escapes, %% for %
124
+ def quote(text) = %("#{text.gsub(/[\\"%]/, QUOTED)}")
125
+
126
+ # A raw path value: only specifiers apply
127
+ def specifiers(text) = text.gsub('%', '%%')
128
+
129
+ # True when the file was there; a unit that stays behind is an error, not "already gone"
130
+ def unlink(path)
131
+ File.unlink(path)
132
+ true
133
+ rescue Errno::ENOENT
134
+ false
135
+ rescue SystemCallError => e
136
+ raise Error, "Could not remove #{path}: #{e.message}"
137
+ end
138
+
139
+ # Disables the timer, removes both units and reloads; returns what to add to the error when that fails too
140
+ def discard(os_id)
141
+ systemctl('disable', "#{os_id}.timer")
142
+ %w[service timer].each { |kind| unlink(unit_path(os_id, kind)) }
143
+ reload = systemctl('daemon-reload')
144
+ reload.success? ? '' : "; also: reload failed: #{Flows.printable(reload.stderr.strip)}"
145
+ rescue Error => e
146
+ "; also: #{e.message}"
147
+ end
148
+
149
+ # Every temp file is written before any unit is replaced, so a failed write changes nothing
150
+ def write(texts)
151
+ temps = {}
152
+ texts.each { |path, text| temps[path] = temp_file(path, text) }
153
+ temps.each { |path, temp| File.rename(temp, path) }
154
+ rescue SystemCallError => e
155
+ raise Error, "Could not write the systemd units in #{units_dir}: #{e.message}"
156
+ ensure
157
+ temps&.each_value { |temp| FileUtils.rm_f(temp) if File.exist?(temp) }
158
+ end
159
+
160
+ def temp_file(path, text)
161
+ dir = File.dirname(path)
162
+ FileUtils.mkdir_p(dir)
163
+ temp = File.join(dir, ".#{File.basename(path)}.#{SecureRandom.hex(6)}.tmp")
164
+ File.open(temp, File::WRONLY | File::CREAT | File::EXCL | NOFOLLOW, 0o644) do |file|
165
+ file.write(text)
166
+ file.flush
167
+ file.fsync
168
+ file.chmod(0o644)
169
+ end
170
+ temp
171
+ rescue SystemCallError
172
+ FileUtils.rm_f(temp) if temp && File.file?(temp)
173
+ raise
174
+ end
175
+ end
176
+ end
177
+ end
178
+ end