|
1 | 1 | package drivers |
2 | 2 |
|
3 | | -import "fmt" |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "os" |
| 6 | + "os/exec" |
| 7 | + "path/filepath" |
| 8 | + "strings" |
| 9 | +) |
4 | 10 |
|
5 | 11 | // registeredDrivers are all the drivers which are currently registered |
6 | 12 | var registeredDrivers = map[string]Interface{} |
@@ -34,3 +40,51 @@ func register(name string, driver Interface) { |
34 | 40 |
|
35 | 41 | registeredDrivers[name] = driver |
36 | 42 | } |
| 43 | + |
| 44 | +// RegisterBinaryFromCmdArg is used to register drivers from a command line argument |
| 45 | +// The argument is either just the driver name or a path to a specific driver |
| 46 | +// Panics if a driver with the same name has been previously loaded. |
| 47 | +func RegisterBinaryFromCmdArg(arg string) (name, path string, err error) { |
| 48 | + path, err = getFullPath(arg) |
| 49 | + if err != nil { |
| 50 | + return name, path, err |
| 51 | + } |
| 52 | + |
| 53 | + name = getNameFromPath(path) |
| 54 | + |
| 55 | + RegisterBinary(name, path) |
| 56 | + |
| 57 | + return name, path, nil |
| 58 | +} |
| 59 | + |
| 60 | +// Get the full path to the driver binary from the given path |
| 61 | +// the path can also be just the driver name e.g. "psql" |
| 62 | +func getFullPath(path string) (string, error) { |
| 63 | + var err error |
| 64 | + |
| 65 | + if strings.ContainsRune(path, os.PathSeparator) { |
| 66 | + return path, nil |
| 67 | + } |
| 68 | + |
| 69 | + path, err = exec.LookPath("sqlboiler-" + path) |
| 70 | + if err != nil { |
| 71 | + return path, fmt.Errorf("could not find driver executable: %w", err) |
| 72 | + } |
| 73 | + |
| 74 | + path, err = filepath.Abs(path) |
| 75 | + if err != nil { |
| 76 | + return path, fmt.Errorf("could not find absolute path to driver: %w", err) |
| 77 | + } |
| 78 | + |
| 79 | + return path, nil |
| 80 | +} |
| 81 | + |
| 82 | +// Get the driver name from the path. |
| 83 | +// strips the "sqlboiler-" prefix if it exists |
| 84 | +// strips the ".exe" suffix if it exits |
| 85 | +func getNameFromPath(name string) string { |
| 86 | + name = strings.Replace(filepath.Base(name), "sqlboiler-", "", 1) |
| 87 | + name = strings.Replace(name, ".exe", "", 1) |
| 88 | + |
| 89 | + return name |
| 90 | +} |
0 commit comments