-
Notifications
You must be signed in to change notification settings - Fork 0
/
connectionstring.go
74 lines (64 loc) · 1.53 KB
/
connectionstring.go
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
/*
* Copyright (c) 2022, Gideon Williams <gideon@gideonw.com>
* Copyright (c) 2023, Dana Burkart <dana.burkart@gmail.com>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
package proto
import (
"errors"
"fmt"
"net/url"
"path"
)
var Protocol = "fossil"
type ConnectionString struct {
Local bool
Address string
Database string
}
// ParseConnectionString takes a connection string and parses it into the parts
// the application needs to make a connection. This function will always parse,
// even horribly malformed connection strings. It will only return an error if
// the protocol is not "fossil" or "file"
//
// Formats:
//
// ./path/to/local/db
// file://./path/to/local/db
// fossil://<host:port>[/<db_name>]
func ParseConnectionString(connStr string) (ConnectionString, error) {
ret := ConnectionString{
Local: true,
Address: "local",
Database: "default",
}
if connStr == "" {
connStr = "./"
}
u, err := url.Parse(connStr)
if err != nil {
return ConnectionString{}, err
}
// Handle the local case
if u.Scheme == "" || u.Scheme == "file" {
ret.Database = u.Path
return ret, nil
}
if u.Scheme == "fossil" {
ret.Local = false
ret.Address = u.Host
d, p := path.Split(u.Path)
if d == "" && p == "" {
ret.Database = "default"
} else if d != "/" {
return ConnectionString{}, errors.New(fmt.Sprintf("invalid database %s", u.Path))
}
if p == "" {
p = "default"
}
ret.Database = p
return ret, nil
}
return ConnectionString{}, errors.New(fmt.Sprintf("unrecognized scheme: %s", u.Scheme))
}