Commit write the appended operations in the repository
(repo repository.ClockedRepo)
| 444 | |
| 445 | // Commit write the appended operations in the repository |
| 446 | func (e *Entity) Commit(repo repository.ClockedRepo) error { |
| 447 | if !e.NeedCommit() { |
| 448 | return fmt.Errorf("can't commit an entity with no pending operation") |
| 449 | } |
| 450 | |
| 451 | err := e.Validate() |
| 452 | if err != nil { |
| 453 | return errors.Wrapf(err, "can't commit a %s with invalid data", e.Definition.Typename) |
| 454 | } |
| 455 | |
| 456 | for len(e.staging) > 0 { |
| 457 | var author identity.Interface |
| 458 | var toCommit []Operation |
| 459 | |
| 460 | // Split into chunks with the same author |
| 461 | for len(e.staging) > 0 { |
| 462 | op := e.staging[0] |
| 463 | if author != nil && op.Author().Id() != author.Id() { |
| 464 | break |
| 465 | } |
| 466 | author = e.staging[0].Author() |
| 467 | toCommit = append(toCommit, op) |
| 468 | e.staging = e.staging[1:] |
| 469 | } |
| 470 | |
| 471 | e.editTime, err = repo.Increment(fmt.Sprintf(editClockPattern, e.Namespace)) |
| 472 | if err != nil { |
| 473 | return err |
| 474 | } |
| 475 | |
| 476 | opp := &operationPack{ |
| 477 | Author: author, |
| 478 | Operations: toCommit, |
| 479 | EditTime: e.editTime, |
| 480 | } |
| 481 | |
| 482 | if e.lastCommit == "" { |
| 483 | e.createTime, err = repo.Increment(fmt.Sprintf(creationClockPattern, e.Namespace)) |
| 484 | if err != nil { |
| 485 | return err |
| 486 | } |
| 487 | opp.CreateTime = e.createTime |
| 488 | } |
| 489 | |
| 490 | var parentCommit []repository.Hash |
| 491 | if e.lastCommit != "" { |
| 492 | parentCommit = []repository.Hash{e.lastCommit} |
| 493 | } |
| 494 | |
| 495 | commitHash, err := opp.Write(e.Definition, repo, parentCommit...) |
| 496 | if err != nil { |
| 497 | return err |
| 498 | } |
| 499 | |
| 500 | e.lastCommit = commitHash |
| 501 | e.ops = append(e.ops, toCommit...) |
| 502 | } |
| 503 |