Skip to content

Commit

Permalink
Fix merge objects
Browse files Browse the repository at this point in the history
  • Loading branch information
nekohasekai committed Feb 10, 2025
1 parent 8dff604 commit 3464ed3
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 6 deletions.
10 changes: 4 additions & 6 deletions common/json/badjson/merge_objects.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ package badjson

import (
"context"
"reflect"

E "github.com/sagernet/sing/common/exceptions"
"github.com/sagernet/sing/common/json"
cJSON "github.com/sagernet/sing/common/json/internal/contextjson"
)

func MarshallObjects(objects ...any) ([]byte, error) {
Expand All @@ -31,16 +33,12 @@ func UnmarshallExcluded(inputContent []byte, parentObject any, object any) error
}

func UnmarshallExcludedContext(ctx context.Context, inputContent []byte, parentObject any, object any) error {
parentContent, err := newJSONObject(ctx, parentObject)
if err != nil {
return err
}
var content JSONObject
err = content.UnmarshalJSONContext(ctx, inputContent)
err := content.UnmarshalJSONContext(ctx, inputContent)
if err != nil {
return err
}
for _, key := range parentContent.Keys() {
for _, key := range cJSON.ObjectKeys(reflect.TypeOf(parentObject)) {
content.Remove(key)
}
if object == nil {
Expand Down
20 changes: 20 additions & 0 deletions common/json/internal/contextjson/keys.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package json

import (
"reflect"

"github.com/sagernet/sing/common"
)

func ObjectKeys(object reflect.Type) []string {
switch object.Kind() {
case reflect.Pointer:
return ObjectKeys(object.Elem())
case reflect.Struct:
default:
panic("invalid non-struct input")
}
return common.Map(cachedTypeFields(object).list, func(field field) string {
return field.name
})
}
25 changes: 25 additions & 0 deletions common/json/internal/contextjson/keys_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package json_test

import (
"reflect"
"testing"

json "github.com/sagernet/sing/common/json/internal/contextjson"

"github.com/stretchr/testify/require"
)

type MyObject struct {
Hello string `json:"hello,omitempty"`
MyWorld
MyWorld2 string `json:"-"`
}

type MyWorld struct {
World string `json:"world,omitempty"`
}

func TestObjectKeys(t *testing.T) {

Check failure on line 22 in common/json/internal/contextjson/keys_test.go

View workflow job for this annotation

GitHub Actions / Build

Function TestObjectKeys missing the call to method parallel (paralleltest)
keys := json.ObjectKeys(reflect.TypeOf(&MyObject{}))
require.Equal(t, []string{"hello", "world"}, keys)
}

0 comments on commit 3464ed3

Please sign in to comment.