Module: Pgpass

Defined in:
lib/pgpass.rb,
lib/pgpass/version.rb

Defined Under Namespace

Classes: Entry

Constant Summary collapse

LOCATIONS =
[ENV['PGPASSFILE'], './.pgpass', '~/.pgpass']
VERSION =
"2012.01"

Class Method Summary collapse

Class Method Details

.guess(paths = PATH) ⇒ Object



130
131
132
133
134
135
136
137
138
# File 'lib/pgpass.rb', line 130

def guess(paths = PATH)
  PATH.each do |path|
    begin
      load_file(File.join(path, ".pgpass"))
    rescue Errno::ENOENT => ex
      warn(ex)
    end
  end
end

.load(io) ⇒ Object



144
145
146
# File 'lib/pgpass.rb', line 144

def load(io)
  io.each_line.map{|line| parse_line(line) }
end

.load_file(path) ⇒ Object



140
141
142
# File 'lib/pgpass.rb', line 140

def load_file(path)
  File.open(File.expand_path(path), 'r'){|io| load(io) }
end

.match(given_options = {}) ⇒ Object



107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/pgpass.rb', line 107

def match(given_options = {})
  search = Entry.create(
    user:     (ENV['PGUSER'] || '*'),
    password: ENV['PGPASSWORD'],
    host:     (ENV['PGHOST'] || '*'),
    port:     (ENV['PGPORT'] || '*'),
    database: (ENV['PGDATABASE'] || '*'),
  ).merge(given_options)

  LOCATIONS.compact.each do |path|
    # consider only files
    next unless File.file?(path)
    # that aren't world/group accessible
    next unless File.stat(path).mode & 077 == 0

    load_file(path).each do |entry|
      return entry.complement(search) if entry == search
    end
  end

  nil
end

.parse_line(line) ⇒ Object



148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# File 'lib/pgpass.rb', line 148

def parse_line(line)
  sc = StringScanner.new(line)
  entry = Entry.new
  key_index = 0
  value = ''

  loop do
    pos = sc.pos

    if sc.bol?
      if sc.scan(/\s*#/)
        # commented line
        return
      elsif sc.scan(/\s*$/)
        # empty line
        return
      end
    end

    if sc.eos?
      entry[Entry.members[key_index]] = value
      return entry # end of string
    end

    if sc.scan(/\\:/)
      value << ':'
    elsif sc.scan(/\\\\/)
      value << '\\'
    elsif sc.scan(/:/)
      entry[Entry.members[key_index]] = value
      key_index += 1
      value = ''
    elsif sc.scan(/\r\n|\r|\n/)
      entry[Entry.members[key_index]] = value
      return entry
    elsif sc.scan(/./)
      value << sc[0]
    end

    if sc.pos == pos
      raise "position didn't advance, stuck in parsing"
    end
  end

  return entry
end