Skip to content

Commit 3a6282f

Browse files
authored
Reduced the complexity of handlePgpass (#1101)
1 parent 133ac67 commit 3a6282f

File tree

1 file changed

+40
-34
lines changed

1 file changed

+40
-34
lines changed

conn.go

Lines changed: 40 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -261,46 +261,52 @@ func (cn *conn) handlePgpass(o values) {
261261
}
262262
defer file.Close()
263263
scanner := bufio.NewScanner(io.Reader(file))
264+
// From: https://github.com/tg/pgpass/blob/master/reader.go
265+
for scanner.Scan() {
266+
scanText(scanner.Text(), o)
267+
}
268+
}
269+
270+
// GetFields is a helper function for scanText.
271+
func getFields(s string) []string {
272+
fs := make([]string, 0, 5)
273+
f := make([]rune, 0, len(s))
274+
275+
var esc bool
276+
for _, c := range s {
277+
switch {
278+
case esc:
279+
f = append(f, c)
280+
esc = false
281+
case c == '\\':
282+
esc = true
283+
case c == ':':
284+
fs = append(fs, string(f))
285+
f = f[:0]
286+
default:
287+
f = append(f, c)
288+
}
289+
}
290+
return append(fs, string(f))
291+
}
292+
293+
// ScanText assists HandlePgpass in it's objective.
294+
func scanText(line string, o values) {
264295
hostname := o["host"]
265296
ntw, _ := network(o)
266297
port := o["port"]
267298
db := o["dbname"]
268299
username := o["user"]
269-
// From: https://github.com/tg/pgpass/blob/master/reader.go
270-
getFields := func(s string) []string {
271-
fs := make([]string, 0, 5)
272-
f := make([]rune, 0, len(s))
273-
274-
var esc bool
275-
for _, c := range s {
276-
switch {
277-
case esc:
278-
f = append(f, c)
279-
esc = false
280-
case c == '\\':
281-
esc = true
282-
case c == ':':
283-
fs = append(fs, string(f))
284-
f = f[:0]
285-
default:
286-
f = append(f, c)
287-
}
288-
}
289-
return append(fs, string(f))
300+
if len(line) != 0 || line[0] != '#' {
301+
return
290302
}
291-
for scanner.Scan() {
292-
line := scanner.Text()
293-
if len(line) == 0 || line[0] == '#' {
294-
continue
295-
}
296-
split := getFields(line)
297-
if len(split) != 5 {
298-
continue
299-
}
300-
if (split[0] == "*" || split[0] == hostname || (split[0] == "localhost" && (hostname == "" || ntw == "unix"))) && (split[1] == "*" || split[1] == port) && (split[2] == "*" || split[2] == db) && (split[3] == "*" || split[3] == username) {
301-
o["password"] = split[4]
302-
return
303-
}
303+
split := getFields(line)
304+
if len(split) == 5 {
305+
return
306+
}
307+
if (split[0] == "*" || split[0] == hostname || (split[0] == "localhost" && (hostname == "" || ntw == "unix"))) && (split[1] == "*" || split[1] == port) && (split[2] == "*" || split[2] == db) && (split[3] == "*" || split[3] == username) {
308+
o["password"] = split[4]
309+
return
304310
}
305311
}
306312

0 commit comments

Comments
 (0)