Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,22 @@ You can install RIDLFMT using `go install`:
go install github.com/webrpc/ridlfmt@latest
```

## REST routes

A method can declare zero or more REST routes with `+ VERB /path` lines.
Routes use absolute paths, and `basepath` at the top level sets the shared prefix.

```ridl
basepath = /v1

service Intents
- CommitIntent(CommitIntentRequest) => (CommitIntentResponse)
+ POST /intents/{intentId}
+ POST /Intents/CommitIntent # backward-compatible with pre-REST API route.
```

RIDLFMT normalizes the route to ` + POST /intents/{intentId}` and keeps the routes in their written order.

## Setting in IDE

### VSCode
Expand Down
126 changes: 114 additions & 12 deletions formatter/formatter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,10 @@ version = v1
basepath = /api

service Users
path = /users # REST prefix
- Get(GetUserRequest) => (GetUserResponse)
GET /{userId} # by id
+ GET /{userId} # by id
- List(ListUsersRequest) => (ListUsersResponse)
QUERY /search
+QUERY /search
- Ping()

struct GetUserRequest
Expand All @@ -50,11 +49,10 @@ version = v1
basepath = /api

service Users
path = /users # REST prefix
- Get(GetUserRequest) => (GetUserResponse)
GET /{userId} # by id
+ GET /{userId} # by id
- List(ListUsersRequest) => (ListUsersResponse)
QUERY /search
+ QUERY /search
- Ping()

struct GetUserRequest
Expand All @@ -71,6 +69,116 @@ struct GetUserRequest
assert.Equal(t, output, again)
}

func TestFormat_MultipleRoutesKeepOrder(t *testing.T) {
input := `webrpc = v1

service Intents
- CommitIntent(CommitIntentRequest) => (CommitIntentResponse)
+ POST /intents/{intentId} # REST
+ POST /Intents/CommitIntent # backward-compatible with pre-REST API route.
+ GET /intents/{intentId}
- Ping()
`
expected := `webrpc = v1

service Intents
- CommitIntent(CommitIntentRequest) => (CommitIntentResponse)
+ POST /intents/{intentId} # REST
+ POST /Intents/CommitIntent # backward-compatible with pre-REST API route.
+ GET /intents/{intentId}
- Ping()
`

output, err := Format(strings.NewReader(input), false)
require.NoError(t, err)
assert.Equal(t, expected, output)

again, err := Format(strings.NewReader(output), false)
require.NoError(t, err)
assert.Equal(t, output, again)
}

func TestFormat_RouteWithMetaLines(t *testing.T) {
input := `webrpc = v1

error 1 Unauthorized "unauthorized" HTTP 401

service Users
- Get(GetUserRequest) => (GetUserResponse)
+ json=id
+ go.field.name = ID
+ GET /users/{id}
+ json = id # trailing
- Ping()
`
expected := `webrpc = v1

error 1 Unauthorized "unauthorized" HTTP 401

service Users
- Get(GetUserRequest) => (GetUserResponse)
+ json = id
+ go.field.name = ID
+ GET /users/{id}
+ json = id # trailing
- Ping()
`

output, err := Format(strings.NewReader(input), false)
require.NoError(t, err)
assert.Equal(t, expected, output)

again, err := Format(strings.NewReader(output), false)
require.NoError(t, err)
assert.Equal(t, output, again)
}

func TestFormat_RouteLikeLineOutsideService(t *testing.T) {
output, err := Format(strings.NewReader("webrpc = v1\n+ GET /users\n"), false)
require.NoError(t, err)
assert.Equal(t, "webrpc = v1\n + GET /users\n", output)
}

func TestFormat_NotARoute(t *testing.T) {
input := `webrpc = v1

service Users
- Ping()
+ FOO /x
+ GET x
+ GET
+ json = /x
`
expected := `webrpc = v1

service Users
- Ping()
+ FOO /x
+ GET x
+ GET
+ json = /x
`

output, err := Format(strings.NewReader(input), false)
require.NoError(t, err)
assert.Equal(t, expected, output)
}

func TestFormat_OldRouteSyntaxRejected(t *testing.T) {
tests := map[string]string{
"service path": "webrpc = v1\n\nservice Users\n path = /users\n",
"bare route line": "webrpc = v1\n\nservice Users\n - Ping()\n GET /x\n",
}

for name, input := range tests {
t.Run(name, func(t *testing.T) {
_, err := Format(strings.NewReader(input), false)
require.Error(t, err)
assert.ErrorContains(t, err, "unknown section")
})
}
}

func TestFormat_ErrorWithoutHTTPStatus(t *testing.T) {
input := `webrpc = v1

