Module: Wheneverd::Systemd::UnitPathUtils

Defined in:
lib/wheneverd/systemd/unit_path_utils.rb

Overview

Shared utilities for unit file path operations.

These methods are used by UnitWriter, UnitDeleter, UnitLister, and Renderer to ensure consistent identifier sanitization, path pattern matching, and marker detection.

Class Method Summary collapse

Class Method Details

.basename_pattern(identifier) ⇒ Regexp

Returns a regex pattern matching unit basenames for the given identifier.

Matches both new-style (SHA-based) and legacy (eN-jN) unit names.

Parameters:

  • identifier (String)

Returns:

  • (Regexp)


37
38
39
40
# File 'lib/wheneverd/systemd/unit_path_utils.rb', line 37

def self.basename_pattern(identifier)
  id = sanitize_identifier(identifier)
  /\Awheneverd-#{Regexp.escape(id)}-(?:[0-9a-f]{12}(?:-\d+)?|e\d+-j\d+)\.(service|timer)\z/
end

.generated_marker?(path) ⇒ Boolean

Checks if a unit file was generated by wheneverd.

Reads the first line of the file and checks for the marker prefix.

Parameters:

  • path (String)

    path to the unit file

Returns:

  • (Boolean)


48
49
50
51
# File 'lib/wheneverd/systemd/unit_path_utils.rb', line 48

def self.generated_marker?(path)
  first_line = File.open(path, "r") { |f| f.gets.to_s }
  first_line.start_with?(Wheneverd::Systemd::Renderer::MARKER_PREFIX)
end

.sanitize_identifier(identifier) ⇒ String

Sanitizes an identifier for use in unit file names.

Invalid characters are replaced with -, and consecutive/leading/trailing dashes are collapsed or removed.

Parameters:

  • identifier (String)

Returns:

  • (String)

Raises:



18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/wheneverd/systemd/unit_path_utils.rb', line 18

def self.sanitize_identifier(identifier)
  raw = identifier.to_s.strip
  raise InvalidIdentifierError, "identifier must not be empty" if raw.empty?

  sanitized = raw.gsub(/[^A-Za-z0-9_-]/, "-").gsub(/-+/, "-").gsub(/\A-|-+\z/, "")
  if sanitized.empty?
    raise InvalidIdentifierError,
          "identifier must include at least one alphanumeric character"
  end

  sanitized
end