Browse Source

History and Version Control for Dashboard Updates

A simple version control system for dashboards. Closes #1504.

Goals

1. To create a new dashboard version every time a dashboard is saved.
2. To allow users to view all versions of a given dashboard.
3. To allow users to rollback to a previous version of a dashboard.
4. To allow users to compare two versions of a dashboard.

Usage

Navigate to a dashboard, and click the settings cog. From there, click
the "Changelog" button to be brought to the Changelog view. In this
view, a table containing each version of a dashboard can be seen. Each
entry in the table represents a dashboard version. A selectable
checkbox, the version number, date created, name of the user who created
that version, and commit message is shown in the table, along with a
button that allows a user to restore to a previous version of that
dashboard. If a user wants to restore to a previous version of their
dashboard, they can do so by clicking the previously mentioned button.
If a user wants to compare two different versions of a dashboard, they
can do so by clicking the checkbox of two different dashboard versions,
then clicking the "Compare versions" button located below the dashboard.
From there, the user is brought to a view showing a summary of the
dashboard differences. Each summarized change contains a link that can
be clicked to take the user a JSON diff highlighting the changes line by
line.

Overview of Changes

Backend Changes

- A `dashboard_version` table was created to store each dashboard
  version, along with a dashboard version model and structs to represent
  the queries and commands necessary for the dashboard version API
  methods.
- API endpoints were created to support working with dashboard
  versions.
- Methods were added to create, update, read, and destroy dashboard
  versions in the database.
  - Logic was added to compute the diff between two versions, and
  display it to the user.
  - The dashboard migration logic was updated to save a "Version
  1" of each existing dashboard in the database.

Frontend Changes

- New views
- Methods to pull JSON and HTML from endpoints

New API Endpoints

Each endpoint requires the authorization header to be sent in
the format,

```
Authorization: Bearer <jwt>
```

where `<jwt>` is a JSON web token obtained from the Grafana
admin panel.

`GET "/api/dashboards/db/:dashboardId/versions?orderBy=<string>&limit=<int>&start=<int>"`

Get all dashboard versions for the given dashboard ID. Accepts
three URL parameters:

- `orderBy` String to order the results by. Possible values
  are `version`, `created`, `created_by`, `message`. Default
  is `versions`. Ordering is always in descending order.
- `limit` Maximum number of results to return
- `start` Position in results to start from

`GET "/api/dashboards/db/:dashboardId/versions/:id"`

Get an individual dashboard version by ID, for the given
dashboard ID.

`POST "/api/dashboards/db/:dashboardId/restore"`

Restore to the given dashboard version. Post body is of
content-type `application/json`, and must contain.

```json
{
  "dashboardId": <int>,
  "version": <int>
}
```

`GET "/api/dashboards/db/:dashboardId/compare/:versionA...:versionB"`

