mennanov / fmutils

Golang protobuf FieldMask missing utils
MIT License
105 stars 10 forks source link

Support filter and prune on repeated fields #7

Open alok87 opened 2 years ago

alok87 commented 2 years ago
fmutils.Prune(&currentColor, []string{"colors[1]")

Proto

message color {
  string name = 1;
}

message mycolors {
   repeated color colors = 1;
}

Go Types for Proto

type Color struct {
  name string
}

type MyColors {
  colors []Colors
}

Feature request

import "github.com/meannanov/fmutils"

func PatchList(currentColor MyColor, newColor MyColor, paths []string) (&MyColor, error) {
    fieldMask := &field_mask.FieldMask{
        Paths: paths,
    }
    fieldMask.Normalize()

    if !fieldMask.IsValid(&currentColor) {
        return  nil, fmt.Errorf("invalid fields passed in patch:%+v", paths)
    }

    // Redact the newColor to keep only the fields provided for patch
    fmutils.Filter(&newColor, fieldMask.GetPaths())

    // Need to prune the currenColor for not affecting the non mentioned fields in field-mask during merge
    fmutils.Prune(&currentColor, fieldMask.GetPaths())

    // merges the existing object to have the patched fields' data
    proto.Merge(&currentColor, &newColor)

    return &currentColor, nil
}

func main() {
   myColors := MyColors{
     colors: []Color{"blue", "green", "white"},
   }

   // want to patch 1st index of newColor to myColor
   patchedColor := PatchList(myColor, newColor, []string{"colors[1]"})

}

Protobuf at present does not support it https://github.com/protocolbuffers/protobuf/issues/8547 but this would be really helpful

mennanov commented 6 months ago

@alok87 Please, checkout https://github.com/mennanov/fmutils/pull/10 and see whether it helps getting closer to what is requested in this feature request.