Module: Do::UnitGenerator

Defined in:
lib/do/systemd.rb

Overview

Generates the systemd user unit files that do manages, and wraps the systemctl --user / journalctl --user commands used to control them.

Generated unit files carry a clear "Managed by do" marker so they can be safely detected, updated, and removed later. Units not carrying this marker are never touched by do.

Constant Summary collapse

MANAGED_MARKER =
'# Managed by do. Do not edit by hand.'.freeze

Class Method Summary collapse

Class Method Details

.managed_header(source_path) ⇒ Object



66
67
68
69
70
# File 'lib/do/systemd.rb', line 66

def managed_header(source_path)
  lines = [MANAGED_MARKER]
  lines << "# Source: #{source_path}" if source_path
  lines.join("\n")
end

.service_content(task, source_path: nil) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/do/systemd.rb', line 16

def service_content(task, source_path: nil)
  env_lines = task.environment.map { |k, v| "Environment=#{k}=#{v}" }
  [
    managed_header(source_path),
    '',
    '[Unit]',
    "Description=do task: #{task.name}",
    '',
    '[Service]',
    'Type=oneshot',
    "ExecStart=#{task.command}"
  ].concat(
    if task.working_directory
      ["WorkingDirectory=#{task.working_directory}"]
    else
      []
    end
  ).concat(
    env_lines,
    ['', '[Install]', 'WantedBy=default.target']
  ).join("\n") + "\n"
end

.timer_content(task, source_path: nil) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/do/systemd.rb', line 39

def timer_content(task, source_path: nil)
  on_calendar = Scheduler.on_calendar(task)
  calendar_line =
    if on_calendar&.start_with?('OnActiveSec=')
      on_calendar
    else
      "OnCalendar=#{on_calendar}"
    end
  [
    managed_header(source_path),
    '',
    '[Unit]',
    "Description=do task: #{task.name} (timer)",
    '',
    '[Timer]',
    calendar_line
  ].concat(
    if task.schedule == 'once'
      []
    else
      ['Persistent=true']
    end
  ).push(
    '', '[Install]', 'WantedBy=timers.target'
  ).join("\n") + "\n"
end