bug: fix a potential crash with malformed data in EditCommentOperation

Michael Muré created

crashed with indexOutOfRange when the target of the op existed but wasn't a
CreateOperation or a AddCommentOperation

Change summary

bug/op_edit_comment.go | 18 +++++++++---------
1 file changed, 9 insertions(+), 9 deletions(-)

Detailed changes

bug/op_edit_comment.go 🔗

@@ -36,7 +36,6 @@ func (op *EditCommentOperation) Apply(snapshot *Snapshot) {
 	snapshot.addActor(op.Author)
 
 	var target TimelineItem
-	var commentIndex int
 
 	for i, item := range snapshot.Timeline {
 		h := item.Hash()
@@ -45,12 +44,6 @@ func (op *EditCommentOperation) Apply(snapshot *Snapshot) {
 			target = snapshot.Timeline[i]
 			break
 		}
-
-		// Track the index in the []Comment
-		switch item.(type) {
-		case *CreateTimelineItem, *AddCommentTimelineItem:
-			commentIndex++
-		}
 	}
 
 	if target == nil {
@@ -75,8 +68,15 @@ func (op *EditCommentOperation) Apply(snapshot *Snapshot) {
 		item.Append(comment)
 	}
 
-	snapshot.Comments[commentIndex].Message = op.Message
-	snapshot.Comments[commentIndex].Files = op.Files
+	// Updating the corresponding comment
+
+	for i := range snapshot.Comments {
+		if snapshot.Comments[i].Id() == string(op.Target) {
+			snapshot.Comments[i].Message = op.Message
+			snapshot.Comments[i].Files = op.Files
+			break
+		}
+	}
 }
 
 func (op *EditCommentOperation) GetFiles() []git.Hash {