Skip to content
This repository has been archived by the owner on Jul 22, 2024. It is now read-only.

Commit

Permalink
add support for "ignore" tag
Browse files Browse the repository at this point in the history
  • Loading branch information
mitchellh committed Feb 2, 2021
1 parent 5db940b commit d6675c7
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
12 changes: 11 additions & 1 deletion copystructure.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ const tagKey = "copy"
//
// The available tag values are:
//
// * "ignore" - The field will be ignored, effectively resulting in it being
// assigned the zero value in the copy.
//
// * "shallow" - The field will be be shallow copied. This means that references
// values such as pointers, maps, slices, etc. will be directly assigned
// versus deep copied.
Expand Down Expand Up @@ -421,12 +424,19 @@ func (w *walker) StructField(f reflect.StructField, v reflect.Value) error {
w.valPush(reflect.ValueOf(f))

// If we're shallow copying then push the value as-is onto the stack.
if tv := f.Tag.Get(tagKey); tv == "shallow" {
switch f.Tag.Get(tagKey) {
case "shallow":
w.valPush(v)

// set ignore depth one level deeper so we don't ignore the value
// we put on the stack but we do ignore diving into it.
w.ignoreDepth = w.depth + 1

case "ignore":
// Do nothing, we have to pop off our structfield so we undo any
// prior work in this func
w.valPop()
return reflectwalk.SkipEntry
}

return nil
Expand Down
20 changes: 20 additions & 0 deletions copystructure_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,26 @@ func TestCopy_structShallow(t *testing.T) {
}
}

func TestCopy_structIgnore(t *testing.T) {
type test struct {
Value string
Value2 *string `copy:"ignore"`
}

value2 := "bar"
value2ptr := &value2
v := test{Value: "foo", Value2: value2ptr}

result, err := Copy(v)
if err != nil {
t.Fatalf("err: %s", err)
}
vcopy := result.(test)
if vcopy.Value2 != nil {
t.Fatal("should be nil")
}
}

func TestCopy_structNested(t *testing.T) {
type TestInner struct{}

Expand Down

0 comments on commit d6675c7

Please sign in to comment.