Compare two dashboard versions by ID for the given
dashboard ID, returning a JSON delta formatted
representation of the diff. The URL format follows
what GitHub does. For example, visiting
[/api/dashboards/db/18/compare/22...33](http://ec2-54-80-139-44.compute-1.amazonaws.com:3000/api/dashboards/db/18/compare/22...33)
will return the diff between versions 22 and 33 for
the dashboard ID 18.

Dependencies Added

- The Go package [gojsondiff](https://github.com/yudai/gojsondiff)
  was added and vendored.
Ben Tranter 8 years ago
parent
commit
b6e46c9eb8
60 changed files with 7843 additions and 84 deletions
  1. 8 0
      pkg/api/api.go
  2. 261 0
      pkg/api/dashboard.go
  3. 334 0
      pkg/components/formatter/formatter_basic.go
  4. 477 0
      pkg/components/formatter/formatter_json.go
  5. 103 0
      pkg/models/dashboard_version.go
  6. 1 0
      pkg/models/dashboards.go
  7. 30 2
      pkg/services/sqlstore/dashboard.go
  8. 274 0
      pkg/services/sqlstore/dashboard_version.go
  9. 188 0
      pkg/services/sqlstore/dashboard_version_test.go
  10. 54 0
      pkg/services/sqlstore/migrations/dashboard_version_mig.go
  11. 1 0
      pkg/services/sqlstore/migrations/migrations.go
  12. 1 0
      public/app/core/core.ts
  13. 1 0
      public/app/core/directives/dash_edit_link.js
  14. 76 0
      public/app/core/directives/diff-view.ts
  15. 14 0
      public/app/core/directives/misc.js
  16. 2 1
      public/app/core/services/backend_srv.ts
  17. 1 0
      public/app/features/all.js
  18. 2 0
      public/app/features/dashboard/all.js
  19. 235 0
      public/app/features/dashboard/audit/audit_ctrl.ts
  20. 32 0
      public/app/features/dashboard/audit/audit_srv.ts
  21. 16 0
      public/app/features/dashboard/audit/models.ts
  22. 161 0
      public/app/features/dashboard/audit/partials/audit.html
  23. 4 0
      public/app/features/dashboard/audit/partials/link-json.html
  24. 52 29
      public/app/features/dashboard/dashboard_srv.ts
  25. 3 1
      public/app/features/dashboard/dashnav/dashnav.html
  26. 49 0
      public/app/features/dashboard/partials/saveDashboardMessage.html
  27. 3 28
      public/app/features/dashboard/saveDashboardAsCtrl.js
  28. 29 0
      public/app/features/dashboard/saveDashboardMessageCtrl.js
  29. 416 0
      public/app/features/dashboard/specs/audit_ctrl_specs.ts
  30. 92 0
      public/app/features/dashboard/specs/audit_srv_specs.ts
  31. 11 11
      public/app/features/dashboard/unsavedChangesSrv.js
  32. 38 11
      public/app/partials/unsaved-changes.html
  33. 1 0
      public/sass/_grafana.scss
  34. 25 0
      public/sass/_variables.dark.scss
  35. 25 0
      public/sass/_variables.light.scss
  36. 11 0
      public/sass/components/_buttons.scss
  37. 10 0
      public/sass/components/_gf-form.scss
  38. 268 0
      public/sass/pages/_audit.scss
  39. 0 1
      public/sass/pages/_dashboard.scss
  40. 197 0
      public/test/mocks/audit-mocks.js
  41. 20 0
      vendor/github.com/sergi/go-diff/LICENSE
  42. 1339 0
      vendor/github.com/sergi/go-diff/diffmatchpatch/diff.go
  43. 46 0
      vendor/github.com/sergi/go-diff/diffmatchpatch/diffmatchpatch.go
  44. 160 0
      vendor/github.com/sergi/go-diff/diffmatchpatch/match.go
  45. 23 0
      vendor/github.com/sergi/go-diff/diffmatchpatch/mathutil.go
  46. 556 0
      vendor/github.com/sergi/go-diff/diffmatchpatch/patch.go
  47. 88 0
      vendor/github.com/sergi/go-diff/diffmatchpatch/stringutil.go
  48. 145 0
      vendor/github.com/yudai/gojsondiff/LICENSE
  49. 2 0
      vendor/github.com/yudai/gojsondiff/Makefile
  50. 157 0
      vendor/github.com/yudai/gojsondiff/README.md
  51. 461 0
      vendor/github.com/yudai/gojsondiff/deltas.go
  52. 370 0
      vendor/github.com/yudai/gojsondiff/formatter/ascii.go
  53. 124 0
      vendor/github.com/yudai/gojsondiff/formatter/delta.go
  54. 426 0
      vendor/github.com/yudai/gojsondiff/gojsondiff.go
  55. 131 0
      vendor/github.com/yudai/gojsondiff/unmarshaler.go
  56. 8 0
      vendor/github.com/yudai/gojsondiff/wercker.yml
  57. 73 0
      vendor/github.com/yudai/golcs/LICENSE
  58. 54 0
      vendor/github.com/yudai/golcs/README.md
  59. 130 0
      vendor/github.com/yudai/golcs/golcs.go
  60. 24 0
      vendor/vendor.json

+ 8 - 0
pkg/api/api.go

@@ -223,6 +223,14 @@ func (hs *HttpServer) registerRoutes() {
 		// Dashboard
 		r.Group("/dashboards", func() {
 			r.Combo("/db/:slug").Get(GetDashboard).Delete(DeleteDashboard)
+
+			r.Get("/db/:dashboardId/versions", GetDashboardVersions)
+			r.Get("/db/:dashboardId/versions/:id", GetDashboardVersion)
+			r.Get("/db/:dashboardId/compare/:versions", CompareDashboardVersions)
+			r.Get("/db/:dashboardId/compare/:versions/html", CompareDashboardVersionsJSON)
+			r.Get("/db/:dashboardId/compare/:versions/basic", CompareDashboardVersionsBasic)
+			r.Post("/db/:dashboardId/restore", reqEditorRole, bind(m.RestoreDashboardVersionCommand{}), wrap(RestoreDashboardVersion))
+
 			r.Post("/db", reqEditorRole, bind(m.SaveDashboardCommand{}), wrap(PostDashboard))
 			r.Get("/file/:file", GetDashboardFromJsonFile)
 			r.Get("/home", wrap(GetHomeDashboard))

+ 261 - 0
pkg/api/dashboard.go

@@ -2,8 +2,10 @@ package api
 
 import (
 	"encoding/json"
+	"fmt"
 	"os"
 	"path"
+	"strconv"
 	"strings"
 
 	"github.com/grafana/grafana/pkg/api/dtos"
@@ -77,6 +79,7 @@ func GetDashboard(c *middleware.Context) {
 		},
 	}
 
+	// TODO(ben): copy this performance metrics logic for the new API endpoints added
 	c.TimeRequest(metrics.M_Api_Dashboard_Get)
 	c.JSON(200, dto)
 }
@@ -255,6 +258,264 @@ func GetDashboardFromJsonFile(c *middleware.Context) {
 	c.JSON(200, &dash)
 }
 
+// GetDashboardVersions returns all dashboardversions as JSON
+func GetDashboardVersions(c *middleware.Context) {
+	dashboardIdStr := c.Params(":dashboardId")
+	dashboardId, err := strconv.Atoi(dashboardIdStr)
+	if err != nil {
+		c.JsonApiErr(400, err.Error(), err)
+		return
+	}
+
+	// TODO(ben) the orderBy arg should be split into snake_case?
+	orderBy := c.Query("orderBy")
+	limit := c.QueryInt("limit")
+	start := c.QueryInt("start")
+	if orderBy == "" {
+		orderBy = "version"
+	}
+	if limit == 0 {
+		limit = 1000
+	}
+
+	query := m.GetDashboardVersionsCommand{
+		DashboardId: int64(dashboardId),
+		OrderBy:     orderBy,
+		Limit:       limit,
+		Start:       start,
+	}
+
+	if err := bus.Dispatch(&query); err != nil {
+		c.JsonApiErr(404, fmt.Sprintf("No versions found for dashboardId %d", dashboardId), err)
+		return
+	}
+
+	dashboardVersions := make([]*m.DashboardVersionDTO, len(query.Result))
+	for i, dashboardVersion := range query.Result {
+		creator := "Anonymous"
+		if dashboardVersion.CreatedBy > 0 {
+			creator = getUserLogin(dashboardVersion.CreatedBy)
+		}
+
+		dashboardVersions[i] = &m.DashboardVersionDTO{
+			Id:            dashboardVersion.Id,
+			DashboardId:   dashboardVersion.DashboardId,
+			ParentVersion: dashboardVersion.ParentVersion,
+			RestoredFrom:  dashboardVersion.RestoredFrom,
+			Version:       dashboardVersion.Version,
+			Created:       dashboardVersion.Created,
+			CreatedBy:     creator,
+			Message:       dashboardVersion.Message,
+		}
+	}
+
+	c.JSON(200, dashboardVersions)
+}
+
+// GetDashboardVersion returns the dashboard version with the given ID.
+func GetDashboardVersion(c *middleware.Context) {
+	dashboardIdStr := c.Params(":dashboardId")
+	dashboardId, err := strconv.Atoi(dashboardIdStr)
+	if err != nil {
+		c.JsonApiErr(400, err.Error(), err)
+		return
+	}
+
+	versionStr := c.Params(":id")
+	version, err := strconv.Atoi(versionStr)
+	if err != nil {
+		c.JsonApiErr(400, err.Error(), err)
+		return
+	}
+
+	query := m.GetDashboardVersionCommand{
+		DashboardId: int64(dashboardId),
+		Version:     version,
+	}
+	if err := bus.Dispatch(&query); err != nil {
+		c.JsonApiErr(500, err.Error(), err)
+		return
+	}
+
+	creator := "Anonymous"
+	if query.Result.CreatedBy > 0 {
+		creator = getUserLogin(query.Result.CreatedBy)
+	}
+
+	dashVersionMeta := &m.DashboardVersionMeta{
+		DashboardVersion: *query.Result,
+		CreatedBy:        creator,
+	}
+
+	c.JSON(200, dashVersionMeta)
+}
+
+func dashCmd(c *middleware.Context) (m.CompareDashboardVersionsCommand, error) {
+	cmd := m.CompareDashboardVersionsCommand{}
+
+	dashboardIdStr := c.Params(":dashboardId")
+	dashboardId, err := strconv.Atoi(dashboardIdStr)
+	if err != nil {
+		return cmd, err
+	}
+
+	versionStrings := strings.Split(c.Params(":versions"), "...")
+	if len(versionStrings) != 2 {
+		return cmd, fmt.Errorf("bad format: urls should be in the format /versions/0...1")
+	}
+
+	originalDash, err := strconv.Atoi(versionStrings[0])
+	if err != nil {
+		return cmd, fmt.Errorf("bad format: first argument is not of type int")
+	}
+
+	newDash, err := strconv.Atoi(versionStrings[1])
+	if err != nil {
+		return cmd, fmt.Errorf("bad format: second argument is not of type int")
+	}
+
+	cmd.DashboardId = int64(dashboardId)
+	cmd.Original = originalDash
+	cmd.New = newDash
+	return cmd, nil
+}
+
+// CompareDashboardVersions compares dashboards the way the GitHub API does.
+func CompareDashboardVersions(c *middleware.Context) {
+	cmd, err := dashCmd(c)
+	if err != nil {
+		c.JsonApiErr(500, err.Error(), err)
+	}
+	cmd.DiffType = m.DiffDelta
+
+	if err := bus.Dispatch(&cmd); err != nil {
+		c.JsonApiErr(500, "cannot-compute-diff", err)
+		return
+	}
+	// here the output is already JSON, so we need to unmarshal it into a
+	// map before marshaling the entire response
+	deltaMap := make(map[string]interface{})
+	err = json.Unmarshal(cmd.Delta, &deltaMap)
+	if err != nil {
+		c.JsonApiErr(500, err.Error(), err)
+		return
+	}
+
+	c.JSON(200, simplejson.NewFromAny(util.DynMap{
+		"meta": util.DynMap{
+			"original": cmd.Original,
+			"new":      cmd.New,
+		},
+		"delta": deltaMap,
+	}))
+}
+
+// CompareDashboardVersionsJSON compares dashboards the way the GitHub API does,
+// returning a human-readable JSON diff.
+func CompareDashboardVersionsJSON(c *middleware.Context) {
+	cmd, err := dashCmd(c)
+	if err != nil {
+		c.JsonApiErr(500, err.Error(), err)
+	}
+	cmd.DiffType = m.DiffJSON
+
+	if err := bus.Dispatch(&cmd); err != nil {
+		c.JsonApiErr(500, err.Error(), err)
+		return
+	}
+
+	c.Header().Set("Content-Type", "text/html")
+	c.WriteHeader(200)
+	c.Write(cmd.Delta)
+}
+
+// CompareDashboardVersionsBasic compares dashboards the way the GitHub API does,
+// returning a human-readable diff.
+func CompareDashboardVersionsBasic(c *middleware.Context) {
+	cmd, err := dashCmd(c)
+	if err != nil {
+		c.JsonApiErr(500, err.Error(), err)
+	}
+	cmd.DiffType = m.DiffBasic
+
+	if err := bus.Dispatch(&cmd); err != nil {
+		c.JsonApiErr(500, err.Error(), err)
+		return
+	}
+
+	c.Header().Set("Content-Type", "text/html")
+	c.WriteHeader(200)
+	c.Write(cmd.Delta)
+}
+
+// RestoreDashboardVersion restores a dashboard to the given version.
+func RestoreDashboardVersion(c *middleware.Context, cmd m.RestoreDashboardVersionCommand) Response {
+	if !c.IsSignedIn {
+		return Json(401, util.DynMap{
+			"message": "Must be signed in to restore a version",
+			"status":  "unauthorized",
+		})
+	}
+
+	cmd.UserId = c.UserId
+	dashboardIdStr := c.Params(":dashboardId")
+	dashboardId, err := strconv.Atoi(dashboardIdStr)
+	if err != nil {
+		return Json(404, util.DynMap{
+			"message": err.Error(),
+			"status":  "cannot-find-dashboard",
+		})
+	}
+	cmd.DashboardId = int64(dashboardId)
+
+	if err := bus.Dispatch(&cmd); err != nil {
+		return Json(500, util.DynMap{
+			"message": err.Error(),
+			"status":  "cannot-restore-version",
+		})
+	}
+
+	isStarred, err := isDashboardStarredByUser(c, cmd.Result.Id)
+	if err != nil {
+		return Json(500, util.DynMap{
+			"message": "Error while checking if dashboard was starred by user",
+			"status":  err.Error(),
+		})
+	}
+
+	// Finding creator and last updater of the dashboard
+	updater, creator := "Anonymous", "Anonymous"
+	if cmd.Result.UpdatedBy > 0 {
+		updater = getUserLogin(cmd.Result.UpdatedBy)
+	}
+	if cmd.Result.CreatedBy > 0 {
+		creator = getUserLogin(cmd.Result.CreatedBy)
+	}
+
+	dto := dtos.DashboardFullWithMeta{
+		Dashboard: cmd.Result.Data,
+		Meta: dtos.DashboardMeta{
+			IsStarred: isStarred,
+			Slug:      cmd.Result.Slug,
+			Type:      m.DashTypeDB,
+			CanStar:   c.IsSignedIn,
+			CanSave:   c.OrgRole == m.ROLE_ADMIN || c.OrgRole == m.ROLE_EDITOR,
+			CanEdit:   canEditDashboard(c.OrgRole),
+			Created:   cmd.Result.Created,
+			Updated:   cmd.Result.Updated,
+			UpdatedBy: updater,
+			CreatedBy: creator,
+			Version:   cmd.Result.Version,
+		},
+	}
+
+	return Json(200, util.DynMap{
+		"message":   fmt.Sprintf("Dashboard restored to version %d", cmd.Result.Version),
+		"version":   cmd.Result.Version,
+		"dashboard": dto,
+	})
+}
+
 func GetDashboardTags(c *middleware.Context) {
 	query := m.GetDashboardTagsQuery{OrgId: c.OrgId}
 	err := bus.Dispatch(&query)

+ 334 - 0
pkg/components/formatter/formatter_basic.go

@@ -0,0 +1,334 @@
+package formatter
+
+import (
+	"bytes"
+	"html/template"
+
+	diff "github.com/yudai/gojsondiff"
+)
+
+// A BasicDiff holds the stateful values that are used when generating a basic
+// diff from JSON tokens.
+type BasicDiff struct {
+	narrow     string
+	keysIdent  int
+	writing    bool
+	LastIndent int
+	Block      *BasicBlock
+	Change     *BasicChange
+	Summary    *BasicSummary
+}
+
+// A BasicBlock represents a top-level element in a basic diff.
+type BasicBlock struct {
+	Title     string
+	Old       interface{}
+	New       interface{}
+	Change    ChangeType
+	Changes   []*BasicChange
+	Summaries []*BasicSummary
+	LineStart int
+	LineEnd   int
+}
+
+// A BasicChange represents the change from an old to new value. There are many
+// BasicChanges in a BasicBlock.
+type BasicChange struct {
+	Key       string
+	Old       interface{}
+	New       interface{}
+	Change    ChangeType
+	LineStart int
+	LineEnd   int
+}
+
+// A BasicSummary represents the changes within a basic block that're too deep
+// or verbose to be represented in the top-level BasicBlock element, or in the
+// BasicChange. Instead of showing the values in this case, we simply print
+// the key and count how many times the given change was applied to that
+// element.
+type BasicSummary struct {
+	Key       string
+	Change    ChangeType
+	Count     int
+	LineStart int
+	LineEnd   int
+}
+
+type BasicFormatter struct {
+	jsonDiff *JSONFormatter
+	tpl      *template.Template
+}
+
+func NewBasicFormatter(left interface{}) *BasicFormatter {
+	tpl := template.Must(template.New("block").Funcs(tplFuncMap).Parse(tplBlock))
+	tpl = template.Must(tpl.New("change").Funcs(tplFuncMap).Parse(tplChange))
+	tpl = template.Must(tpl.New("summary").Funcs(tplFuncMap).Parse(tplSummary))
+
+	return &BasicFormatter{
+		jsonDiff: NewJSONFormatter(left),
+		tpl:      tpl,
+	}
+}
+
+func (b *BasicFormatter) Format(d diff.Diff) ([]byte, error) {
+	// calling jsonDiff.Format(d) populates the JSON diff's "Lines" value,
+	// which we use to compute the basic dif
+	_, err := b.jsonDiff.Format(d)
+	if err != nil {
+		return nil, err
+	}
+
+	bd := &BasicDiff{}
+	blocks := bd.Basic(b.jsonDiff.Lines)
+	buf := &bytes.Buffer{}
+
+	err = b.tpl.ExecuteTemplate(buf, "block", blocks)
+	if err != nil {
+		return nil, err
+	}
+	return buf.Bytes(), nil
+}
+
+// Basic is V2 of the basic diff
+func (b *BasicDiff) Basic(lines []*JSONLine) []*BasicBlock {
+	// init an array you can append to for the basic "blocks"
+	blocks := make([]*BasicBlock, 0)
+
+	// iterate through each line
+	for _, line := range lines {
+		if b.LastIndent == 3 && line.Indent == 2 && line.Change == ChangeNil {
+			if b.Block != nil {
+				blocks = append(blocks, b.Block)
+			}
+		}
+		b.LastIndent = line.Indent
+
+		if line.Indent == 2 {
+			switch line.Change {
+			case ChangeNil:
+				if line.Change == ChangeNil {
+					if line.Key != "" {
+						b.Block = &BasicBlock{
+							Title:  line.Key,
+							Change: line.Change,
+						}
+					}
+				}
+
+			case ChangeAdded, ChangeDeleted:
+				blocks = append(blocks, &BasicBlock{
+					Title:     line.Key,
+					Change:    line.Change,
+					New:       line.Val,
+					LineStart: line.LineNum,
+				})
+
+			case ChangeOld:
+				b.Block = &BasicBlock{
+					Title:     line.Key,
+					Old:       line.Val,
+					Change:    line.Change,
+					LineStart: line.LineNum,
+				}
+
+			case ChangeNew:
+				b.Block.New = line.Val
+				b.Block.LineEnd = line.LineNum
+
+				// then write out the change
+				blocks = append(blocks, b.Block)
+			default:
+				// ok
+			}
+		}
+
+		// Other Lines
+		if line.Indent > 2 {
+			// Ensure single line change
+			if line.Key != "" && line.Val != nil && !b.writing {
+				switch line.Change {
+				case ChangeAdded, ChangeDeleted:
+					b.Block.Changes = append(b.Block.Changes, &BasicChange{
+						Key:       line.Key,
+						Change:    line.Change,
+						New:       line.Val,
+						LineStart: line.LineNum,
+					})
+
+				case ChangeOld:
+					b.Change = &BasicChange{
+						Key:       line.Key,
+						Change:    line.Change,
+						Old:       line.Val,
+						LineStart: line.LineNum,
+					}
+
+				case ChangeNew:
+					b.Change.New = line.Val
+					b.Change.LineEnd = line.LineNum
+					b.Block.Changes = append(b.Block.Changes, b.Change)
+
+				default:
+					//ok
+				}
+
+			} else {
+				if line.Change != ChangeUnchanged {
+					if line.Key != "" {
+						b.narrow = line.Key
+						b.keysIdent = line.Indent
+					}
+
+					if line.Change != ChangeNil {
+						if !b.writing {
+							b.writing = true
+							key := b.Block.Title
+
+							if b.narrow != "" {
+								key = b.narrow
+								if b.keysIdent > line.Indent {
+									key = b.Block.Title
+								}
+							}
+
+							b.Summary = &BasicSummary{
+								Key:       key,
+								Change:    line.Change,
+								LineStart: line.LineNum,
+							}
+						}
+					}
+				} else {
+					if b.writing {
+						b.writing = false
+						b.Summary.LineEnd = line.LineNum
+						b.Block.Summaries = append(b.Block.Summaries, b.Summary)
+					}
+				}
+			}
+		}
+	}
+
+	return blocks
+}
+
+// encStateMap is used in the template helper
+var (
+	encStateMap = map[ChangeType]string{
+		ChangeAdded:   "added",
+		ChangeDeleted: "deleted",
+		ChangeOld:     "changed",
+		ChangeNew:     "changed",
+	}
+
+	// tplFuncMap is the function map for each template
+	tplFuncMap = template.FuncMap{
+		"getChange": func(c ChangeType) string {
+			state, ok := encStateMap[c]
+			if !ok {
+				return "changed"
+			}
+			return state
+		},
+	}
+)
+
+var (
+	// tplBlock is the whole thing
+	tplBlock = `{{ define "block" -}}
+{{ range . }}
+<div class="diff-group">
+	<div class="diff-block">
+		<h2 class="diff-block-title">
+			<i class="diff-circle diff-circle-{{ getChange .Change }} fa fa-circle"></i>
+			<strong class="diff-title">{{ .Title }}</strong> {{ getChange .Change }}
+		</h2>
+
+
+		<!-- Overview -->
+		{{ if .Old }}
+			<div class="change list-change diff-label">{{ .Old }}</div>
+			<i class="diff-arrow fa fa-long-arrow-right"></i>
+		{{ end }}
+		{{ if .New }}
+				<div class="change list-change diff-label">{{ .New }}</div>
+		{{ end }}
+
+		{{ if .LineStart }}
+			<diff-link-json
+				line-link="{{ .LineStart }}"
+				line-display="{{ .LineStart }}{{ if .LineEnd }} - {{ .LineEnd }}{{ end }}"
+				switch-view="ctrl.getDiff('html')"
+			/>
+		{{ end }} 
+
+	</div>
+
+	<!-- Basic Changes -->
+	{{ range .Changes }}
+		<ul class="diff-change-container">
+		{{ template "change" . }}
+		</ul>
+	{{ end }}
+
+	<!-- Basic Summary -->
+	{{ range .Summaries }}
+		{{ template "summary" . }}
+	{{ end }}
+
+</div>
+{{ end }}
+{{ end }}`
+
+	// tplChange is the template for changes
+	tplChange = `{{ define "change" -}}
+<li class="diff-change-group">
+	<span class="bullet-position-container">
+		<div class="diff-change-item diff-change-title">{{ getChange .Change }} {{ .Key }}</div>
+		
+		<div class="diff-change-item">
+			{{ if .Old }}
+				<div class="change list-change diff-label">{{ .Old }}</div>
+				<i class="diff-arrow fa fa-long-arrow-right"></i>
+			{{ end }}
+			{{ if .New }}
+					<div class="change list-change diff-label">{{ .New }}</div>
+			{{ end }}
+		</div>
+
+		{{ if .LineStart }}
+			<diff-link-json
+				line-link="{{ .LineStart }}"
+				line-display="{{ .LineStart }}{{ if .LineEnd }} - {{ .LineEnd }}{{ end }}"
+				switch-view="ctrl.getDiff('html')"
+			/>
+		{{ end }}
+	</span>
+</li>
+{{ end }}`
+
+	// tplSummary is for basis summaries
+	tplSummary = `{{ define "summary" -}}
+<div class="diff-group-name">
+	<i class="diff-circle diff-circle-{{ getChange .Change }} fa fa-circle-o diff-list-circle"></i>
+	
+	{{ if .Count }}
+		<strong>{{ .Count }}</strong>
+	{{ end }}
+
+	{{ if .Key }}
+		<strong class="diff-summary-key">{{ .Key }}</strong>
+		{{ getChange .Change }}
+	{{ end }}
+
+	{{ if .LineStart }}
+		<diff-link-json
+			line-link="{{ .LineStart }}"
+			line-display="{{ .LineStart }}{{ if .LineEnd }} - {{ .LineEnd }}{{ end }}"
+			switch-view="ctrl.getDiff('html')"
+		/>
+	{{ end }}
+</div>
+{{ end }}`
+)

+ 477 - 0
pkg/components/formatter/formatter_json.go

@@ -0,0 +1,477 @@
+package formatter
+
+import (
+	"bytes"
+	"errors"
+	"fmt"
+	"html/template"
+	"sort"
+
+	diff "github.com/yudai/gojsondiff"
+)
+
+type ChangeType int
+
+const (
+	ChangeNil ChangeType = iota
+	ChangeAdded
+	ChangeDeleted
+	ChangeOld
+	ChangeNew
+	ChangeUnchanged
+)
+
+var (
+	// changeTypeToSymbol is used for populating the terminating characer in
+	// the diff
+	changeTypeToSymbol = map[ChangeType]string{
+		ChangeNil:     "",
+		ChangeAdded:   "+",
+		ChangeDeleted: "-",
+		ChangeOld:     "-",
+		ChangeNew:     "+",
+	}
+
+	// changeTypeToName is used for populating class names in the diff
+	changeTypeToName = map[ChangeType]string{
+		ChangeNil:     "same",
+		ChangeAdded:   "added",
+		ChangeDeleted: "deleted",
+		ChangeOld:     "old",
+		ChangeNew:     "new",
+	}
+)
+
+var (
+	// tplJSONDiffWrapper is the template that wraps a diff
+	tplJSONDiffWrapper = `{{ define "JSONDiffWrapper" -}}
+	{{ range $index, $element := . }}
+		{{ template "JSONDiffLine" $element }}
+	{{ end }}
+{{ end }}`
+
+	// tplJSONDiffLine is the template that prints each line in a diff
+	tplJSONDiffLine = `{{ define "JSONDiffLine" -}}
+<p id="l{{ .LineNum }}" class="diff-line diff-json-{{ cton .Change }}">
+	<span class="diff-line-number">
+		{{if .LeftLine }}{{ .LeftLine }}{{ end }}
+	</span>
+	<span class="diff-line-number">
+		{{if .RightLine }}{{ .RightLine }}{{ end }}
+	</span>
+	<span class="diff-value diff-indent-{{ .Indent }}" title="{{ .Text }}">
+		{{ .Text }}
+	</span>
+	<span class="diff-line-icon">{{ ctos .Change }}</span>
+</p>
+{{ end }}`
+)
+
+var diffTplFuncs = template.FuncMap{
+	"ctos": func(c ChangeType) string {
+		if symbol, ok := changeTypeToSymbol[c]; ok {
+			return symbol
+		}
+		return ""
+	},
+	"cton": func(c ChangeType) string {
+		if name, ok := changeTypeToName[c]; ok {
+			return name
+		}
+		return ""
+	},
+}
+
+// JSONLine contains the data required to render each line of the JSON diff
+// and contains the data required to produce the tokens output in the basic
+// diff.
+type JSONLine struct {
+	LineNum   int         `json:"line"`
+	LeftLine  int         `json:"leftLine"`
+	RightLine int         `json:"rightLine"`
+	Indent    int         `json:"indent"`
+	Text      string      `json:"text"`
+	Change    ChangeType  `json:"changeType"`
+	Key       string      `json:"key"`
+	Val       interface{} `json:"value"`
+}
+
+func NewJSONFormatter(left interface{}) *JSONFormatter {
+	tpl := template.Must(template.New("JSONDiffWrapper").Funcs(diffTplFuncs).Parse(tplJSONDiffWrapper))
+	tpl = template.Must(tpl.New("JSONDiffLine").Funcs(diffTplFuncs).Parse(tplJSONDiffLine))
+
+	return &JSONFormatter{
+		left:      left,
+		Lines:     []*JSONLine{},
+		tpl:       tpl,
+		path:      []string{},
+		size:      []int{},
+		lineCount: 0,
+		inArray:   []bool{},
+	}
+}
+
+type JSONFormatter struct {
+	left      interface{}
+	path      []string
+	size      []int
+	inArray   []bool
+	lineCount int
+	leftLine  int
+	rightLine int
+	line      *AsciiLine
+	Lines     []*JSONLine
+	tpl       *template.Template
+}
+
+type AsciiLine struct {
+	// the type of change
+	change ChangeType
+
+	// the actual changes - no formatting
+	key string
+	val interface{}
+
+	// level of indentation for the current line
+	indent int
+
+	// buffer containing the fully formatted line
+	buffer *bytes.Buffer
+}
+
+func (f *JSONFormatter) Format(diff diff.Diff) (result string, err error) {
+	if v, ok := f.left.(map[string]interface{}); ok {
+		f.formatObject(v, diff)
+	} else if v, ok := f.left.([]interface{}); ok {
+		f.formatArray(v, diff)
+	} else {
+		return "", fmt.Errorf("expected map[string]interface{} or []interface{}, got %T",
+			f.left)
+	}
+
+	b := &bytes.Buffer{}
+	err = f.tpl.ExecuteTemplate(b, "JSONDiffWrapper", f.Lines)
+	if err != nil {
+		fmt.Printf("%v\n", err)
+		return "", err
+	}
+	return b.String(), nil
+}
+
+func (f *JSONFormatter) formatObject(left map[string]interface{}, df diff.Diff) {
+	f.addLineWith(ChangeNil, "{")
+	f.push("ROOT", len(left), false)
+	f.processObject(left, df.Deltas())
+	f.pop()
+	f.addLineWith(ChangeNil, "}")
+}
+
+func (f *JSONFormatter) formatArray(left []interface{}, df diff.Diff) {
+	f.addLineWith(ChangeNil, "[")
+	f.push("ROOT", len(left), true)
+	f.processArray(left, df.Deltas())
+	f.pop()
+	f.addLineWith(ChangeNil, "]")
+}
+
+func (f *JSONFormatter) processArray(array []interface{}, deltas []diff.Delta) error {
+	patchedIndex := 0
+	for index, value := range array {
+		f.processItem(value, deltas, diff.Index(index))
+		patchedIndex++
+	}
+
+	// additional Added
+	for _, delta := range deltas {
+		switch delta.(type) {
+		case *diff.Added:
+			d := delta.(*diff.Added)
+			// skip items already processed
+			if int(d.Position.(diff.Index)) < len(array) {
+				continue
+			}
+			f.printRecursive(d.Position.String(), d.Value, ChangeAdded)
+		}
+	}
+
+	return nil
+}
+
+func (f *JSONFormatter) processObject(object map[string]interface{}, deltas []diff.Delta) error {
+	names := sortKeys(object)
+	for _, name := range names {
+		value := object[name]
+		f.processItem(value, deltas, diff.Name(name))
+	}
+
+	// Added
+	for _, delta := range deltas {
+		switch delta.(type) {
+		case *diff.Added:
+			d := delta.(*diff.Added)
+			f.printRecursive(d.Position.String(), d.Value, ChangeAdded)
+		}
+	}
+
+	return nil
+}
+
+func (f *JSONFormatter) processItem(value interface{}, deltas []diff.Delta, position diff.Position) error {
+	matchedDeltas := f.searchDeltas(deltas, position)
+	positionStr := position.String()
+	if len(matchedDeltas) > 0 {
+		for _, matchedDelta := range matchedDeltas {
+
+			switch matchedDelta.(type) {
+			case *diff.Object:
+				d := matchedDelta.(*diff.Object)
+				switch value.(type) {
+				case map[string]interface{}:
+					//ok
+				default:
+					return errors.New("Type mismatch")
+				}
+				o := value.(map[string]interface{})
+
+				f.newLine(ChangeNil)
+				f.printKey(positionStr)
+				f.print("{")
+				f.closeLine()
+				f.push(positionStr, len(o), false)
+				f.processObject(o, d.Deltas)
+				f.pop()
+				f.newLine(ChangeNil)
+				f.print("}")
+				f.printComma()
+				f.closeLine()
+
+			case *diff.Array:
+				d := matchedDelta.(*diff.Array)
+				switch value.(type) {
+				case []interface{}:
+					//ok
+				default:
+					return errors.New("Type mismatch")
+				}
+				a := value.([]interface{})
+
+				f.newLine(ChangeNil)
+				f.printKey(positionStr)
+				f.print("[")
+				f.closeLine()
+				f.push(positionStr, len(a), true)
+				f.processArray(a, d.Deltas)
+				f.pop()
+				f.newLine(ChangeNil)
+				f.print("]")
+				f.printComma()
+				f.closeLine()
+
+			case *diff.Added:
+				d := matchedDelta.(*diff.Added)
+				f.printRecursive(positionStr, d.Value, ChangeAdded)
+				f.size[len(f.size)-1]++
+
+			case *diff.Modified:
+				d := matchedDelta.(*diff.Modified)
+				savedSize := f.size[len(f.size)-1]
+				f.printRecursive(positionStr, d.OldValue, ChangeOld)
+				f.size[len(f.size)-1] = savedSize
+				f.printRecursive(positionStr, d.NewValue, ChangeNew)
+
+			case *diff.TextDiff:
+				savedSize := f.size[len(f.size)-1]
+				d := matchedDelta.(*diff.TextDiff)
+				f.printRecursive(positionStr, d.OldValue, ChangeOld)
+				f.size[len(f.size)-1] = savedSize
+				f.printRecursive(positionStr, d.NewValue, ChangeNew)
+
+			case *diff.Deleted:
+				d := matchedDelta.(*diff.Deleted)
+				f.printRecursive(positionStr, d.Value, ChangeDeleted)
+
+			default:
+				return errors.New("Unknown Delta type detected")
+			}
+
+		}
+	} else {
+		f.printRecursive(positionStr, value, ChangeUnchanged)
+	}
+
+	return nil
+}
+
+func (f *JSONFormatter) searchDeltas(deltas []diff.Delta, postion diff.Position) (results []diff.Delta) {
+	results = make([]diff.Delta, 0)
+	for _, delta := range deltas {
+		switch delta.(type) {
+		case diff.PostDelta:
+			if delta.(diff.PostDelta).PostPosition() == postion {
+				results = append(results, delta)
+			}
+		case diff.PreDelta:
+			if delta.(diff.PreDelta).PrePosition() == postion {
+				results = append(results, delta)
+			}
+		default:
+			panic("heh")
+		}
+	}
+	return
+}
+
+func (f *JSONFormatter) push(name string, size int, array bool) {
+	f.path = append(f.path, name)
+	f.size = append(f.size, size)
+	f.inArray = append(f.inArray, array)
+}
+
+func (f *JSONFormatter) pop() {
+	f.path = f.path[0 : len(f.path)-1]
+	f.size = f.size[0 : len(f.size)-1]
+	f.inArray = f.inArray[0 : len(f.inArray)-1]
+}
+
+func (f *JSONFormatter) addLineWith(change ChangeType, value string) {
+	f.line = &AsciiLine{
+		change: change,
+		indent: len(f.path),
+		buffer: bytes.NewBufferString(value),
+	}
+	f.closeLine()
+}
+
+func (f *JSONFormatter) newLine(change ChangeType) {
+	f.line = &AsciiLine{
+		change: change,
+		indent: len(f.path),
+		buffer: bytes.NewBuffer([]byte{}),
+	}
+}
+
+func (f *JSONFormatter) closeLine() {
+	leftLine := 0
+	rightLine := 0
+	f.lineCount++
+
+	switch f.line.change {
+	case ChangeAdded, ChangeNew:
+		f.rightLine++
+		rightLine = f.rightLine
+
+	case ChangeDeleted, ChangeOld:
+		f.leftLine++
+		leftLine = f.leftLine
+
+	case ChangeNil, ChangeUnchanged:
+		f.rightLine++
+		f.leftLine++
+		rightLine = f.rightLine
+		leftLine = f.leftLine
+	}
+
+	s := f.line.buffer.String()
+	f.Lines = append(f.Lines, &JSONLine{
+		LineNum:   f.lineCount,
+		RightLine: rightLine,
+		LeftLine:  leftLine,
+		Indent:    f.line.indent,
+		Text:      s,
+		Change:    f.line.change,
+		Key:       f.line.key,
+		Val:       f.line.val,
+	})
+}
+
+func (f *JSONFormatter) printKey(name string) {
+	if !f.inArray[len(f.inArray)-1] {
+		f.line.key = name
+		fmt.Fprintf(f.line.buffer, `"%s": `, name)
+	}
+}
+
+func (f *JSONFormatter) printComma() {
+	f.size[len(f.size)-1]--
+	if f.size[len(f.size)-1] > 0 {
+		f.line.buffer.WriteRune(',')
+	}
+}
+
+func (f *JSONFormatter) printValue(value interface{}) {
+	switch value.(type) {
+	case string:
+		f.line.val = value
+		fmt.Fprintf(f.line.buffer, `"%s"`, value)
+	case nil:
+		f.line.val = "null"
+		f.line.buffer.WriteString("null")
+	default:
+		f.line.val = value
+		fmt.Fprintf(f.line.buffer, `%#v`, value)
+	}
+}
+
+func (f *JSONFormatter) print(a string) {
+	f.line.buffer.WriteString(a)
+}
+
+func (f *JSONFormatter) printRecursive(name string, value interface{}, change ChangeType) {
+	switch value.(type) {
+	case map[string]interface{}:
+		f.newLine(change)
+		f.printKey(name)
+		f.print("{")
+		f.closeLine()
+
+		m := value.(map[string]interface{})
+		size := len(m)
+		f.push(name, size, false)
+
+		keys := sortKeys(m)
+		for _, key := range keys {
+			f.printRecursive(key, m[key], change)
+		}
+		f.pop()
+
+		f.newLine(change)
+		f.print("}")
+		f.printComma()
+		f.closeLine()
+
+	case []interface{}:
+		f.newLine(change)
+		f.printKey(name)
+		f.print("[")
+		f.closeLine()
+
+		s := value.([]interface{})
+		size := len(s)
+		f.push("", size, true)
+		for _, item := range s {
+			f.printRecursive("", item, change)
+		}
+		f.pop()
+
+		f.newLine(change)
+		f.print("]")
+		f.printComma()
+		f.closeLine()
+
+	default:
+		f.newLine(change)
+		f.printKey(name)
+		f.printValue(value)
+		f.printComma()
+		f.closeLine()
+	}
+}
+
+func sortKeys(m map[string]interface{}) (keys []string) {
+	keys = make([]string, 0, len(m))
+	for key := range m {
+		keys = append(keys, key)
+	}
+	sort.Strings(keys)
+	return
+}

+ 103 - 0
pkg/models/dashboard_version.go

@@ -0,0 +1,103 @@
+package models
+
+import (
+	"errors"
+	"time"
+
+	"github.com/grafana/grafana/pkg/components/simplejson"
+)
+
+type DiffType int
+
+const (
+	DiffJSON DiffType = iota
+	DiffBasic
+	DiffDelta
+)
+
+var (
+	ErrDashboardVersionNotFound = errors.New("Dashboard version not found")
+	ErrNoVersionsForDashboardId = errors.New("No dashboard versions found for the given DashboardId")
+)
+
+// A DashboardVersion represents the comparable data in a dashboard, allowing
+// diffs of the dashboard to be performed.
+type DashboardVersion struct {
+	Id            int64 `json:"id"`
+	DashboardId   int64 `json:"dashboardId"`
+	ParentVersion int   `json:"parentVersion"`
+	RestoredFrom  int   `json:"restoredFrom"`
+	Version       int   `json:"version"`
+
+	Created time.Time `json:"created"`
+
+	CreatedBy int64 `json:"createdBy"`
+
+	Message string           `json:"message"`
+	Data    *simplejson.Json `json:"data"`
+}
+
+// DashboardVersionMeta extends the dashboard version model with the names
+// associated with the UserIds, overriding the field with the same name from
+// the DashboardVersion model.
+type DashboardVersionMeta struct {
+	DashboardVersion
+	CreatedBy string `json:"createdBy"`
+}
+
+// DashboardVersionDTO represents a dashboard version, without the dashboard
+// map.
+type DashboardVersionDTO struct {
+	Id            int64     `json:"id"`
+	DashboardId   int64     `json:"dashboardId"`
+	ParentVersion int       `json:"parentVersion"`
+	RestoredFrom  int       `json:"restoredFrom"`
+	Version       int       `json:"version"`
+	Created       time.Time `json:"created"`
+	CreatedBy     string    `json:"createdBy"`
+	Message       string    `json:"message"`
+}
+
+//
+// COMMANDS
+//
+
+// GetDashboardVersionCommand contains the data required to execute the
+// sqlstore.GetDashboardVersionCommand, which returns the DashboardVersion for
+// the given Version.
+type GetDashboardVersionCommand struct {
+	DashboardId int64 `json:"dashboardId" binding:"Required"`
+	Version     int   `json:"version" binding:"Required"`
+
+	Result *DashboardVersion
+}
+
+// GetDashboardVersionsCommand contains the data required to execute the
+// sqlstore.GetDashboardVersionsCommand, which returns all dashboard versions.
+type GetDashboardVersionsCommand struct {
+	DashboardId int64  `json:"dashboardId" binding:"Required"`
+	OrderBy     string `json:"orderBy"`
+	Limit       int    `json:"limit"`
+	Start       int    `json:"start"`
+
+	Result []*DashboardVersion
+}
+
+// RestoreDashboardVersionCommand creates a new dashboard version.
+type RestoreDashboardVersionCommand struct {
+	DashboardId int64 `json:"dashboardId"`
+	Version     int   `json:"version" binding:"Required"`
+	UserId      int64 `json:"-"`
+
+	Result *Dashboard
+}
+
+// CompareDashboardVersionsCommand is used to compare two versions.
+type CompareDashboardVersionsCommand struct {
+	DashboardId int64    `json:"dashboardId"`
+	Original    int      `json:"original" binding:"Required"`
+	New         int      `json:"new" binding:"Required"`
+	DiffType    DiffType `json:"-"`
+
+	Delta []byte `json:"delta"`
+}

+ 1 - 0
pkg/models/dashboards.go

@@ -131,6 +131,7 @@ type SaveDashboardCommand struct {
 	OrgId     int64            `json:"-"`
 	Overwrite bool             `json:"overwrite"`
 	PluginId  string           `json:"-"`
+	Message   string           `json:"message"`
 
 	Result *Dashboard
 }

+ 30 - 2
pkg/services/sqlstore/dashboard.go

@@ -3,6 +3,7 @@ package sqlstore
 import (
 	"bytes"
 	"fmt"
+	"time"
 
 	"github.com/go-xorm/xorm"
 	"github.com/grafana/grafana/pkg/bus"
@@ -69,17 +70,43 @@ func SaveDashboard(cmd *m.SaveDashboardCommand) error {
 			}
 		}
 
-		affectedRows := int64(0)
+		parentVersion := dash.Version
+		version, err := getMaxVersion(sess, dash.Id)
+		if err != nil {
+			return err
+		}
+		dash.Version = version
 
+		affectedRows := int64(0)
 		if dash.Id == 0 {
 			metrics.M_Models_Dashboard_Insert.Inc(1)
+			dash.Data.Set("version", dash.Version)
 			affectedRows, err = sess.Insert(dash)
 		} else {
-			dash.Version += 1
 			dash.Data.Set("version", dash.Version)
 			affectedRows, err = sess.Id(dash.Id).Update(dash)
 		}
+		if err != nil {
+			return err
+		}
+		if affectedRows == 0 {
+			return m.ErrDashboardNotFound
+		}
 
+		dashVersion := &m.DashboardVersion{
+			DashboardId:   dash.Id,
+			ParentVersion: parentVersion,
+			RestoredFrom:  -1,
+			Version:       dash.Version,
+			Created:       time.Now(),
+			CreatedBy:     dash.UpdatedBy,
+			Message:       cmd.Message,
+			Data:          dash.Data,
+		}
+		affectedRows, err = sess.Insert(dashVersion)
+		if err != nil {
+			return err
+		}
 		if affectedRows == 0 {
 			return m.ErrDashboardNotFound
 		}
@@ -234,6 +261,7 @@ func DeleteDashboard(cmd *m.DeleteDashboardCommand) error {
 			"DELETE FROM star WHERE dashboard_id = ? ",
 			"DELETE FROM dashboard WHERE id = ?",
 			"DELETE FROM playlist_item WHERE type = 'dashboard_by_id' AND value = ?",
+			"DELETE FROM dashboard_version WHERE dashboard_id = ?",
 		}
 
 		for _, sql := range deletes {

+ 274 - 0
pkg/services/sqlstore/dashboard_version.go

@@ -0,0 +1,274 @@
+package sqlstore
+
+import (
+	"encoding/json"
+	"errors"
+	"time"
+
+	"github.com/go-xorm/xorm"
+	"github.com/grafana/grafana/pkg/bus"
+	"github.com/grafana/grafana/pkg/components/formatter"
+	"github.com/grafana/grafana/pkg/components/simplejson"
+	m "github.com/grafana/grafana/pkg/models"
+
+	diff "github.com/yudai/gojsondiff"
+	deltaFormatter "github.com/yudai/gojsondiff/formatter"
+)
+
+var (
+	// ErrUnsupportedDiffType occurs when an invalid diff type is used.
+	ErrUnsupportedDiffType = errors.New("sqlstore: unsupported diff type")
+
+	// ErrNilDiff occurs when two compared interfaces are identical.
+	ErrNilDiff = errors.New("sqlstore: diff is nil")
+)
+
+func init() {
+	bus.AddHandler("sql", CompareDashboardVersionsCommand)
+	bus.AddHandler("sql", GetDashboardVersion)
+	bus.AddHandler("sql", GetDashboardVersions)
+	bus.AddHandler("sql", RestoreDashboardVersion)
+}
+
+// CompareDashboardVersionsCommand computes the JSON diff of two versions,
+// assigning the delta of the diff to the `Delta` field.
+func CompareDashboardVersionsCommand(cmd *m.CompareDashboardVersionsCommand) error {
+	original, err := getDashboardVersion(cmd.DashboardId, cmd.Original)
+	if err != nil {
+		return err
+	}
+
+	newDashboard, err := getDashboardVersion(cmd.DashboardId, cmd.New)
+	if err != nil {
+		return err
+	}
+
+	left, jsonDiff, err := getDiff(original, newDashboard)
+	if err != nil {
+		return err
+	}
+
+	switch cmd.DiffType {
+	case m.DiffDelta:
+
+		deltaOutput, err := deltaFormatter.NewDeltaFormatter().Format(jsonDiff)
+		if err != nil {
+			return err
+		}
+		cmd.Delta = []byte(deltaOutput)
+
+	case m.DiffJSON:
+		jsonOutput, err := formatter.NewJSONFormatter(left).Format(jsonDiff)
+		if err != nil {
+			return err
+		}
+		cmd.Delta = []byte(jsonOutput)
+
+	case m.DiffBasic:
+		basicOutput, err := formatter.NewBasicFormatter(left).Format(jsonDiff)
+		if err != nil {
+			return err
+		}
+		cmd.Delta = basicOutput
+
+	default:
+		return ErrUnsupportedDiffType
+	}
+
+	return nil
+}
+
+// GetDashboardVersion gets the dashboard version for the given dashboard ID
+// and version number.
+func GetDashboardVersion(query *m.GetDashboardVersionCommand) error {
+	result, err := getDashboardVersion(query.DashboardId, query.Version)
+	if err != nil {
+		return err
+	}
+
+	query.Result = result
+	return nil
+}
+
+// GetDashboardVersions gets all dashboard versions for the given dashboard ID.
+func GetDashboardVersions(query *m.GetDashboardVersionsCommand) error {
+	order := ""
+
+	// the query builder in xorm doesn't provide a way to set
+	// a default order, so we perform this check
+	if query.OrderBy != "" {
+		order = " desc"
+	}
+	err := x.In("dashboard_id", query.DashboardId).
+		OrderBy(query.OrderBy+order).
+		Limit(query.Limit, query.Start).
+		Find(&query.Result)
+	if err != nil {
+		return err
+	}
+
+	if len(query.Result) < 1 {
+		return m.ErrNoVersionsForDashboardId
+	}
+	return nil
+}
+
+// RestoreDashboardVersion restores the dashboard data to the given version.
+func RestoreDashboardVersion(cmd *m.RestoreDashboardVersionCommand) error {
+	return inTransaction(func(sess *xorm.Session) error {
+		// check if dashboard version exists in dashboard_version table
+		//
+		// normally we could use the getDashboardVersion func here, but since
+		// we're in a transaction, we need to run the queries using the
+		// session instead of using the global `x`, so we copy those functions
+		// here, replacing `x` with `sess`
+		dashboardVersion := m.DashboardVersion{}
+		has, err := sess.Where(
+			"dashboard_id=? AND version=?",
+			cmd.DashboardId,
+			cmd.Version,
+		).Get(&dashboardVersion)
+		if err != nil {
+			return err
+		}
+		if !has {
+			return m.ErrDashboardVersionNotFound
+		}
+		dashboardVersion.Data.Set("id", dashboardVersion.DashboardId)
+
+		// get the dashboard version
+		dashboard := m.Dashboard{Id: cmd.DashboardId}
+		has, err = sess.Get(&dashboard)
+		if err != nil {
+			return err
+		}
+		if has == false {
+			return m.ErrDashboardNotFound
+		}
+
+		version, err := getMaxVersion(sess, dashboard.Id)
+		if err != nil {
+			return err
+		}
+
+		// revert and save to a new dashboard version
+		dashboard.Data = dashboardVersion.Data
+		dashboard.Updated = time.Now()
+		dashboard.UpdatedBy = cmd.UserId
+		dashboard.Version = version
+		dashboard.Data.Set("version", dashboard.Version)
+		affectedRows, err := sess.Id(dashboard.Id).Update(dashboard)
+		if err != nil {
+			return err
+		}
+		if affectedRows == 0 {
+			return m.ErrDashboardNotFound
+		}
+
+		// save that version a new version
+		dashVersion := &m.DashboardVersion{
+			DashboardId:   dashboard.Id,
+			ParentVersion: cmd.Version,
+			RestoredFrom:  cmd.Version,
+			Version:       dashboard.Version,
+			Created:       time.Now(),
+			CreatedBy:     dashboard.UpdatedBy,
+			Message:       "",
+			Data:          dashboard.Data,
+		}
+		affectedRows, err = sess.Insert(dashVersion)
+		if err != nil {
+			return err
+		}
+		if affectedRows == 0 {
+			return m.ErrDashboardNotFound
+		}
+
+		cmd.Result = &dashboard
+		return nil
+	})
+}
+
+// getDashboardVersion is a helper function that gets the dashboard version for
+// the given dashboard ID and version ID.
+func getDashboardVersion(dashboardId int64, version int) (*m.DashboardVersion, error) {
+	dashboardVersion := m.DashboardVersion{}
+	has, err := x.Where("dashboard_id=? AND version=?", dashboardId, version).Get(&dashboardVersion)
+	if err != nil {
+		return nil, err
+	}
+	if !has {
+		return nil, m.ErrDashboardVersionNotFound
+	}
+
+	dashboardVersion.Data.Set("id", dashboardVersion.DashboardId)
+	return &dashboardVersion, nil
+}
+
+// getDashboard gets a dashboard by ID. Used for retrieving the dashboard
+// associated with dashboard versions.
+func getDashboard(dashboardId int64) (*m.Dashboard, error) {
+	dashboard := m.Dashboard{Id: dashboardId}
+	has, err := x.Get(&dashboard)
+	if err != nil {
+		return nil, err
+	}
+	if has == false {
+		return nil, m.ErrDashboardNotFound
+	}
+	return &dashboard, nil
+}
+
+// getDiff computes the diff of two dashboard versions.
+func getDiff(originalDash, newDash *m.DashboardVersion) (interface{}, diff.Diff, error) {
+	leftBytes, err := simplejson.NewFromAny(originalDash).Encode()
+	if err != nil {
+		return nil, nil, err
+	}
+
+	rightBytes, err := simplejson.NewFromAny(newDash).Encode()
+	if err != nil {
+		return nil, nil, err
+	}
+
+	jsonDiff, err := diff.New().Compare(leftBytes, rightBytes)
+	if err != nil {
+		return nil, nil, err
+	}
+
+	if !jsonDiff.Modified() {
+		return nil, nil, ErrNilDiff
+	}
+
+	left := make(map[string]interface{})
+	err = json.Unmarshal(leftBytes, &left)
+	return left, jsonDiff, nil
+}
+
+type version struct {
+	Max int
+}
+
+// getMaxVersion returns the highest version number in the `dashboard_version`
+// table.
+//
+// This is necessary because sqlite3 doesn't support autoincrement in the same
+// way that Postgres or MySQL do, so we use this to get around that. Since it's
+// impossible to delete a version in Grafana, this is believed to be a
+// safe-enough alternative.
+func getMaxVersion(sess *xorm.Session, dashboardId int64) (int, error) {
+	v := version{}
+	has, err := sess.Table("dashboard_version").
+		Select("MAX(version) AS max").
+		Where("dashboard_id = ?", dashboardId).
+		Get(&v)
+	if !has {
+		return 0, m.ErrDashboardNotFound
+	}
+	if err != nil {
+		return 0, err
+	}
+
+	v.Max++
+	return v.Max, nil
+}

+ 188 - 0
pkg/services/sqlstore/dashboard_version_test.go

@@ -0,0 +1,188 @@
+package sqlstore
+
+import (
+	"reflect"
+	"testing"
+
+	. "github.com/smartystreets/goconvey/convey"
+
+	"github.com/grafana/grafana/pkg/components/simplejson"
+	m "github.com/grafana/grafana/pkg/models"
+)
+
+func updateTestDashboard(dashboard *m.Dashboard, data map[string]interface{}) {
+	data["title"] = dashboard.Title
+
+	saveCmd := m.SaveDashboardCommand{
+		OrgId:     dashboard.OrgId,
+		Overwrite: true,
+		Dashboard: simplejson.NewFromAny(data),
+	}
+
+	err := SaveDashboard(&saveCmd)
+	So(err, ShouldBeNil)
+}
+
+func TestGetDashboardVersion(t *testing.T) {
+	Convey("Testing dashboard version retrieval", t, func() {
+		InitTestDB(t)
+
+		Convey("Get a Dashboard ID and version ID", func() {
+			savedDash := insertTestDashboard("test dash 26", 1, "diff")
+
+			cmd := m.GetDashboardVersionCommand{
+				DashboardId: savedDash.Id,
+				Version:     savedDash.Version,
+			}
+
+			err := GetDashboardVersion(&cmd)
+			So(err, ShouldBeNil)
+			So(savedDash.Id, ShouldEqual, cmd.DashboardId)
+			So(savedDash.Version, ShouldEqual, cmd.Version)
+
+			dashCmd := m.GetDashboardQuery{
+				OrgId: savedDash.OrgId,
+				Slug:  savedDash.Slug,
+			}
+			err = GetDashboard(&dashCmd)
+			So(err, ShouldBeNil)
+			eq := reflect.DeepEqual(dashCmd.Result.Data, cmd.Result.Data)
+			So(eq, ShouldEqual, true)
+		})
+
+		Convey("Attempt to get a version that doesn't exist", func() {
+			cmd := m.GetDashboardVersionCommand{
+				DashboardId: int64(999),
+				Version:     123,
+			}
+
+			err := GetDashboardVersion(&cmd)
+			So(err, ShouldNotBeNil)
+			So(err, ShouldEqual, m.ErrDashboardVersionNotFound)
+		})
+	})
+}
+
+func TestGetDashboardVersions(t *testing.T) {
+	Convey("Testing dashboard versions retrieval", t, func() {
+		InitTestDB(t)
+		savedDash := insertTestDashboard("test dash 43", 1, "diff-all")
+
+		Convey("Get all versions for a given Dashboard ID", func() {
+			cmd := m.GetDashboardVersionsCommand{
+				DashboardId: savedDash.Id,
+			}
+
+			err := GetDashboardVersions(&cmd)
+			So(err, ShouldBeNil)
+			So(len(cmd.Result), ShouldEqual, 1)
+		})
+
+		Convey("Attempt to get the versions for a non-existent Dashboard ID", func() {
+			cmd := m.GetDashboardVersionsCommand{
+				DashboardId: int64(999),
+			}
+
+			err := GetDashboardVersions(&cmd)
+			So(err, ShouldNotBeNil)
+			So(err, ShouldEqual, m.ErrNoVersionsForDashboardId)
+			So(len(cmd.Result), ShouldEqual, 0)
+		})
+
+		Convey("Get all versions for an updated dashboard", func() {
+			updateTestDashboard(savedDash, map[string]interface{}{
+				"tags": "different-tag",
+			})
+
+			cmd := m.GetDashboardVersionsCommand{
+				DashboardId: savedDash.Id,
+			}
+			err := GetDashboardVersions(&cmd)
+			So(err, ShouldBeNil)
+			So(len(cmd.Result), ShouldEqual, 2)
+		})
+	})
+}
+
+func TestCompareDashboardVersions(t *testing.T) {
+	Convey("Testing dashboard version comparison", t, func() {
+		InitTestDB(t)
+
+		savedDash := insertTestDashboard("test dash 43", 1, "x")
+		updateTestDashboard(savedDash, map[string]interface{}{
+			"tags": "y",
+		})
+
+		Convey("Compare two versions that are different", func() {
+			getVersionCmd := m.GetDashboardVersionsCommand{
+				DashboardId: savedDash.Id,
+			}
+			err := GetDashboardVersions(&getVersionCmd)
+			So(err, ShouldBeNil)
+			So(len(getVersionCmd.Result), ShouldEqual, 2)
+
+			cmd := m.CompareDashboardVersionsCommand{
+				DashboardId: savedDash.Id,
+				Original:    getVersionCmd.Result[0].Version,
+				New:         getVersionCmd.Result[1].Version,
+				DiffType:    m.DiffDelta,
+			}
+			err = CompareDashboardVersionsCommand(&cmd)
+			So(err, ShouldBeNil)
+			So(cmd.Delta, ShouldNotBeNil)
+		})
+
+		Convey("Compare two versions that are the same", func() {
+			cmd := m.CompareDashboardVersionsCommand{
+				DashboardId: savedDash.Id,
+				Original:    savedDash.Version,
+				New:         savedDash.Version,
+				DiffType:    m.DiffDelta,
+			}
+
+			err := CompareDashboardVersionsCommand(&cmd)
+			So(err, ShouldNotBeNil)
+			So(cmd.Delta, ShouldBeNil)
+		})
+
+		Convey("Compare two versions that don't exist", func() {
+			cmd := m.CompareDashboardVersionsCommand{
+				DashboardId: savedDash.Id,
+				Original:    123,
+				New:         456,
+				DiffType:    m.DiffDelta,
+			}
+
+			err := CompareDashboardVersionsCommand(&cmd)
+			So(err, ShouldNotBeNil)
+			So(cmd.Delta, ShouldBeNil)
+		})
+	})
+}
+
+func TestRestoreDashboardVersion(t *testing.T) {
+	Convey("Testing dashboard version restoration", t, func() {
+		InitTestDB(t)
+		savedDash := insertTestDashboard("test dash 26", 1, "restore")
+		updateTestDashboard(savedDash, map[string]interface{}{
+			"tags": "not restore",
+		})
+
+		Convey("Restore dashboard to a previous version", func() {
+			versionsCmd := m.GetDashboardVersionsCommand{
+				DashboardId: savedDash.Id,
+			}
+			err := GetDashboardVersions(&versionsCmd)
+			So(err, ShouldBeNil)
+
+			cmd := m.RestoreDashboardVersionCommand{
+				DashboardId: savedDash.Id,
+				Version:     savedDash.Version,
+				UserId:      0,
+			}
+
+			err = RestoreDashboardVersion(&cmd)
+			So(err, ShouldBeNil)
+		})
+	})
+}

+ 54 - 0
pkg/services/sqlstore/migrations/dashboard_version_mig.go

@@ -0,0 +1,54 @@
+package migrations
+
+import . "github.com/grafana/grafana/pkg/services/sqlstore/migrator"
+
+func addDashboardVersionMigration(mg *Migrator) {
+	dashboardVersionV1 := Table{
+		Name: "dashboard_version",
+		Columns: []*Column{
+			{Name: "id", Type: DB_BigInt, IsPrimaryKey: true, IsAutoIncrement: true},
+			{Name: "dashboard_id", Type: DB_BigInt},
+			{Name: "parent_version", Type: DB_Int, Nullable: false},
+			{Name: "restored_from", Type: DB_Int, Nullable: false},
+			{Name: "version", Type: DB_Int, Nullable: false},
+			{Name: "created", Type: DB_DateTime, Nullable: false},
+			{Name: "created_by", Type: DB_BigInt, Nullable: false},
+			{Name: "message", Type: DB_Text, Nullable: false},
+			{Name: "data", Type: DB_Text, Nullable: false},
+		},
+		Indices: []*Index{
+			{Cols: []string{"dashboard_id"}},
+			{Cols: []string{"dashboard_id", "version"}, Type: UniqueIndex},
+		},
+	}
+
+	mg.AddMigration("create dashboard_version table v1", NewAddTableMigration(dashboardVersionV1))
+	mg.AddMigration("add index dashboard_version.dashboard_id", NewAddIndexMigration(dashboardVersionV1, dashboardVersionV1.Indices[0]))
+	mg.AddMigration("add unique index dashboard_version.dashboard_id and dashboard_version.version", NewAddIndexMigration(dashboardVersionV1, dashboardVersionV1.Indices[1]))
+
+	const rawSQL = `INSERT INTO dashboard_version
+(
+	dashboard_id,
+	version,
+	parent_version,
+	restored_from,
+	created,
+	created_by,
+	message,
+	data
+)
+SELECT
+	dashboard.id,
+	dashboard.version + 1,
+	dashboard.version,
+	dashboard.version,
+	dashboard.updated,
+	dashboard.updated_by,
+	'',
+	dashboard.data
+FROM dashboard;`
+	mg.AddMigration("save existing dashboard data in dashboard_version table v1", new(RawSqlMigration).
+		Sqlite(rawSQL).
+		Postgres(rawSQL).
+		Mysql(rawSQL))
+}

+ 1 - 0
pkg/services/sqlstore/migrations/migrations.go

@@ -25,6 +25,7 @@ func AddMigrations(mg *Migrator) {
 	addAlertMigrations(mg)
 	addAnnotationMig(mg)
 	addTestDataMigrations(mg)
+	addDashboardVersionMigration(mg)
 }
 
 func addMigrationLogMigrations(mg *Migrator) {

+ 1 - 0
public/app/core/core.ts

@@ -16,6 +16,7 @@ import "./directives/value_select_dropdown";
 import "./directives/plugin_component";
 import "./directives/rebuild_on_change";
 import "./directives/give_focus";
+import "./directives/diff-view";
 import './jquery_extended';
 import './partials';
 import './components/jsontree/jsontree';

+ 1 - 0
public/app/core/directives/dash_edit_link.js

@@ -8,6 +8,7 @@ function ($, coreModule) {
   var editViewMap = {
     'settings':    { src: 'public/app/features/dashboard/partials/settings.html'},
     'annotations': { src: 'public/app/features/annotations/partials/editor.html'},
+    'audit':       { src: 'public/app/features/dashboard/audit/partials/audit.html'},
     'templating':  { src: 'public/app/features/templating/partials/editor.html'},
     'import':      { src: '<dash-import></dash-import>' }
   };

+ 76 - 0
public/app/core/directives/diff-view.ts

@@ -0,0 +1,76 @@
+///<reference path="../../headers/common.d.ts" />
+
+import angular from 'angular';
+import coreModule from '../core_module';
+
+export class DeltaCtrl {
+  observer: any;
+
+  constructor(private $rootScope) {
+    const waitForCompile = function(mutations) {
+      if (mutations.length === 1) {
+        this.$rootScope.appEvent('json-diff-ready');
+      }
+    };
+
+    this.observer = new MutationObserver(waitForCompile.bind(this));
+
+    const observerConfig = {
+      attributes: true,
+      attributeFilter: ['class'],
+      characterData: false,
+      childList: true,
+      subtree: false,
+    };
+
+    this.observer.observe(angular.element('.delta-html')[0], observerConfig);
+  }
+
+  $onDestroy() {
+    this.observer.disconnect();
+  }
+}
+
+export function delta() {
+  return {
+    controller: DeltaCtrl,
+    replace: false,
+    restrict: 'A',
+  };
+}
+coreModule.directive('diffDelta', delta);
+
+// Link to JSON line number
+export class LinkJSONCtrl {
+  /** @ngInject */
+  constructor(private $scope, private $rootScope, private $anchorScroll) {}
+
+  goToLine(line: number) {
+    let unbind;
+
+    const scroll = () => {
+      this.$anchorScroll(`l${line}`);
+      unbind();
+    };
+
+    this.$scope.switchView().then(() => {
+      unbind = this.$rootScope.$on('json-diff-ready', scroll.bind(this));
+    });
+  }
+}
+
+export function linkJson() {
+  return {
+    controller: LinkJSONCtrl,
+    controllerAs: 'ctrl',
+    replace: true,
+    restrict: 'E',
+    scope: {
+      line: '@lineDisplay',
+      link: '@lineLink',
+      switchView: '&',
+    },
+    templateUrl: 'public/app/features/dashboard/audit/partials/link-json.html',
+  };
+}
+coreModule.directive('diffLinkJson', linkJson);

+ 14 - 0
public/app/core/directives/misc.js

@@ -18,6 +18,20 @@ function (angular, coreModule, kbn) {
     };
   });
 
+  coreModule.default.directive('compile', function($compile) {
+    return {
+      restrict: 'A',
+      link: function(scope, element, attrs) {
+        scope.$watch(function(scope) {
+          return scope.$eval(attrs.compile);
+        }, function(value) {
+          element.html(value);
+          $compile(element.contents())(scope);
+        });
+      }
+    };
+  });
+
   coreModule.default.directive('watchChange', function() {
     return {
       scope: { onchange: '&watchChange' },

+ 2 - 1
public/app/core/services/backend_srv.ts

@@ -202,7 +202,8 @@ export class BackendSrv {
 
   saveDashboard(dash, options) {
     options = (options || {});
-    return this.post('/api/dashboards/db/', {dashboard: dash, overwrite: options.overwrite === true});
+    const message = options.message || '';
+    return this.post('/api/dashboards/db/', {dashboard: dash, overwrite: options.overwrite === true, message});
   }
 }
 

+ 1 - 0
public/app/features/all.js

@@ -2,6 +2,7 @@ define([
   './panellinks/module',
   './dashlinks/module',
   './annotations/all',
+  './annotations/annotations_srv',
   './templating/all',
   './dashboard/all',
   './playlist/all',

+ 2 - 0
public/app/features/dashboard/all.js

@@ -1,10 +1,12 @@
 define([
   './dashboard_ctrl',
   './alerting_srv',
+  './audit/audit_srv',
   './dashboardLoaderSrv',
   './dashnav/dashnav',
   './submenu/submenu',
   './saveDashboardAsCtrl',
+  './saveDashboardMessageCtrl',
   './shareModalCtrl',
   './shareSnapshotCtrl',
   './dashboard_srv',

+ 235 - 0
public/app/features/dashboard/audit/audit_ctrl.ts

@@ -0,0 +1,235 @@
+///<reference path="../../../headers/common.d.ts" />
+
+import _ from 'lodash';
+import angular from 'angular';
+import moment from 'moment';
+
+import coreModule from 'app/core/core_module';
+
+import {DashboardModel} from '../model';
+import {AuditLogOpts, RevisionsModel} from './models';
+
+export class AuditLogCtrl {
+  appending: boolean;
+  dashboard: DashboardModel;
+  delta: { basic: string; html: string; };
+  diff: string;
+  limit: number;
+  loading: boolean;
+  max: number;
+  mode: string;
+  orderBy: string;
+  revisions: RevisionsModel[];
+  selected: number[];
+  start: number;
+
+  /** @ngInject */
+  constructor(private $scope,
+              private $rootScope,
+              private $window,
+              private $q,
+              private contextSrv,
+              private auditSrv) {
+    $scope.ctrl = this;
+
+    this.appending = false;
+    this.dashboard = $scope.dashboard;
+    this.diff = 'basic';
+    this.limit = 10;
+    this.loading = false;
+    this.max = 2;
+    this.mode = 'list';
+    this.orderBy = 'version';
+    this.selected = [];
+    this.start = 0;
+
+    this.resetFromSource();
+
+    $scope.$watch('ctrl.mode', newVal => {
+      $window.scrollTo(0, 0);
+      if (newVal === 'list') {
+        this.reset();
+      }
+    });
+
+    $rootScope.onAppEvent('dashboard-saved', this.onDashboardSaved.bind(this));
+  }
+
+  addToLog() {
+    this.start = this.start + this.limit;
+    this.getLog(true);
+  }
+
+  compareRevisionStateChanged(revision: any) {
+    if (revision.checked) {
+      this.selected.push(revision.version);
+    } else {
+      _.remove(this.selected, version => version === revision.version);
+    }
+    this.selected = _.sortBy(this.selected);
+  }
+
+  compareRevisionDisabled(checked: boolean) {
+    return (this.selected.length === this.max && !checked) || this.revisions.length === 1;
+  }
+
+  formatDate(date) {
+    date = moment.isMoment(date) ? date : moment(date);
+    const format = 'YYYY-MM-DD HH:mm:ss';
+
+    return this.dashboard.timezone === 'browser' ?
+      moment(date).format(format) :
+      moment.utc(date).format(format);
+  }
+
+  formatBasicDate(date) {
+    const now = this.dashboard.timezone === 'browser' ?  moment() : moment.utc();
+    const then = this.dashboard.timezone === 'browser' ?  moment(date) : moment.utc(date);
+    return then.from(now);
+  }
+
+  getDiff(diff: string) {
+    if (!this.isComparable()) { return; } // disable button but not tooltip
+
+    this.diff = diff;
+    this.mode = 'compare';
+    this.loading = true;
+
+    // instead of using lodash to find min/max we use the index
+    // due to the array being sorted in ascending order
+    const compare = {
+      new: this.selected[1],
+      original: this.selected[0],
+    };
+
+    if (this.delta[this.diff]) {
+      this.loading = false;
+      return this.$q.when(this.delta[this.diff]);
+    } else {
+      return this.auditSrv.compareVersions(this.dashboard, compare, diff).then(response => {
+        this.delta[this.diff] = response;
+      }).catch(err => {
+        this.mode = 'list';
+        this.$rootScope.appEvent('alert-error', ['There was an error fetching the diff', (err.message || err)]);
+      }).finally(() => { this.loading = false; });
+    }
+  }
+
+  getLog(append = false) {
+    this.loading = !append;
+    this.appending = append;
+    const options: AuditLogOpts = {
+      limit: this.limit,
+      start: this.start,
+      orderBy: this.orderBy,
+    };
+    return this.auditSrv.getAuditLog(this.dashboard, options).then(revisions => {
+      const formattedRevisions =  _.flow(
+        _.partialRight(_.map, rev => _.extend({}, rev, {
+          checked: false,
+          message: (revision => {
+            if (revision.message === '') {
+              if (revision.version === 1) {
+                return 'Dashboard\'s initial save';
+              }
+
+              if (revision.restoredFrom > 0) {
+                return `Restored from version ${revision.restoredFrom}`;
+              }
+
+              if (revision.parentVersion === 0) {
+                return 'Dashboard overwritten';
+              }
+
+              return 'Dashboard saved';
+            }
+            return revision.message;
+          })(rev),
+        })))(revisions);
+
+      this.revisions = append ? this.revisions.concat(formattedRevisions) : formattedRevisions;
+    }).catch(err => {
+      this.$rootScope.appEvent('alert-error', ['There was an error fetching the audit log', (err.message || err)]);
+    }).finally(() => {
+      this.loading = false;
+      this.appending = false;
+    });
+  }
+
+  getMeta(version: number, property: string) {
+    const revision = _.find(this.revisions, rev => rev.version === version);
+    return revision[property];
+  }
+
+  isOriginalCurrent() {
+    return this.selected[1] === this.dashboard.version;
+  }
+
+  isComparable() {
+    const isParamLength = this.selected.length === 2;
+    const areNumbers = this.selected.every(version => _.isNumber(version));
+    const areValidVersions = _.filter(this.revisions, revision => {
+      return revision.version === this.selected[0] || revision.version === this.selected[1];
+    }).length === 2;
+    return isParamLength && areNumbers && areValidVersions;
+  }
+
+  isLastPage() {
+    return _.find(this.revisions, rev => rev.version === 1);
+  }
+
+  onDashboardSaved() {
+    this.$rootScope.appEvent('hide-dash-editor');
+  }
+
+  reset() {
+    this.delta = { basic: '', html: '' };
+    this.diff = 'basic';
+    this.mode = 'list';
+    this.revisions = _.map(this.revisions, rev => _.extend({}, rev, { checked: false }));
+    this.selected = [];
+    this.start = 0;
+  }
+
+  resetFromSource() {
+    this.revisions = [];
+    return this.getLog().then(this.reset.bind(this));
+  }
+
+  restore(version: number) {
+    this.$rootScope.appEvent('confirm-modal', {
+      title: 'Restore version',
+      text: '',
+      text2: `Are you sure you want to restore the dashboard to version ${version}? All unsaved changes will be lost.`,
+      icon: 'fa-rotate-right',
+      yesText: `Yes, restore to version ${version}`,
+      onConfirm: this.restoreConfirm.bind(this, version),
+    });
+  }
+
+  restoreConfirm(version: number) {
+    this.loading = true;
+    return this.auditSrv.restoreDashboard(this.dashboard, version).then(response => {
+      this.revisions.unshift({
+        id: this.revisions[0].id + 1,
+        checked: false,
+        dashboardId: this.dashboard.id,
+        parentVersion: version,
+        version: this.revisions[0].version + 1,
+        created: new Date(),
+        createdBy: this.contextSrv.user.name,
+        message: `Restored from version ${version}`,
+      });
+
+      this.reset();
+      const restoredData = response.dashboard;
+      this.dashboard = restoredData.dashboard;
+      this.dashboard.meta = restoredData.meta;
+      this.$scope.setupDashboard(restoredData);
+    }).catch(err => {
+      this.$rootScope.appEvent('alert-error', ['There was an error restoring the dashboard', (err.message || err)]);
+    }).finally(() => { this.loading = false; });
+  }
+}
+
+coreModule.controller('AuditLogCtrl', AuditLogCtrl);

+ 32 - 0
public/app/features/dashboard/audit/audit_srv.ts

@@ -0,0 +1,32 @@
+///<reference path="../../../headers/common.d.ts" />
+
+import './audit_ctrl';
+
+import _ from 'lodash';
+import coreModule from 'app/core/core_module';
+import {DashboardModel} from '../model';
+import {AuditLogOpts} from './models';
+
+export class AuditSrv {
+  /** @ngInject */
+  constructor(private backendSrv, private $q) {}
+
+  getAuditLog(dashboard: DashboardModel, options: AuditLogOpts) {
+    const id = dashboard && dashboard.id ? dashboard.id : void 0;
+    return id ? this.backendSrv.get(`api/dashboards/db/${id}/versions`, options) : this.$q.when([]);
+  }
+
+  compareVersions(dashboard: DashboardModel, compare: { new: number, original: number }, view = 'html') {
+    const id = dashboard && dashboard.id ? dashboard.id : void 0;
+    const url = `api/dashboards/db/${id}/compare/${compare.original}...${compare.new}/${view}`;
+    return id ? this.backendSrv.get(url) : this.$q.when({});
+  }
+
+  restoreDashboard(dashboard: DashboardModel, version: number) {
+    const id = dashboard && dashboard.id ? dashboard.id : void 0;
+    const url = `api/dashboards/db/${id}/restore`;
+    return id && _.isNumber(version) ? this.backendSrv.post(url, { version }) : this.$q.when({});
+  }
+}
+
+coreModule.service('auditSrv', AuditSrv);

+ 16 - 0
public/app/features/dashboard/audit/models.ts

@@ -0,0 +1,16 @@
+export interface AuditLogOpts {
+  limit: number;
+  start: number;
+  orderBy: string;
+}
+
+export interface RevisionsModel {
+  id: number;
+  checked: boolean;
+  dashboardId: number;
+  parentVersion: number;
+  version: number;
+  created: Date;
+  createdBy: string;
+  message: string;
+}

+ 161 - 0
public/app/features/dashboard/audit/partials/audit.html

@@ -0,0 +1,161 @@
+<div ng-controller="AuditLogCtrl">
+	<div class="tabbed-view-header">
+		<h2 class="tabbed-view-title">
+			Changelog
+		</h2>
+
+		<ul class="gf-tabs">
+			<li class="gf-tabs-item" >
+				<a class="gf-tabs-link" ng-click="ctrl.mode = 'list';" ng-class="{active: ctrl.mode === 'list'}">
+					List
+				</a>
+			</li>
+			<li class="gf-tabs-item" ng-show="ctrl.mode === 'compare'">
+				<span ng-if="ctrl.isOriginalCurrent()" class="active gf-tabs-link">
+					Version {{ctrl.selected[0]}} <i class="fa fa-arrows-h" /> Current
+				</span>
+				<span ng-if="!ctrl.isOriginalCurrent()" class="active gf-tabs-link">
+					Version {{ctrl.selected[0]}} <i class="fa fa-arrows-h" /> Version {{ctrl.selected[1]}}
+				</span>
+			</li>
+		</ul>
+
+		<button class="tabbed-view-close-btn" ng-click="dismiss();">
+			<i class="fa fa-remove"></i>
+		</button>
+	</div>
+
+	<div class="tabbed-view-body">
+
+		<div ng-if="ctrl.mode === 'list'">
+			<div ng-if="ctrl.loading">
+				<i class="fa fa-spinner fa-spin"></i>
+				<em>Fetching audit log&hellip;</em>
+			</div>
+
+			<div ng-if="!ctrl.loading">
+				<div class="audit-table gf-form">
+					<div class="gf-form-group">
+						<table class="filter-table">
+							<thead>
+								<tr>
+									<th class="width-4"></th>
+									<th class="width-4">Version</th>
+									<th class="width-14">Date</th>
+									<th class="width-10">Updated By</th>
+									<th class="width-30">Notes</th>
+									<th></th>
+								</tr>
+							</thead>
+							<tbody>
+								<tr ng-repeat="revision in ctrl.revisions">
+									<td bs-tooltip="ctrl.compareRevisionDisabled(revision.checked) ? 'You can only compare 2 versions at a time' : ''">
+										<gf-form-switch
+											checked="revision.checked"
+											on-change="ctrl.compareRevisionStateChanged(revision)"
+											ng-disabled="ctrl.compareRevisionDisabled(revision.checked)">
+										</gf-form-switch>
+									</td>
+									<td>{{revision.version}}</td>
+									<td>{{ctrl.formatDate(revision.created)}}</td>
+									<td>{{revision.createdBy}}</td>
+									<td>{{revision.message}}</td>
+									<td class="text-right">
+										<a class="btn btn-inverse btn-small" ng-show="revision.version !== ctrl.dashboard.version" ng-click="ctrl.restore(revision.version)">
+											<i class="fa fa-rotate-right"></i>&nbsp;&nbsp;Restore
+										</a>
+										<a class="btn btn-outline-disabled btn-small" ng-show="revision.version === ctrl.dashboard.version">
+											<i class="fa fa-check"></i>&nbsp;&nbsp;Current
+										</a>
+									</td>
+								</tr>
+							</tbody>
+						</table>
+
+					<div ng-if="ctrl.appending">
+						<i class="fa fa-spinner fa-spin"></i>
+						<em>Fetching more entries&hellip;</em>
+					</div>
+
+						<div class="gf-form-group" ng-show="ctrl.mode === 'list'">
+							<div class="gf-form-button-row">
+								<a	type="button"
+										class="btn gf-form-button btn-primary"
+										ng-if="ctrl.revisions.length > 1"
+										ng-class="{disabled: !ctrl.isComparable()}"
+										ng-click="ctrl.getDiff(ctrl.diff)"
+										bs-tooltip="ctrl.isComparable() ? '' : 'Select 2 versions to start comparing'">
+									<i class="fa fa-code-fork" ></i>&nbsp;&nbsp;Compare versions
+								</a>
+								<a  type="button"
+										class="btn gf-form-button btn-inverse"
+										ng-if="ctrl.revisions.length >= ctrl.limit"
+										ng-click="ctrl.addToLog()"
+										ng-class="{disabled: ctrl.isLastPage()}"
+										ng-disabled="ctrl.isLastPage()">
+									Show more versions
+								</a>
+							</div>
+						</div>
+					</div>
+				</div>
+			</div>
+		</div>
+
+		<div class="audit-log" ng-if="ctrl.mode === 'compare'">
+			<div class="page-container">
+				<div class="page-body">
+					<aside class="page-sidebar">
+						<section class="page-sidebar-section">
+							<ul class="ui-list">
+								<li><a ng-class="{active: ctrl.diff === 'basic'}" ng-click="ctrl.getDiff('basic')" href="">Change Summary</a></li>
+								<li><a ng-class="{active: ctrl.diff === 'html'}" ng-click="ctrl.getDiff('html')" href="">JSON Code View</a></li>
+							</ul>
+						</section>
+					</aside>
+
+					<div class="tab-content page-content-with-sidebar">
+						<div ng-if="ctrl.loading">
+							<i class="fa fa-spinner fa-spin"></i>
+							<em>Fetching changes&hellip;</em>
+						</div>
+
+						<div ng-if="!ctrl.loading" ng-init="new = ctrl.selected[0]; original = ctrl.selected[1]">
+							<a type="button"
+								class="btn gf-form-button btn-primary diff-restore-btn"
+								ng-click="ctrl.restore(new)"
+								ng-if="ctrl.isOriginalCurrent()">
+								<i class="fa fa-rotate-right" ></i>&nbsp;&nbsp;Restore to version {{new}}
+							</a>
+							<h4>
+								Comparing Version {{ctrl.selected[0]}}
+								<i class="fa fa-arrows-h" />
+								Version {{ctrl.selected[1]}}
+								<cite class="muted" ng-if="ctrl.isOriginalCurrent()">(Current)</cite>
+							</h4>
+							<section ng-if="ctrl.diff === 'basic'">
+								<p class="small muted">
+									<strong>Version {{new}}</strong> updated by
+									<span>{{ctrl.getMeta(new, 'createdBy')}} </span>
+									<span>{{ctrl.formatBasicDate(ctrl.getMeta(new, 'created'))}}</span>
+									<span> - {{ctrl.getMeta(new, 'message')}}</span>
+								</p>
+								<p class="small muted">
+									<strong>Version {{original}}</strong> updated by
+									<span>{{ctrl.getMeta(original, 'createdBy')}} </span>
+									<span>{{ctrl.formatBasicDate(ctrl.getMeta(original, 'created'))}}</span>
+									<span> - {{ctrl.getMeta(original, 'message')}}</span>
+								</p>
+							</section>
+							<div id="delta" diff-delta>
+								<div class="delta-basic" ng-show="ctrl.diff === 'basic'" compile="ctrl.delta.basic" />
+								<div class="delta-html" ng-show="ctrl.diff === 'html'" compile="ctrl.delta.html" />
+							</div>
+						</div>
+					</div>
+				</div>
+			</div>
+		</div>
+
+	</div>
+</div>

+ 4 - 0
public/app/features/dashboard/audit/partials/link-json.html

@@ -0,0 +1,4 @@
+<a class="change list-linenum diff-linenum btn btn-inverse btn-small" ng-click="ctrl.goToLine(link)">
+  Line {{ line }}
+</a>
+

+ 52 - 29
public/app/features/dashboard/dashboard_srv.ts

@@ -23,32 +23,7 @@ export class DashboardSrv {
     return this.dash;
   }
 
-  saveDashboard(options) {
-    if (!this.dash.meta.canSave && options.makeEditable !== true) {
-      return Promise.resolve();
-    }
-
-    if (this.dash.title === 'New dashboard') {
-      return this.saveDashboardAs();
-    }
-
-    var clone = this.dash.getSaveModelClone();
-
-    return this.backendSrv.saveDashboard(clone, options).then(data => {
-      this.dash.version = data.version;
-
-      this.$rootScope.appEvent('dashboard-saved', this.dash);
-
-      var dashboardUrl = '/dashboard/db/' + data.slug;
-      if (dashboardUrl !== this.$location.path()) {
-        this.$location.url(dashboardUrl);
-      }
-
-      this.$rootScope.appEvent('alert-success', ['Dashboard saved', 'Saved as ' + clone.title]);
-    }).catch(this.handleSaveDashboardError.bind(this));
-  }
-
-  handleSaveDashboardError(err) {
+  handleSaveDashboardError(clone, err) {
     if (err.data && err.data.status === "version-mismatch") {
       err.isHandled = true;
 
@@ -59,7 +34,7 @@ export class DashboardSrv {
         yesText: "Save & Overwrite",
         icon: "fa-warning",
         onConfirm: () => {
-          this.saveDashboard({overwrite: true});
+          this.saveDashboard({overwrite: true}, clone);
         }
       });
     }
@@ -74,7 +49,7 @@ export class DashboardSrv {
         yesText: "Save & Overwrite",
         icon: "fa-warning",
         onConfirm: () => {
-          this.saveDashboard({overwrite: true});
+          this.saveDashboard({overwrite: true}, clone);
         }
       });
     }
@@ -93,12 +68,50 @@ export class DashboardSrv {
           this.saveDashboardAs();
         },
         onConfirm: () => {
-          this.saveDashboard({overwrite: true});
+          this.saveDashboard({overwrite: true}, clone);
         }
       });
     }
   }
 
+  postSave(clone, data) {
+    this.dash.version = data.version;
+
+    var dashboardUrl = '/dashboard/db/' + data.slug;
+    if (dashboardUrl !== this.$location.path()) {
+      this.$location.url(dashboardUrl);
+    }
+
+    this.$rootScope.appEvent('dashboard-saved', this.dash);
+    this.$rootScope.appEvent('alert-success', ['Dashboard saved', 'Saved as ' + clone.title]);
+  }
+
+  save(clone, options) {
+    return this.backendSrv.saveDashboard(clone, options)
+      .then(this.postSave.bind(this, clone))
+      .catch(this.handleSaveDashboardError.bind(this, clone));
+  }
+
+  saveDashboard(options, clone) {
+    if (clone) {
+      this.setCurrent(this.create(clone, this.dash.meta));
+    }
+
+    if (!this.dash.meta.canSave && options.makeEditable !== true) {
+      return Promise.resolve();
+    }
+
+    if (this.dash.title === 'New dashboard') {
+      return this.saveDashboardAs();
+    }
+
+    if (this.dash.version > 0) {
+      return this.saveDashboardMessage();
+    }
+
+    return this.save(this.dash.getSaveModelClone(), options);
+  }
+
   saveDashboardAs() {
     var newScope = this.$rootScope.$new();
     newScope.clone = this.dash.getSaveModelClone();
@@ -112,6 +125,16 @@ export class DashboardSrv {
     });
   }
 
+  saveDashboardMessage() {
+    var newScope = this.$rootScope.$new();
+    newScope.clone = this.dash.getSaveModelClone();
+
+    this.$rootScope.appEvent('show-modal', {
+      src: 'public/app/features/dashboard/partials/saveDashboardMessage.html',
+      scope: newScope,
+      modalClass: 'modal--narrow'
+    });
+  }
 }
 
 coreModule.service('dashboardSrv', DashboardSrv);

+ 3 - 1
public/app/features/dashboard/dashnav/dashnav.html

@@ -56,7 +56,8 @@
 		</ul>
 	</li>
 	<li ng-show="::dashboardMeta.canSave">
-		<a ng-click="saveDashboard()" bs-tooltip="'Save dashboard <br> CTRL+S'" data-placement="bottom"><i class="fa fa-save"></i></a>
+		<a ng-show="dashboard.version === 0" ng-click="saveDashboard()" bs-tooltip="'Save dashboard <br> CTRL+S'" data-placement="bottom"><i class="fa fa-save"></i></a>
+		<a ng-show="dashboard.version > 0" ng-click="saveDashboard()" bs-tooltip="'Save to changelog <br> CTRL+S'" data-placement="bottom"><i class="fa fa-save"></i></a>
 	</li>
 	<li ng-if="dashboard.snapshot.originalUrl">
 		<a ng-href="{{dashboard.snapshot.originalUrl}}" bs-tooltip="'Open original dashboard'" data-placement="bottom"><i class="fa fa-link"></i></a>
@@ -66,6 +67,7 @@
 		<ul class="dropdown-menu">
 			<li ng-if="dashboardMeta.canEdit"><a class="pointer" ng-click="openEditView('settings');">Settings</a></li>
 			<li ng-if="dashboardMeta.canEdit"><a class="pointer" ng-click="openEditView('annotations');">Annotations</a></li>
+			<li ng-if="dashboardMeta.canEdit && dashboard.version > 0 && !dashboardMeta.isHome"><a class="pointer" ng-click="openEditView('audit');">Changelog</a></li>
 			<li ng-if="dashboardMeta.canEdit"><a class="pointer" ng-click="openEditView('templating');">Templating</a></li>
 			<li ng-if="dashboardMeta.canEdit"><a class="pointer" ng-click="viewJson();">View JSON</a></li>
 			<li ng-if="contextSrv.isEditor && !dashboard.editable"><a class="pointer" ng-click="makeEditable();">Make Editable</a></li>

+ 49 - 0
public/app/features/dashboard/partials/saveDashboardMessage.html

@@ -0,0 +1,49 @@
+<div class="modal-body" ng-controller="SaveDashboardMessageCtrl" ng-init="init();">
+	<div class="modal-header">
+		<h2 class="modal-header-title">
+			<i class="fa fa-save"></i>
+			<span class="p-l-1">Save to changelog</span>
+		</h2>
+
+		<a class="modal-header-close" ng-click="dismiss();">
+			<i class="fa fa-remove"></i>
+		</a>
+	</div>
+
+	<form name="saveMessage" ng-submit="saveVersion(saveMessage.$valid)" class="modal-content" novalidate>
+		<h6 class="text-center">Add a note to describe the changes in this version</h6>
+		<div class="p-t-2">
+			<div class="gf-form">
+				<label class="gf-form-hint">
+					<input
+						type="text"
+						name="message"
+						class="gf-form-input"
+						placeholder="Updates to &hellip;"
+						give-focus="true"
+						ng-model="clone.message"
+						ng-model-options="{allowInvalid: true}"
+						ng-keydown="keyDown($event)"
+						ng-maxlength="clone.max"
+						autocomplete="off"
+						required />
+					<small class="gf-form-hint-text muted" ng-cloak>
+						<span ng-class="{'text-error': saveMessage.message.$invalid && saveMessage.message.$dirty }">
+							{{clone.message.length || 0}}
+						</span>
+						/ {{clone.max}} characters
+					</small>
+				</label>
+			</div>
+		</div>
+
+		<div class="gf-form-button-row text-center">
+			<button type="submit" class="btn btn-success" ng-disabled="saveMessage.$invalid">
+				Save to changelog
+			</button>
+			<button class="btn btn-inverse" ng-click="dismiss();">Cancel</button>
+		</div>
+	</form>
+</div>
+
+

+ 3 - 28
public/app/features/dashboard/saveDashboardAsCtrl.js

@@ -6,7 +6,7 @@ function (angular) {
 
   var module = angular.module('grafana.controllers');
 
-  module.controller('SaveDashboardAsCtrl', function($scope, backendSrv, $location) {
+  module.controller('SaveDashboardAsCtrl', function($scope, dashboardSrv) {
 
     $scope.init = function() {
       $scope.clone.id = null;
@@ -24,17 +24,6 @@ function (angular) {
       delete $scope.clone.autoUpdate;
     };
 
-    function saveDashboard(options) {
-      return backendSrv.saveDashboard($scope.clone, options).then(function(result) {
-        $scope.appEvent('alert-success', ['Dashboard saved', 'Saved as ' + $scope.clone.title]);
-
-        $location.url('/dashboard/db/' + result.slug);
-
-        $scope.appEvent('dashboard-saved', $scope.clone);
-        $scope.dismiss();
-      });
-    }
-
     $scope.keyDown = function (evt) {
       if (evt.keyCode === 13) {
         $scope.saveClone();
@@ -42,22 +31,8 @@ function (angular) {
     };
 
     $scope.saveClone = function() {
-      saveDashboard({overwrite: false}).then(null, function(err) {
-        if (err.data && err.data.status === "name-exists") {
-          err.isHandled = true;
-
-          $scope.appEvent('confirm-modal', {
-            title: 'Conflict',
-            text: 'Dashboard with the same name exists.',
-            text2: 'Would you still like to save this dashboard?',
-            yesText: "Save & Overwrite",
-            icon: "fa-warning",
-            onConfirm: function() {
-              saveDashboard({overwrite: true});
-            }
-          });
-        }
-      });
+      return dashboardSrv.save($scope.clone, {overwrite: false})
+        .then(function() { $scope.dismiss(); });
     };
   });
 

+ 29 - 0
public/app/features/dashboard/saveDashboardMessageCtrl.js

@@ -0,0 +1,29 @@
+define([
+  'angular',
+],
+function (angular) {
+  'use strict';
+
+  var module = angular.module('grafana.controllers');
+
+  module.controller('SaveDashboardMessageCtrl', function($scope, dashboardSrv) {
+
+    $scope.init = function() {
+      $scope.clone.message = '';
+      $scope.clone.max = 64;
+    };
+
+    function saveDashboard(options) {
+      options.message = $scope.clone.message;
+      return dashboardSrv.save($scope.clone, options)
+        .then(function() { $scope.dismiss(); });
+    }
+
+    $scope.saveVersion = function(isValid) {
+      if (!isValid) { return; }
+      saveDashboard({overwrite: false});
+    };
+  });
+
+});
+

+ 416 - 0
public/app/features/dashboard/specs/audit_ctrl_specs.ts

@@ -0,0 +1,416 @@
+import {describe, beforeEach, it, sinon, expect, angularMocks} from 'test/lib/common';
+
+import _ from 'lodash';
+import {AuditLogCtrl} from 'app/features/dashboard/audit/audit_ctrl';
+import { versions, compare, restore } from 'test/mocks/audit-mocks';
+import config from 'app/core/config';
+
+describe('AuditLogCtrl', function() {
+  var RESTORE_ID = 4;
+
+  var ctx: any = {};
+  var versionsResponse: any = versions();
+  var restoreResponse: any = restore(7, RESTORE_ID);
+
+  beforeEach(angularMocks.module('grafana.core'));
+  beforeEach(angularMocks.module('grafana.services'));
+  beforeEach(angularMocks.inject($rootScope => {
+    ctx.scope = $rootScope.$new();
+  }));
+
+  var auditSrv;
+  var $rootScope;
+  beforeEach(function() {
+    auditSrv = {
+      getAuditLog: sinon.stub(),
+      compareVersions: sinon.stub(),
+      restoreDashboard: sinon.stub(),
+    };
+    $rootScope = {
+      appEvent: sinon.spy(),
+      onAppEvent: sinon.spy(),
+    };
+  });
+
+  describe('when the audit log component is loaded', function() {
+    var deferred;
+
+    beforeEach(angularMocks.inject(($controller, $q) => {
+      deferred = $q.defer();
+      auditSrv.getAuditLog.returns(deferred.promise);
+      ctx.ctrl = $controller(AuditLogCtrl, {
+        auditSrv,
+        $rootScope,
+        $scope: ctx.scope,
+      });
+    }));
+
+    it('should immediately attempt to fetch the audit log', function() {
+      expect(auditSrv.getAuditLog.calledOnce).to.be(true);
+    });
+
+    describe('and the audit log is successfully fetched', function() {
+      beforeEach(function() {
+        deferred.resolve(versionsResponse);
+        ctx.ctrl.$scope.$apply();
+      });
+
+      it('should reset the controller\'s state', function() {
+        expect(ctx.ctrl.mode).to.be('list');
+        expect(ctx.ctrl.delta).to.eql({ basic: '', html: '' });
+        expect(ctx.ctrl.selected.length).to.be(0);
+        expect(ctx.ctrl.selected).to.eql([]);
+        expect(_.find(ctx.ctrl.revisions, rev => rev.checked)).to.be.undefined;
+      });
+
+      it('should indicate loading has finished', function() {
+        expect(ctx.ctrl.loading).to.be(false);
+      });
+
+      it('should store the revisions sorted desc by version id', function() {
+        expect(ctx.ctrl.revisions[0].version).to.be(4);
+        expect(ctx.ctrl.revisions[1].version).to.be(3);
+        expect(ctx.ctrl.revisions[2].version).to.be(2);
+        expect(ctx.ctrl.revisions[3].version).to.be(1);
+      });
+
+      it('should add a checked property to each revision', function() {
+        var actual = _.filter(ctx.ctrl.revisions, rev => rev.hasOwnProperty('checked'));
+        expect(actual.length).to.be(4);
+      });
+
+      it('should set all checked properties to false on reset', function() {
+        ctx.ctrl.revisions[0].checked = true;
+        ctx.ctrl.revisions[2].checked = true;
+        ctx.ctrl.selected = [0, 2];
+        ctx.ctrl.reset();
+        var actual = _.filter(ctx.ctrl.revisions, rev => !rev.checked);
+        expect(actual.length).to.be(4);
+        expect(ctx.ctrl.selected).to.eql([]);
+      });
+
+      it('should add a default message to versions without a message', function() {
+        expect(ctx.ctrl.revisions[0].message).to.be('Dashboard saved');
+      });
+
+      it('should add a message to revisions restored from another version', function() {
+        expect(ctx.ctrl.revisions[1].message).to.be('Restored from version 1');
+      });
+
+      it('should add a message to entries that overwrote version history', function() {
+        expect(ctx.ctrl.revisions[2].message).to.be('Dashboard overwritten');
+      });
+
+      it('should add a message to the initial dashboard save', function() {
+        expect(ctx.ctrl.revisions[3].message).to.be('Dashboard\'s initial save');
+      });
+    });
+
+    describe('and fetching the audit log fails', function() {
+      beforeEach(function() {
+        deferred.reject(new Error('AuditLogError'));
+        ctx.ctrl.$scope.$apply();
+      });
+
+      it('should reset the controller\'s state', function() {
+        expect(ctx.ctrl.mode).to.be('list');
+        expect(ctx.ctrl.delta).to.eql({ basic: '', html: '' });
+        expect(ctx.ctrl.selected.length).to.be(0);
+        expect(ctx.ctrl.selected).to.eql([]);
+        expect(_.find(ctx.ctrl.revisions, rev => rev.checked)).to.be.undefined;
+      });
+
+      it('should indicate loading has finished', function() {
+        expect(ctx.ctrl.loading).to.be(false);
+      });
+
+      it('should broadcast an event indicating the failure', function() {
+        expect($rootScope.appEvent.calledOnce).to.be(true);
+        expect($rootScope.appEvent.calledWith('alert-error')).to.be(true);
+      });
+
+      it('should have an empty revisions list', function() {
+        expect(ctx.ctrl.revisions).to.eql([]);
+      });
+    });
+
+    describe('should update the audit log when the dashboard is saved', function() {
+      beforeEach(function() {
+        ctx.ctrl.dashboard = { version: 3 };
+        ctx.ctrl.resetFromSource = sinon.spy();
+      });
+
+      it('should listen for the `dashboard-saved` appEvent', function() {
+        expect($rootScope.onAppEvent.calledOnce).to.be(true);
+        expect($rootScope.onAppEvent.getCall(0).args[0]).to.be('dashboard-saved');
+      });
+
+      it('should call `onDashboardSaved` when the appEvent is received', function() {
+        expect($rootScope.onAppEvent.getCall(0).args[1]).to.not.be(ctx.ctrl.onDashboardSaved);
+        expect($rootScope.onAppEvent.getCall(0).args[1].toString).to.be(ctx.ctrl.onDashboardSaved.toString);
+      });
+
+      it('should emit an appEvent to hide the changelog', function() {
+        ctx.ctrl.onDashboardSaved();
+        expect($rootScope.appEvent.calledOnce).to.be(true);
+        expect($rootScope.appEvent.getCall(0).args[0]).to.be('hide-dash-editor');
+      });
+    });
+  });
+
+  describe('when the user wants to compare two revisions', function() {
+    var deferred;
+
+    beforeEach(angularMocks.inject(($controller, $q) => {
+      deferred = $q.defer();
+      auditSrv.getAuditLog.returns($q.when(versionsResponse));
+      auditSrv.compareVersions.returns(deferred.promise);
+      ctx.ctrl = $controller(AuditLogCtrl, {
+        auditSrv,
+        $rootScope,
+        $scope: ctx.scope,
+      });
+      ctx.ctrl.$scope.onDashboardSaved = sinon.spy();
+      ctx.ctrl.$scope.$apply();
+    }));
+
+    it('should have already fetched the audit log', function() {
+      expect(auditSrv.getAuditLog.calledOnce).to.be(true);
+      expect(ctx.ctrl.revisions.length).to.be.above(0);
+    });
+
+    it('should check that two valid versions are selected', function() {
+      // []
+      expect(ctx.ctrl.isComparable()).to.be(false);
+
+      // single value
+      ctx.ctrl.selected = [4];
+      expect(ctx.ctrl.isComparable()).to.be(false);
+
+      // both values in range
+      ctx.ctrl.selected = [4, 2];
+      expect(ctx.ctrl.isComparable()).to.be(true);
+
+      // values out of range
+      ctx.ctrl.selected = [7, 4];
+      expect(ctx.ctrl.isComparable()).to.be(false);
+    });
+
+    describe('and the basic diff is successfully fetched', function() {
+      beforeEach(function() {
+        deferred.resolve(compare('basic'));
+        ctx.ctrl.selected = [3, 1];
+        ctx.ctrl.getDiff('basic');
+        ctx.ctrl.$scope.$apply();
+      });
+
+      it('should fetch the basic diff if two valid versions are selected', function() {
+        expect(auditSrv.compareVersions.calledOnce).to.be(true);
+        expect(ctx.ctrl.delta.basic).to.be('<div></div>');
+        expect(ctx.ctrl.delta.html).to.be('');
+      });
+
+      it('should set the basic diff view as active', function() {
+        expect(ctx.ctrl.mode).to.be('compare');
+        expect(ctx.ctrl.diff).to.be('basic');
+      });
+
+      it('should indicate loading has finished', function() {
+        expect(ctx.ctrl.loading).to.be(false);
+      });
+    });
+
+    describe('and the json diff is successfully fetched', function() {
+      beforeEach(function() {
+        deferred.resolve(compare('html'));
+        ctx.ctrl.selected = [3, 1];
+        ctx.ctrl.getDiff('html');
+        ctx.ctrl.$scope.$apply();
+      });
+
+      it('should fetch the json diff if two valid versions are selected', function() {
+        expect(auditSrv.compareVersions.calledOnce).to.be(true);
+        expect(ctx.ctrl.delta.basic).to.be('');
+        expect(ctx.ctrl.delta.html).to.be('<pre><code></code></pre>');
+      });
+
+      it('should set the json diff view as active', function() {
+        expect(ctx.ctrl.mode).to.be('compare');
+        expect(ctx.ctrl.diff).to.be('html');
+      });
+
+      it('should indicate loading has finished', function() {
+        expect(ctx.ctrl.loading).to.be(false);
+      });
+    });
+
+    describe('and diffs have already been fetched', function() {
+      beforeEach(function() {
+        deferred.resolve(compare('basic'));
+        ctx.ctrl.selected = [3, 1];
+        ctx.ctrl.delta.basic = 'cached basic';
+        ctx.ctrl.getDiff('basic');
+        ctx.ctrl.$scope.$apply();
+      });
+
+      it('should use the cached diffs instead of fetching', function() {
+        expect(auditSrv.compareVersions.calledOnce).to.be(false);
+        expect(ctx.ctrl.delta.basic).to.be('cached basic');
+      });
+
+      it('should indicate loading has finished', function() {
+        expect(ctx.ctrl.loading).to.be(false);
+      });
+    });
+
+    describe('and fetching the diff fails', function() {
+      beforeEach(function() {
+        deferred.reject(new Error('DiffError'));
+        ctx.ctrl.selected = [4, 2];
+        ctx.ctrl.getDiff('basic');
+        ctx.ctrl.$scope.$apply();
+      });
+
+      it('should fetch the diff if two valid versions are selected', function() {
+        expect(auditSrv.compareVersions.calledOnce).to.be(true);
+      });
+
+      it('should return to the audit log view', function() {
+        expect(ctx.ctrl.mode).to.be('list');
+      });
+
+      it('should indicate loading has finished', function() {
+        expect(ctx.ctrl.loading).to.be(false);
+      });
+
+      it('should broadcast an event indicating the failure', function() {
+        expect($rootScope.appEvent.calledOnce).to.be(true);
+        expect($rootScope.appEvent.calledWith('alert-error')).to.be(true);
+      });
+
+      it('should have an empty delta/changeset', function() {
+        expect(ctx.ctrl.delta).to.eql({ basic: '', html: '' });
+      });
+    });
+  });
+
+  describe('when the user wants to restore a revision', function() {
+    var deferred;
+
+    beforeEach(angularMocks.inject(($controller, $q) => {
+      deferred = $q.defer();
+      auditSrv.getAuditLog.returns($q.when(versionsResponse));
+      auditSrv.restoreDashboard.returns(deferred.promise);
+      ctx.ctrl = $controller(AuditLogCtrl, {
+        auditSrv,
+        contextSrv: { user: { name: 'Carlos' }},
+        $rootScope,
+        $scope: ctx.scope,
+      });
+      ctx.ctrl.$scope.setupDashboard = sinon.stub();
+      ctx.ctrl.dashboard = { id: 1 };
+      ctx.ctrl.restore();
+      ctx.ctrl.$scope.$apply();
+    }));
+
+    it('should display a modal allowing the user to restore or cancel', function() {
+      expect($rootScope.appEvent.calledOnce).to.be(true);
+      expect($rootScope.appEvent.calledWith('confirm-modal')).to.be(true);
+    });
+
+    describe('from the diff view', function() {
+      it('should return to the list view on restore', function() {
+        ctx.ctrl.mode = 'compare';
+        deferred.resolve(restoreResponse);
+        ctx.ctrl.restoreConfirm(RESTORE_ID);
+        ctx.ctrl.$scope.$apply();
+        expect(ctx.ctrl.mode).to.be('list');
+      });
+    });
+
+    describe('and restore is selected and successful', function() {
+      beforeEach(function() {
+        deferred.resolve(restoreResponse);
+        ctx.ctrl.restoreConfirm(RESTORE_ID);
+        ctx.ctrl.$scope.$apply();
+      });
+
+      it('should indicate loading has finished', function() {
+        expect(ctx.ctrl.loading).to.be(false);
+      });
+
+      it('should add an entry for the restored revision to the audit log', function() {
+        expect(ctx.ctrl.revisions.length).to.be(5);
+      });
+
+      describe('the restored revision', function() {
+        var first;
+        beforeEach(function() { first = ctx.ctrl.revisions[0]; });
+
+        it('should have its `id` and `version` numbers incremented', function() {
+          expect(first.id).to.be(5);
+          expect(first.version).to.be(5);
+        });
+
+        it('should set `parentVersion` to the reverted version', function() {
+          expect(first.parentVersion).to.be(RESTORE_ID);
+        });
+
+        it('should set `dashboardId` to the dashboard\'s id', function() {
+          expect(first.dashboardId).to.be(1);
+        });
+
+        it('should set `created` to date to the current time', function() {
+          expect(_.isDate(first.created)).to.be(true);
+        });
+
+        it('should set `createdBy` to the username of the user who reverted', function() {
+          expect(first.createdBy).to.be('Carlos');
+        });
+
+        it('should set `message` to the user\'s commit message', function() {
+          expect(first.message).to.be('Restored from version 4');
+        });
+      });
+
+      it('should reset the controller\'s state', function() {
+        expect(ctx.ctrl.mode).to.be('list');
+        expect(ctx.ctrl.delta).to.eql({ basic: '', html: '' });
+        expect(ctx.ctrl.selected.length).to.be(0);
+        expect(ctx.ctrl.selected).to.eql([]);
+        expect(_.find(ctx.ctrl.revisions, rev => rev.checked)).to.be.undefined;
+      });
+
+      it('should set the dashboard object to the response dashboard data', function() {
+        expect(ctx.ctrl.dashboard).to.eql(restoreResponse.dashboard.dashboard);
+        expect(ctx.ctrl.dashboard.meta).to.eql(restoreResponse.dashboard.meta);
+      });
+
+      it('should call setupDashboard to render new revision', function() {
+        expect(ctx.ctrl.$scope.setupDashboard.calledOnce).to.be(true);
+        expect(ctx.ctrl.$scope.setupDashboard.getCall(0).args[0]).to.eql(restoreResponse.dashboard);
+      });
+    });
+
+    describe('and restore fails to fetch', function() {
+      beforeEach(function() {
+        deferred.reject(new Error('RestoreError'));
+        ctx.ctrl.restoreConfirm(RESTORE_ID);
+        ctx.ctrl.$scope.$apply();
+      });
+
+      it('should indicate loading has finished', function() {
+        expect(ctx.ctrl.loading).to.be(false);
+      });
+
+      it('should broadcast an event indicating the failure', function() {
+        expect($rootScope.appEvent.callCount).to.be(2);
+        expect($rootScope.appEvent.getCall(0).calledWith('confirm-modal')).to.be(true);
+        expect($rootScope.appEvent.getCall(1).args[0]).to.be('alert-error');
+        expect($rootScope.appEvent.getCall(1).args[1][0]).to.be('There was an error restoring the dashboard');
+      });
+
+      // TODO: test state after failure i.e. do we hide the modal or keep it visible
+    });
+  });
+});

+ 92 - 0
public/app/features/dashboard/specs/audit_srv_specs.ts

@@ -0,0 +1,92 @@
+import {describe, beforeEach, it, sinon, expect, angularMocks} from 'test/lib/common';
+
+import helpers from 'test/specs/helpers';
+import AuditSrv from '../audit/audit_srv';
+import { versions, compare, restore } from 'test/mocks/audit-mocks';
+
+describe('auditSrv', function() {
+  var ctx = new helpers.ServiceTestContext();
+
+  var versionsResponse = versions();
+  var compareResponse = compare();
+  var restoreResponse = restore;
+
+  beforeEach(angularMocks.module('grafana.core'));
+  beforeEach(angularMocks.module('grafana.services'));
+  beforeEach(angularMocks.inject(function($httpBackend) {
+    ctx.$httpBackend = $httpBackend;
+    $httpBackend.whenRoute('GET', 'api/dashboards/db/:id/versions').respond(versionsResponse);
+    $httpBackend.whenRoute('GET', 'api/dashboards/db/:id/compare/:original...:new').respond(compareResponse);
+    $httpBackend.whenRoute('POST', 'api/dashboards/db/:id/restore')
+      .respond(function(method, url, data, headers, params) {
+        const parsedData = JSON.parse(data);
+        return [200, restoreResponse(parsedData.version)];
+      });
+  }));
+  beforeEach(ctx.createService('auditSrv'));
+
+  describe('getAuditLog', function() {
+    it('should return a versions array for the given dashboard id', function(done) {
+      ctx.service.getAuditLog({ id: 1 }).then(function(versions) {
+        expect(versions).to.eql(versionsResponse);
+        done();
+      });
+      ctx.$httpBackend.flush();
+    });
+
+    it('should return an empty array when not given an id', function(done) {
+      ctx.service.getAuditLog({ }).then(function(versions) {
+        expect(versions).to.eql([]);
+        done();
+      });
+      ctx.$httpBackend.flush();
+    });
+
+    it('should return an empty array when not given a dashboard', function(done) {
+      ctx.service.getAuditLog().then(function(versions) {
+        expect(versions).to.eql([]);
+        done();
+      });
+      ctx.$httpBackend.flush();
+    });
+  });
+
+  describe('compareVersions', function() {
+    it('should return a diff object for the given dashboard revisions', function(done) {
+      var compare = { original: 6, new: 4 };
+      ctx.service.compareVersions({ id: 1 }, compare).then(function(response) {
+        expect(response).to.eql(compareResponse);
+        done();
+      });
+      ctx.$httpBackend.flush();
+    });
+
+    it('should return an empty object when not given an id', function(done) {
+      var compare = { original: 6, new: 4 };
+      ctx.service.compareVersions({ }, compare).then(function(response) {
+        expect(response).to.eql({});
+        done();
+      });
+      ctx.$httpBackend.flush();
+    });
+  });
+
+  describe('restoreDashboard', function() {
+    it('should return a success response given valid parameters', function(done) {
+      var version = 6;
+      ctx.service.restoreDashboard({ id: 1 }, version).then(function(response) {
+        expect(response).to.eql(restoreResponse(version));
+        done();
+      });
+      ctx.$httpBackend.flush();
+    });
+
+    it('should return an empty object when not given an id', function(done) {
+      ctx.service.restoreDashboard({}, 6).then(function(response) {
+        expect(response).to.eql({});
+        done();
+      });
+      ctx.$httpBackend.flush();
+    });
+  });
+});

+ 11 - 11
public/app/features/dashboard/unsavedChangesSrv.js

@@ -7,7 +7,7 @@ function(angular, _) {
 
   var module = angular.module('grafana.services');
 
-  module.service('unsavedChangesSrv', function($rootScope, $q, $location, $timeout, contextSrv, $window) {
+  module.service('unsavedChangesSrv', function($rootScope, $q, $location, $timeout, contextSrv, dashboardSrv, $window) {
 
     function Tracker(dashboard, scope, originalCopyDelay) {
       var self = this;
@@ -136,28 +136,28 @@ function(angular, _) {
 
     p.open_modal = function() {
       var tracker = this;
+      var dashboard = this.current;
 
       var modalScope = this.scope.$new();
+      var clone = dashboard.getSaveModelClone();
+
+      modalScope.clone = clone;
       modalScope.ignore = function() {
         tracker.original = null;
         tracker.goto_next();
       };
 
-      modalScope.save = function() {
-        var cancel = $rootScope.$on('dashboard-saved', function() {
-          cancel();
-          $timeout(function() {
-            tracker.goto_next();
-          });
+      var cancel = $rootScope.$on('dashboard-saved', function() {
+        cancel();
+        $timeout(function() {
+          tracker.goto_next();
         });
-
-        $rootScope.$emit('save-dashboard');
-      };
+      });
 
       $rootScope.appEvent('show-modal', {
         src: 'public/app/partials/unsaved-changes.html',
-        modalClass: 'confirm-modal',
         scope: modalScope,
+        modalClass: 'modal--narrow'
       });
     };
 

+ 38 - 11
public/app/partials/unsaved-changes.html

@@ -1,7 +1,7 @@
-<div class="modal-body">
+<div class="modal-body" ng-controller="SaveDashboardMessageCtrl" ng-init="init();">
 	<div class="modal-header">
 		<h2 class="modal-header-title">
-		<i class="fa fa-exclamation"></i>
+			<i class="fa fa-exclamation"></i>
 			<span class="p-l-1">Unsaved changes</span>
 		</h2>
 
@@ -10,18 +10,45 @@
 		</a>
 	</div>
 
-	<div class="modal-content text-center">
-
-		<div class="confirm-modal-text">
-			What do you want to do?
+	<form name="saveMessage" ng-submit="saveVersion(saveMessage.$valid)" class="modal-content" novalidate>
+		<h6 class="text-center">
+			You're leaving without saving your changes, are you sure you want to leave? To save, add a small note to describe the changes in this version.
+		</h6>
+		<div class="p-t-2">
+			<div class="gf-form">
+				<label class="gf-form-hint">
+					<input
+						type="text"
+						name="message"
+						class="gf-form-input"
+						placeholder="Updates to &hellip;"
+						give-focus="true"
+						ng-model="clone.message"
+						ng-model-options="{allowInvalid: true}"
+						ng-keydown="keyDown($event)"
+						ng-maxlength="clone.max"
+						autocomplete="off"
+						required />
+					<small class="gf-form-hint-text muted" ng-cloak>
+						<span ng-class="{'text-error': saveMessage.message.$invalid && saveMessage.message.$dirty }">
+							{{clone.message.length || 0}}
+						</span>
+						/ {{clone.max}} characters
+					</small>
+				</label>
+			</div>
 		</div>
 
-		<div class="confirm-modal-buttons">
-			<button type="button" class="btn btn-inverse" ng-click="dismiss()">Cancel</button>
-			<button type="button" class="btn btn-danger" ng-click="ignore();dismiss()">Ignore</button>
-			<button type="button" class="btn btn-success" ng-click="save();dismiss();">Save</button>
+		<div class="gf-form-button-row text-center">
+			<button type="submit" class="btn btn-success" ng-disabled="saveMessage.$invalid">
+				Save changes
+			</button>
+			<button type="button" class="btn btn-danger" ng-click="ignore();dismiss()">
+				Discard changes and leave
+			</button>
+			<button class="btn btn-inverse" ng-click="dismiss();">Cancel</button>
 		</div>
-	</div>
+	</form>
 
 </div>
 

+ 1 - 0
public/sass/_grafana.scss

@@ -82,6 +82,7 @@
 @import "pages/playlist";
 @import "pages/admin";
 @import "pages/alerting";
+@import "pages/audit";
 @import "pages/plugins";
 @import "pages/signup";
 @import "pages/styleguide";

+ 25 - 0
public/sass/_variables.dark.scss

@@ -280,3 +280,28 @@ $card-shadow: -1px -1px 0 0 hsla(0, 0%, 100%, .1), 1px 1px 0 0 rgba(0, 0, 0, .3)
 $footer-link-color:   $gray-1;
 $footer-link-hover:   $gray-4;
 
+
+// Changelog and diff
+// -------------------------
+$diff-label-bg:         $dark-2;
+$diff-label-fg:         $white;
+
+$diff-switch-bg:        $dark-5;
+$diff-switch-disabled:  $gray-1;
+
+$diff-group-bg:         $dark-4;
+$diff-arrow-color:      $white;
+
+$diff-json-bg:          $dark-4;
+$diff-json-fg:          $gray-5;
+
+$diff-json-added:       #2f5f40;
+$diff-json-deleted:     #862d2d;
+
+$diff-json-old:         #5a372a;
+$diff-json-new:         #664e33;
+
+$diff-json-changed-fg:  $gray-5;
+$diff-json-changed-num: $text-muted;
+
+$diff-json-icon:        $gray-7;

+ 25 - 0
public/sass/_variables.light.scss

@@ -303,3 +303,28 @@ $card-shadow: -1px -1px 0 0 hsla(0, 0%, 100%, .1), 1px 1px 0 0 rgba(0, 0, 0, .1)
 // footer
 $footer-link-color:   $gray-3;
 $footer-link-hover:   $dark-5;
+
+
+// Changelog and diff
+// -------------------------
+$diff-label-bg:         $gray-5;
+$diff-label-fg:         $gray-2;
+
+$diff-switch-bg:        $gray-7;
+$diff-switch-disabled:  $gray-5;
+
+$diff-arrow-color:      $dark-3;
+$diff-group-bg:         $gray-7;
+
+$diff-json-bg:          $gray-5;
+$diff-json-fg:          $gray-2;
+
+$diff-json-added:       lighten(desaturate($green, 30%), 10%);
+$diff-json-deleted:     desaturate($red, 35%);
+
+$diff-json-old:       #5a372a;
+$diff-json-new:       #664e33;
+
+$diff-json-changed-fg:  $gray-6;
+$diff-json-changed-num: $gray-4;
+$diff-json-icon:        $gray-4;

+ 11 - 0
public/sass/components/_buttons.scss

@@ -118,5 +118,16 @@
 .btn-outline-danger {
   @include button-outline-variant($btn-danger-bg);
 }
+.btn-outline-disabled {
+  @include button-outline-variant($gray-1);
+  @include box-shadow(none);
+  cursor: default;
+
+  &:hover, &:active, &:active:hover, &:focus {
+    color: $gray-1;
+    background-color: transparent;
+        border-color: $gray-1;
+  }
+}
 
 

+ 10 - 0
public/sass/components/_gf-form.scss

@@ -178,6 +178,16 @@ $gf-form-margin: 0.25rem;
   }
 }
 
+.gf-form-hint {
+  width: 100%;
+}
+
+.gf-form-hint-text {
+  display: block;
+  text-align: right;
+  padding-top: 0.5em;
+}
+
 .gf-form-select-wrapper {
   margin-right: $gf-form-margin;
   position: relative;

+ 268 - 0
public/sass/pages/_audit.scss

@@ -0,0 +1,268 @@
+// Audit Table
+.audit-table {
+  // .gf-form overrides
+  .gf-form-label { display: none; }
+
+  .gf-form-switch {
+    margin-bottom: 0;
+
+    input + label {
+      height: 3.6rem;
+      width: 110%;
+    }
+
+    input + label::before, input + label::after {
+      background-color: $diff-switch-bg;
+      background-image: none;
+      border: 0;
+      height: 50px;
+      line-height: 3.7rem;
+    }
+  }
+
+  gf-form-switch[disabled]  {
+    .gf-form-switch input + label {
+      &::before {
+        color: $diff-switch-disabled;
+        text-shadow: none;
+      }
+    }
+  }
+
+  // .filter-table overrides
+  .filter-table {
+    tr {
+      border-bottom: 3px solid $page-bg;
+    }
+
+    thead tr {
+      border-width: 3px;
+    }
+
+    $date-padding: 1em;
+
+    td {
+      padding: 0;
+
+      &:nth-child(2) {
+        border-left: 5px solid $page-bg;
+        padding-left: 1.5em;
+      }
+      &:nth-child(3) { padding-left: $date-padding; }
+      &:last-child { padding-right: 1.5em; }
+    }
+
+    th:nth-child(2) { padding-left: 0.5em; }
+    th:nth-child(3) { padding-left: $date-padding; }
+  }
+}
+
+// Diff View
+.audit-log {
+  h4 {
+    margin-bottom: 0.75em;
+  }
+
+  .page-container {
+    padding: 0;
+    background: none;
+  }
+
+  .page-sidebar {
+    margin-left: 0;
+    margin-right: 3em;
+  }
+
+  .small.muted { margin-bottom: 0.25em; }
+
+  .ui-list > li  {
+    margin-bottom: 1.5em;
+
+    & > a { padding-left: 15px; }
+    & > a.active { @include left-brand-border-gradient(); }
+  }
+}
+
+// Actual Diff
+#delta {
+  margin: 2em 0;
+}
+
+// JSON
+@for $i from 0 through 16 {
+  .diff-indent-#{$i} {
+    padding-left: $i * 1.5rem;
+    margin-left: 10px;
+  }
+}
+
+.delta-html {
+  background: $diff-json-bg;
+  padding-top: 5px;
+  padding-bottom: 5px;
+  user-select: none;
+}
+
+.diff-line {
+  color: $diff-json-fg;
+  font-family: $font-family-monospace;
+  font-size: $font-size-sm;
+  line-height: 2;
+  margin-bottom: 0;
+  overflow: hidden;
+  text-overflow: ellipsis;
+  white-space: nowrap;
+  position: relative;
+
+  &:before, &:after {
+  }
+
+  &:after { left: -40px; }
+}
+
+.diff-line-number {
+  color: $text-muted;
+  display: inline-block;
+  font-size: $font-size-xs;
+  line-height: 2.3;
+  text-align: right;
+  width: 30px;
+}
+
+.diff-line-number-hide { visibility: hidden; }
+
+.diff-line-icon {
+  color: $diff-json-icon;
+  font-size: $font-size-xs;
+  float: right;
+  position: relative;
+  top: 2px;
+  right: 10px;
+}
+
+.diff-json-new, .diff-json-old {
+  color: $diff-json-changed-fg;
+
+  & .diff-line-number { color: $diff-json-changed-num; }
+}
+
+.diff-json-new { background-color: $diff-json-new; }
+.diff-json-old { background-color: $diff-json-old; }
+.diff-json-added { background-color: $diff-json-added; }
+.diff-json-deleted { background-color: $diff-json-deleted; }
+
+.diff-value {
+  user-select: all;
+}
+
+// Basic
+.diff-circle { margin-right: .5em; }
+.diff-circle-changed { color: #f59433; }
+.diff-circle-added   { color: #29D761; }
+.diff-circle-deleted { color: #fd474a; }
+
+.diff-item-added, .diff-item-deleted { list-style: none; }
+
+.diff-restore-btn {
+  float: right;
+}
+
+.diff-group {
+  background: $diff-group-bg;
+  font-size: 16px;
+  font-style: normal;
+  padding: 10px 15px;
+  margin: 1rem 0;
+
+  & .diff-group { padding: 0 5px; }
+}
+
+.diff-group-name {
+  display: inline-block;
+  width: 100%;
+  font-size: 16px;
+  padding-left: 1.75em;
+  margin: 0 0 14px 0;
+}
+
+.diff-summary-key {
+  padding-left: .25em;
+}
+
+.diff-list {
+  padding-left: 40px;
+
+  & .diff-list { padding-left: 0; }
+}
+
+.diff-item {
+  color: $gray-2;
+  line-height: 2.5;
+
+  & > div { display: inline; }
+}
+
+.diff-item-changeset {
+  list-style: none;
+}
+
+.diff-label {
+  background-color: $diff-label-bg;
+  border-radius: 3px;
+  color: $diff-label-fg;
+  display: inline;
+  font-size: .95rem;
+  margin: 0 5px;
+  padding: 3px 8px;
+}
+
+.diff-linenum {
+  float: right;
+}
+
+.diff-arrow {
+  color: $diff-arrow-color;
+}
+
+.diff-block {
+  width: 100%;
+  display: inline-block;
+}
+
+.diff-block-title {
+  font-size: 16px;
+  display: inline-block;
+}
+
+.diff-title {
+  font-size: 16px;
+}
+
+.diff-change-container {
+  margin: 0 0;
+  padding-left: 3em;
+  padding-right: 0;
+}
+
+.diff-change-group {
+  width: 100%;
+  color: rgba(223,224,225, .6);
+  margin-bottom: 14px;
+}
+
+.diff-change-item {
+  display: inline-block;
+}
+
+.diff-change-title {
+  font-size: 16px;
+}
+
+.bullet-position-container {
+  position: relative;
+  left: -6px;
+}
+
+.diff-list-circle {
+  font-size: 10px;
+}

+ 0 - 1
public/sass/pages/_dashboard.scss

@@ -255,4 +255,3 @@ div.flot-text {
     padding: 0.5rem .5rem .2rem .5rem;
   }
 }
-

+ 197 - 0
public/test/mocks/audit-mocks.js

@@ -0,0 +1,197 @@
+define([],
+  function() {
+  'use strict';
+
+  return {
+    versions: function() {
+      return [{
+        id: 4,
+        dashboardId: 1,
+        parentVersion: 3,
+        restoredFrom: 0,
+        version: 4,
+        created: '2017-02-22T17:43:01-08:00',
+        createdBy: 'admin',
+        message: '',
+      },
+      {
+        id: 3,
+        dashboardId: 1,
+        parentVersion: 1,
+        restoredFrom: 1,
+        version: 3,
+        created: '2017-02-22T17:43:01-08:00',
+        createdBy: 'admin',
+        message: '',
+      },
+      {
+        id: 2,
+        dashboardId: 1,
+        parentVersion: 0,
+        restoredFrom: -1,
+        version: 2,
+        created: '2017-02-22T17:29:52-08:00',
+        createdBy: 'admin',
+        message: '',
+      },
+      {
+        id: 1,
+        dashboardId: 1,
+        parentVersion: 0,
+        restoredFrom: -1,
+        slug: 'audit-dashboard',
+        version: 1,
+        created: '2017-02-22T17:06:37-08:00',
+        createdBy: 'admin',
+        message: '',
+      }];
+    },
+    compare: function(type) {
+      return type === 'basic' ? '<div></div>' : '<pre><code></code></pre>';
+    },
+    restore: function(version, restoredFrom) {
+      return {
+        dashboard: {
+          meta: {
+            type: 'db',
+            canSave: true,
+            canEdit: true,
+            canStar: true,
+            slug: 'audit-dashboard',
+            expires: '0001-01-01T00:00:00Z',
+            created: '2017-02-21T18:40:45-08:00',
+            updated: '2017-04-11T21:31:22.59219665-07:00',
+            updatedBy: 'admin',
+            createdBy: 'admin',
+            version: version,
+          },
+          dashboard: {
+            annotations: {
+              list: []
+            },
+            description: 'A random dashboard for implementing the audit log',
+            editable: true,
+            gnetId: null,
+            graphTooltip: 0,
+            hideControls: false,
+            id: 1,
+            links: [],
+            restoredFrom: restoredFrom,
+            rows: [{
+                collapse: false,
+                height: '250px',
+                panels: [{
+                  aliasColors: {},
+                  bars: false,
+                  datasource: null,
+                  fill: 1,
+                  id: 1,
+                  legend: {
+                    avg: false,
+                    current: false,
+                    max: false,
+                    min: false,
+                    show: true,
+                    total: false,
+                    values: false
+                  },
+                  lines: true,
+                  linewidth: 1,
+                  nullPointMode: "null",
+                  percentage: false,
+                  pointradius: 5,
+                  points: false,
+                  renderer: 'flot',
+                  seriesOverrides: [],
+                  span: 12,
+                  stack: false,
+                  steppedLine: false,
+                  targets: [{}],
+                  thresholds: [],
+                  timeFrom: null,
+                  timeShift: null,
+                  title: 'Panel Title',
+                  tooltip: {
+                    shared: true,
+                    sort: 0,
+                    value_type: 'individual'
+                  },
+                  type: 'graph',
+                  xaxis: {
+                    mode: 'time',
+                    name: null,
+                    show: true,
+                    values: []
+                  },
+                  yaxes: [{
+                    format: 'short',
+                    label: null,
+                    logBase: 1,
+                    max: null,
+                    min: null,
+                    show: true
+                  }, {
+                    format: 'short',
+                    label: null,
+                    logBase: 1,
+                    max: null,
+                    min: null,
+                    show: true
+                  }]
+                }],
+                repeat: null,
+                repeatIteration: null,
+                repeatRowId: null,
+                showTitle: false,
+                title: 'Dashboard Row',
+                titleSize: 'h6'
+              }
+            ],
+            schemaVersion: 14,
+            style: 'dark',
+            tags: [
+              'development'
+            ],
+            templating: {
+              'list': []
+            },
+            time: {
+              from: 'now-6h',
+              to: 'now'
+            },
+            timepicker: {
+              refresh_intervals: [
+                '5s',
+                '10s',
+                '30s',
+                '1m',
+                '5m',
+                '15m',
+                '30m',
+                '1h',
+                '2h',
+                '1d',
+              ],
+              time_options: [
+                '5m',
+                '15m',
+                '1h',
+                '6h',
+                '12h',
+                '24h',
+                '2d',
+                '7d',
+                '30d'
+              ]
+            },
+            timezone: 'utc',
+            title: 'Audit Dashboard',
+            version: version,
+          }
+        },
+        message: 'Dashboard restored to version ' + version,
+        version: version
+      };
+    },
+  };
+});

+ 20 - 0
vendor/github.com/sergi/go-diff/LICENSE

@@ -0,0 +1,20 @@
+Copyright (c) 2012-2016 The go-diff Authors. All rights reserved.
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the rights to use, copy, modify, merge, publish, distribute, sublicense,
+and/or sell copies of the Software, and to permit persons to whom the
+Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included
+in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+

+ 1339 - 0
vendor/github.com/sergi/go-diff/diffmatchpatch/diff.go

@@ -0,0 +1,1339 @@
+// Copyright (c) 2012-2016 The go-diff authors. All rights reserved.
+// https://github.com/sergi/go-diff
+// See the included LICENSE file for license details.
+//
+// go-diff is a Go implementation of Google's Diff, Match, and Patch library
+// Original library is Copyright (c) 2006 Google Inc.
+// http://code.google.com/p/google-diff-match-patch/
+
+package diffmatchpatch
+
+import (
+	"bytes"
+	"errors"
+	"fmt"
+	"html"
+	"math"
+	"net/url"
+	"regexp"
+	"strconv"
+	"strings"
+	"time"
+	"unicode/utf8"
+)
+
+// Operation defines the operation of a diff item.
+type Operation int8
+
+const (
+	// DiffDelete item represents a delete diff.
+	DiffDelete Operation = -1
+	// DiffInsert item represents an insert diff.
+	DiffInsert Operation = 1
+	// DiffEqual item represents an equal diff.
+	DiffEqual Operation = 0
+)
+
+// Diff represents one diff operation
+type Diff struct {
+	Type Operation
+	Text string
+}
+
+func splice(slice []Diff, index int, amount int, elements ...Diff) []Diff {
+	return append(slice[:index], append(elements, slice[index+amount:]...)...)
+}
+
+// DiffMain finds the differences between two texts.
+// If an invalid UTF-8 sequence is encountered, it will be replaced by the Unicode replacement character.
+func (dmp *DiffMatchPatch) DiffMain(text1, text2 string, checklines bool) []Diff {
+	return dmp.DiffMainRunes([]rune(text1), []rune(text2), checklines)
+}
+
+// DiffMainRunes finds the differences between two rune sequences.
+// If an invalid UTF-8 sequence is encountered, it will be replaced by the Unicode replacement character.
+func (dmp *DiffMatchPatch) DiffMainRunes(text1, text2 []rune, checklines bool) []Diff {
+	var deadline time.Time
+	if dmp.DiffTimeout > 0 {
+		deadline = time.Now().Add(dmp.DiffTimeout)
+	}
+	return dmp.diffMainRunes(text1, text2, checklines, deadline)
+}
+
+func (dmp *DiffMatchPatch) diffMainRunes(text1, text2 []rune, checklines bool, deadline time.Time) []Diff {
+	if runesEqual(text1, text2) {
+		var diffs []Diff
+		if len(text1) > 0 {
+			diffs = append(diffs, Diff{DiffEqual, string(text1)})
+		}
+		return diffs
+	}
+	// Trim off common prefix (speedup).
+	commonlength := commonPrefixLength(text1, text2)
+	commonprefix := text1[:commonlength]
+	text1 = text1[commonlength:]
+	text2 = text2[commonlength:]
+
+	// Trim off common suffix (speedup).
+	commonlength = commonSuffixLength(text1, text2)
+	commonsuffix := text1[len(text1)-commonlength:]
+	text1 = text1[:len(text1)-commonlength]
+	text2 = text2[:len(text2)-commonlength]
+
+	// Compute the diff on the middle block.
+	diffs := dmp.diffCompute(text1, text2, checklines, deadline)
+
+	// Restore the prefix and suffix.
+	if len(commonprefix) != 0 {
+		diffs = append([]Diff{Diff{DiffEqual, string(commonprefix)}}, diffs...)
+	}
+	if len(commonsuffix) != 0 {
+		diffs = append(diffs, Diff{DiffEqual, string(commonsuffix)})
+	}
+
+	return dmp.DiffCleanupMerge(diffs)
+}
+
+// diffCompute finds the differences between two rune slices.  Assumes that the texts do not have any common prefix or suffix.
+func (dmp *DiffMatchPatch) diffCompute(text1, text2 []rune, checklines bool, deadline time.Time) []Diff {
+	diffs := []Diff{}
+	if len(text1) == 0 {
+		// Just add some text (speedup).
+		return append(diffs, Diff{DiffInsert, string(text2)})
+	} else if len(text2) == 0 {
+		// Just delete some text (speedup).
+		return append(diffs, Diff{DiffDelete, string(text1)})
+	}
+
+	var longtext, shorttext []rune
+	if len(text1) > len(text2) {
+		longtext = text1
+		shorttext = text2
+	} else {
+		longtext = text2
+		shorttext = text1
+	}
+
+	if i := runesIndex(longtext, shorttext); i != -1 {
+		op := DiffInsert
+		// Swap insertions for deletions if diff is reversed.
+		if len(text1) > len(text2) {
+			op = DiffDelete
+		}
+		// Shorter text is inside the longer text (speedup).
+		return []Diff{
+			Diff{op, string(longtext[:i])},
+			Diff{DiffEqual, string(shorttext)},
+			Diff{op, string(longtext[i+len(shorttext):])},
+		}
+	} else if len(shorttext) == 1 {
+		// Single character string.
+		// After the previous speedup, the character can't be an equality.
+		return []Diff{
+			Diff{DiffDelete, string(text1)},
+			Diff{DiffInsert, string(text2)},
+		}
+		// Check to see if the problem can be split in two.
+	} else if hm := dmp.diffHalfMatch(text1, text2); hm != nil {
+		// A half-match was found, sort out the return data.
+		text1A := hm[0]
+		text1B := hm[1]
+		text2A := hm[2]
+		text2B := hm[3]
+		midCommon := hm[4]
+		// Send both pairs off for separate processing.
+		diffsA := dmp.diffMainRunes(text1A, text2A, checklines, deadline)
+		diffsB := dmp.diffMainRunes(text1B, text2B, checklines, deadline)
+		// Merge the results.
+		return append(diffsA, append([]Diff{Diff{DiffEqual, string(midCommon)}}, diffsB...)...)
+	} else if checklines && len(text1) > 100 && len(text2) > 100 {
+		return dmp.diffLineMode(text1, text2, deadline)
+	}
+	return dmp.diffBisect(text1, text2, deadline)
+}
+
+// diffLineMode does a quick line-level diff on both []runes, then rediff the parts for greater accuracy. This speedup can produce non-minimal diffs.
+func (dmp *DiffMatchPatch) diffLineMode(text1, text2 []rune, deadline time.Time) []Diff {
+	// Scan the text on a line-by-line basis first.
+	text1, text2, linearray := dmp.diffLinesToRunes(text1, text2)
+
+	diffs := dmp.diffMainRunes(text1, text2, false, deadline)
+
+	// Convert the diff back to original text.
+	diffs = dmp.DiffCharsToLines(diffs, linearray)
+	// Eliminate freak matches (e.g. blank lines)
+	diffs = dmp.DiffCleanupSemantic(diffs)
+
+	// Rediff any replacement blocks, this time character-by-character.
+	// Add a dummy entry at the end.
+	diffs = append(diffs, Diff{DiffEqual, ""})
+
+	pointer := 0
+	countDelete := 0
+	countInsert := 0
+
+	// NOTE: Rune slices are slower than using strings in this case.
+	textDelete := ""
+	textInsert := ""
+
+	for pointer < len(diffs) {
+		switch diffs[pointer].Type {
+		case DiffInsert:
+			countInsert++
+			textInsert += diffs[pointer].Text
+		case DiffDelete:
+			countDelete++
+			textDelete += diffs[pointer].Text
+		case DiffEqual:
+			// Upon reaching an equality, check for prior redundancies.
+			if countDelete >= 1 && countInsert >= 1 {
+				// Delete the offending records and add the merged ones.
+				diffs = splice(diffs, pointer-countDelete-countInsert,
+					countDelete+countInsert)
+
+				pointer = pointer - countDelete - countInsert
+				a := dmp.diffMainRunes([]rune(textDelete), []rune(textInsert), false, deadline)
+				for j := len(a) - 1; j >= 0; j-- {
+					diffs = splice(diffs, pointer, 0, a[j])
+				}
+				pointer = pointer + len(a)
+			}
+
+			countInsert = 0
+			countDelete = 0
+			textDelete = ""
+			textInsert = ""
+		}
+		pointer++
+	}
+
+	return diffs[:len(diffs)-1] // Remove the dummy entry at the end.
+}
+
+// DiffBisect finds the 'middle snake' of a diff, split the problem in two and return the recursively constructed diff.
+// If an invalid UTF-8 sequence is encountered, it will be replaced by the Unicode replacement character.
+// See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.
+func (dmp *DiffMatchPatch) DiffBisect(text1, text2 string, deadline time.Time) []Diff {
+	// Unused in this code, but retained for interface compatibility.
+	return dmp.diffBisect([]rune(text1), []rune(text2), deadline)
+}
+
+// diffBisect finds the 'middle snake' of a diff, splits the problem in two and returns the recursively constructed diff.
+// See Myers's 1986 paper: An O(ND) Difference Algorithm and Its Variations.
+func (dmp *DiffMatchPatch) diffBisect(runes1, runes2 []rune, deadline time.Time) []Diff {
+	// Cache the text lengths to prevent multiple calls.
+	runes1Len, runes2Len := len(runes1), len(runes2)
+
+	maxD := (runes1Len + runes2Len + 1) / 2
+	vOffset := maxD
+	vLength := 2 * maxD
+
+	v1 := make([]int, vLength)
+	v2 := make([]int, vLength)
+	for i := range v1 {
+		v1[i] = -1
+		v2[i] = -1
+	}
+	v1[vOffset+1] = 0
+	v2[vOffset+1] = 0
+
+	delta := runes1Len - runes2Len
+	// If the total number of characters is odd, then the front path will collide with the reverse path.
+	front := (delta%2 != 0)
+	// Offsets for start and end of k loop. Prevents mapping of space beyond the grid.
+	k1start := 0
+	k1end := 0
+	k2start := 0
+	k2end := 0
+	for d := 0; d < maxD; d++ {
+		// Bail out if deadline is reached.
+		if !deadline.IsZero() && time.Now().After(deadline) {
+			break
+		}
+
+		// Walk the front path one step.
+		for k1 := -d + k1start; k1 <= d-k1end; k1 += 2 {
+			k1Offset := vOffset + k1
+			var x1 int
+
+			if k1 == -d || (k1 != d && v1[k1Offset-1] < v1[k1Offset+1]) {
+				x1 = v1[k1Offset+1]
+			} else {
+				x1 = v1[k1Offset-1] + 1
+			}
+
+			y1 := x1 - k1
+			for x1 < runes1Len && y1 < runes2Len {
+				if runes1[x1] != runes2[y1] {
+					break
+				}
+				x1++
+				y1++
+			}
+			v1[k1Offset] = x1
+			if x1 > runes1Len {
+				// Ran off the right of the graph.
+				k1end += 2
+			} else if y1 > runes2Len {
+				// Ran off the bottom of the graph.
+				k1start += 2
+			} else if front {
+				k2Offset := vOffset + delta - k1
+				if k2Offset >= 0 && k2Offset < vLength && v2[k2Offset] != -1 {
+					// Mirror x2 onto top-left coordinate system.
+					x2 := runes1Len - v2[k2Offset]
+					if x1 >= x2 {
+						// Overlap detected.
+						return dmp.diffBisectSplit(runes1, runes2, x1, y1, deadline)
+					}
+				}
+			}
+		}
+		// Walk the reverse path one step.
+		for k2 := -d + k2start; k2 <= d-k2end; k2 += 2 {
+			k2Offset := vOffset + k2
+			var x2 int
+			if k2 == -d || (k2 != d && v2[k2Offset-1] < v2[k2Offset+1]) {
+				x2 = v2[k2Offset+1]
+			} else {
+				x2 = v2[k2Offset-1] + 1
+			}
+			var y2 = x2 - k2
+			for x2 < runes1Len && y2 < runes2Len {
+				if runes1[runes1Len-x2-1] != runes2[runes2Len-y2-1] {
+					break
+				}
+				x2++
+				y2++
+			}
+			v2[k2Offset] = x2
+			if x2 > runes1Len {
+				// Ran off the left of the graph.
+				k2end += 2
+			} else if y2 > runes2Len {
+				// Ran off the top of the graph.
+				k2start += 2
+			} else if !front {
+				k1Offset := vOffset + delta - k2
+				if k1Offset >= 0 && k1Offset < vLength && v1[k1Offset] != -1 {
+					x1 := v1[k1Offset]
+					y1 := vOffset + x1 - k1Offset
+					// Mirror x2 onto top-left coordinate system.
+					x2 = runes1Len - x2
+					if x1 >= x2 {
+						// Overlap detected.
+						return dmp.diffBisectSplit(runes1, runes2, x1, y1, deadline)
+					}
+				}
+			}
+		}
+	}
+	// Diff took too long and hit the deadline or number of diffs equals number of characters, no commonality at all.
+	return []Diff{
+		Diff{DiffDelete, string(runes1)},
+		Diff{DiffInsert, string(runes2)},
+	}
+}
+
+func (dmp *DiffMatchPatch) diffBisectSplit(runes1, runes2 []rune, x, y int,
+	deadline time.Time) []Diff {
+	runes1a := runes1[:x]
+	runes2a := runes2[:y]
+	runes1b := runes1[x:]
+	runes2b := runes2[y:]
+
+	// Compute both diffs serially.
+	diffs := dmp.diffMainRunes(runes1a, runes2a, false, deadline)
+	diffsb := dmp.diffMainRunes(runes1b, runes2b, false, deadline)
+
+	return append(diffs, diffsb...)
+}
+
+// DiffLinesToChars splits two texts into a list of strings, and educes the texts to a string of hashes where each Unicode character represents one line.
+// It's slightly faster to call DiffLinesToRunes first, followed by DiffMainRunes.
+func (dmp *DiffMatchPatch) DiffLinesToChars(text1, text2 string) (string, string, []string) {
+	chars1, chars2, lineArray := dmp.DiffLinesToRunes(text1, text2)
+	return string(chars1), string(chars2), lineArray
+}
+
+// DiffLinesToRunes splits two texts into a list of runes. Each rune represents one line.
+func (dmp *DiffMatchPatch) DiffLinesToRunes(text1, text2 string) ([]rune, []rune, []string) {
+	// '\x00' is a valid character, but various debuggers don't like it. So we'll insert a junk entry to avoid generating a null character.
+	lineArray := []string{""}    // e.g. lineArray[4] == 'Hello\n'
+	lineHash := map[string]int{} // e.g. lineHash['Hello\n'] == 4
+
+	chars1 := dmp.diffLinesToRunesMunge(text1, &lineArray, lineHash)
+	chars2 := dmp.diffLinesToRunesMunge(text2, &lineArray, lineHash)
+
+	return chars1, chars2, lineArray
+}
+
+func (dmp *DiffMatchPatch) diffLinesToRunes(text1, text2 []rune) ([]rune, []rune, []string) {
+	return dmp.DiffLinesToRunes(string(text1), string(text2))
+}
+
+// diffLinesToRunesMunge splits a text into an array of strings, and reduces the texts to a []rune where each Unicode character represents one line.
+// We use strings instead of []runes as input mainly because you can't use []rune as a map key.
+func (dmp *DiffMatchPatch) diffLinesToRunesMunge(text string, lineArray *[]string, lineHash map[string]int) []rune {
+	// Walk the text, pulling out a substring for each line. text.split('\n') would would temporarily double our memory footprint. Modifying text would create many large strings to garbage collect.
+	lineStart := 0
+	lineEnd := -1
+	runes := []rune{}
+
+	for lineEnd < len(text)-1 {
+		lineEnd = indexOf(text, "\n", lineStart)
+
+		if lineEnd == -1 {
+			lineEnd = len(text) - 1
+		}
+
+		line := text[lineStart : lineEnd+1]
+		lineStart = lineEnd + 1
+		lineValue, ok := lineHash[line]
+
+		if ok {
+			runes = append(runes, rune(lineValue))
+		} else {
+			*lineArray = append(*lineArray, line)
+			lineHash[line] = len(*lineArray) - 1
+			runes = append(runes, rune(len(*lineArray)-1))
+		}
+	}
+
+	return runes
+}
+
+// DiffCharsToLines rehydrates the text in a diff from a string of line hashes to real lines of text.
+func (dmp *DiffMatchPatch) DiffCharsToLines(diffs []Diff, lineArray []string) []Diff {
+	hydrated := make([]Diff, 0, len(diffs))
+	for _, aDiff := range diffs {
+		chars := aDiff.Text
+		text := make([]string, len(chars))
+
+		for i, r := range chars {
+			text[i] = lineArray[r]
+		}
+
+		aDiff.Text = strings.Join(text, "")
+		hydrated = append(hydrated, aDiff)
+	}
+	return hydrated
+}
+
+// DiffCommonPrefix determines the common prefix length of two strings.
+func (dmp *DiffMatchPatch) DiffCommonPrefix(text1, text2 string) int {
+	// Unused in this code, but retained for interface compatibility.
+	return commonPrefixLength([]rune(text1), []rune(text2))
+}
+
+// DiffCommonSuffix determines the common suffix length of two strings.
+func (dmp *DiffMatchPatch) DiffCommonSuffix(text1, text2 string) int {
+	// Unused in this code, but retained for interface compatibility.
+	return commonSuffixLength([]rune(text1), []rune(text2))
+}
+
+// commonPrefixLength returns the length of the common prefix of two rune slices.
+func commonPrefixLength(text1, text2 []rune) int {
+	short, long := text1, text2
+	if len(short) > len(long) {
+		short, long = long, short
+	}
+	for i, r := range short {
+		if r != long[i] {
+			return i
+		}
+	}
+	return len(short)
+}
+
+// commonSuffixLength returns the length of the common suffix of two rune slices.
+func commonSuffixLength(text1, text2 []rune) int {
+	n := min(len(text1), len(text2))
+	for i := 0; i < n; i++ {
+		if text1[len(text1)-i-1] != text2[len(text2)-i-1] {
+			return i
+		}
+	}
+	return n
+
+	// TODO research and benchmark this, why is it not activated? https://github.com/sergi/go-diff/issues/54
+	// Binary search.
+	// Performance analysis: http://neil.fraser.name/news/2007/10/09/
+	/*
+	   pointermin := 0
+	   pointermax := math.Min(len(text1), len(text2))
+	   pointermid := pointermax
+	   pointerend := 0
+	   for pointermin < pointermid {
+	       if text1[len(text1)-pointermid:len(text1)-pointerend] ==
+	           text2[len(text2)-pointermid:len(text2)-pointerend] {
+	           pointermin = pointermid
+	           pointerend = pointermin
+	       } else {
+	           pointermax = pointermid
+	       }
+	       pointermid = math.Floor((pointermax-pointermin)/2 + pointermin)
+	   }
+	   return pointermid
+	*/
+}
+
+// DiffCommonOverlap determines if the suffix of one string is the prefix of another.
+func (dmp *DiffMatchPatch) DiffCommonOverlap(text1 string, text2 string) int {
+	// Cache the text lengths to prevent multiple calls.
+	text1Length := len(text1)
+	text2Length := len(text2)
+	// Eliminate the null case.
+	if text1Length == 0 || text2Length == 0 {
+		return 0
+	}
+	// Truncate the longer string.
+	if text1Length > text2Length {
+		text1 = text1[text1Length-text2Length:]
+	} else if text1Length < text2Length {
+		text2 = text2[0:text1Length]
+	}
+	textLength := int(math.Min(float64(text1Length), float64(text2Length)))
+	// Quick check for the worst case.
+	if text1 == text2 {
+		return textLength
+	}
+
+	// Start by looking for a single character match and increase length until no match is found. Performance analysis: http://neil.fraser.name/news/2010/11/04/
+	best := 0
+	length := 1
+	for {
+		pattern := text1[textLength-length:]
+		found := strings.Index(text2, pattern)
+		if found == -1 {
+			break
+		}
+		length += found
+		if found == 0 || text1[textLength-length:] == text2[0:length] {
+			best = length
+			length++
+		}
+	}
+
+	return best
+}
+
+// DiffHalfMatch checks whether the two texts share a substring which is at least half the length of the longer text. This speedup can produce non-minimal diffs.
+func (dmp *DiffMatchPatch) DiffHalfMatch(text1, text2 string) []string {
+	// Unused in this code, but retained for interface compatibility.
+	runeSlices := dmp.diffHalfMatch([]rune(text1), []rune(text2))
+	if runeSlices == nil {
+		return nil
+	}
+
+	result := make([]string, len(runeSlices))
+	for i, r := range runeSlices {
+		result[i] = string(r)
+	}
+	return result
+}
+
+func (dmp *DiffMatchPatch) diffHalfMatch(text1, text2 []rune) [][]rune {
+	if dmp.DiffTimeout <= 0 {
+		// Don't risk returning a non-optimal diff if we have unlimited time.
+		return nil
+	}
+
+	var longtext, shorttext []rune
+	if len(text1) > len(text2) {
+		longtext = text1
+		shorttext = text2
+	} else {
+		longtext = text2
+		shorttext = text1
+	}
+
+	if len(longtext) < 4 || len(shorttext)*2 < len(longtext) {
+		return nil // Pointless.
+	}
+
+	// First check if the second quarter is the seed for a half-match.
+	hm1 := dmp.diffHalfMatchI(longtext, shorttext, int(float64(len(longtext)+3)/4))
+
+	// Check again based on the third quarter.
+	hm2 := dmp.diffHalfMatchI(longtext, shorttext, int(float64(len(longtext)+1)/2))
+
+	hm := [][]rune{}
+	if hm1 == nil && hm2 == nil {
+		return nil
+	} else if hm2 == nil {
+		hm = hm1
+	} else if hm1 == nil {
+		hm = hm2
+	} else {
+		// Both matched.  Select the longest.
+		if len(hm1[4]) > len(hm2[4]) {
+			hm = hm1
+		} else {
+			hm = hm2
+		}
+	}
+
+	// A half-match was found, sort out the return data.
+	if len(text1) > len(text2) {
+		return hm
+	}
+
+	return [][]rune{hm[2], hm[3], hm[0], hm[1], hm[4]}
+}
+
+// diffHalfMatchI checks if a substring of shorttext exist within longtext such that the substring is at least half the length of longtext?
+// Returns a slice containing the prefix of longtext, the suffix of longtext, the prefix of shorttext, the suffix of shorttext and the common middle, or null if there was no match.
+func (dmp *DiffMatchPatch) diffHalfMatchI(l, s []rune, i int) [][]rune {
+	var bestCommonA []rune
+	var bestCommonB []rune
+	var bestCommonLen int
+	var bestLongtextA []rune
+	var bestLongtextB []rune
+	var bestShorttextA []rune
+	var bestShorttextB []rune
+
+	// Start with a 1/4 length substring at position i as a seed.
+	seed := l[i : i+len(l)/4]
+
+	for j := runesIndexOf(s, seed, 0); j != -1; j = runesIndexOf(s, seed, j+1) {
+		prefixLength := commonPrefixLength(l[i:], s[j:])
+		suffixLength := commonSuffixLength(l[:i], s[:j])
+
+		if bestCommonLen < suffixLength+prefixLength {
+			bestCommonA = s[j-suffixLength : j]
+			bestCommonB = s[j : j+prefixLength]
+			bestCommonLen = len(bestCommonA) + len(bestCommonB)
+			bestLongtextA = l[:i-suffixLength]
+			bestLongtextB = l[i+prefixLength:]
+			bestShorttextA = s[:j-suffixLength]
+			bestShorttextB = s[j+prefixLength:]
+		}
+	}
+
+	if bestCommonLen*2 < len(l) {
+		return nil
+	}
+
+	return [][]rune{
+		bestLongtextA,
+		bestLongtextB,
+		bestShorttextA,
+		bestShorttextB,
+		append(bestCommonA, bestCommonB...),
+	}
+}
+
+// DiffCleanupSemantic reduces the number of edits by eliminating semantically trivial equalities.
+func (dmp *DiffMatchPatch) DiffCleanupSemantic(diffs []Diff) []Diff {
+	changes := false
+	// Stack of indices where equalities are found.
+	type equality struct {
+		data int
+		next *equality
+	}
+	var equalities *equality
+
+	var lastequality string
+	// Always equal to diffs[equalities[equalitiesLength - 1]][1]
+	var pointer int // Index of current position.
+	// Number of characters that changed prior to the equality.
+	var lengthInsertions1, lengthDeletions1 int
+	// Number of characters that changed after the equality.
+	var lengthInsertions2, lengthDeletions2 int
+
+	for pointer < len(diffs) {
+		if diffs[pointer].Type == DiffEqual {
+			// Equality found.
+
+			equalities = &equality{
+				data: pointer,
+				next: equalities,
+			}
+			lengthInsertions1 = lengthInsertions2
+			lengthDeletions1 = lengthDeletions2
+			lengthInsertions2 = 0
+			lengthDeletions2 = 0
+			lastequality = diffs[pointer].Text
+		} else {
+			// An insertion or deletion.
+
+			if diffs[pointer].Type == DiffInsert {
+				lengthInsertions2 += len(diffs[pointer].Text)
+			} else {
+				lengthDeletions2 += len(diffs[pointer].Text)
+			}
+			// Eliminate an equality that is smaller or equal to the edits on both sides of it.
+			difference1 := int(math.Max(float64(lengthInsertions1), float64(lengthDeletions1)))
+			difference2 := int(math.Max(float64(lengthInsertions2), float64(lengthDeletions2)))
+			if len(lastequality) > 0 &&
+				(len(lastequality) <= difference1) &&
+				(len(lastequality) <= difference2) {
+				// Duplicate record.
+				insPoint := equalities.data
+				diffs = append(
+					diffs[:insPoint],
+					append([]Diff{Diff{DiffDelete, lastequality}}, diffs[insPoint:]...)...)
+
+				// Change second copy to insert.
+				diffs[insPoint+1].Type = DiffInsert
+				// Throw away the equality we just deleted.
+				equalities = equalities.next
+
+				if equalities != nil {
+					equalities = equalities.next
+				}
+				if equalities != nil {
+					pointer = equalities.data
+				} else {
+					pointer = -1
+				}
+
+				lengthInsertions1 = 0 // Reset the counters.
+				lengthDeletions1 = 0
+				lengthInsertions2 = 0
+				lengthDeletions2 = 0
+				lastequality = ""
+				changes = true
+			}
+		}
+		pointer++
+	}
+
+	// Normalize the diff.
+	if changes {
+		diffs = dmp.DiffCleanupMerge(diffs)
+	}
+	diffs = dmp.DiffCleanupSemanticLossless(diffs)
+	// Find any overlaps between deletions and insertions.
+	// e.g: <del>abcxxx</del><ins>xxxdef</ins>
+	//   -> <del>abc</del>xxx<ins>def</ins>
+	// e.g: <del>xxxabc</del><ins>defxxx</ins>
+	//   -> <ins>def</ins>xxx<del>abc</del>
+	// Only extract an overlap if it is as big as the edit ahead or behind it.
+	pointer = 1
+	for pointer < len(diffs) {
+		if diffs[pointer-1].Type == DiffDelete &&
+			diffs[pointer].Type == DiffInsert {
+			deletion := diffs[pointer-1].Text
+			insertion := diffs[pointer].Text
+			overlapLength1 := dmp.DiffCommonOverlap(deletion, insertion)
+			overlapLength2 := dmp.DiffCommonOverlap(insertion, deletion)
+			if overlapLength1 >= overlapLength2 {
+				if float64(overlapLength1) >= float64(len(deletion))/2 ||
+					float64(overlapLength1) >= float64(len(insertion))/2 {
+
+					// Overlap found. Insert an equality and trim the surrounding edits.
+					diffs = append(
+						diffs[:pointer],
+						append([]Diff{Diff{DiffEqual, insertion[:overlapLength1]}}, diffs[pointer:]...)...)
+
+					diffs[pointer-1].Text =
+						deletion[0 : len(deletion)-overlapLength1]
+					diffs[pointer+1].Text = insertion[overlapLength1:]
+					pointer++
+				}
+			} else {
+				if float64(overlapLength2) >= float64(len(deletion))/2 ||
+					float64(overlapLength2) >= float64(len(insertion))/2 {
+					// Reverse overlap found. Insert an equality and swap and trim the surrounding edits.
+					overlap := Diff{DiffEqual, deletion[:overlapLength2]}
+					diffs = append(
+						diffs[:pointer],
+						append([]Diff{overlap}, diffs[pointer:]...)...)
+
+					diffs[pointer-1].Type = DiffInsert
+					diffs[pointer-1].Text = insertion[0 : len(insertion)-overlapLength2]
+					diffs[pointer+1].Type = DiffDelete
+					diffs[pointer+1].Text = deletion[overlapLength2:]
+					pointer++
+				}
+			}
+			pointer++
+		}
+		pointer++
+	}
+
+	return diffs
+}
+
+// Define some regex patterns for matching boundaries.
+var (
+	nonAlphaNumericRegex = regexp.MustCompile(`[^a-zA-Z0-9]`)
+	whitespaceRegex      = regexp.MustCompile(`\s`)
+	linebreakRegex       = regexp.MustCompile(`[\r\n]`)
+	blanklineEndRegex    = regexp.MustCompile(`\n\r?\n$`)
+	blanklineStartRegex  = regexp.MustCompile(`^\r?\n\r?\n`)
+)
+
+// diffCleanupSemanticScore computes a score representing whether the internal boundary falls on logical boundaries.
+// Scores range from 6 (best) to 0 (worst). Closure, but does not reference any external variables.
+func diffCleanupSemanticScore(one, two string) int {
+	if len(one) == 0 || len(two) == 0 {
+		// Edges are the best.
+		return 6
+	}
+
+	// Each port of this function behaves slightly differently due to subtle differences in each language's definition of things like 'whitespace'.  Since this function's purpose is largely cosmetic, the choice has been made to use each language's native features rather than force total conformity.
+	rune1, _ := utf8.DecodeLastRuneInString(one)
+	rune2, _ := utf8.DecodeRuneInString(two)
+	char1 := string(rune1)
+	char2 := string(rune2)
+
+	nonAlphaNumeric1 := nonAlphaNumericRegex.MatchString(char1)
+	nonAlphaNumeric2 := nonAlphaNumericRegex.MatchString(char2)
+	whitespace1 := nonAlphaNumeric1 && whitespaceRegex.MatchString(char1)
+	whitespace2 := nonAlphaNumeric2 && whitespaceRegex.MatchString(char2)
+	lineBreak1 := whitespace1 && linebreakRegex.MatchString(char1)
+	lineBreak2 := whitespace2 && linebreakRegex.MatchString(char2)
+	blankLine1 := lineBreak1 && blanklineEndRegex.MatchString(one)
+	blankLine2 := lineBreak2 && blanklineEndRegex.MatchString(two)
+
+	if blankLine1 || blankLine2 {
+		// Five points for blank lines.
+		return 5
+	} else if lineBreak1 || lineBreak2 {
+		// Four points for line breaks.
+		return 4
+	} else if nonAlphaNumeric1 && !whitespace1 && whitespace2 {
+		// Three points for end of sentences.
+		return 3
+	} else if whitespace1 || whitespace2 {
+		// Two points for whitespace.
+		return 2
+	} else if nonAlphaNumeric1 || nonAlphaNumeric2 {
+		// One point for non-alphanumeric.
+		return 1
+	}
+	return 0
+}
+
+// DiffCleanupSemanticLossless looks for single edits surrounded on both sides by equalities which can be shifted sideways to align the edit to a word boundary.
+// E.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came.
+func (dmp *DiffMatchPatch) DiffCleanupSemanticLossless(diffs []Diff) []Diff {
+	pointer := 1
+
+	// Intentionally ignore the first and last element (don't need checking).
+	for pointer < len(diffs)-1 {
+		if diffs[pointer-1].Type == DiffEqual &&
+			diffs[pointer+1].Type == DiffEqual {
+
+			// This is a single edit surrounded by equalities.
+			equality1 := diffs[pointer-1].Text
+			edit := diffs[pointer].Text
+			equality2 := diffs[pointer+1].Text
+
+			// First, shift the edit as far left as possible.
+			commonOffset := dmp.DiffCommonSuffix(equality1, edit)
+			if commonOffset > 0 {
+				commonString := edit[len(edit)-commonOffset:]
+				equality1 = equality1[0 : len(equality1)-commonOffset]
+				edit = commonString + edit[:len(edit)-commonOffset]
+				equality2 = commonString + equality2
+			}
+
+			// Second, step character by character right, looking for the best fit.
+			bestEquality1 := equality1
+			bestEdit := edit
+			bestEquality2 := equality2
+			bestScore := diffCleanupSemanticScore(equality1, edit) +
+				diffCleanupSemanticScore(edit, equality2)
+
+			for len(edit) != 0 && len(equality2) != 0 {
+				_, sz := utf8.DecodeRuneInString(edit)
+				if len(equality2) < sz || edit[:sz] != equality2[:sz] {
+					break
+				}
+				equality1 += edit[:sz]
+				edit = edit[sz:] + equality2[:sz]
+				equality2 = equality2[sz:]
+				score := diffCleanupSemanticScore(equality1, edit) +
+					diffCleanupSemanticScore(edit, equality2)
+				// The >= encourages trailing rather than leading whitespace on edits.
+				if score >= bestScore {
+					bestScore = score
+					bestEquality1 = equality1
+					bestEdit = edit
+					bestEquality2 = equality2
+				}
+			}
+
+			if diffs[pointer-1].Text != bestEquality1 {
+				// We have an improvement, save it back to the diff.
+				if len(bestEquality1) != 0 {
+					diffs[pointer-1].Text = bestEquality1
+				} else {
+					diffs = splice(diffs, pointer-1, 1)
+					pointer--
+				}
+
+				diffs[pointer].Text = bestEdit
+				if len(bestEquality2) != 0 {
+					diffs[pointer+1].Text = bestEquality2
+				} else {
+					diffs = append(diffs[:pointer+1], diffs[pointer+2:]...)
+					pointer--
+				}
+			}
+		}
+		pointer++
+	}
+
+	return diffs
+}
+
+// DiffCleanupEfficiency reduces the number of edits by eliminating operationally trivial equalities.
+func (dmp *DiffMatchPatch) DiffCleanupEfficiency(diffs []Diff) []Diff {
+	changes := false
+	// Stack of indices where equalities are found.
+	type equality struct {
+		data int
+		next *equality
+	}
+	var equalities *equality
+	// Always equal to equalities[equalitiesLength-1][1]
+	lastequality := ""
+	pointer := 0 // Index of current position.
+	// Is there an insertion operation before the last equality.
+	preIns := false
+	// Is there a deletion operation before the last equality.
+	preDel := false
+	// Is there an insertion operation after the last equality.
+	postIns := false
+	// Is there a deletion operation after the last equality.
+	postDel := false
+	for pointer < len(diffs) {
+		if diffs[pointer].Type == DiffEqual { // Equality found.
+			if len(diffs[pointer].Text) < dmp.DiffEditCost &&
+				(postIns || postDel) {
+				// Candidate found.
+				equalities = &equality{
+					data: pointer,
+					next: equalities,
+				}
+				preIns = postIns
+				preDel = postDel
+				lastequality = diffs[pointer].Text
+			} else {
+				// Not a candidate, and can never become one.
+				equalities = nil
+				lastequality = ""
+			}
+			postIns = false
+			postDel = false
+		} else { // An insertion or deletion.
+			if diffs[pointer].Type == DiffDelete {
+				postDel = true
+			} else {
+				postIns = true
+			}
+
+			// Five types to be split:
+			// <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del>
+			// <ins>A</ins>X<ins>C</ins><del>D</del>
+			// <ins>A</ins><del>B</del>X<ins>C</ins>
+			// <ins>A</del>X<ins>C</ins><del>D</del>
+			// <ins>A</ins><del>B</del>X<del>C</del>
+			var sumPres int
+			if preIns {
+				sumPres++
+			}
+			if preDel {
+				sumPres++
+			}
+			if postIns {
+				sumPres++
+			}
+			if postDel {
+				sumPres++
+			}
+			if len(lastequality) > 0 &&
+				((preIns && preDel && postIns && postDel) ||
+					((len(lastequality) < dmp.DiffEditCost/2) && sumPres == 3)) {
+
+				insPoint := equalities.data
+
+				// Duplicate record.
+				diffs = append(diffs[:insPoint],
+					append([]Diff{Diff{DiffDelete, lastequality}}, diffs[insPoint:]...)...)
+
+				// Change second copy to insert.
+				diffs[insPoint+1].Type = DiffInsert
+				// Throw away the equality we just deleted.
+				equalities = equalities.next
+				lastequality = ""
+
+				if preIns && preDel {
+					// No changes made which could affect previous entry, keep going.
+					postIns = true
+					postDel = true
+					equalities = nil
+				} else {
+					if equalities != nil {
+						equalities = equalities.next
+					}
+					if equalities != nil {
+						pointer = equalities.data
+					} else {
+						pointer = -1
+					}
+					postIns = false
+					postDel = false
+				}
+				changes = true
+			}
+		}
+		pointer++
+	}
+
+	if changes {
+		diffs = dmp.DiffCleanupMerge(diffs)
+	}
+
+	return diffs
+}
+
+// DiffCleanupMerge reorders and merges like edit sections. Merge equalities.
+// Any edit section can move as long as it doesn't cross an equality.
+func (dmp *DiffMatchPatch) DiffCleanupMerge(diffs []Diff) []Diff {
+	// Add a dummy entry at the end.
+	diffs = append(diffs, Diff{DiffEqual, ""})
+	pointer := 0
+	countDelete := 0
+	countInsert := 0
+	commonlength := 0
+	textDelete := []rune(nil)
+	textInsert := []rune(nil)
+
+	for pointer < len(diffs) {
+		switch diffs[pointer].Type {
+		case DiffInsert:
+			countInsert++
+			textInsert = append(textInsert, []rune(diffs[pointer].Text)...)
+			pointer++
+			break
+		case DiffDelete:
+			countDelete++
+			textDelete = append(textDelete, []rune(diffs[pointer].Text)...)
+			pointer++
+			break
+		case DiffEqual:
+			// Upon reaching an equality, check for prior redundancies.
+			if countDelete+countInsert > 1 {
+				if countDelete != 0 && countInsert != 0 {
+					// Factor out any common prefixies.
+					commonlength = commonPrefixLength(textInsert, textDelete)
+					if commonlength != 0 {
+						x := pointer - countDelete - countInsert
+						if x > 0 && diffs[x-1].Type == DiffEqual {
+							diffs[x-1].Text += string(textInsert[:commonlength])
+						} else {
+							diffs = append([]Diff{Diff{DiffEqual, string(textInsert[:commonlength])}}, diffs...)
+							pointer++
+						}
+						textInsert = textInsert[commonlength:]
+						textDelete = textDelete[commonlength:]
+					}
+					// Factor out any common suffixies.
+					commonlength = commonSuffixLength(textInsert, textDelete)
+					if commonlength != 0 {
+						insertIndex := len(textInsert) - commonlength
+						deleteIndex := len(textDelete) - commonlength
+						diffs[pointer].Text = string(textInsert[insertIndex:]) + diffs[pointer].Text
+						textInsert = textInsert[:insertIndex]
+						textDelete = textDelete[:deleteIndex]
+					}
+				}
+				// Delete the offending records and add the merged ones.
+				if countDelete == 0 {
+					diffs = splice(diffs, pointer-countInsert,
+						countDelete+countInsert,
+						Diff{DiffInsert, string(textInsert)})
+				} else if countInsert == 0 {
+					diffs = splice(diffs, pointer-countDelete,
+						countDelete+countInsert,
+						Diff{DiffDelete, string(textDelete)})
+				} else {
+					diffs = splice(diffs, pointer-countDelete-countInsert,
+						countDelete+countInsert,
+						Diff{DiffDelete, string(textDelete)},
+						Diff{DiffInsert, string(textInsert)})
+				}
+
+				pointer = pointer - countDelete - countInsert + 1
+				if countDelete != 0 {
+					pointer++
+				}
+				if countInsert != 0 {
+					pointer++
+				}
+			} else if pointer != 0 && diffs[pointer-1].Type == DiffEqual {
+				// Merge this equality with the previous one.
+				diffs[pointer-1].Text += diffs[pointer].Text
+				diffs = append(diffs[:pointer], diffs[pointer+1:]...)
+			} else {
+				pointer++
+			}
+			countInsert = 0
+			countDelete = 0
+			textDelete = nil
+			textInsert = nil
+			break
+		}
+	}
+
+	if len(diffs[len(diffs)-1].Text) == 0 {
+		diffs = diffs[0 : len(diffs)-1] // Remove the dummy entry at the end.
+	}
+
+	// Second pass: look for single edits surrounded on both sides by equalities which can be shifted sideways to eliminate an equality. E.g: A<ins>BA</ins>C -> <ins>AB</ins>AC
+	changes := false
+	pointer = 1
+	// Intentionally ignore the first and last element (don't need checking).
+	for pointer < (len(diffs) - 1) {
+		if diffs[pointer-1].Type == DiffEqual &&
+			diffs[pointer+1].Type == DiffEqual {
+			// This is a single edit surrounded by equalities.
+			if strings.HasSuffix(diffs[pointer].Text, diffs[pointer-1].Text) {
+				// Shift the edit over the previous equality.
+				diffs[pointer].Text = diffs[pointer-1].Text +
+					diffs[pointer].Text[:len(diffs[pointer].Text)-len(diffs[pointer-1].Text)]
+				diffs[pointer+1].Text = diffs[pointer-1].Text + diffs[pointer+1].Text
+				diffs = splice(diffs, pointer-1, 1)
+				changes = true
+			} else if strings.HasPrefix(diffs[pointer].Text, diffs[pointer+1].Text) {
+				// Shift the edit over the next equality.
+				diffs[pointer-1].Text += diffs[pointer+1].Text
+				diffs[pointer].Text =
+					diffs[pointer].Text[len(diffs[pointer+1].Text):] + diffs[pointer+1].Text
+				diffs = splice(diffs, pointer+1, 1)
+				changes = true
+			}
+		}
+		pointer++
+	}
+
+	// If shifts were made, the diff needs reordering and another shift sweep.
+	if changes {
+		diffs = dmp.DiffCleanupMerge(diffs)
+	}
+
+	return diffs
+}
+
+// DiffXIndex returns the equivalent location in s2.
+func (dmp *DiffMatchPatch) DiffXIndex(diffs []Diff, loc int) int {
+	chars1 := 0
+	chars2 := 0
+	lastChars1 := 0
+	lastChars2 := 0
+	lastDiff := Diff{}
+	for i := 0; i < len(diffs); i++ {
+		aDiff := diffs[i]
+		if aDiff.Type != DiffInsert {
+			// Equality or deletion.
+			chars1 += len(aDiff.Text)
+		}
+		if aDiff.Type != DiffDelete {
+			// Equality or insertion.
+			chars2 += len(aDiff.Text)
+		}
+		if chars1 > loc {
+			// Overshot the location.
+			lastDiff = aDiff
+			break
+		}
+		lastChars1 = chars1
+		lastChars2 = chars2
+	}
+	if lastDiff.Type == DiffDelete {
+		// The location was deleted.
+		return lastChars2
+	}
+	// Add the remaining character length.
+	return lastChars2 + (loc - lastChars1)
+}
+
+// DiffPrettyHtml converts a []Diff into a pretty HTML report.
+// It is intended as an example from which to write one's own display functions.
+func (dmp *DiffMatchPatch) DiffPrettyHtml(diffs []Diff) string {
+	var buff bytes.Buffer
+	for _, diff := range diffs {
+		text := strings.Replace(html.EscapeString(diff.Text), "\n", "&para;<br>", -1)
+		switch diff.Type {
+		case DiffInsert:
+			_, _ = buff.WriteString("<ins style=\"background:#e6ffe6;\">")
+			_, _ = buff.WriteString(text)
+			_, _ = buff.WriteString("</ins>")
+		case DiffDelete:
+			_, _ = buff.WriteString("<del style=\"background:#ffe6e6;\">")
+			_, _ = buff.WriteString(text)
+			_, _ = buff.WriteString("</del>")
+		case DiffEqual:
+			_, _ = buff.WriteString("<span>")
+			_, _ = buff.WriteString(text)
+			_, _ = buff.WriteString("</span>")
+		}
+	}
+	return buff.String()
+}
+
+// DiffPrettyText converts a []Diff into a colored text report.
+func (dmp *DiffMatchPatch) DiffPrettyText(diffs []Diff) string {
+	var buff bytes.Buffer
+	for _, diff := range diffs {
+		text := diff.Text
+
+		switch diff.Type {
+		case DiffInsert:
+			_, _ = buff.WriteString("\x1b[32m")
+			_, _ = buff.WriteString(text)
+			_, _ = buff.WriteString("\x1b[0m")
+		case DiffDelete:
+			_, _ = buff.WriteString("\x1b[31m")
+			_, _ = buff.WriteString(text)
+			_, _ = buff.WriteString("\x1b[0m")
+		case DiffEqual:
+			_, _ = buff.WriteString(text)
+		}
+	}
+
+	return buff.String()
+}
+
+// DiffText1 computes and returns the source text (all equalities and deletions).
+func (dmp *DiffMatchPatch) DiffText1(diffs []Diff) string {
+	//StringBuilder text = new StringBuilder()
+	var text bytes.Buffer
+
+	for _, aDiff := range diffs {
+		if aDiff.Type != DiffInsert {
+			_, _ = text.WriteString(aDiff.Text)
+		}
+	}
+	return text.String()
+}
+
+// DiffText2 computes and returns the destination text (all equalities and insertions).
+func (dmp *DiffMatchPatch) DiffText2(diffs []Diff) string {
+	var text bytes.Buffer
+
+	for _, aDiff := range diffs {
+		if aDiff.Type != DiffDelete {
+			_, _ = text.WriteString(aDiff.Text)
+		}
+	}
+	return text.String()
+}
+
+// DiffLevenshtein computes the Levenshtein distance that is the number of inserted, deleted or substituted characters.
+func (dmp *DiffMatchPatch) DiffLevenshtein(diffs []Diff) int {
+	levenshtein := 0
+	insertions := 0
+	deletions := 0
+
+	for _, aDiff := range diffs {
+		switch aDiff.Type {
+		case DiffInsert:
+			insertions += len(aDiff.Text)
+		case DiffDelete:
+			deletions += len(aDiff.Text)
+		case DiffEqual:
+			// A deletion and an insertion is one substitution.
+			levenshtein += max(insertions, deletions)
+			insertions = 0
+			deletions = 0
+		}
+	}
+
+	levenshtein += max(insertions, deletions)
+	return levenshtein
+}
+
+// DiffToDelta crushes the diff into an encoded string which describes the operations required to transform text1 into text2.
+// E.g. =3\t-2\t+ing  -> Keep 3 chars, delete 2 chars, insert 'ing'. Operations are tab-separated.  Inserted text is escaped using %xx notation.
+func (dmp *DiffMatchPatch) DiffToDelta(diffs []Diff) string {
+	var text bytes.Buffer
+	for _, aDiff := range diffs {
+		switch aDiff.Type {
+		case DiffInsert:
+			_, _ = text.WriteString("+")
+			_, _ = text.WriteString(strings.Replace(url.QueryEscape(aDiff.Text), "+", " ", -1))
+			_, _ = text.WriteString("\t")
+			break
+		case DiffDelete:
+			_, _ = text.WriteString("-")
+			_, _ = text.WriteString(strconv.Itoa(utf8.RuneCountInString(aDiff.Text)))
+			_, _ = text.WriteString("\t")
+			break
+		case DiffEqual:
+			_, _ = text.WriteString("=")
+			_, _ = text.WriteString(strconv.Itoa(utf8.RuneCountInString(aDiff.Text)))
+			_, _ = text.WriteString("\t")
+			break
+		}
+	}
+	delta := text.String()
+	if len(delta) != 0 {
+		// Strip off trailing tab character.
+		delta = delta[0 : utf8.RuneCountInString(delta)-1]
+		delta = unescaper.Replace(delta)
+	}
+	return delta
+}
+
+// DiffFromDelta given the original text1, and an encoded string which describes the operations required to transform text1 into text2, comAdde the full diff.
+func (dmp *DiffMatchPatch) DiffFromDelta(text1 string, delta string) (diffs []Diff, err error) {
+	i := 0
+
+	for _, token := range strings.Split(delta, "\t") {
+		if len(token) == 0 {
+			// Blank tokens are ok (from a trailing \t).
+			continue
+		}
+
+		// Each token begins with a one character parameter which specifies the operation of this token (delete, insert, equality).
+		param := token[1:]
+
+		switch op := token[0]; op {
+		case '+':
+			// Decode would Diff all "+" to " "
+			param = strings.Replace(param, "+", "%2b", -1)
+			param, err = url.QueryUnescape(param)
+			if err != nil {
+				return nil, err
+			}
+			if !utf8.ValidString(param) {
+				return nil, fmt.Errorf("invalid UTF-8 token: %q", param)
+			}
+
+			diffs = append(diffs, Diff{DiffInsert, param})
+		case '=', '-':
+			n, err := strconv.ParseInt(param, 10, 0)
+			if err != nil {
+				return nil, err
+			} else if n < 0 {
+				return nil, errors.New("Negative number in DiffFromDelta: " + param)
+			}
+
+			// Remember that string slicing is by byte - we want by rune here.
+			text := string([]rune(text1)[i : i+int(n)])
+			i += int(n)
+
+			if op == '=' {
+				diffs = append(diffs, Diff{DiffEqual, text})
+			} else {
+				diffs = append(diffs, Diff{DiffDelete, text})
+			}
+		default:
+			// Anything else is an error.
+			return nil, errors.New("Invalid diff operation in DiffFromDelta: " + string(token[0]))
+		}
+	}
+
+	if i != len([]rune(text1)) {
+		return nil, fmt.Errorf("Delta length (%v) smaller than source text length (%v)", i, len(text1))
+	}
+
+	return diffs, nil
+}

+ 46 - 0
vendor/github.com/sergi/go-diff/diffmatchpatch/diffmatchpatch.go

@@ -0,0 +1,46 @@
+// Copyright (c) 2012-2016 The go-diff authors. All rights reserved.
+// https://github.com/sergi/go-diff
+// See the included LICENSE file for license details.
+//
+// go-diff is a Go implementation of Google's Diff, Match, and Patch library
+// Original library is Copyright (c) 2006 Google Inc.
+// http://code.google.com/p/google-diff-match-patch/
+
+// Package diffmatchpatch offers robust algorithms to perform the operations required for synchronizing plain text.
+package diffmatchpatch
+
+import (
+	"time"
+)
+
+// DiffMatchPatch holds the configuration for diff-match-patch operations.
+type DiffMatchPatch struct {
+	// Number of seconds to map a diff before giving up (0 for infinity).
+	DiffTimeout time.Duration
+	// Cost of an empty edit operation in terms of edit characters.
+	DiffEditCost int
+	// How far to search for a match (0 = exact location, 1000+ = broad match). A match this many characters away from the expected location will add 1.0 to the score (0.0 is a perfect match).
+	MatchDistance int
+	// When deleting a large block of text (over ~64 characters), how close do the contents have to be to match the expected contents. (0.0 = perfection, 1.0 = very loose).  Note that MatchThreshold controls how closely the end points of a delete need to match.
+	PatchDeleteThreshold float64
+	// Chunk size for context length.
+	PatchMargin int
+	// The number of bits in an int.
+	MatchMaxBits int
+	// At what point is no match declared (0.0 = perfection, 1.0 = very loose).
+	MatchThreshold float64
+}
+
+// New creates a new DiffMatchPatch object with default parameters.
+func New() *DiffMatchPatch {
+	// Defaults.
+	return &DiffMatchPatch{
+		DiffTimeout:          time.Second,
+		DiffEditCost:         4,
+		MatchThreshold:       0.5,
+		MatchDistance:        1000,
+		PatchDeleteThreshold: 0.5,
+		PatchMargin:          4,
+		MatchMaxBits:         32,
+	}
+}

+ 160 - 0
vendor/github.com/sergi/go-diff/diffmatchpatch/match.go

@@ -0,0 +1,160 @@
+// Copyright (c) 2012-2016 The go-diff authors. All rights reserved.
+// https://github.com/sergi/go-diff
+// See the included LICENSE file for license details.
+//
+// go-diff is a Go implementation of Google's Diff, Match, and Patch library
+// Original library is Copyright (c) 2006 Google Inc.
+// http://code.google.com/p/google-diff-match-patch/
+
+package diffmatchpatch
+
+import (
+	"math"
+)
+
+// MatchMain locates the best instance of 'pattern' in 'text' near 'loc'.
+// Returns -1 if no match found.
+func (dmp *DiffMatchPatch) MatchMain(text, pattern string, loc int) int {
+	// Check for null inputs not needed since null can't be passed in C#.
+
+	loc = int(math.Max(0, math.Min(float64(loc), float64(len(text)))))
+	if text == pattern {
+		// Shortcut (potentially not guaranteed by the algorithm)
+		return 0
+	} else if len(text) == 0 {
+		// Nothing to match.
+		return -1
+	} else if loc+len(pattern) <= len(text) && text[loc:loc+len(pattern)] == pattern {
+		// Perfect match at the perfect spot!  (Includes case of null pattern)
+		return loc
+	}
+	// Do a fuzzy compare.
+	return dmp.MatchBitap(text, pattern, loc)
+}
+
+// MatchBitap locates the best instance of 'pattern' in 'text' near 'loc' using the Bitap algorithm.
+// Returns -1 if no match was found.
+func (dmp *DiffMatchPatch) MatchBitap(text, pattern string, loc int) int {
+	// Initialise the alphabet.
+	s := dmp.MatchAlphabet(pattern)
+
+	// Highest score beyond which we give up.
+	scoreThreshold := dmp.MatchThreshold
+	// Is there a nearby exact match? (speedup)
+	bestLoc := indexOf(text, pattern, loc)
+	if bestLoc != -1 {
+		scoreThreshold = math.Min(dmp.matchBitapScore(0, bestLoc, loc,
+			pattern), scoreThreshold)
+		// What about in the other direction? (speedup)
+		bestLoc = lastIndexOf(text, pattern, loc+len(pattern))
+		if bestLoc != -1 {
+			scoreThreshold = math.Min(dmp.matchBitapScore(0, bestLoc, loc,
+				pattern), scoreThreshold)
+		}
+	}
+
+	// Initialise the bit arrays.
+	matchmask := 1 << uint((len(pattern) - 1))
+	bestLoc = -1
+
+	var binMin, binMid int
+	binMax := len(pattern) + len(text)
+	lastRd := []int{}
+	for d := 0; d < len(pattern); d++ {
+		// Scan for the best match; each iteration allows for one more error. Run a binary search to determine how far from 'loc' we can stray at this error level.
+		binMin = 0
+		binMid = binMax
+		for binMin < binMid {
+			if dmp.matchBitapScore(d, loc+binMid, loc, pattern) <= scoreThreshold {
+				binMin = binMid
+			} else {
+				binMax = binMid
+			}
+			binMid = (binMax-binMin)/2 + binMin
+		}
+		// Use the result from this iteration as the maximum for the next.
+		binMax = binMid
+		start := int(math.Max(1, float64(loc-binMid+1)))
+		finish := int(math.Min(float64(loc+binMid), float64(len(text))) + float64(len(pattern)))
+
+		rd := make([]int, finish+2)
+		rd[finish+1] = (1 << uint(d)) - 1
+
+		for j := finish; j >= start; j-- {
+			var charMatch int
+			if len(text) <= j-1 {
+				// Out of range.
+				charMatch = 0
+			} else if _, ok := s[text[j-1]]; !ok {
+				charMatch = 0
+			} else {
+				charMatch = s[text[j-1]]
+			}
+
+			if d == 0 {
+				// First pass: exact match.
+				rd[j] = ((rd[j+1] << 1) | 1) & charMatch
+			} else {
+				// Subsequent passes: fuzzy match.
+				rd[j] = ((rd[j+1]<<1)|1)&charMatch | (((lastRd[j+1] | lastRd[j]) << 1) | 1) | lastRd[j+1]
+			}
+			if (rd[j] & matchmask) != 0 {
+				score := dmp.matchBitapScore(d, j-1, loc, pattern)
+				// This match will almost certainly be better than any existing match.  But check anyway.
+				if score <= scoreThreshold {
+					// Told you so.
+					scoreThreshold = score
+					bestLoc = j - 1
+					if bestLoc > loc {
+						// When passing loc, don't exceed our current distance from loc.
+						start = int(math.Max(1, float64(2*loc-bestLoc)))
+					} else {
+						// Already passed loc, downhill from here on in.
+						break
+					}
+				}
+			}
+		}
+		if dmp.matchBitapScore(d+1, loc, loc, pattern) > scoreThreshold {
+			// No hope for a (better) match at greater error levels.
+			break
+		}
+		lastRd = rd
+	}
+	return bestLoc
+}
+
+// matchBitapScore computes and returns the score for a match with e errors and x location.
+func (dmp *DiffMatchPatch) matchBitapScore(e, x, loc int, pattern string) float64 {
+	accuracy := float64(e) / float64(len(pattern))
+	proximity := math.Abs(float64(loc - x))
+	if dmp.MatchDistance == 0 {
+		// Dodge divide by zero error.
+		if proximity == 0 {
+			return accuracy
+		}
+
+		return 1.0
+	}
+	return accuracy + (proximity / float64(dmp.MatchDistance))
+}
+
+// MatchAlphabet initialises the alphabet for the Bitap algorithm.
+func (dmp *DiffMatchPatch) MatchAlphabet(pattern string) map[byte]int {
+	s := map[byte]int{}
+	charPattern := []byte(pattern)
+	for _, c := range charPattern {
+		_, ok := s[c]
+		if !ok {
+			s[c] = 0
+		}
+	}
+	i := 0
+
+	for _, c := range charPattern {
+		value := s[c] | int(uint(1)<<uint((len(pattern)-i-1)))
+		s[c] = value
+		i++
+	}
+	return s
+}

+ 23 - 0
vendor/github.com/sergi/go-diff/diffmatchpatch/mathutil.go

@@ -0,0 +1,23 @@
+// Copyright (c) 2012-2016 The go-diff authors. All rights reserved.
+// https://github.com/sergi/go-diff
+// See the included LICENSE file for license details.
+//
+// go-diff is a Go implementation of Google's Diff, Match, and Patch library
+// Original library is Copyright (c) 2006 Google Inc.
+// http://code.google.com/p/google-diff-match-patch/
+
+package diffmatchpatch
+
+func min(x, y int) int {
+	if x < y {
+		return x
+	}
+	return y
+}
+
+func max(x, y int) int {
+	if x > y {
+		return x
+	}
+	return y
+}

+ 556 - 0
vendor/github.com/sergi/go-diff/diffmatchpatch/patch.go

@@ -0,0 +1,556 @@
+// Copyright (c) 2012-2016 The go-diff authors. All rights reserved.
+// https://github.com/sergi/go-diff
+// See the included LICENSE file for license details.
+//
+// go-diff is a Go implementation of Google's Diff, Match, and Patch library
+// Original library is Copyright (c) 2006 Google Inc.
+// http://code.google.com/p/google-diff-match-patch/
+
+package diffmatchpatch
+
+import (
+	"bytes"
+	"errors"
+	"math"
+	"net/url"
+	"regexp"
+	"strconv"
+	"strings"
+)
+
+// Patch represents one patch operation.
+type Patch struct {
+	diffs   []Diff
+	start1  int
+	start2  int
+	length1 int
+	length2 int
+}
+
+// String emulates GNU diff's format.
+// Header: @@ -382,8 +481,9 @@
+// Indicies are printed as 1-based, not 0-based.
+func (p *Patch) String() string {
+	var coords1, coords2 string
+
+	if p.length1 == 0 {
+		coords1 = strconv.Itoa(p.start1) + ",0"
+	} else if p.length1 == 1 {
+		coords1 = strconv.Itoa(p.start1 + 1)
+	} else {
+		coords1 = strconv.Itoa(p.start1+1) + "," + strconv.Itoa(p.length1)
+	}
+
+	if p.length2 == 0 {
+		coords2 = strconv.Itoa(p.start2) + ",0"
+	} else if p.length2 == 1 {
+		coords2 = strconv.Itoa(p.start2 + 1)
+	} else {
+		coords2 = strconv.Itoa(p.start2+1) + "," + strconv.Itoa(p.length2)
+	}
+
+	var text bytes.Buffer
+	_, _ = text.WriteString("@@ -" + coords1 + " +" + coords2 + " @@\n")
+
+	// Escape the body of the patch with %xx notation.
+	for _, aDiff := range p.diffs {
+		switch aDiff.Type {
+		case DiffInsert:
+			_, _ = text.WriteString("+")
+		case DiffDelete:
+			_, _ = text.WriteString("-")
+		case DiffEqual:
+			_, _ = text.WriteString(" ")
+		}
+
+		_, _ = text.WriteString(strings.Replace(url.QueryEscape(aDiff.Text), "+", " ", -1))
+		_, _ = text.WriteString("\n")
+	}
+
+	return unescaper.Replace(text.String())
+}
+
+// PatchAddContext increases the context until it is unique, but doesn't let the pattern expand beyond MatchMaxBits.
+func (dmp *DiffMatchPatch) PatchAddContext(patch Patch, text string) Patch {
+	if len(text) == 0 {
+		return patch
+	}
+
+	pattern := text[patch.start2 : patch.start2+patch.length1]
+	padding := 0
+
+	// Look for the first and last matches of pattern in text.  If two different matches are found, increase the pattern length.
+	for strings.Index(text, pattern) != strings.LastIndex(text, pattern) &&
+		len(pattern) < dmp.MatchMaxBits-2*dmp.PatchMargin {
+		padding += dmp.PatchMargin
+		maxStart := max(0, patch.start2-padding)
+		minEnd := min(len(text), patch.start2+patch.length1+padding)
+		pattern = text[maxStart:minEnd]
+	}
+	// Add one chunk for good luck.
+	padding += dmp.PatchMargin
+
+	// Add the prefix.
+	prefix := text[max(0, patch.start2-padding):patch.start2]
+	if len(prefix) != 0 {
+		patch.diffs = append([]Diff{Diff{DiffEqual, prefix}}, patch.diffs...)
+	}
+	// Add the suffix.
+	suffix := text[patch.start2+patch.length1 : min(len(text), patch.start2+patch.length1+padding)]
+	if len(suffix) != 0 {
+		patch.diffs = append(patch.diffs, Diff{DiffEqual, suffix})
+	}
+
+	// Roll back the start points.
+	patch.start1 -= len(prefix)
+	patch.start2 -= len(prefix)
+	// Extend the lengths.
+	patch.length1 += len(prefix) + len(suffix)
+	patch.length2 += len(prefix) + len(suffix)
+
+	return patch
+}
+
+// PatchMake computes a list of patches.
+func (dmp *DiffMatchPatch) PatchMake(opt ...interface{}) []Patch {
+	if len(opt) == 1 {
+		diffs, _ := opt[0].([]Diff)
+		text1 := dmp.DiffText1(diffs)
+		return dmp.PatchMake(text1, diffs)
+	} else if len(opt) == 2 {
+		text1 := opt[0].(string)
+		switch t := opt[1].(type) {
+		case string:
+			diffs := dmp.DiffMain(text1, t, true)
+			if len(diffs) > 2 {
+				diffs = dmp.DiffCleanupSemantic(diffs)
+				diffs = dmp.DiffCleanupEfficiency(diffs)
+			}
+			return dmp.PatchMake(text1, diffs)
+		case []Diff:
+			return dmp.patchMake2(text1, t)
+		}
+	} else if len(opt) == 3 {
+		return dmp.PatchMake(opt[0], opt[2])
+	}
+	return []Patch{}
+}
+
+// patchMake2 computes a list of patches to turn text1 into text2.
+// text2 is not provided, diffs are the delta between text1 and text2.
+func (dmp *DiffMatchPatch) patchMake2(text1 string, diffs []Diff) []Patch {
+	// Check for null inputs not needed since null can't be passed in C#.
+	patches := []Patch{}
+	if len(diffs) == 0 {
+		return patches // Get rid of the null case.
+	}
+
+	patch := Patch{}
+	charCount1 := 0 // Number of characters into the text1 string.
+	charCount2 := 0 // Number of characters into the text2 string.
+	// Start with text1 (prepatchText) and apply the diffs until we arrive at text2 (postpatchText). We recreate the patches one by one to determine context info.
+	prepatchText := text1
+	postpatchText := text1
+
+	for i, aDiff := range diffs {
+		if len(patch.diffs) == 0 && aDiff.Type != DiffEqual {
+			// A new patch starts here.
+			patch.start1 = charCount1
+			patch.start2 = charCount2
+		}
+
+		switch aDiff.Type {
+		case DiffInsert:
+			patch.diffs = append(patch.diffs, aDiff)
+			patch.length2 += len(aDiff.Text)
+			postpatchText = postpatchText[:charCount2] +
+				aDiff.Text + postpatchText[charCount2:]
+		case DiffDelete:
+			patch.length1 += len(aDiff.Text)
+			patch.diffs = append(patch.diffs, aDiff)
+			postpatchText = postpatchText[:charCount2] + postpatchText[charCount2+len(aDiff.Text):]
+		case DiffEqual:
+			if len(aDiff.Text) <= 2*dmp.PatchMargin &&
+				len(patch.diffs) != 0 && i != len(diffs)-1 {
+				// Small equality inside a patch.
+				patch.diffs = append(patch.diffs, aDiff)
+				patch.length1 += len(aDiff.Text)
+				patch.length2 += len(aDiff.Text)
+			}
+			if len(aDiff.Text) >= 2*dmp.PatchMargin {
+				// Time for a new patch.
+				if len(patch.diffs) != 0 {
+					patch = dmp.PatchAddContext(patch, prepatchText)
+					patches = append(patches, patch)
+					patch = Patch{}
+					// Unlike Unidiff, our patch lists have a rolling context. http://code.google.com/p/google-diff-match-patch/wiki/Unidiff Update prepatch text & pos to reflect the application of the just completed patch.
+					prepatchText = postpatchText
+					charCount1 = charCount2
+				}
+			}
+		}
+
+		// Update the current character count.
+		if aDiff.Type != DiffInsert {
+			charCount1 += len(aDiff.Text)
+		}
+		if aDiff.Type != DiffDelete {
+			charCount2 += len(aDiff.Text)
+		}
+	}
+
+	// Pick up the leftover patch if not empty.
+	if len(patch.diffs) != 0 {
+		patch = dmp.PatchAddContext(patch, prepatchText)
+		patches = append(patches, patch)
+	}
+
+	return patches
+}
+
+// PatchDeepCopy returns an array that is identical to a given an array of patches.
+func (dmp *DiffMatchPatch) PatchDeepCopy(patches []Patch) []Patch {
+	patchesCopy := []Patch{}
+	for _, aPatch := range patches {
+		patchCopy := Patch{}
+		for _, aDiff := range aPatch.diffs {
+			patchCopy.diffs = append(patchCopy.diffs, Diff{
+				aDiff.Type,
+				aDiff.Text,
+			})
+		}
+		patchCopy.start1 = aPatch.start1
+		patchCopy.start2 = aPatch.start2
+		patchCopy.length1 = aPatch.length1
+		patchCopy.length2 = aPatch.length2
+		patchesCopy = append(patchesCopy, patchCopy)
+	}
+	return patchesCopy
+}
+
+// PatchApply merges a set of patches onto the text.  Returns a patched text, as well as an array of true/false values indicating which patches were applied.
+func (dmp *DiffMatchPatch) PatchApply(patches []Patch, text string) (string, []bool) {
+	if len(patches) == 0 {
+		return text, []bool{}
+	}
+
+	// Deep copy the patches so that no changes are made to originals.
+	patches = dmp.PatchDeepCopy(patches)
+
+	nullPadding := dmp.PatchAddPadding(patches)
+	text = nullPadding + text + nullPadding
+	patches = dmp.PatchSplitMax(patches)
+
+	x := 0
+	// delta keeps track of the offset between the expected and actual location of the previous patch.  If there are patches expected at positions 10 and 20, but the first patch was found at 12, delta is 2 and the second patch has an effective expected position of 22.
+	delta := 0
+	results := make([]bool, len(patches))
+	for _, aPatch := range patches {
+		expectedLoc := aPatch.start2 + delta
+		text1 := dmp.DiffText1(aPatch.diffs)
+		var startLoc int
+		endLoc := -1
+		if len(text1) > dmp.MatchMaxBits {
+			// PatchSplitMax will only provide an oversized pattern in the case of a monster delete.
+			startLoc = dmp.MatchMain(text, text1[:dmp.MatchMaxBits], expectedLoc)
+			if startLoc != -1 {
+				endLoc = dmp.MatchMain(text,
+					text1[len(text1)-dmp.MatchMaxBits:], expectedLoc+len(text1)-dmp.MatchMaxBits)
+				if endLoc == -1 || startLoc >= endLoc {
+					// Can't find valid trailing context.  Drop this patch.
+					startLoc = -1
+				}
+			}
+		} else {
+			startLoc = dmp.MatchMain(text, text1, expectedLoc)
+		}
+		if startLoc == -1 {
+			// No match found.  :(
+			results[x] = false
+			// Subtract the delta for this failed patch from subsequent patches.
+			delta -= aPatch.length2 - aPatch.length1
+		} else {
+			// Found a match.  :)
+			results[x] = true
+			delta = startLoc - expectedLoc
+			var text2 string
+			if endLoc == -1 {
+				text2 = text[startLoc:int(math.Min(float64(startLoc+len(text1)), float64(len(text))))]
+			} else {
+				text2 = text[startLoc:int(math.Min(float64(endLoc+dmp.MatchMaxBits), float64(len(text))))]
+			}
+			if text1 == text2 {
+				// Perfect match, just shove the Replacement text in.
+				text = text[:startLoc] + dmp.DiffText2(aPatch.diffs) + text[startLoc+len(text1):]
+			} else {
+				// Imperfect match.  Run a diff to get a framework of equivalent indices.
+				diffs := dmp.DiffMain(text1, text2, false)
+				if len(text1) > dmp.MatchMaxBits && float64(dmp.DiffLevenshtein(diffs))/float64(len(text1)) > dmp.PatchDeleteThreshold {
+					// The end points match, but the content is unacceptably bad.
+					results[x] = false
+				} else {
+					diffs = dmp.DiffCleanupSemanticLossless(diffs)
+					index1 := 0
+					for _, aDiff := range aPatch.diffs {
+						if aDiff.Type != DiffEqual {
+							index2 := dmp.DiffXIndex(diffs, index1)
+							if aDiff.Type == DiffInsert {
+								// Insertion
+								text = text[:startLoc+index2] + aDiff.Text + text[startLoc+index2:]
+							} else if aDiff.Type == DiffDelete {
+								// Deletion
+								startIndex := startLoc + index2
+								text = text[:startIndex] +
+									text[startIndex+dmp.DiffXIndex(diffs, index1+len(aDiff.Text))-index2:]
+							}
+						}
+						if aDiff.Type != DiffDelete {
+							index1 += len(aDiff.Text)
+						}
+					}
+				}
+			}
+		}
+		x++
+	}
+	// Strip the padding off.
+	text = text[len(nullPadding) : len(nullPadding)+(len(text)-2*len(nullPadding))]
+	return text, results
+}
+
+// PatchAddPadding adds some padding on text start and end so that edges can match something.
+// Intended to be called only from within patchApply.
+func (dmp *DiffMatchPatch) PatchAddPadding(patches []Patch) string {
+	paddingLength := dmp.PatchMargin
+	nullPadding := ""
+	for x := 1; x <= paddingLength; x++ {
+		nullPadding += string(x)
+	}
+
+	// Bump all the patches forward.
+	for i := range patches {
+		patches[i].start1 += paddingLength
+		patches[i].start2 += paddingLength
+	}
+
+	// Add some padding on start of first diff.
+	if len(patches[0].diffs) == 0 || patches[0].diffs[0].Type != DiffEqual {
+		// Add nullPadding equality.
+		patches[0].diffs = append([]Diff{Diff{DiffEqual, nullPadding}}, patches[0].diffs...)
+		patches[0].start1 -= paddingLength // Should be 0.
+		patches[0].start2 -= paddingLength // Should be 0.
+		patches[0].length1 += paddingLength
+		patches[0].length2 += paddingLength
+	} else if paddingLength > len(patches[0].diffs[0].Text) {
+		// Grow first equality.
+		extraLength := paddingLength - len(patches[0].diffs[0].Text)
+		patches[0].diffs[0].Text = nullPadding[len(patches[0].diffs[0].Text):] + patches[0].diffs[0].Text
+		patches[0].start1 -= extraLength
+		patches[0].start2 -= extraLength
+		patches[0].length1 += extraLength
+		patches[0].length2 += extraLength
+	}
+
+	// Add some padding on end of last diff.
+	last := len(patches) - 1
+	if len(patches[last].diffs) == 0 || patches[last].diffs[len(patches[last].diffs)-1].Type != DiffEqual {
+		// Add nullPadding equality.
+		patches[last].diffs = append(patches[last].diffs, Diff{DiffEqual, nullPadding})
+		patches[last].length1 += paddingLength
+		patches[last].length2 += paddingLength
+	} else if paddingLength > len(patches[last].diffs[len(patches[last].diffs)-1].Text) {
+		// Grow last equality.
+		lastDiff := patches[last].diffs[len(patches[last].diffs)-1]
+		extraLength := paddingLength - len(lastDiff.Text)
+		patches[last].diffs[len(patches[last].diffs)-1].Text += nullPadding[:extraLength]
+		patches[last].length1 += extraLength
+		patches[last].length2 += extraLength
+	}
+
+	return nullPadding
+}
+
+// PatchSplitMax looks through the patches and breaks up any which are longer than the maximum limit of the match algorithm.
+// Intended to be called only from within patchApply.
+func (dmp *DiffMatchPatch) PatchSplitMax(patches []Patch) []Patch {
+	patchSize := dmp.MatchMaxBits
+	for x := 0; x < len(patches); x++ {
+		if patches[x].length1 <= patchSize {
+			continue
+		}
+		bigpatch := patches[x]
+		// Remove the big old patch.
+		patches = append(patches[:x], patches[x+1:]...)
+		x--
+
+		start1 := bigpatch.start1
+		start2 := bigpatch.start2
+		precontext := ""
+		for len(bigpatch.diffs) != 0 {
+			// Create one of several smaller patches.
+			patch := Patch{}
+			empty := true
+			patch.start1 = start1 - len(precontext)
+			patch.start2 = start2 - len(precontext)
+			if len(precontext) != 0 {
+				patch.length1 = len(precontext)
+				patch.length2 = len(precontext)
+				patch.diffs = append(patch.diffs, Diff{DiffEqual, precontext})
+			}
+			for len(bigpatch.diffs) != 0 && patch.length1 < patchSize-dmp.PatchMargin {
+				diffType := bigpatch.diffs[0].Type
+				diffText := bigpatch.diffs[0].Text
+				if diffType == DiffInsert {
+					// Insertions are harmless.
+					patch.length2 += len(diffText)
+					start2 += len(diffText)
+					patch.diffs = append(patch.diffs, bigpatch.diffs[0])
+					bigpatch.diffs = bigpatch.diffs[1:]
+					empty = false
+				} else if diffType == DiffDelete && len(patch.diffs) == 1 && patch.diffs[0].Type == DiffEqual && len(diffText) > 2*patchSize {
+					// This is a large deletion.  Let it pass in one chunk.
+					patch.length1 += len(diffText)
+					start1 += len(diffText)
+					empty = false
+					patch.diffs = append(patch.diffs, Diff{diffType, diffText})
+					bigpatch.diffs = bigpatch.diffs[1:]
+				} else {
+					// Deletion or equality.  Only take as much as we can stomach.
+					diffText = diffText[:min(len(diffText), patchSize-patch.length1-dmp.PatchMargin)]
+
+					patch.length1 += len(diffText)
+					start1 += len(diffText)
+					if diffType == DiffEqual {
+						patch.length2 += len(diffText)
+						start2 += len(diffText)
+					} else {
+						empty = false
+					}
+					patch.diffs = append(patch.diffs, Diff{diffType, diffText})
+					if diffText == bigpatch.diffs[0].Text {
+						bigpatch.diffs = bigpatch.diffs[1:]
+					} else {
+						bigpatch.diffs[0].Text =
+							bigpatch.diffs[0].Text[len(diffText):]
+					}
+				}
+			}
+			// Compute the head context for the next patch.
+			precontext = dmp.DiffText2(patch.diffs)
+			precontext = precontext[max(0, len(precontext)-dmp.PatchMargin):]
+
+			postcontext := ""
+			// Append the end context for this patch.
+			if len(dmp.DiffText1(bigpatch.diffs)) > dmp.PatchMargin {
+				postcontext = dmp.DiffText1(bigpatch.diffs)[:dmp.PatchMargin]
+			} else {
+				postcontext = dmp.DiffText1(bigpatch.diffs)
+			}
+
+			if len(postcontext) != 0 {
+				patch.length1 += len(postcontext)
+				patch.length2 += len(postcontext)
+				if len(patch.diffs) != 0 && patch.diffs[len(patch.diffs)-1].Type == DiffEqual {
+					patch.diffs[len(patch.diffs)-1].Text += postcontext
+				} else {
+					patch.diffs = append(patch.diffs, Diff{DiffEqual, postcontext})
+				}
+			}
+			if !empty {
+				x++
+				patches = append(patches[:x], append([]Patch{patch}, patches[x:]...)...)
+			}
+		}
+	}
+	return patches
+}
+
+// PatchToText takes a list of patches and returns a textual representation.
+func (dmp *DiffMatchPatch) PatchToText(patches []Patch) string {
+	var text bytes.Buffer
+	for _, aPatch := range patches {
+		_, _ = text.WriteString(aPatch.String())
+	}
+	return text.String()
+}
+
+// PatchFromText parses a textual representation of patches and returns a List of Patch objects.
+func (dmp *DiffMatchPatch) PatchFromText(textline string) ([]Patch, error) {
+	patches := []Patch{}
+	if len(textline) == 0 {
+		return patches, nil
+	}
+	text := strings.Split(textline, "\n")
+	textPointer := 0
+	patchHeader := regexp.MustCompile("^@@ -(\\d+),?(\\d*) \\+(\\d+),?(\\d*) @@$")
+
+	var patch Patch
+	var sign uint8
+	var line string
+	for textPointer < len(text) {
+
+		if !patchHeader.MatchString(text[textPointer]) {
+			return patches, errors.New("Invalid patch string: " + text[textPointer])
+		}
+
+		patch = Patch{}
+		m := patchHeader.FindStringSubmatch(text[textPointer])
+
+		patch.start1, _ = strconv.Atoi(m[1])
+		if len(m[2]) == 0 {
+			patch.start1--
+			patch.length1 = 1
+		} else if m[2] == "0" {
+			patch.length1 = 0
+		} else {
+			patch.start1--
+			patch.length1, _ = strconv.Atoi(m[2])
+		}
+
+		patch.start2, _ = strconv.Atoi(m[3])
+
+		if len(m[4]) == 0 {
+			patch.start2--
+			patch.length2 = 1
+		} else if m[4] == "0" {
+			patch.length2 = 0
+		} else {
+			patch.start2--
+			patch.length2, _ = strconv.Atoi(m[4])
+		}
+		textPointer++
+
+		for textPointer < len(text) {
+			if len(text[textPointer]) > 0 {
+				sign = text[textPointer][0]
+			} else {
+				textPointer++
+				continue
+			}
+
+			line = text[textPointer][1:]
+			line = strings.Replace(line, "+", "%2b", -1)
+			line, _ = url.QueryUnescape(line)
+			if sign == '-' {
+				// Deletion.
+				patch.diffs = append(patch.diffs, Diff{DiffDelete, line})
+			} else if sign == '+' {
+				// Insertion.
+				patch.diffs = append(patch.diffs, Diff{DiffInsert, line})
+			} else if sign == ' ' {
+				// Minor equality.
+				patch.diffs = append(patch.diffs, Diff{DiffEqual, line})
+			} else if sign == '@' {
+				// Start of next patch.
+				break
+			} else {
+				// WTF?
+				return patches, errors.New("Invalid patch mode '" + string(sign) + "' in: " + string(line))
+			}
+			textPointer++
+		}
+
+		patches = append(patches, patch)
+	}
+	return patches, nil
+}

+ 88 - 0
vendor/github.com/sergi/go-diff/diffmatchpatch/stringutil.go

@@ -0,0 +1,88 @@
+// Copyright (c) 2012-2016 The go-diff authors. All rights reserved.
+// https://github.com/sergi/go-diff
+// See the included LICENSE file for license details.
+//
+// go-diff is a Go implementation of Google's Diff, Match, and Patch library
+// Original library is Copyright (c) 2006 Google Inc.
+// http://code.google.com/p/google-diff-match-patch/
+
+package diffmatchpatch
+
+import (
+	"strings"
+	"unicode/utf8"
+)
+
+// unescaper unescapes selected chars for compatibility with JavaScript's encodeURI.
+// In speed critical applications this could be dropped since the receiving application will certainly decode these fine. Note that this function is case-sensitive.  Thus "%3F" would not be unescaped.  But this is ok because it is only called with the output of HttpUtility.UrlEncode which returns lowercase hex. Example: "%3f" -> "?", "%24" -> "$", etc.
+var unescaper = strings.NewReplacer(
+	"%21", "!", "%7E", "~", "%27", "'",
+	"%28", "(", "%29", ")", "%3B", ";",
+	"%2F", "/", "%3F", "?", "%3A", ":",
+	"%40", "@", "%26", "&", "%3D", "=",
+	"%2B", "+", "%24", "$", "%2C", ",", "%23", "#", "%2A", "*")
+
+// indexOf returns the first index of pattern in str, starting at str[i].
+func indexOf(str string, pattern string, i int) int {
+	if i > len(str)-1 {
+		return -1
+	}
+	if i <= 0 {
+		return strings.Index(str, pattern)
+	}
+	ind := strings.Index(str[i:], pattern)
+	if ind == -1 {
+		return -1
+	}
+	return ind + i
+}
+
+// lastIndexOf returns the last index of pattern in str, starting at str[i].
+func lastIndexOf(str string, pattern string, i int) int {
+	if i < 0 {
+		return -1
+	}
+	if i >= len(str) {
+		return strings.LastIndex(str, pattern)
+	}
+	_, size := utf8.DecodeRuneInString(str[i:])
+	return strings.LastIndex(str[:i+size], pattern)
+}
+
+// runesIndexOf returns the index of pattern in target, starting at target[i].
+func runesIndexOf(target, pattern []rune, i int) int {
+	if i > len(target)-1 {
+		return -1
+	}
+	if i <= 0 {
+		return runesIndex(target, pattern)
+	}
+	ind := runesIndex(target[i:], pattern)
+	if ind == -1 {
+		return -1
+	}
+	return ind + i
+}
+
+func runesEqual(r1, r2 []rune) bool {
+	if len(r1) != len(r2) {
+		return false
+	}
+	for i, c := range r1 {
+		if c != r2[i] {
+			return false
+		}
+	}
+	return true
+}
+
+// runesIndex is the equivalent of strings.Index for rune slices.
+func runesIndex(r1, r2 []rune) int {
+	last := len(r1) - len(r2)
+	for i := 0; i <= last; i++ {
+		if runesEqual(r1[i:i+len(r2)], r2) {
+			return i
+		}
+	}
+	return -1
+}

+ 145 - 0
vendor/github.com/yudai/gojsondiff/LICENSE

@@ -0,0 +1,145 @@
+The MIT License (MIT)
+
+Copyright (c) 2015 Iwasaki Yudai
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+============================================================================
+
+This repository is build with following third party libraries. Thank you!
+
+## go-diff - https://github.com/sergi/go-diff
+
+Copyright (c) 2012 Sergi Mansilla <sergi.mansilla@gmail.com>
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the rights to use, copy, modify, merge, publish, distribute, sublicense,
+and/or sell copies of the Software, and to permit persons to whom the
+Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included
+in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+
+## golcs - https://github.com/yudai/golcs
+
+The MIT License (MIT)
+
+Copyright (c) 2015 Iwasaki Yudai
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+
+## cli.go - https://github.com/urfave/cli
+
+Copyright (C) 2013 Jeremy Saenz
+All Rights Reserved.
+
+MIT LICENSE
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+
+## ginkgo - https://github.com/onsi/ginkgo
+
+Copyright (c) 2013-2014 Onsi Fakhouri
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+
+# gomega - https://github.com/onsi/gomega
+
+Copyright (c) 2013-2014 Onsi Fakhouri
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ 2 - 0
vendor/github.com/yudai/gojsondiff/Makefile

@@ -0,0 +1,2 @@
+test:
+	if [ `go fmt $(go list ./... | grep -v /vendor/) | wc -l` -gt 0 ]; then echo "go fmt error"; exit 1; fi

+ 157 - 0
vendor/github.com/yudai/gojsondiff/README.md

@@ -0,0 +1,157 @@
+# Go JSON Diff (and Patch)
+
+[![Wercker](https://app.wercker.com/status/00d70daaf40ce277fd4f10290f097b9d/s/master)][wercker]
+[![GoDoc](https://godoc.org/github.com/yudai/gojsondiff?status.svg)][godoc]
+[![MIT License](http://img.shields.io/badge/license-MIT-blue.svg)][license]
+
+[wercker]: https://app.wercker.com/project/bykey/00d70daaf40ce277fd4f10290f097b9d
+[godoc]: https://godoc.org/github.com/yudai/gojsondiff
+[license]: https://github.com/yudai/gojsondiff/blob/master/LICENSE
+
+## How to use
+
+### Installation
+
+```sh
+go get github.com/yudai/gojsondiff
+```
+
+### Comparing two JSON strings
+
+See `jd/main.go` for how to use this library.
+
+
+## CLI tool
+
+This repository contains a package that you can use as a CLI tool.
+
+### Installation
+
+```sh
+go get github.com/yudai/gojsondiff/jd
+```
+
+### Usage
+
+#### Diff
+
+Just give two json files to the `jd` command:
+
+```sh
+jd one.json another.json
+```
+
+Outputs would be something like:
+
+```diff
+ {
+   "arr": [
+     0: "arr0",
+     1: 21,
+     2: {
+       "num": 1,
+-      "str": "pek3f"
++      "str": "changed"
+     },
+     3: [
+       0: 0,
+-      1: "1"
++      1: "changed"
+     ]
+   ],
+   "bool": true,
+   "num_float": 39.39,
+   "num_int": 13,
+   "obj": {
+     "arr": [
+       0: 17,
+       1: "str",
+       2: {
+-        "str": "eafeb"
++        "str": "changed"
+       }
+     ],
++    "new": "added",
+-    "num": 19,
+     "obj": {
+-      "num": 14,
++      "num": 9999
+-      "str": "efj3"
++      "str": "changed"
+     },
+     "str": "bcded"
+   },
+   "str": "abcde"
+ }
+```
+
+When you prefer the delta foramt of [jsondiffpatch](https://github.com/benjamine/jsondiffpatch), add the `-f delta` option.
+
+```sh
+jd -f delta one.json another.json
+```
+
+This command shows:
+
+```json
+{
+  "arr": {
+    "2": {
+      "str": [
+        "pek3f",
+        "changed"
+      ]
+    },
+    "3": {
+      "1": [
+        "1",
+        "changed"
+      ],
+      "_t": "a"
+    },
+    "_t": "a"
+  },
+  "obj": {
+    "arr": {
+      "2": {
+        "str": [
+          "eafeb",
+          "changed"
+        ]
+      },
+      "_t": "a"
+    },
+    "new": [
+      "added"
+    ],
+    "num": [
+      19,
+      0,
+      0
+    ],
+    "obj": {
+      "num": [
+        14,
+        9999
+      ],
+      "str": [
+        "efj3",
+        "changed"
+      ]
+    }
+  }
+}
+```
+
+#### Patch
+
+Give a diff file in the delta format and the JSON file to the `jp` command.
+
+```sh
+jp diff.delta one.json
+```
+
+
+## License
+
+MIT License (see `LICENSE` for detail)

+ 461 - 0
vendor/github.com/yudai/gojsondiff/deltas.go

@@ -0,0 +1,461 @@
+package gojsondiff
+
+import (
+	"errors"
+	dmp "github.com/sergi/go-diff/diffmatchpatch"
+	"reflect"
+	"strconv"
+)
+
+// A Delta represents an atomic difference between two JSON objects.
+type Delta interface {
+	// Similarity calculates the similarity of the Delta values.
+	// The return value is normalized from 0 to 1,
+	// 0 is completely different and 1 is they are same
+	Similarity() (similarity float64)
+}
+
+// To cache the calculated similarity,
+// concrete Deltas can use similariter and similarityCache
+type similariter interface {
+	similarity() (similarity float64)
+}
+
+type similarityCache struct {
+	similariter
+	value float64
+}
+
+func newSimilarityCache(sim similariter) similarityCache {
+	cache := similarityCache{similariter: sim, value: -1}
+	return cache
+}
+
+func (cache similarityCache) Similarity() (similarity float64) {
+	if cache.value < 0 {
+		cache.value = cache.similariter.similarity()
+	}
+	return cache.value
+}
+
+// A Position represents the position of a Delta in an object or an array.
+type Position interface {
+	// String returns the position as a string
+	String() (name string)
+
+	// CompareTo returns a true if the Position is smaller than another Position.
+	// This function is used to sort Positions by the sort package.
+	CompareTo(another Position) bool
+}
+
+// A Name is a Postition with a string, which means the delta is in an object.
+type Name string
+
+func (n Name) String() (name string) {
+	return string(n)
+}
+
+func (n Name) CompareTo(another Position) bool {
+	return n < another.(Name)
+}
+
+// A Index is a Position with an int value, which means the Delta is in an Array.
+type Index int
+
+func (i Index) String() (name string) {
+	return strconv.Itoa(int(i))
+}
+
+func (i Index) CompareTo(another Position) bool {
+	return i < another.(Index)
+}
+
+// A PreDelta is a Delta that has a position of the left side JSON object.
+// Deltas implements this interface should be applies before PostDeltas.
+type PreDelta interface {
+	// PrePosition returns the Position.
+	PrePosition() Position
+
+	// PreApply applies the delta to object.
+	PreApply(object interface{}) interface{}
+}
+
+type preDelta struct{ Position }
+
+func (i preDelta) PrePosition() Position {
+	return Position(i.Position)
+}
+
+type preDeltas []PreDelta
+
+// for sorting
+func (s preDeltas) Len() int {
+	return len(s)
+}
+
+// for sorting
+func (s preDeltas) Swap(i, j int) {
+	s[i], s[j] = s[j], s[i]
+}
+
+// for sorting
+func (s preDeltas) Less(i, j int) bool {
+	return !s[i].PrePosition().CompareTo(s[j].PrePosition())
+}
+
+// A PreDelta is a Delta that has a position of the right side JSON object.
+// Deltas implements this interface should be applies after PreDeltas.
+type PostDelta interface {
+	// PostPosition returns the Position.
+	PostPosition() Position
+
+	// PostApply applies the delta to object.
+	PostApply(object interface{}) interface{}
+}
+
+type postDelta struct{ Position }
+
+func (i postDelta) PostPosition() Position {
+	return Position(i.Position)
+}
+
+type postDeltas []PostDelta
+
+// for sorting
+func (s postDeltas) Len() int {
+	return len(s)
+}
+
+// for sorting
+func (s postDeltas) Swap(i, j int) {
+	s[i], s[j] = s[j], s[i]
+}
+
+// for sorting
+func (s postDeltas) Less(i, j int) bool {
+	return s[i].PostPosition().CompareTo(s[j].PostPosition())
+}
+
+// An Object is a Delta that represents an object of JSON
+type Object struct {
+	postDelta
+	similarityCache
+
+	// Deltas holds internal Deltas
+	Deltas []Delta
+}
+
+// NewObject returns an Object
+func NewObject(position Position, deltas []Delta) *Object {
+	d := Object{postDelta: postDelta{position}, Deltas: deltas}
+	d.similarityCache = newSimilarityCache(&d)
+	return &d
+}
+
+func (d *Object) PostApply(object interface{}) interface{} {
+	switch object.(type) {
+	case map[string]interface{}:
+		o := object.(map[string]interface{})
+		n := string(d.PostPosition().(Name))
+		o[n] = applyDeltas(d.Deltas, o[n])
+	case []interface{}:
+		o := object.([]interface{})
+		n := int(d.PostPosition().(Index))
+		o[n] = applyDeltas(d.Deltas, o[n])
+	}
+	return object
+}
+
+func (d *Object) similarity() (similarity float64) {
+	similarity = deltasSimilarity(d.Deltas)
+	return
+}
+
+// An Array is a Delta that represents an array of JSON
+type Array struct {
+	postDelta
+	similarityCache
+
+	// Deltas holds internal Deltas
+	Deltas []Delta
+}
+
+// NewArray returns an Array
+func NewArray(position Position, deltas []Delta) *Array {
+	d := Array{postDelta: postDelta{position}, Deltas: deltas}
+	d.similarityCache = newSimilarityCache(&d)
+	return &d
+}
+
+func (d *Array) PostApply(object interface{}) interface{} {
+	switch object.(type) {
+	case map[string]interface{}:
+		o := object.(map[string]interface{})
+		n := string(d.PostPosition().(Name))
+		o[n] = applyDeltas(d.Deltas, o[n])
+	case []interface{}:
+		o := object.([]interface{})
+		n := int(d.PostPosition().(Index))
+		o[n] = applyDeltas(d.Deltas, o[n])
+	}
+	return object
+}
+
+func (d *Array) similarity() (similarity float64) {
+	similarity = deltasSimilarity(d.Deltas)
+	return
+}
+
+// An Added represents a new added field of an object or an array
+type Added struct {
+	postDelta
+	similarityCache
+
+	// Values holds the added value
+	Value interface{}
+}
+
+// NewAdded returns a new Added
+func NewAdded(position Position, value interface{}) *Added {
+	d := Added{postDelta: postDelta{position}, Value: value}
+	return &d
+}
+
+func (d *Added) PostApply(object interface{}) interface{} {
+	switch object.(type) {
+	case map[string]interface{}:
+		object.(map[string]interface{})[string(d.PostPosition().(Name))] = d.Value
+	case []interface{}:
+		i := int(d.PostPosition().(Index))
+		o := object.([]interface{})
+		if i < len(o) {
+			o = append(o, 0) //dummy
+			copy(o[i+1:], o[i:])
+			o[i] = d.Value
+			object = o
+		} else {
+			object = append(o, d.Value)
+		}
+	}
+
+	return object
+}
+
+func (d *Added) similarity() (similarity float64) {
+	return 0
+}
+
+// A Modified represents a field whose value is changed.
+type Modified struct {
+	postDelta
+	similarityCache
+
+	// The value before modification
+	OldValue interface{}
+
+	// The value after modification
+	NewValue interface{}
+}
+
+// NewModified returns a Modified
+func NewModified(position Position, oldValue, newValue interface{}) *Modified {
+	d := Modified{
+		postDelta: postDelta{position},
+		OldValue:  oldValue,
+		NewValue:  newValue,
+	}
+	d.similarityCache = newSimilarityCache(&d)
+	return &d
+
+}
+
+func (d *Modified) PostApply(object interface{}) interface{} {
+	switch object.(type) {
+	case map[string]interface{}:
+		// TODO check old value
+		object.(map[string]interface{})[string(d.PostPosition().(Name))] = d.NewValue
+	case []interface{}:
+		object.([]interface{})[int(d.PostPosition().(Index))] = d.NewValue
+	}
+	return object
+}
+
+func (d *Modified) similarity() (similarity float64) {
+	similarity += 0.3 // at least, they are at the same position
+	if reflect.TypeOf(d.OldValue) == reflect.TypeOf(d.NewValue) {
+		similarity += 0.3 // types are same
+
+		switch d.OldValue.(type) {
+		case string:
+			similarity += 0.4 * stringSimilarity(d.OldValue.(string), d.NewValue.(string))
+		case float64:
+			ratio := d.OldValue.(float64) / d.NewValue.(float64)
+			if ratio > 1 {
+				ratio = 1 / ratio
+			}
+			similarity += 0.4 * ratio
+		}
+	}
+	return
+}
+
+// A TextDiff represents a Modified with TextDiff between the old and the new values.
+type TextDiff struct {
+	Modified
+
+	// Diff string
+	Diff []dmp.Patch
+}
+
+// NewTextDiff returns
+func NewTextDiff(position Position, diff []dmp.Patch, oldValue, newValue interface{}) *TextDiff {
+	d := TextDiff{
+		Modified: *NewModified(position, oldValue, newValue),
+		Diff:     diff,
+	}
+	return &d
+}
+
+func (d *TextDiff) PostApply(object interface{}) interface{} {
+	switch object.(type) {
+	case map[string]interface{}:
+		o := object.(map[string]interface{})
+		i := string(d.PostPosition().(Name))
+		// TODO error
+		d.OldValue = o[i]
+		// TODO error
+		d.patch()
+		o[i] = d.NewValue
+	case []interface{}:
+		o := object.([]interface{})
+		i := d.PostPosition().(Index)
+		d.OldValue = o[i]
+		// TODO error
+		d.patch()
+		o[i] = d.NewValue
+	}
+	return object
+}
+
+func (d *TextDiff) patch() error {
+	if d.OldValue == nil {
+		return errors.New("Old Value is not set")
+	}
+	patcher := dmp.New()
+	patched, successes := patcher.PatchApply(d.Diff, d.OldValue.(string))
+	for _, success := range successes {
+		if !success {
+			return errors.New("Failed to apply a patch")
+		}
+	}
+	d.NewValue = patched
+	return nil
+}
+
+func (d *TextDiff) DiffString() string {
+	dmp := dmp.New()
+	return dmp.PatchToText(d.Diff)
+}
+
+// A Delted represents deleted field or index of an Object or an Array.
+type Deleted struct {
+	preDelta
+
+	// The value deleted
+	Value interface{}
+}
+
+// NewDeleted returns a Deleted
+func NewDeleted(position Position, value interface{}) *Deleted {
+	d := Deleted{
+		preDelta: preDelta{position},
+		Value:    value,
+	}
+	return &d
+
+}
+
+func (d *Deleted) PreApply(object interface{}) interface{} {
+	switch object.(type) {
+	case map[string]interface{}:
+		// TODO check old value
+		delete(object.(map[string]interface{}), string(d.PrePosition().(Name)))
+	case []interface{}:
+		i := int(d.PrePosition().(Index))
+		o := object.([]interface{})
+		object = append(o[:i], o[i+1:]...)
+	}
+	return object
+}
+
+func (d Deleted) Similarity() (similarity float64) {
+	return 0
+}
+
+// A Moved represents field that is moved, which means the index or name is
+// changed. Note that, in this library, assigning a Moved and a Modified to
+// a single position is not allowed. For the compatibility with jsondiffpatch,
+// the Moved in this library can hold the old and new value in it.
+type Moved struct {
+	preDelta
+	postDelta
+	similarityCache
+	// The value before moving
+	Value interface{}
+	// The delta applied after moving (for compatibility)
+	Delta interface{}
+}
+
+func NewMoved(oldPosition Position, newPosition Position, value interface{}, delta Delta) *Moved {
+	d := Moved{
+		preDelta:  preDelta{oldPosition},
+		postDelta: postDelta{newPosition},
+		Value:     value,
+		Delta:     delta,
+	}
+	d.similarityCache = newSimilarityCache(&d)
+	return &d
+}
+
+func (d *Moved) PreApply(object interface{}) interface{} {
+	switch object.(type) {
+	case map[string]interface{}:
+		//not supported
+	case []interface{}:
+		i := int(d.PrePosition().(Index))
+		o := object.([]interface{})
+		d.Value = o[i]
+		object = append(o[:i], o[i+1:]...)
+	}
+	return object
+}
+
+func (d *Moved) PostApply(object interface{}) interface{} {
+	switch object.(type) {
+	case map[string]interface{}:
+		//not supported
+	case []interface{}:
+		i := int(d.PostPosition().(Index))
+		o := object.([]interface{})
+		o = append(o, 0) //dummy
+		copy(o[i+1:], o[i:])
+		o[i] = d.Value
+		object = o
+	}
+
+	if d.Delta != nil {
+		d.Delta.(PostDelta).PostApply(object)
+	}
+
+	return object
+}
+
+func (d *Moved) similarity() (similarity float64) {
+	similarity = 0.6 // as type and contens are same
+	ratio := float64(d.PrePosition().(Index)) / float64(d.PostPosition().(Index))
+	if ratio > 1 {
+		ratio = 1 / ratio
+	}
+	similarity += 0.4 * ratio
+	return
+}

+ 370 - 0
vendor/github.com/yudai/gojsondiff/formatter/ascii.go

@@ -0,0 +1,370 @@
+package formatter
+
+import (
+	"bytes"
+	"errors"
+	"fmt"
+	"sort"
+
+	diff "github.com/yudai/gojsondiff"
+)
+
+func NewAsciiFormatter(left interface{}, config AsciiFormatterConfig) *AsciiFormatter {
+	return &AsciiFormatter{
+		left:   left,
+		config: config,
+	}
+}
+
+type AsciiFormatter struct {
+	left    interface{}
+	config  AsciiFormatterConfig
+	buffer  *bytes.Buffer
+	path    []string
+	size    []int
+	inArray []bool
+	line    *AsciiLine
+}
+
+type AsciiFormatterConfig struct {
+	ShowArrayIndex bool
+	Coloring       bool
+}
+
+var AsciiFormatterDefaultConfig = AsciiFormatterConfig{}
+
+type AsciiLine struct {
+	marker string
+	indent int
+	buffer *bytes.Buffer
+}
+
+func (f *AsciiFormatter) Format(diff diff.Diff) (result string, err error) {
+	f.buffer = bytes.NewBuffer([]byte{})
+	f.path = []string{}
+	f.size = []int{}
+	f.inArray = []bool{}
+
+	if v, ok := f.left.(map[string]interface{}); ok {
+		f.formatObject(v, diff)
+	} else if v, ok := f.left.([]interface{}); ok {
+		f.formatArray(v, diff)
+	} else {
+		return "", fmt.Errorf("expected map[string]interface{} or []interface{}, got %T",
+			f.left)
+	}
+
+	return f.buffer.String(), nil
+}
+
+func (f *AsciiFormatter) formatObject(left map[string]interface{}, df diff.Diff) {
+	f.addLineWith(AsciiSame, "{")
+	f.push("ROOT", len(left), false)
+	f.processObject(left, df.Deltas())
+	f.pop()
+	f.addLineWith(AsciiSame, "}")
+}
+
+func (f *AsciiFormatter) formatArray(left []interface{}, df diff.Diff) {
+	f.addLineWith(AsciiSame, "[")
+	f.push("ROOT", len(left), true)
+	f.processArray(left, df.Deltas())
+	f.pop()
+	f.addLineWith(AsciiSame, "]")
+}
+
+func (f *AsciiFormatter) processArray(array []interface{}, deltas []diff.Delta) error {
+	patchedIndex := 0
+	for index, value := range array {
+		f.processItem(value, deltas, diff.Index(index))
+		patchedIndex++
+	}
+
+	// additional Added
+	for _, delta := range deltas {
+		switch delta.(type) {
+		case *diff.Added:
+			d := delta.(*diff.Added)
+			// skip items already processed
+			if int(d.Position.(diff.Index)) < len(array) {
+				continue
+			}
+			f.printRecursive(d.Position.String(), d.Value, AsciiAdded)
+		}
+	}
+
+	return nil
+}
+
+func (f *AsciiFormatter) processObject(object map[string]interface{}, deltas []diff.Delta) error {
+	names := sortedKeys(object)
+	for _, name := range names {
+		value := object[name]
+		f.processItem(value, deltas, diff.Name(name))
+	}
+
+	// Added
+	for _, delta := range deltas {
+		switch delta.(type) {
+		case *diff.Added:
+			d := delta.(*diff.Added)
+			f.printRecursive(d.Position.String(), d.Value, AsciiAdded)
+		}
+	}
+
+	return nil
+}
+
+func (f *AsciiFormatter) processItem(value interface{}, deltas []diff.Delta, position diff.Position) error {
+	matchedDeltas := f.searchDeltas(deltas, position)
+	positionStr := position.String()
+	if len(matchedDeltas) > 0 {
+		for _, matchedDelta := range matchedDeltas {
+
+			switch matchedDelta.(type) {
+			case *diff.Object:
+				d := matchedDelta.(*diff.Object)
+				switch value.(type) {
+				case map[string]interface{}:
+					//ok
+				default:
+					return errors.New("Type mismatch")
+				}
+				o := value.(map[string]interface{})
+
+				f.newLine(AsciiSame)
+				f.printKey(positionStr)
+				f.print("{")
+				f.closeLine()
+				f.push(positionStr, len(o), false)
+				f.processObject(o, d.Deltas)
+				f.pop()
+				f.newLine(AsciiSame)
+				f.print("}")
+				f.printComma()
+				f.closeLine()
+
+			case *diff.Array:
+				d := matchedDelta.(*diff.Array)
+				switch value.(type) {
+				case []interface{}:
+					//ok
+				default:
+					return errors.New("Type mismatch")
+				}
+				a := value.([]interface{})
+
+				f.newLine(AsciiSame)
+				f.printKey(positionStr)
+				f.print("[")
+				f.closeLine()
+				f.push(positionStr, len(a), true)
+				f.processArray(a, d.Deltas)
+				f.pop()
+				f.newLine(AsciiSame)
+				f.print("]")
+				f.printComma()
+				f.closeLine()
+
+			case *diff.Added:
+				d := matchedDelta.(*diff.Added)
+				f.printRecursive(positionStr, d.Value, AsciiAdded)
+				f.size[len(f.size)-1]++
+
+			case *diff.Modified:
+				d := matchedDelta.(*diff.Modified)
+				savedSize := f.size[len(f.size)-1]
+				f.printRecursive(positionStr, d.OldValue, AsciiDeleted)
+				f.size[len(f.size)-1] = savedSize
+				f.printRecursive(positionStr, d.NewValue, AsciiAdded)
+
+			case *diff.TextDiff:
+				savedSize := f.size[len(f.size)-1]
+				d := matchedDelta.(*diff.TextDiff)
+				f.printRecursive(positionStr, d.OldValue, AsciiDeleted)
+				f.size[len(f.size)-1] = savedSize
+				f.printRecursive(positionStr, d.NewValue, AsciiAdded)
+
+			case *diff.Deleted:
+				d := matchedDelta.(*diff.Deleted)
+				f.printRecursive(positionStr, d.Value, AsciiDeleted)
+
+			default:
+				return errors.New("Unknown Delta type detected")
+			}
+
+		}
+	} else {
+		f.printRecursive(positionStr, value, AsciiSame)
+	}
+
+	return nil
+}
+
+func (f *AsciiFormatter) searchDeltas(deltas []diff.Delta, postion diff.Position) (results []diff.Delta) {
+	results = make([]diff.Delta, 0)
+	for _, delta := range deltas {
+		switch delta.(type) {
+		case diff.PostDelta:
+			if delta.(diff.PostDelta).PostPosition() == postion {
+				results = append(results, delta)
+			}
+		case diff.PreDelta:
+			if delta.(diff.PreDelta).PrePosition() == postion {
+				results = append(results, delta)
+			}
+		default:
+			panic("heh")
+		}
+	}
+	return
+}
+
+const (
+	AsciiSame    = " "
+	AsciiAdded   = "+"
+	AsciiDeleted = "-"
+)
+
+var AsciiStyles = map[string]string{
+	AsciiAdded:   "30;42",
+	AsciiDeleted: "30;41",
+}
+
+func (f *AsciiFormatter) push(name string, size int, array bool) {
+	f.path = append(f.path, name)
+	f.size = append(f.size, size)
+	f.inArray = append(f.inArray, array)
+}
+
+func (f *AsciiFormatter) pop() {
+	f.path = f.path[0 : len(f.path)-1]
+	f.size = f.size[0 : len(f.size)-1]
+	f.inArray = f.inArray[0 : len(f.inArray)-1]
+}
+
+func (f *AsciiFormatter) addLineWith(marker string, value string) {
+	f.line = &AsciiLine{
+		marker: marker,
+		indent: len(f.path),
+		buffer: bytes.NewBufferString(value),
+	}
+	f.closeLine()
+}
+
+func (f *AsciiFormatter) newLine(marker string) {
+	f.line = &AsciiLine{
+		marker: marker,
+		indent: len(f.path),
+		buffer: bytes.NewBuffer([]byte{}),
+	}
+}
+
+func (f *AsciiFormatter) closeLine() {
+	style, ok := AsciiStyles[f.line.marker]
+	if f.config.Coloring && ok {
+		f.buffer.WriteString("\x1b[" + style + "m")
+	}
+
+	f.buffer.WriteString(f.line.marker)
+	for n := 0; n < f.line.indent; n++ {
+		f.buffer.WriteString("  ")
+	}
+	f.buffer.Write(f.line.buffer.Bytes())
+
+	if f.config.Coloring && ok {
+		f.buffer.WriteString("\x1b[0m")
+	}
+
+	f.buffer.WriteRune('\n')
+}
+
+func (f *AsciiFormatter) printKey(name string) {
+	if !f.inArray[len(f.inArray)-1] {
+		fmt.Fprintf(f.line.buffer, `"%s": `, name)
+	} else if f.config.ShowArrayIndex {
+		fmt.Fprintf(f.line.buffer, `%s: `, name)
+	}
+}
+
+func (f *AsciiFormatter) printComma() {
+	f.size[len(f.size)-1]--
+	if f.size[len(f.size)-1] > 0 {
+		f.line.buffer.WriteRune(',')
+	}
+}
+
+func (f *AsciiFormatter) printValue(value interface{}) {
+	switch value.(type) {
+	case string:
+		fmt.Fprintf(f.line.buffer, `"%s"`, value)
+	case nil:
+		f.line.buffer.WriteString("null")
+	default:
+		fmt.Fprintf(f.line.buffer, `%#v`, value)
+	}
+}
+
+func (f *AsciiFormatter) print(a string) {
+	f.line.buffer.WriteString(a)
+}
+
+func (f *AsciiFormatter) printRecursive(name string, value interface{}, marker string) {
+	switch value.(type) {
+	case map[string]interface{}:
+		f.newLine(marker)
+		f.printKey(name)
+		f.print("{")
+		f.closeLine()
+
+		m := value.(map[string]interface{})
+		size := len(m)
+		f.push(name, size, false)
+
+		keys := sortedKeys(m)
+		for _, key := range keys {
+			f.printRecursive(key, m[key], marker)
+		}
+		f.pop()
+
+		f.newLine(marker)
+		f.print("}")
+		f.printComma()
+		f.closeLine()
+
+	case []interface{}:
+		f.newLine(marker)
+		f.printKey(name)
+		f.print("[")
+		f.closeLine()
+
+		s := value.([]interface{})
+		size := len(s)
+		f.push("", size, true)
+		for _, item := range s {
+			f.printRecursive("", item, marker)
+		}
+		f.pop()
+
+		f.newLine(marker)
+		f.print("]")
+		f.printComma()
+		f.closeLine()
+
+	default:
+		f.newLine(marker)
+		f.printKey(name)
+		f.printValue(value)
+		f.printComma()
+		f.closeLine()
+	}
+}
+
+func sortedKeys(m map[string]interface{}) (keys []string) {
+	keys = make([]string, 0, len(m))
+	for key, _ := range m {
+		keys = append(keys, key)
+	}
+	sort.Strings(keys)
+	return
+}

+ 124 - 0
vendor/github.com/yudai/gojsondiff/formatter/delta.go

@@ -0,0 +1,124 @@
+package formatter
+
+import (
+	"encoding/json"
+	"errors"
+	"fmt"
+
+	diff "github.com/yudai/gojsondiff"
+)
+
+const (
+	DeltaDelete   = 0
+	DeltaTextDiff = 2
+	DeltaMove     = 3
+)
+
+func NewDeltaFormatter() *DeltaFormatter {
+	return &DeltaFormatter{
+		PrintIndent: true,
+	}
+}
+
+type DeltaFormatter struct {
+	PrintIndent bool
+}
+
+func (f *DeltaFormatter) Format(diff diff.Diff) (result string, err error) {
+	jsonObject, err := f.formatObject(diff.Deltas())
+	if err != nil {
+		return "", err
+	}
+	var resultBytes []byte
+	if f.PrintIndent {
+		resultBytes, err = json.MarshalIndent(jsonObject, "", "  ")
+	} else {
+		resultBytes, err = json.Marshal(jsonObject)
+	}
+	if err != nil {
+		return "", err
+	}
+
+	return string(resultBytes) + "\n", nil
+}
+
+func (f *DeltaFormatter) FormatAsJson(diff diff.Diff) (json map[string]interface{}, err error) {
+	return f.formatObject(diff.Deltas())
+}
+
+func (f *DeltaFormatter) formatObject(deltas []diff.Delta) (deltaJson map[string]interface{}, err error) {
+	deltaJson = map[string]interface{}{}
+	for _, delta := range deltas {
+		switch delta.(type) {
+		case *diff.Object:
+			d := delta.(*diff.Object)
+			deltaJson[d.Position.String()], err = f.formatObject(d.Deltas)
+			if err != nil {
+				return nil, err
+			}
+		case *diff.Array:
+			d := delta.(*diff.Array)
+			deltaJson[d.Position.String()], err = f.formatArray(d.Deltas)
+			if err != nil {
+				return nil, err
+			}
+		case *diff.Added:
+			d := delta.(*diff.Added)
+			deltaJson[d.PostPosition().String()] = []interface{}{d.Value}
+		case *diff.Modified:
+			d := delta.(*diff.Modified)
+			deltaJson[d.PostPosition().String()] = []interface{}{d.OldValue, d.NewValue}
+		case *diff.TextDiff:
+			d := delta.(*diff.TextDiff)
+			deltaJson[d.PostPosition().String()] = []interface{}{d.DiffString(), 0, DeltaTextDiff}
+		case *diff.Deleted:
+			d := delta.(*diff.Deleted)
+			deltaJson[d.PrePosition().String()] = []interface{}{d.Value, 0, DeltaDelete}
+		case *diff.Moved:
+			return nil, errors.New("Delta type 'Move' is not supported in objects")
+		default:
+			return nil, errors.New(fmt.Sprintf("Unknown Delta type detected: %#v", delta))
+		}
+	}
+	return
+}
+
+func (f *DeltaFormatter) formatArray(deltas []diff.Delta) (deltaJson map[string]interface{}, err error) {
+	deltaJson = map[string]interface{}{
+		"_t": "a",
+	}
+	for _, delta := range deltas {
+		switch delta.(type) {
+		case *diff.Object:
+			d := delta.(*diff.Object)
+			deltaJson[d.Position.String()], err = f.formatObject(d.Deltas)
+			if err != nil {
+				return nil, err
+			}
+		case *diff.Array:
+			d := delta.(*diff.Array)
+			deltaJson[d.Position.String()], err = f.formatArray(d.Deltas)
+			if err != nil {
+				return nil, err
+			}
+		case *diff.Added:
+			d := delta.(*diff.Added)
+			deltaJson[d.PostPosition().String()] = []interface{}{d.Value}
+		case *diff.Modified:
+			d := delta.(*diff.Modified)
+			deltaJson[d.PostPosition().String()] = []interface{}{d.OldValue, d.NewValue}
+		case *diff.TextDiff:
+			d := delta.(*diff.TextDiff)
+			deltaJson[d.PostPosition().String()] = []interface{}{d.DiffString(), 0, DeltaTextDiff}
+		case *diff.Deleted:
+			d := delta.(*diff.Deleted)
+			deltaJson["_"+d.PrePosition().String()] = []interface{}{d.Value, 0, DeltaDelete}
+		case *diff.Moved:
+			d := delta.(*diff.Moved)
+			deltaJson["_"+d.PrePosition().String()] = []interface{}{"", d.PostPosition(), DeltaMove}
+		default:
+			return nil, errors.New(fmt.Sprintf("Unknown Delta type detected: %#v", delta))
+		}
+	}
+	return
+}

+ 426 - 0
vendor/github.com/yudai/gojsondiff/gojsondiff.go

@@ -0,0 +1,426 @@
+// Package gojsondiff implements "Diff" that compares two JSON objects and
+// generates Deltas that describes differences between them. The package also
+// provides "Patch" that apply Deltas to a JSON object.
+package gojsondiff
+
+import (
+	"container/list"
+	"encoding/json"
+	"reflect"
+	"sort"
+
+	dmp "github.com/sergi/go-diff/diffmatchpatch"
+	"github.com/yudai/golcs"
+)
+
+// A Diff holds deltas generated by a Differ
+type Diff interface {
+	// Deltas returns Deltas that describe differences between two JSON objects
+	Deltas() []Delta
+	// Modified returnes true if Diff has at least one Delta.
+	Modified() bool
+}
+
+type diff struct {
+	deltas []Delta
+}
+
+func (diff *diff) Deltas() []Delta {
+	return diff.deltas
+}
+
+func (diff *diff) Modified() bool {
+	return len(diff.deltas) > 0
+}
+
+// A Differ conmapres JSON objects and apply patches
+type Differ struct {
+	textDiffMinimumLength int
+}
+
+// New returns new Differ with default configuration
+func New() *Differ {
+	return &Differ{
+		textDiffMinimumLength: 30,
+	}
+}
+
+// Compare compares two JSON strings as []bytes and return a Diff object.
+func (differ *Differ) Compare(
+	left []byte,
+	right []byte,
+) (Diff, error) {
+	var leftMap, rightMap map[string]interface{}
+	err := json.Unmarshal(left, &leftMap)
+	if err != nil {
+		return nil, err
+	}
+
+	err = json.Unmarshal(right, &rightMap)
+	if err != nil {
+		return nil, err
+	}
+	return differ.CompareObjects(leftMap, rightMap), nil
+}
+
+// CompareObjects compares two JSON object as map[string]interface{}
+// and return a Diff object.
+func (differ *Differ) CompareObjects(
+	left map[string]interface{},
+	right map[string]interface{},
+) Diff {
+	deltas := differ.compareMaps(left, right)
+	return &diff{deltas: deltas}
+}
+
+// CompareArrays compares two JSON arrays as []interface{}
+// and return a Diff object.
+func (differ *Differ) CompareArrays(
+	left []interface{},
+	right []interface{},
+) Diff {
+	deltas := differ.compareArrays(left, right)
+	return &diff{deltas: deltas}
+}
+
+func (differ *Differ) compareMaps(
+	left map[string]interface{},
+	right map[string]interface{},
+) (deltas []Delta) {
+	deltas = make([]Delta, 0)
+
+	names := sortedKeys(left) // stabilize delta order
+	for _, name := range names {
+		if rightValue, ok := right[name]; ok {
+			same, delta := differ.compareValues(Name(name), left[name], rightValue)
+			if !same {
+				deltas = append(deltas, delta)
+			}
+		} else {
+			deltas = append(deltas, NewDeleted(Name(name), left[name]))
+		}
+	}
+
+	names = sortedKeys(right) // stabilize delta order
+	for _, name := range names {
+		if _, ok := left[name]; !ok {
+			deltas = append(deltas, NewAdded(Name(name), right[name]))
+		}
+	}
+
+	return deltas
+}
+
+// ApplyPatch applies a Diff to an JSON object. This method is destructive.
+func (differ *Differ) ApplyPatch(json map[string]interface{}, patch Diff) {
+	applyDeltas(patch.Deltas(), json)
+}
+
+type maybe struct {
+	index    int
+	lcsIndex int
+	item     interface{}
+}
+
+func (differ *Differ) compareArrays(
+	left []interface{},
+	right []interface{},
+) (deltas []Delta) {
+	deltas = make([]Delta, 0)
+	// LCS index pairs
+	lcsPairs := lcs.New(left, right).IndexPairs()
+
+	// list up items not in LCS, they are maybe deleted
+	maybeDeleted := list.New() // but maybe moved or modified
+	lcsI := 0
+	for i, leftValue := range left {
+		if lcsI < len(lcsPairs) && lcsPairs[lcsI].Left == i {
+			lcsI++
+		} else {
+			maybeDeleted.PushBack(maybe{index: i, lcsIndex: lcsI, item: leftValue})
+		}
+	}
+
+	// list up items not in LCS, they are maybe Added
+	maybeAdded := list.New() // but maybe moved or modified
+	lcsI = 0
+	for i, rightValue := range right {
+		if lcsI < len(lcsPairs) && lcsPairs[lcsI].Right == i {
+			lcsI++
+		} else {
+			maybeAdded.PushBack(maybe{index: i, lcsIndex: lcsI, item: rightValue})
+		}
+	}
+
+	// find moved items
+	var delNext *list.Element // for prefetch to remove item in iteration
+	for delCandidate := maybeDeleted.Front(); delCandidate != nil; delCandidate = delNext {
+		delCan := delCandidate.Value.(maybe)
+		delNext = delCandidate.Next()
+
+		for addCandidate := maybeAdded.Front(); addCandidate != nil; addCandidate = addCandidate.Next() {
+			addCan := addCandidate.Value.(maybe)
+			if reflect.DeepEqual(delCan.item, addCan.item) {
+				deltas = append(deltas, NewMoved(Index(delCan.index), Index(addCan.index), delCan.item, nil))
+				maybeAdded.Remove(addCandidate)
+				maybeDeleted.Remove(delCandidate)
+				break
+			}
+		}
+	}
+
+	// find modified or add+del
+	prevIndexDel := 0
+	prevIndexAdd := 0
+	delElement := maybeDeleted.Front()
+	addElement := maybeAdded.Front()
+	for i := 0; i <= len(lcsPairs); i++ { // not "< len(lcsPairs)"
+		var lcsPair lcs.IndexPair
+		var delSize, addSize int
+		if i < len(lcsPairs) {
+			lcsPair = lcsPairs[i]
+			delSize = lcsPair.Left - prevIndexDel - 1
+			addSize = lcsPair.Right - prevIndexAdd - 1
+			prevIndexDel = lcsPair.Left
+			prevIndexAdd = lcsPair.Right
+		}
+
+		var delSlice []maybe
+		if delSize > 0 {
+			delSlice = make([]maybe, 0, delSize)
+		} else {
+			delSlice = make([]maybe, 0, maybeDeleted.Len())
+		}
+		for ; delElement != nil; delElement = delElement.Next() {
+			d := delElement.Value.(maybe)
+			if d.lcsIndex != i {
+				break
+			}
+			delSlice = append(delSlice, d)
+		}
+
+		var addSlice []maybe
+		if addSize > 0 {
+			addSlice = make([]maybe, 0, addSize)
+		} else {
+			addSlice = make([]maybe, 0, maybeAdded.Len())
+		}
+		for ; addElement != nil; addElement = addElement.Next() {
+			a := addElement.Value.(maybe)
+			if a.lcsIndex != i {
+				break
+			}
+			addSlice = append(addSlice, a)
+		}
+
+		if len(delSlice) > 0 && len(addSlice) > 0 {
+			var bestDeltas []Delta
+			bestDeltas, delSlice, addSlice = differ.maximizeSimilarities(delSlice, addSlice)
+			for _, delta := range bestDeltas {
+				deltas = append(deltas, delta)
+			}
+		}
+
+		for _, del := range delSlice {
+			deltas = append(deltas, NewDeleted(Index(del.index), del.item))
+		}
+		for _, add := range addSlice {
+			deltas = append(deltas, NewAdded(Index(add.index), add.item))
+		}
+	}
+
+	return deltas
+}
+
+func (differ *Differ) compareValues(
+	position Position,
+	left interface{},
+	right interface{},
+) (same bool, delta Delta) {
+	if reflect.TypeOf(left) != reflect.TypeOf(right) {
+		return false, NewModified(position, left, right)
+	}
+
+	switch left.(type) {
+
+	case map[string]interface{}:
+		l := left.(map[string]interface{})
+		childDeltas := differ.compareMaps(l, right.(map[string]interface{}))
+		if len(childDeltas) > 0 {
+			return false, NewObject(position, childDeltas)
+		}
+
+	case []interface{}:
+		l := left.([]interface{})
+		childDeltas := differ.compareArrays(l, right.([]interface{}))
+
+		if len(childDeltas) > 0 {
+			return false, NewArray(position, childDeltas)
+		}
+
+	default:
+		if !reflect.DeepEqual(left, right) {
+
+			if reflect.ValueOf(left).Kind() == reflect.String &&
+				reflect.ValueOf(right).Kind() == reflect.String &&
+				differ.textDiffMinimumLength <= len(left.(string)) {
+
+				textDiff := dmp.New()
+				patchs := textDiff.PatchMake(left.(string), right.(string))
+				return false, NewTextDiff(position, patchs, left, right)
+
+			} else {
+				return false, NewModified(position, left, right)
+			}
+		}
+	}
+
+	return true, nil
+}
+
+func applyDeltas(deltas []Delta, object interface{}) interface{} {
+	preDeltas := make(preDeltas, 0)
+	for _, delta := range deltas {
+		switch delta.(type) {
+		case PreDelta:
+			preDeltas = append(preDeltas, delta.(PreDelta))
+		}
+	}
+	sort.Sort(preDeltas)
+	for _, delta := range preDeltas {
+		object = delta.PreApply(object)
+	}
+
+	postDeltas := make(postDeltas, 0, len(deltas)-len(preDeltas))
+	for _, delta := range deltas {
+		switch delta.(type) {
+		case PostDelta:
+			postDeltas = append(postDeltas, delta.(PostDelta))
+		}
+	}
+	sort.Sort(postDeltas)
+
+	for _, delta := range postDeltas {
+		object = delta.PostApply(object)
+	}
+
+	return object
+}
+
+func (differ *Differ) maximizeSimilarities(left []maybe, right []maybe) (resultDeltas []Delta, freeLeft, freeRight []maybe) {
+	deltaTable := make([][]Delta, len(left))
+	for i := 0; i < len(left); i++ {
+		deltaTable[i] = make([]Delta, len(right))
+	}
+	for i, leftValue := range left {
+		for j, rightValue := range right {
+			_, delta := differ.compareValues(Index(rightValue.index), leftValue.item, rightValue.item)
+			deltaTable[i][j] = delta
+		}
+	}
+
+	sizeX := len(left) + 1 // margins for both sides
+	sizeY := len(right) + 1
+
+	// fill out with similarities
+	dpTable := make([][]float64, sizeX)
+	for i := 0; i < sizeX; i++ {
+		dpTable[i] = make([]float64, sizeY)
+	}
+	for x := sizeX - 2; x >= 0; x-- {
+		for y := sizeY - 2; y >= 0; y-- {
+			prevX := dpTable[x+1][y]
+			prevY := dpTable[x][y+1]
+			score := deltaTable[x][y].Similarity() + dpTable[x+1][y+1]
+
+			dpTable[x][y] = max(prevX, prevY, score)
+		}
+	}
+
+	minLength := len(left)
+	if minLength > len(right) {
+		minLength = len(right)
+	}
+	maxInvalidLength := minLength - 1
+
+	freeLeft = make([]maybe, 0, len(left)-minLength)
+	freeRight = make([]maybe, 0, len(right)-minLength)
+
+	resultDeltas = make([]Delta, 0, minLength)
+	var x, y int
+	for x, y = 0, 0; x <= sizeX-2 && y <= sizeY-2; {
+		current := dpTable[x][y]
+		nextX := dpTable[x+1][y]
+		nextY := dpTable[x][y+1]
+
+		xValidLength := len(left) - maxInvalidLength + y
+		yValidLength := len(right) - maxInvalidLength + x
+
+		if x+1 < xValidLength && current == nextX {
+			freeLeft = append(freeLeft, left[x])
+			x++
+		} else if y+1 < yValidLength && current == nextY {
+			freeRight = append(freeRight, right[y])
+			y++
+		} else {
+			resultDeltas = append(resultDeltas, deltaTable[x][y])
+			x++
+			y++
+		}
+	}
+	for ; x < sizeX-1; x++ {
+		freeLeft = append(freeLeft, left[x-1])
+	}
+	for ; y < sizeY-1; y++ {
+		freeRight = append(freeRight, right[y-1])
+	}
+
+	return resultDeltas, freeLeft, freeRight
+}
+
+func deltasSimilarity(deltas []Delta) (similarity float64) {
+	for _, delta := range deltas {
+		similarity += delta.Similarity()
+	}
+	similarity = similarity / float64(len(deltas))
+	return
+}
+
+func stringSimilarity(left, right string) (similarity float64) {
+	matchingLength := float64(
+		lcs.New(
+			stringToInterfaceSlice(left),
+			stringToInterfaceSlice(right),
+		).Length(),
+	)
+	similarity =
+		(matchingLength / float64(len(left))) * (matchingLength / float64(len(right)))
+	return
+}
+
+func stringToInterfaceSlice(str string) []interface{} {
+	s := make([]interface{}, len(str))
+	for i, v := range str {
+		s[i] = v
+	}
+	return s
+}
+
+func sortedKeys(m map[string]interface{}) (keys []string) {
+	keys = make([]string, 0, len(m))
+	for key, _ := range m {
+		keys = append(keys, key)
+	}
+	sort.Strings(keys)
+	return
+}
+
+func max(first float64, rest ...float64) (max float64) {
+	max = first
+	for _, value := range rest {
+		if max < value {
+			max = value
+		}
+	}
+	return max
+}

+ 131 - 0
vendor/github.com/yudai/gojsondiff/unmarshaler.go

@@ -0,0 +1,131 @@
+package gojsondiff
+
+import (
+	"encoding/json"
+	"errors"
+	dmp "github.com/sergi/go-diff/diffmatchpatch"
+	"io"
+	"strconv"
+)
+
+type Unmarshaller struct {
+}
+
+func NewUnmarshaller() *Unmarshaller {
+	return &Unmarshaller{}
+}
+
+func (um *Unmarshaller) UnmarshalBytes(diffBytes []byte) (Diff, error) {
+	var diffObj map[string]interface{}
+	json.Unmarshal(diffBytes, &diffObj)
+	return um.UnmarshalObject(diffObj)
+}
+
+func (um *Unmarshaller) UnmarshalString(diffString string) (Diff, error) {
+	return um.UnmarshalBytes([]byte(diffString))
+}
+
+func (um *Unmarshaller) UnmarshalReader(diffReader io.Reader) (Diff, error) {
+	var diffBytes []byte
+	io.ReadFull(diffReader, diffBytes)
+	return um.UnmarshalBytes(diffBytes)
+}
+
+func (um *Unmarshaller) UnmarshalObject(diffObj map[string]interface{}) (Diff, error) {
+	result, err := process(Name(""), diffObj)
+	if err != nil {
+		return nil, err
+	}
+	return &diff{deltas: result.(*Object).Deltas}, nil
+}
+
+func process(position Position, object interface{}) (Delta, error) {
+	var delta Delta
+	switch object.(type) {
+	case map[string]interface{}:
+		o := object.(map[string]interface{})
+		if isArray, typed := o["_t"]; typed && isArray == "a" {
+			deltas := make([]Delta, 0, len(o))
+			for name, value := range o {
+				if name == "_t" {
+					continue
+				}
+
+				normalizedName := name
+				if normalizedName[0] == '_' {
+					normalizedName = name[1:]
+				}
+				index, err := strconv.Atoi(normalizedName)
+				if err != nil {
+					return nil, err
+				}
+
+				childDelta, err := process(Index(index), value)
+				if err != nil {
+					return nil, err
+				}
+
+				deltas = append(deltas, childDelta)
+			}
+
+			for _, d := range deltas {
+				switch d.(type) {
+				case *Moved:
+					moved := d.(*Moved)
+
+					var dd interface{}
+					var i int
+					for i, dd = range deltas {
+						switch dd.(type) {
+						case *Moved:
+						case PostDelta:
+							pd := dd.(PostDelta)
+							if moved.PostPosition() == pd.PostPosition() {
+								moved.Delta = pd
+								deltas = append(deltas[:i], deltas[i+1:]...)
+							}
+						}
+					}
+				}
+			}
+
+			delta = NewArray(position, deltas)
+		} else {
+			deltas := make([]Delta, 0, len(o))
+			for name, value := range o {
+				childDelta, err := process(Name(name), value)
+				if err != nil {
+					return nil, err
+				}
+				deltas = append(deltas, childDelta)
+			}
+			delta = NewObject(position, deltas)
+		}
+	case []interface{}:
+		o := object.([]interface{})
+		switch len(o) {
+		case 1:
+			delta = NewAdded(position, o[0])
+		case 2:
+			delta = NewModified(position, o[0], o[1])
+		case 3:
+			switch o[2] {
+			case float64(0):
+				delta = NewDeleted(position, o[0])
+			case float64(2):
+				dmp := dmp.New()
+				patches, err := dmp.PatchFromText(o[0].(string))
+				if err != nil {
+					return nil, err
+				}
+				delta = NewTextDiff(position, patches, nil, nil)
+			case float64(3):
+				delta = NewMoved(position, Index(int(o[1].(float64))), nil, nil)
+			default:
+				return nil, errors.New("Unknown delta type")
+			}
+		}
+	}
+
+	return delta, nil
+}

+ 8 - 0
vendor/github.com/yudai/gojsondiff/wercker.yml

@@ -0,0 +1,8 @@
+box: golang:1.6.3
+
+build:
+  steps:
+    - setup-go-workspace
+    - script:
+        name: test
+        code: make test

+ 73 - 0
vendor/github.com/yudai/golcs/LICENSE

@@ -0,0 +1,73 @@
+The MIT License (MIT)
+
+Copyright (c) 2015 Iwasaki Yudai
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+============================================================================
+
+This repository is build with following third party libraries. Thank you!
+
+
+## ginkgo - https://github.com/onsi/ginkgo
+
+Copyright (c) 2013-2014 Onsi Fakhouri
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+
+# gomega - https://github.com/onsi/gomega
+
+Copyright (c) 2013-2014 Onsi Fakhouri
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ 54 - 0
vendor/github.com/yudai/golcs/README.md

@@ -0,0 +1,54 @@
+# Go Longest Common Subsequence (LCS)
+
+A package to calculate [LCS](http://en.wikipedia.org/wiki/Longest_common_subsequence_problem) of slices.
+
+## Usage
+
+```sh
+go get github.com/yudai/golcs
+```
+
+```go
+import " github.com/yudai/golcs"
+
+left = []interface{}{1, 2, 5, 3, 1, 1, 5, 8, 3}
+right = []interface{}{1, 2, 3, 3, 4, 4, 5, 1, 6}
+
+lcs := golcs.New(left, right)
+
+lcs.Values()     // LCS values       => []interface{}{1, 2, 5, 1}
+lcs.IndexPairs() // Matched indices  => [{Left: 0, Right: 0}, {Left: 1, Right: 1}, {Left: 2, Right: 6}, {Left: 4, Right: 7}]
+lcs.Length()     // Matched length   => 4
+
+lcs.Table()      // Memo table
+```
+
+All the methods of `Lcs` cache their return values. For example, the memo table is calculated only once and reused when `Values()`, `Length()` and other methods are called.
+
+
+## FAQ
+
+### How can I give `[]byte` values to `Lcs()` as its arguments?
+
+As `[]interface{}` is incompatible with `[]othertype` like `[]byte`, you need to create a `[]interface{}` slice and copy the values in your `[]byte` slice into it. Unfortunately, Go doesn't provide any mesure to cast a slice into `[]interface{}` with zero cost. Your copy costs O(n).
+
+```go
+leftBytes := []byte("TGAGTA")
+left = make([]interface{}, len(leftBytes))
+for i, v := range leftBytes {
+	left[i] = v
+}
+
+rightBytes := []byte("GATA")
+right = make([]interface{}, len(rightBytes))
+for i, v := range rightBytes {
+	right[i] = v
+}
+
+lcs.New(left, right)
+```
+
+
+## LICENSE
+
+The MIT license (See `LICENSE` for detail)

+ 130 - 0
vendor/github.com/yudai/golcs/golcs.go

@@ -0,0 +1,130 @@
+package lcs
+
+import (
+	"reflect"
+)
+
+type Lcs interface {
+	Values() (values []interface{})
+	IndexPairs() (pairs []IndexPair)
+	Length() (length int)
+	Left() (leftValues []interface{})
+	Right() (righttValues []interface{})
+}
+
+type IndexPair struct {
+	Left  int
+	Right int
+}
+
+type lcs struct {
+	left  []interface{}
+	right []interface{}
+	/* for caching */
+	table      [][]int
+	indexPairs []IndexPair
+	values     []interface{}
+}
+
+func New(left, right []interface{}) Lcs {
+	return &lcs{
+		left:       left,
+		right:      right,
+		table:      nil,
+		indexPairs: nil,
+		values:     nil,
+	}
+}
+
+func (lcs *lcs) Table() (table [][]int) {
+	if lcs.table != nil {
+		return lcs.table
+	}
+
+	sizeX := len(lcs.left) + 1
+	sizeY := len(lcs.right) + 1
+
+	table = make([][]int, sizeX)
+	for x := 0; x < sizeX; x++ {
+		table[x] = make([]int, sizeY)
+	}
+
+	for y := 1; y < sizeY; y++ {
+		for x := 1; x < sizeX; x++ {
+			increment := 0
+			if reflect.DeepEqual(lcs.left[x-1], lcs.right[y-1]) {
+				increment = 1
+			}
+			table[x][y] = max(table[x-1][y-1]+increment, table[x-1][y], table[x][y-1])
+		}
+	}
+
+	lcs.table = table
+	return
+}
+
+func (lcs *lcs) Length() (length int) {
+	length = lcs.Table()[len(lcs.left)][len(lcs.right)]
+	return
+}
+
+func (lcs *lcs) IndexPairs() (pairs []IndexPair) {
+	if lcs.indexPairs != nil {
+		return lcs.indexPairs
+	}
+
+	table := lcs.Table()
+	pairs = make([]IndexPair, table[len(table)-1][len(table[0])-1])
+
+	for x, y := len(lcs.left), len(lcs.right); x > 0 && y > 0; {
+		if reflect.DeepEqual(lcs.left[x-1], lcs.right[y-1]) {
+			pairs[table[x][y]-1] = IndexPair{Left: x - 1, Right: y - 1}
+			x--
+			y--
+		} else {
+			if table[x-1][y] >= table[x][y-1] {
+				x--
+			} else {
+				y--
+			}
+		}
+	}
+
+	lcs.indexPairs = pairs
+
+	return
+}
+
+func (lcs *lcs) Values() (values []interface{}) {
+	if lcs.values != nil {
+		return lcs.values
+	}
+
+	pairs := lcs.IndexPairs()
+	values = make([]interface{}, len(pairs))
+	for i, pair := range pairs {
+		values[i] = lcs.left[pair.Left]
+	}
+	lcs.values = values
+	return
+}
+
+func (lcs *lcs) Left() (leftValues []interface{}) {
+	leftValues = lcs.left
+	return
+}
+
+func (lcs *lcs) Right() (rightValues []interface{}) {
+	rightValues = lcs.right
+	return
+}
+
+func max(first int, rest ...int) (max int) {
+	max = first
+	for _, value := range rest {
+		if value > max {
+			max = value
+		}
+	}
+	return
+}

+ 24 - 0
vendor/vendor.json

@@ -452,6 +452,12 @@
 			"revision": "9a94032291f2192936512bab367bc45e77990d6a",
 			"revisionTime": "2016-09-17T18:44:01Z"
 		},
+		{
+			"checksumSHA1": "iWCtyR1TkJ22Bi/ygzfKDvOQdQY=",
+			"path": "github.com/sergi/go-diff/diffmatchpatch",
+			"revision": "24e2351369ec4949b2ed0dc5c477afdd4c4034e8",
+			"revisionTime": "2017-01-18T13:12:30Z"
+		},
 		{
 			"checksumSHA1": "6AYg4fjEvFuAVN3wHakGApjhZAM=",
 			"path": "github.com/smartystreets/assertions",
@@ -494,6 +500,24 @@
 			"revision": "3543873453996aaab2fc6b3928a35fc5ca2b5afb",
 			"revisionTime": "2017-04-18T16:44:36Z"
 		},
+		{
+			"checksumSHA1": "r7o16T0WQ/XSe2mlQuioMi8gxbw=",
+			"path": "github.com/yudai/gojsondiff",
+			"revision": "9209d1532c51cabe0439993586a71c207b09a0ac",
+			"revisionTime": "2017-02-27T22:09:00Z"
+		},
+		{
+			"checksumSHA1": "7/V6fDOOfkmSHQahCK+J5G4Y1uk=",
+			"path": "github.com/yudai/gojsondiff/formatter",
+			"revision": "9209d1532c51cabe0439993586a71c207b09a0ac",
+			"revisionTime": "2017-02-27T22:09:00Z"
+		},
+		{
+			"checksumSHA1": "OCkp7qxxdxjpoM3T6Q3CTiMP5kM=",
+			"path": "github.com/yudai/golcs",
+			"revision": "d1c525dea8ce39ea9a783d33cf08932305373f2c",
+			"revisionTime": "2015-04-05T16:34:35Z"
+		},
 		{
 			"checksumSHA1": "WHc3uByvGaMcnSoI21fhzYgbOgg=",
 			"path": "golang.org/x/net/context/ctxhttp",