jmsperu opened a new pull request, #152:
URL: https://github.com/apache/cloudstack-go/pull/152
Fixes #103.
### Problem
The generated `Get<Entity>ID` / `Get<Entity>ByID` helpers index the result
slice at `[0]` as soon as `Count == 1`, without checking that the slice is
actually non-empty:
```go
if l.Count == 1 {
return l.VirtualMachinesMetrics[0].Id, l.Count, nil
}
```
When the backend reports `count >= 1` but returns an empty list — a
count/slice mismatch that occurs e.g. on the metrics APIs — this panics:
```
panic: runtime error: index out of range [0] with length 0
```
This is the panic reported in #103 (it surfaced via CAPC calling
`GetVirtualMachinesMetricID`). As @rajeshvenkata suggested in the issue, the
helper should check the slice before accessing it.
### Fix
The helpers are generated, so the root-cause fix is in the generator
template (`generate/generate.go`, both the `Get<Entity>ID` and
`Get<Entity>ByID` emitters). A length guard is emitted before the `[0]` access,
returning the same `No match found` error already used for the `count == 0`
case. The guard is then applied to the generated helpers — **additive only**
(212 guards across 64 files; no other lines change), so the diff stays
reviewable and a future regeneration reproduces it.
### Test
Adds `test/GetMetricIDRegression_test.go`, a self-contained regression test
that serves `{"count":1,"virtualmachine":[]}` and asserts
`GetVirtualMachinesMetricID` returns an error rather than panicking. It
**panics on the unpatched code** (reproducing #103) and **passes with the
guard**.
### Verification
- `go build ./...` — clean
- `go test ./test/ -run
TestGetVirtualMachinesMetricIDEmptyListWithNonZeroCount` — passes (and fails
with the exact `index out of range [0]` panic when the guard is reverted)
### Note
The count/empty-list mismatch this guards against is the same family as the
metrics JSON-tag issues (#135/#136, PR #137): when a response key does not
match the struct tag, `count` parses but the slice is `nil`. This guard makes
the helpers robust to that regardless of root cause.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]