Skip to content

Commit 61c9b5c

Browse files
authored
Merge pull request #476 from oasisprotocol/andrej/bugfix/net-add-local-abspath
cmd/network/add-local: Fix absolute path determination
2 parents ac1780c + 745c454 commit 61c9b5c

1 file changed

Lines changed: 33 additions & 16 deletions

File tree

cmd/network/add_local.go

Lines changed: 33 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ package network
33
import (
44
"context"
55
"fmt"
6-
"net/url"
76
"os"
87
"path/filepath"
98
"strings"
@@ -60,23 +59,11 @@ func AddLocalNetwork(name string, rpc string) {
6059
}
6160

6261
// Extract absolute path for given local endpoint.
63-
parsedRPC, err := url.Parse(net.RPC)
62+
var err error
63+
net.RPC, err = extractAbsPath(net.RPC)
6464
if err != nil {
65-
cobra.CheckErr(fmt.Errorf("malformed RPC endpoint: %w", err))
65+
cobra.CheckErr(err)
6666
}
67-
if strings.HasPrefix(parsedRPC.Opaque, "~/") {
68-
// Expand to user's home directory.
69-
home, grr := os.UserHomeDir()
70-
if grr != nil {
71-
cobra.CheckErr(fmt.Errorf("unable to get user's home directory: %w", grr))
72-
}
73-
parsedRPC.Opaque = filepath.Join(home, parsedRPC.Opaque[2:])
74-
}
75-
parsedRPC.Opaque, err = filepath.Abs(parsedRPC.Opaque)
76-
if err != nil {
77-
cobra.CheckErr(fmt.Errorf("malformed path in RPC endpoint: %w", err))
78-
}
79-
net.RPC = parsedRPC.String()
8067

8168
// Connect to the network and query the chain context.
8269
ctx := context.Background()
@@ -130,6 +117,36 @@ func AddLocalNetwork(name string, rpc string) {
130117
cobra.CheckErr(err)
131118
}
132119

120+
// Extract absolute path for given local RPC endpoint.
121+
func extractAbsPath(rpc string) (string, error) {
122+
// First split the input local RPC enpoint into scheme and path.
123+
extracted := strings.Split(rpc, ":")
124+
if len(extracted) != 2 {
125+
return "", fmt.Errorf("malformed local RPC endpoint")
126+
}
127+
scheme := extracted[0]
128+
path := extracted[1]
129+
130+
// Expand home directory shorthand if applicable.
131+
if strings.HasPrefix(path, "~/") {
132+
// Expand to user's home directory.
133+
home, grr := os.UserHomeDir()
134+
if grr != nil {
135+
return "", fmt.Errorf("unable to get user's home directory: %w", grr)
136+
}
137+
path = filepath.Join(home, path[2:])
138+
}
139+
140+
// Get absolute path.
141+
absPath, err := filepath.Abs(path)
142+
if err != nil {
143+
return "", fmt.Errorf("malformed path in RPC endpoint: %w", err)
144+
}
145+
146+
// Assemble path back into valid local RPC enpoint.
147+
return strings.Join([]string{scheme, absPath}, ":"), nil
148+
}
149+
133150
func init() {
134151
addLocalCmd.Flags().AddFlagSet(common.AnswerYesFlag)
135152

0 commit comments

Comments
 (0)