blob: deceb87164ee82b6fd901373ed18178994c2d106 [file] [log] [blame]
Stephane Barbarie4a2564d2018-07-26 11:02:58 -04001package model
2
3import (
4 "bytes"
5 "crypto/md5"
6 "encoding/json"
7 "fmt"
8 "github.com/golang/protobuf/proto"
9 "reflect"
10)
11
12type DataRevision struct {
13 Data interface{}
14 Hash string
15}
16
17func NewDataRevision(data interface{}) *DataRevision {
18 cdr := &DataRevision{}
19 cdr.Data = data
20 cdr.Hash = cdr.hashData(data)
21
22 return cdr
23}
24
25func (cr *DataRevision) hashData(data interface{}) string {
26 var buffer bytes.Buffer
27
28 if IsProtoMessage(data) {
29 if pbdata, err := proto.Marshal(data.(proto.Message)); err != nil {
30 fmt.Errorf("problem to marshal protobuf data --> err: %s", err.Error())
31 } else {
32 buffer.Write(pbdata)
33 }
34
35 } else if reflect.ValueOf(data).IsValid() {
36 dataObj := reflect.New(reflect.TypeOf(data).Elem())
37 if json, err := json.Marshal(dataObj.Interface()); err != nil {
38 fmt.Errorf("problem to marshal data --> err: %s", err.Error())
39 } else {
40 buffer.Write(json)
41 }
42 } else {
43 dataObj := reflect.New(reflect.TypeOf(data).Elem())
44 buffer.Write(dataObj.Bytes())
45 }
46
47 return fmt.Sprintf("%x", md5.Sum(buffer.Bytes()))[:12]
48}