File: procfile.rb

package info (click to toggle)
ruby-foreman 0.90.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 584 kB
  • sloc: ruby: 2,020; sh: 88; makefile: 8
file content (100 lines) | stat: -rw-r--r-- 2,028 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
require "foreman"

# Reads and writes Procfiles
#
# A valid Procfile entry is captured by this regex:
#
#   /^([A-Za-z0-9_-]+):\s*(.+)$/
#
# All other lines are ignored.
#
class Foreman::Procfile

  EmptyFileError = Class.new(StandardError)

  # Initialize a Procfile
  #
  # @param [String] filename (nil)  An optional filename to read from
  #
  def initialize(filename=nil)
    @entries = []
    load(filename) if filename
  end

  # Yield each +Procfile+ entry in order
  #
  def entries
    @entries.each do |(name, command)|
      yield name, command
    end
  end

  # Retrieve a +Procfile+ command by name
  #
  # @param [String] name  The name of the Procfile entry to retrieve
  #
  def [](name)
    if entry = @entries.detect { |n,c| name == n }
      entry.last
    end
  end

  # Create a +Procfile+ entry
  #
  # @param [String] name     The name of the +Procfile+ entry to create
  # @param [String] command  The command of the +Procfile+ entry to create
  #
  def []=(name, command)
    delete name
    @entries << [name, command]
  end

  # Remove a +Procfile+ entry
  #
  # @param [String] name  The name of the +Procfile+ entry to remove
  #
  def delete(name)
    @entries.reject! { |n,c| name == n }
  end

  # Load a Procfile from a file
  #
  # @param [String] filename  The filename of the +Procfile+ to load
  #
  def load(filename)
    parse_data = parse(filename)

    raise EmptyFileError if parse_data.empty?

    @entries.replace parse_data
  end

  # Save a Procfile to a file
  #
  # @param [String] filename  Save the +Procfile+ to this file
  #
  def save(filename)
    File.open(filename, 'w') do |file|
      file.puts self.to_s
    end
  end

  # Get the +Procfile+ as a +String+
  #
  def to_s
    @entries.map do |name, command|
      [ name, command ].join(": ")
    end.join("\n")
  end

private

  def parse(filename)
    File.read(filename).gsub("\r\n","\n").split("\n").map do |line|
      if line =~ /^([A-Za-z0-9_-]+):\s*(.+)$/
        [$1, $2]
      end
    end.compact
  end

end