Expand All @@ -87,9 +195,3 @@ error 200 UserNotFound "user not found" # defaults to HTTP 400
require.NoError(t, err)
assert.Equal(t, expected, output)
}

func TestFormat_RouteLikeLineOutsideService(t *testing.T) {
_, err := Format(strings.NewReader("webrpc = v1\nGET /users\n"), false)
require.Error(t, err)
assert.ErrorContains(t, err, "unknown section")
}
38 changes: 8 additions & 30 deletions formatter/processor.go
Original file line number Diff line number Diff line change
Expand Up @@ -251,25 +251,11 @@ func (f *form) formatLine(line string) (string, error) {

line = fmt.Sprintf("%s%s", strings.Repeat(" ", f.padding), line)
line = c.appendInlineComment(line)
case sectionServicePath:
f.padding = 2
s, c := parseAndDivideInlineComment(line)
parts := strings.Split(s, "=")
if len(parts) != 2 {
return "", fmt.Errorf("unexpected amount of parts=(%d) %s", len(parts), line)
}

line = fmt.Sprintf("%spath = %s", strings.Repeat(" ", f.padding), removeSpaces(parts[1]))
line = c.appendInlineComment(line)
case sectionRoute:
f.padding = 6
f.padding = 4
s, c := parseAndDivideInlineComment(line)
parts := strings.Fields(s)
if len(parts) != 2 {
return "", fmt.Errorf("unexpected amount of parts=(%d) %s", len(parts), line)
}

line = fmt.Sprintf("%s%s %s", strings.Repeat(" ", f.padding), parts[0], parts[1])
parts := strings.Fields(strings.TrimPrefix(s, "+"))
line = fmt.Sprintf("%s+ %s %s", strings.Repeat(" ", f.padding), parts[0], parts[1])
line = c.appendInlineComment(line)
case sectionAnnotation:
f.padding = 4
Expand Down Expand Up @@ -329,10 +315,6 @@ func (f *form) parseSection(line string) {
case strings.HasPrefix(line, "basepath"):
f.section = sectionBasepath
f.topLvlSection = sectionBasepath
case f.topLvlSection == sectionService && isServicePathLine(line):
f.section = sectionServicePath
case f.topLvlSection == sectionService && isRouteLine(line):
f.section = sectionRoute
case strings.HasPrefix(line, "import"):
f.section = sectionImport
f.topLvlSection = sectionImport
Expand All @@ -352,6 +334,8 @@ func (f *form) parseSection(line string) {
f.topLvlSection = sectionError
case strings.HasPrefix(line, "-"):
f.section = sectionField
case strings.HasPrefix(line, "+") && f.topLvlSection == sectionService && isRouteLine(line):
f.section = sectionRoute
case strings.HasPrefix(line, "+"):
f.section = sectionTag
case strings.HasPrefix(line, "@"):
Expand Down Expand Up @@ -534,14 +518,8 @@ func findComma(ic int, s string) (int, bool) {

var routeVerbs = []string{"GET", "POST", "PUT", "PATCH", "DELETE", "QUERY"}

// isServicePathLine matches a service's REST path prefix, e.g. "path = /users".
func isServicePathLine(line string) bool {
rest, ok := strings.CutPrefix(line, "path")
return ok && strings.HasPrefix(strings.TrimSpace(rest), "=")
}

// isRouteLine matches a method's REST route, e.g. "GET /{userId}".
// isRouteLine matches a method's REST route tag, e.g. "+ GET /{userId}".
func isRouteLine(line string) bool {
verb, rest, ok := strings.Cut(line, " ")
return ok && strings.HasPrefix(strings.TrimSpace(rest), "/") && slices.Contains(routeVerbs, verb)
parts := strings.Fields(strings.TrimPrefix(line, "+"))
return len(parts) >= 2 && slices.Contains(routeVerbs, parts[0]) && strings.HasPrefix(parts[1], "/")
}
1 change: 0 additions & 1 deletion formatter/section.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,5 @@ const (
sectionImport
sectionAnnotation
sectionBasepath
sectionServicePath
sectionRoute
)
Loading