Просмотр исходного кода

Merge branch 'walmartlabs-master' (Dashboard History Feature, #8472)

Torkel Ödegaard 8 лет назад
Родитель
Сommit
e7e675e471
74 измененных файлов с 7571 добавлено и 346 удалено
  1. 7 0
      pkg/api/api.go
  2. 138 6
      pkg/api/dashboard.go
  3. 49 0
      pkg/api/dtos/dashboard.go
  4. 0 27
      pkg/api/dtos/models.go
  5. 149 0
      pkg/components/dashdiffs/compare.go
  6. 339 0
      pkg/components/dashdiffs/formatter_basic.go
  7. 477 0
      pkg/components/dashdiffs/formatter_json.go
  8. 71 0
      pkg/models/dashboard_version.go
  9. 16 8
      pkg/models/dashboards.go
  10. 30 2
      pkg/services/sqlstore/dashboard.go
  11. 59 0
      pkg/services/sqlstore/dashboard_version.go
  12. 102 0
      pkg/services/sqlstore/dashboard_version_test.go
  13. 9 18
      pkg/services/sqlstore/logger.go
  14. 61 0
      pkg/services/sqlstore/migrations/dashboard_version_mig.go
  15. 1 0
      pkg/services/sqlstore/migrations/migrations.go
  16. 2 1
      public/app/core/components/switch.ts
  17. 1 0
      public/app/core/core.ts
  18. 41 28
      public/app/core/directives/dash_edit_link.js
  19. 77 0
      public/app/core/directives/diff-view.ts
  20. 14 0
      public/app/core/directives/misc.js
  21. 8 0
      public/app/core/nav_model_srv.ts
  22. 6 1
      public/app/core/services/backend_srv.ts
  23. 4 2
      public/app/features/dashboard/all.js
  24. 0 11
      public/app/features/dashboard/dash_list_ctrl.ts
  25. 52 32
      public/app/features/dashboard/dashboard_srv.ts
  26. 1 1
      public/app/features/dashboard/dashnav/dashnav.html
  27. 3 3
      public/app/features/dashboard/dashnav/dashnav.ts
  28. 146 0
      public/app/features/dashboard/history/history.html
  29. 203 0
      public/app/features/dashboard/history/history.ts
  30. 55 0
      public/app/features/dashboard/history/history_srv.ts
  31. 1 1
      public/app/features/dashboard/model.ts
  32. 0 10
      public/app/features/dashboard/partials/dash_list.html
  33. 0 35
      public/app/features/dashboard/partials/graphiteImport.html
  34. 0 27
      public/app/features/dashboard/partials/saveDashboardAs.html
  35. 0 64
      public/app/features/dashboard/saveDashboardAsCtrl.js
  36. 79 0
      public/app/features/dashboard/save_as_modal.ts
  37. 88 0
      public/app/features/dashboard/save_modal.ts
  38. 315 0
      public/app/features/dashboard/specs/history_ctrl_specs.ts
  39. 70 0
      public/app/features/dashboard/specs/history_srv_specs.ts
  40. 1 2
      public/app/features/dashboard/timepicker/timepicker.ts
  41. 22 24
      public/app/features/dashboard/unsavedChangesSrv.js
  42. 63 0
      public/app/features/dashboard/unsaved_changes_modal.ts
  43. 0 27
      public/app/partials/unsaved-changes.html
  44. 1 1
      public/dashboards/home.json
  45. 1 0
      public/sass/_grafana.scss
  46. 22 0
      public/sass/_variables.dark.scss
  47. 25 0
      public/sass/_variables.light.scss
  48. 12 0
      public/sass/components/_buttons.scss
  49. 8 9
      public/sass/components/_filter-table.scss
  50. 10 4
      public/sass/components/_gf-form.scss
  51. 16 1
      public/sass/components/_switch.scss
  52. 0 1
      public/sass/components/edit_sidemenu.scss
  53. 182 0
      public/sass/pages/_history.scss
  54. 197 0
      public/test/mocks/history-mocks.js
  55. 20 0
      vendor/github.com/sergi/go-diff/LICENSE
  56. 1339 0
      vendor/github.com/sergi/go-diff/diffmatchpatch/diff.go
  57. 46 0
      vendor/github.com/sergi/go-diff/diffmatchpatch/diffmatchpatch.go
  58. 160 0
      vendor/github.com/sergi/go-diff/diffmatchpatch/match.go
  59. 23 0
      vendor/github.com/sergi/go-diff/diffmatchpatch/mathutil.go
  60. 556 0
      vendor/github.com/sergi/go-diff/diffmatchpatch/patch.go
  61. 88 0
      vendor/github.com/sergi/go-diff/diffmatchpatch/stringutil.go
  62. 145 0
      vendor/github.com/yudai/gojsondiff/LICENSE
  63. 2 0
      vendor/github.com/yudai/gojsondiff/Makefile
  64. 157 0
      vendor/github.com/yudai/gojsondiff/README.md
  65. 461 0
      vendor/github.com/yudai/gojsondiff/deltas.go
  66. 370 0
      vendor/github.com/yudai/gojsondiff/formatter/ascii.go
  67. 124 0
      vendor/github.com/yudai/gojsondiff/formatter/delta.go
  68. 426 0
      vendor/github.com/yudai/gojsondiff/gojsondiff.go
  69. 131 0
      vendor/github.com/yudai/gojsondiff/unmarshaler.go
  70. 8 0
      vendor/github.com/yudai/gojsondiff/wercker.yml
  71. 73 0
      vendor/github.com/yudai/golcs/LICENSE
  72. 54 0
      vendor/github.com/yudai/golcs/README.md
  73. 130 0
      vendor/github.com/yudai/golcs/golcs.go
  74. 24 0
      vendor/vendor.json

+ 7 - 0
pkg/api/api.go

@@ -223,6 +223,13 @@ func (hs *HttpServer) registerRoutes() {
 		// Dashboard
 		r.Group("/dashboards", func() {
 			r.Combo("/db/:slug").Get(GetDashboard).Delete(DeleteDashboard)
+
+			r.Get("/id/:dashboardId/versions", wrap(GetDashboardVersions))
+			r.Get("/id/:dashboardId/versions/:id", wrap(GetDashboardVersion))
+			r.Post("/id/:dashboardId/restore", reqEditorRole, bind(dtos.RestoreDashboardVersionCommand{}), wrap(RestoreDashboardVersion))
+
+			r.Post("/calculate-diff", bind(dtos.CalculateDiffOptions{}), wrap(CalculateDashboardDiff))
+
 			r.Post("/db", reqEditorRole, bind(m.SaveDashboardCommand{}), wrap(PostDashboard))
 			r.Get("/file/:file", GetDashboardFromJsonFile)
 			r.Get("/home", wrap(GetHomeDashboard))

+ 138 - 6
pkg/api/dashboard.go

@@ -2,12 +2,14 @@ package api
 
 import (
 	"encoding/json"
+	"fmt"
 	"os"
 	"path"
 	"strings"
 
 	"github.com/grafana/grafana/pkg/api/dtos"
 	"github.com/grafana/grafana/pkg/bus"
+	"github.com/grafana/grafana/pkg/components/dashdiffs"
 	"github.com/grafana/grafana/pkg/components/simplejson"
 	"github.com/grafana/grafana/pkg/log"
 	"github.com/grafana/grafana/pkg/metrics"
@@ -60,6 +62,9 @@ func GetDashboard(c *middleware.Context) {
 		creator = getUserLogin(dash.CreatedBy)
 	}
 
+	// make sure db version is in sync with json model version
+	dash.Data.Set("version", dash.Version)
+
 	dto := dtos.DashboardFullWithMeta{
 		Dashboard: dash.Data,
 		Meta: dtos.DashboardMeta{
@@ -77,6 +82,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)
 }
@@ -114,18 +120,15 @@ func DeleteDashboard(c *middleware.Context) {
 
 func PostDashboard(c *middleware.Context, cmd m.SaveDashboardCommand) Response {
 	cmd.OrgId = c.OrgId
-
-	if !c.IsSignedIn {
-		cmd.UserId = -1
-	} else {
-		cmd.UserId = c.UserId
-	}
+	cmd.UserId = c.UserId
 
 	dash := cmd.GetDashboardModel()
+
 	// Check if Title is empty
 	if dash.Title == "" {
 		return ApiError(400, m.ErrDashboardTitleEmpty.Error(), nil)
 	}
+
 	if dash.Id == 0 {
 		limitReached, err := middleware.QuotaReached(c, "dashboard")
 		if err != nil {
@@ -255,6 +258,135 @@ func GetDashboardFromJsonFile(c *middleware.Context) {
 	c.JSON(200, &dash)
 }
 
+// GetDashboardVersions returns all dashboard versions as JSON
+func GetDashboardVersions(c *middleware.Context) Response {
+	dashboardId := c.ParamsInt64(":dashboardId")
+	limit := c.QueryInt("limit")
+	start := c.QueryInt("start")
+
+	if limit == 0 {
+		limit = 1000
+	}
+
+	query := m.GetDashboardVersionsQuery{
+		OrgId:       c.OrgId,
+		DashboardId: dashboardId,
+		Limit:       limit,
+		Start:       start,
+	}
+
+	if err := bus.Dispatch(&query); err != nil {
+		return ApiError(404, fmt.Sprintf("No versions found for dashboardId %d", dashboardId), err)
+	}
+
+	for _, version := range query.Result {
+		if version.RestoredFrom == version.Version {
+			version.Message = "Initial save (created by migration)"
+			continue
+		}
+
+		if version.RestoredFrom > 0 {
+			version.Message = fmt.Sprintf("Restored from version %d", version.RestoredFrom)
+			continue
+		}
+
+		if version.ParentVersion == 0 {
+			version.Message = "Initial save"
+		}
+	}
+
+	return Json(200, query.Result)
+}
+
+// GetDashboardVersion returns the dashboard version with the given ID.
+func GetDashboardVersion(c *middleware.Context) Response {
+	dashboardId := c.ParamsInt64(":dashboardId")
+	version := c.ParamsInt(":id")
+
+	query := m.GetDashboardVersionQuery{
+		OrgId:       c.OrgId,
+		DashboardId: dashboardId,
+		Version:     version,
+	}
+
+	if err := bus.Dispatch(&query); err != nil {
+		return ApiError(500, fmt.Sprintf("Dashboard version %d not found for dashboardId %d", version, dashboardId), err)
+	}
+
+	creator := "Anonymous"
+	if query.Result.CreatedBy > 0 {
+		creator = getUserLogin(query.Result.CreatedBy)
+	}
+
+	dashVersionMeta := &m.DashboardVersionMeta{
+		DashboardVersion: *query.Result,
+		CreatedBy:        creator,
+	}
+
+	return Json(200, dashVersionMeta)
+}
+
+// POST /api/dashboards/calculate-diff performs diffs on two dashboards
+func CalculateDashboardDiff(c *middleware.Context, apiOptions dtos.CalculateDiffOptions) Response {
+
+	options := dashdiffs.Options{
+		OrgId:    c.OrgId,
+		DiffType: dashdiffs.ParseDiffType(apiOptions.DiffType),
+		Base: dashdiffs.DiffTarget{
+			DashboardId:      apiOptions.Base.DashboardId,
+			Version:          apiOptions.Base.Version,
+			UnsavedDashboard: apiOptions.Base.UnsavedDashboard,
+		},
+		New: dashdiffs.DiffTarget{
+			DashboardId:      apiOptions.New.DashboardId,
+			Version:          apiOptions.New.Version,
+			UnsavedDashboard: apiOptions.New.UnsavedDashboard,
+		},
+	}
+
+	result, err := dashdiffs.CalculateDiff(&options)
+	if err != nil {
+		if err == m.ErrDashboardVersionNotFound {
+			return ApiError(404, "Dashboard version not found", err)
+		}
+		return ApiError(500, "Unable to compute diff", err)
+	}
+
+	if options.DiffType == dashdiffs.DiffDelta {
+		return Respond(200, result.Delta).Header("Content-Type", "application/json")
+	} else {
+		return Respond(200, result.Delta).Header("Content-Type", "text/html")
+	}
+}
+
+// RestoreDashboardVersion restores a dashboard to the given version.
+func RestoreDashboardVersion(c *middleware.Context, apiCmd dtos.RestoreDashboardVersionCommand) Response {
+	dashboardId := c.ParamsInt64(":dashboardId")
+
+	dashQuery := m.GetDashboardQuery{Id: dashboardId, OrgId: c.OrgId}
+	if err := bus.Dispatch(&dashQuery); err != nil {
+		return ApiError(404, "Dashboard not found", nil)
+	}
+
+	versionQuery := m.GetDashboardVersionQuery{DashboardId: dashboardId, Version: apiCmd.Version, OrgId: c.OrgId}
+	if err := bus.Dispatch(&versionQuery); err != nil {
+		return ApiError(404, "Dashboard version not found", nil)
+	}
+
+	dashboard := dashQuery.Result
+	version := versionQuery.Result
+
+	saveCmd := m.SaveDashboardCommand{}
+	saveCmd.RestoredFrom = version.Version
+	saveCmd.OrgId = c.OrgId
+	saveCmd.UserId = c.UserId
+	saveCmd.Dashboard = version.Data
+	saveCmd.Dashboard.Set("version", dashboard.Version)
+	saveCmd.Message = fmt.Sprintf("Restored from version %d", version.Version)
+
+	return PostDashboard(c, saveCmd)
+}
+
 func GetDashboardTags(c *middleware.Context) {
 	query := m.GetDashboardTagsQuery{OrgId: c.OrgId}
 	err := bus.Dispatch(&query)

+ 49 - 0
pkg/api/dtos/dashboard.go

@@ -0,0 +1,49 @@
+package dtos
+
+import (
+	"time"
+
+	"github.com/grafana/grafana/pkg/components/simplejson"
+)
+
+type DashboardMeta struct {
+	IsStarred  bool      `json:"isStarred,omitempty"`
+	IsHome     bool      `json:"isHome,omitempty"`
+	IsSnapshot bool      `json:"isSnapshot,omitempty"`
+	Type       string    `json:"type,omitempty"`
+	CanSave    bool      `json:"canSave"`
+	CanEdit    bool      `json:"canEdit"`
+	CanStar    bool      `json:"canStar"`
+	Slug       string    `json:"slug"`
+	Expires    time.Time `json:"expires"`
+	Created    time.Time `json:"created"`
+	Updated    time.Time `json:"updated"`
+	UpdatedBy  string    `json:"updatedBy"`
+	CreatedBy  string    `json:"createdBy"`
+	Version    int       `json:"version"`
+}
+
+type DashboardFullWithMeta struct {
+	Meta      DashboardMeta    `json:"meta"`
+	Dashboard *simplejson.Json `json:"dashboard"`
+}
+
+type DashboardRedirect struct {
+	RedirectUri string `json:"redirectUri"`
+}
+
+type CalculateDiffOptions struct {
+	Base     CalculateDiffTarget `json:"base" binding:"Required"`
+	New      CalculateDiffTarget `json:"new" binding:"Required"`
+	DiffType string              `json:"diffType" binding:"Required"`
+}
+
+type CalculateDiffTarget struct {
+	DashboardId      int64            `json:"dashboardId"`
+	Version          int              `json:"version"`
+	UnsavedDashboard *simplejson.Json `json:"unsavedDashboard"`
+}
+
+type RestoreDashboardVersionCommand struct {
+	Version int `json:"version" binding:"Required"`
+}

+ 0 - 27
pkg/api/dtos/models.go

@@ -4,7 +4,6 @@ import (
 	"crypto/md5"
 	"fmt"
 	"strings"
-	"time"
 
 	"github.com/grafana/grafana/pkg/components/simplejson"
 	m "github.com/grafana/grafana/pkg/models"
@@ -38,32 +37,6 @@ type CurrentUser struct {
 	HelpFlags1     m.HelpFlags1 `json:"helpFlags1"`
 }
 
-type DashboardMeta struct {
-	IsStarred  bool      `json:"isStarred,omitempty"`
-	IsHome     bool      `json:"isHome,omitempty"`
-	IsSnapshot bool      `json:"isSnapshot,omitempty"`
-	Type       string    `json:"type,omitempty"`
-	CanSave    bool      `json:"canSave"`
-	CanEdit    bool      `json:"canEdit"`
-	CanStar    bool      `json:"canStar"`
-	Slug       string    `json:"slug"`
-	Expires    time.Time `json:"expires"`
-	Created    time.Time `json:"created"`
-	Updated    time.Time `json:"updated"`
-	UpdatedBy  string    `json:"updatedBy"`
-	CreatedBy  string    `json:"createdBy"`
-	Version    int       `json:"version"`
-}
-
-type DashboardFullWithMeta struct {
-	Meta      DashboardMeta    `json:"meta"`
-	Dashboard *simplejson.Json `json:"dashboard"`
-}
-
-type DashboardRedirect struct {
-	RedirectUri string `json:"redirectUri"`
-}
-
 type DataSource struct {
 	Id                int64            `json:"id"`
 	OrgId             int64            `json:"orgId"`

+ 149 - 0
pkg/components/dashdiffs/compare.go

@@ -0,0 +1,149 @@
+package dashdiffs
+
+import (
+	"encoding/json"
+	"errors"
+
+	"github.com/grafana/grafana/pkg/bus"
+	"github.com/grafana/grafana/pkg/components/simplejson"
+	"github.com/grafana/grafana/pkg/log"
+	"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("dashdiff: unsupported diff type")
+
+	// ErrNilDiff occurs when two compared interfaces are identical.
+	ErrNilDiff = errors.New("dashdiff: diff is nil")
+
+	diffLogger = log.New("dashdiffs")
+)
+
+type DiffType int
+
+const (
+	DiffJSON DiffType = iota
+	DiffBasic
+	DiffDelta
+)
+
+type Options struct {
+	OrgId    int64
+	Base     DiffTarget
+	New      DiffTarget
+	DiffType DiffType
+}
+
+type DiffTarget struct {
+	DashboardId      int64
+	Version          int
+	UnsavedDashboard *simplejson.Json
+}
+
+type Result struct {
+	Delta []byte `json:"delta"`
+}
+
+func ParseDiffType(diff string) DiffType {
+	switch diff {
+	case "json":
+		return DiffJSON
+	case "basic":
+		return DiffBasic
+	case "delta":
+		return DiffDelta
+	}
+	return DiffBasic
+}
+
+// CompareDashboardVersionsCommand computes the JSON diff of two versions,
+// assigning the delta of the diff to the `Delta` field.
+func CalculateDiff(options *Options) (*Result, error) {
+	baseVersionQuery := models.GetDashboardVersionQuery{
+		DashboardId: options.Base.DashboardId,
+		Version:     options.Base.Version,
+		OrgId:       options.OrgId,
+	}
+
+	if err := bus.Dispatch(&baseVersionQuery); err != nil {
+		return nil, err
+	}
+
+	newVersionQuery := models.GetDashboardVersionQuery{
+		DashboardId: options.New.DashboardId,
+		Version:     options.New.Version,
+		OrgId:       options.OrgId,
+	}
+
+	if err := bus.Dispatch(&newVersionQuery); err != nil {
+		return nil, err
+	}
+
+	baseData := baseVersionQuery.Result.Data
+	newData := newVersionQuery.Result.Data
+
+	left, jsonDiff, err := getDiff(baseData, newData)
+	if err != nil {
+		return nil, err
+	}
+
+	result := &Result{}
+
+	switch options.DiffType {
+	case DiffDelta:
+
+		deltaOutput, err := deltaFormatter.NewDeltaFormatter().Format(jsonDiff)
+		if err != nil {
+			return nil, err
+		}
+		result.Delta = []byte(deltaOutput)
+
+	case DiffJSON:
+		jsonOutput, err := NewJSONFormatter(left).Format(jsonDiff)
+		if err != nil {
+			return nil, err
+		}
+		result.Delta = []byte(jsonOutput)
+
+	case DiffBasic:
+		basicOutput, err := NewBasicFormatter(left).Format(jsonDiff)
+		if err != nil {
+			return nil, err
+		}
+		result.Delta = basicOutput
+
+	default:
+		return nil, ErrUnsupportedDiffType
+	}
+
+	return result, nil
+}
+
+// getDiff computes the diff of two dashboard versions.
+func getDiff(baseData, newData *simplejson.Json) (interface{}, diff.Diff, error) {
+	leftBytes, err := baseData.Encode()
+	if err != nil {
+		return nil, nil, err
+	}
+
+	rightBytes, err := newData.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
+}

+ 339 - 0
pkg/components/dashdiffs/formatter_basic.go

@@ -0,0 +1,339 @@
+package dashdiffs
+
+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 {
+		// TODO: this condition needs an explaination? what does it mean?
+		if b.LastIndent == 2 && line.Indent == 1 && line.Change == ChangeNil {
+			if b.Block != nil {
+				blocks = append(blocks, b.Block)
+			}
+		}
+
+		b.LastIndent = line.Indent
+
+		// TODO: why special handling for indent 2?
+		if line.Indent == 1 {
+			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
+			}
+		}
+
+		// TODO: why special handling for indent > 2 ?
+		// Other Lines
+		if line.Indent > 1 {
+			// 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="diff-label">{{ .Old }}</div>
+			<i class="diff-arrow fa fa-long-arrow-right"></i>
+		{{ end }}
+		{{ if .New }}
+				<div class="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="diff-label">{{ .Old }}</div>
+				<i class="diff-arrow fa fa-long-arrow-right"></i>
+			{{ end }}
+			{{ if .New }}
+					<div class="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('json')"
+			/>
+		{{ 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('json')"
+		/>
+	{{ end }}
+</div>
+{{ end }}`
+)

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

@@ -0,0 +1,477 @@
+package dashdiffs
+
+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
+}

+ 71 - 0
pkg/models/dashboard_version.go

@@ -0,0 +1,71 @@
+package models
+
+import (
+	"errors"
+	"time"
+
+	"github.com/grafana/grafana/pkg/components/simplejson"
+)
+
+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"`
+}
+
+//
+// Queries
+//
+
+type GetDashboardVersionQuery struct {
+	DashboardId int64
+	OrgId       int64
+	Version     int
+
+	Result *DashboardVersion
+}
+
+type GetDashboardVersionsQuery struct {
+	DashboardId int64
+	OrgId       int64
+	Limit       int
+	Start       int
+
+	Result []*DashboardVersionDTO
+}

+ 16 - 8
pkg/models/dashboards.go

@@ -98,12 +98,17 @@ func NewDashboardFromJson(data *simplejson.Json) *Dashboard {
 // GetDashboardModel turns the command into the savable model
 func (cmd *SaveDashboardCommand) GetDashboardModel() *Dashboard {
 	dash := NewDashboardFromJson(cmd.Dashboard)
+	userId := cmd.UserId
+
+	if userId == 0 {
+		userId = -1
+	}
 
 	if dash.Data.Get("version").MustInt(0) == 0 {
-		dash.CreatedBy = cmd.UserId
+		dash.CreatedBy = userId
 	}
 
-	dash.UpdatedBy = cmd.UserId
+	dash.UpdatedBy = userId
 	dash.OrgId = cmd.OrgId
 	dash.PluginId = cmd.PluginId
 	dash.UpdateSlug()
@@ -126,11 +131,13 @@ func (dash *Dashboard) UpdateSlug() {
 //
 
 type SaveDashboardCommand struct {
-	Dashboard *simplejson.Json `json:"dashboard" binding:"Required"`
-	UserId    int64            `json:"userId"`
-	OrgId     int64            `json:"-"`
-	Overwrite bool             `json:"overwrite"`
-	PluginId  string           `json:"-"`
+	Dashboard    *simplejson.Json `json:"dashboard" binding:"Required"`
+	UserId       int64            `json:"userId"`
+	Overwrite    bool             `json:"overwrite"`
+	Message      string           `json:"message"`
+	OrgId        int64            `json:"-"`
+	RestoredFrom int              `json:"-"`
+	PluginId     string           `json:"-"`
 
 	Result *Dashboard
 }
@@ -145,7 +152,8 @@ type DeleteDashboardCommand struct {
 //
 
 type GetDashboardQuery struct {
-	Slug  string
+	Slug  string // required if no Id is specified
+	Id    int64  // optional if slug is set
 	OrgId int64
 
 	Result *Dashboard

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

@@ -3,6 +3,7 @@ package sqlstore
 import (
 	"bytes"
 	"fmt"
+	"time"
 
 	"github.com/grafana/grafana/pkg/bus"
 	"github.com/grafana/grafana/pkg/metrics"
@@ -62,16 +63,20 @@ func SaveDashboard(cmd *m.SaveDashboardCommand) error {
 			if dash.Id != sameTitle.Id {
 				if cmd.Overwrite {
 					dash.Id = sameTitle.Id
+					dash.Version = sameTitle.Version
 				} else {
 					return m.ErrDashboardWithSameNameExists
 				}
 			}
 		}
 
+		parentVersion := dash.Version
 		affectedRows := int64(0)
 
 		if dash.Id == 0 {
+			dash.Version = 1
 			metrics.M_Models_Dashboard_Insert.Inc(1)
+			dash.Data.Set("version", dash.Version)
 			affectedRows, err = sess.Insert(dash)
 		} else {
 			dash.Version += 1
@@ -79,10 +84,32 @@ func SaveDashboard(cmd *m.SaveDashboardCommand) error {
 			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:  cmd.RestoredFrom,
+			Version:       dash.Version,
+			Created:       time.Now(),
+			CreatedBy:     dash.UpdatedBy,
+			Message:       cmd.Message,
+			Data:          dash.Data,
+		}
+
+		// insert version entry
+		if affectedRows, err = sess.Insert(dashVersion); err != nil {
+			return err
+		} else if affectedRows == 0 {
+			return m.ErrDashboardNotFound
+		}
+
 		// delete existing tabs
 		_, err = sess.Exec("DELETE FROM dashboard_tag WHERE dashboard_id=?", dash.Id)
 		if err != nil {
@@ -106,8 +133,9 @@ func SaveDashboard(cmd *m.SaveDashboardCommand) error {
 }
 
 func GetDashboard(query *m.GetDashboardQuery) error {
-	dashboard := m.Dashboard{Slug: query.Slug, OrgId: query.OrgId}
+	dashboard := m.Dashboard{Slug: query.Slug, OrgId: query.OrgId, Id: query.Id}
 	has, err := x.Get(&dashboard)
+
 	if err != nil {
 		return err
 	} else if has == false {
@@ -116,7 +144,6 @@ func GetDashboard(query *m.GetDashboardQuery) error {
 
 	dashboard.Data.Set("id", dashboard.Id)
 	query.Result = &dashboard
-
 	return nil
 }
 
@@ -233,6 +260,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 {

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

@@ -0,0 +1,59 @@
+package sqlstore
+
+import (
+	"github.com/grafana/grafana/pkg/bus"
+	m "github.com/grafana/grafana/pkg/models"
+)
+
+func init() {
+	bus.AddHandler("sql", GetDashboardVersion)
+	bus.AddHandler("sql", GetDashboardVersions)
+}
+
+// GetDashboardVersion gets the dashboard version for the given dashboard ID and version number.
+func GetDashboardVersion(query *m.GetDashboardVersionQuery) error {
+	version := m.DashboardVersion{}
+	has, err := x.Where("dashboard_version.dashboard_id=? AND dashboard_version.version=? AND dashboard.org_id=?", query.DashboardId, query.Version, query.OrgId).
+		Join("LEFT", "dashboard", `dashboard.id = dashboard_version.dashboard_id`).
+		Get(&version)
+
+	if err != nil {
+		return err
+	}
+
+	if !has {
+		return m.ErrDashboardVersionNotFound
+	}
+
+	query.Result = &version
+	return nil
+}
+
+// GetDashboardVersions gets all dashboard versions for the given dashboard ID.
+func GetDashboardVersions(query *m.GetDashboardVersionsQuery) error {
+	err := x.Table("dashboard_version").
+		Select(`dashboard_version.id,
+				dashboard_version.dashboard_id,
+				dashboard_version.parent_version,
+				dashboard_version.restored_from,
+				dashboard_version.version,
+				dashboard_version.created,
+				dashboard_version.created_by as created_by_id,
+				dashboard_version.message,
+				dashboard_version.data,`+
+			dialect.Quote("user")+`.login as created_by`).
+		Join("LEFT", "user", `dashboard_version.created_by = `+dialect.Quote("user")+`.id`).
+		Join("LEFT", "dashboard", `dashboard.id = dashboard_version.dashboard_id`).
+		Where("dashboard_version.dashboard_id=? AND dashboard.org_id=?", query.DashboardId, query.OrgId).
+		OrderBy("dashboard_version.version DESC").
+		Limit(query.Limit, query.Start).
+		Find(&query.Result)
+	if err != nil {
+		return err
+	}
+
+	if len(query.Result) < 1 {
+		return m.ErrNoVersionsForDashboardId
+	}
+	return nil
+}

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

@@ -0,0 +1,102 @@
+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")
+
+			query := m.GetDashboardVersionQuery{
+				DashboardId: savedDash.Id,
+				Version:     savedDash.Version,
+				OrgId:       1,
+			}
+
+			err := GetDashboardVersion(&query)
+			So(err, ShouldBeNil)
+			So(savedDash.Id, ShouldEqual, query.DashboardId)
+			So(savedDash.Version, ShouldEqual, query.Version)
+
+			dashCmd := m.GetDashboardQuery{
+				OrgId: savedDash.OrgId,
+				Slug:  savedDash.Slug,
+			}
+			err = GetDashboard(&dashCmd)
+			So(err, ShouldBeNil)
+			eq := reflect.DeepEqual(dashCmd.Result.Data, query.Result.Data)
+			So(eq, ShouldEqual, true)
+		})
+
+		Convey("Attempt to get a version that doesn't exist", func() {
+			query := m.GetDashboardVersionQuery{
+				DashboardId: int64(999),
+				Version:     123,
+				OrgId:       1,
+			}
+
+			err := GetDashboardVersion(&query)
+			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() {
+			query := m.GetDashboardVersionsQuery{DashboardId: savedDash.Id, OrgId: 1}
+
+			err := GetDashboardVersions(&query)
+			So(err, ShouldBeNil)
+			So(len(query.Result), ShouldEqual, 1)
+		})
+
+		Convey("Attempt to get the versions for a non-existent Dashboard ID", func() {
+			query := m.GetDashboardVersionsQuery{DashboardId: int64(999), OrgId: 1}
+
+			err := GetDashboardVersions(&query)
+			So(err, ShouldNotBeNil)
+			So(err, ShouldEqual, m.ErrNoVersionsForDashboardId)
+			So(len(query.Result), ShouldEqual, 0)
+		})
+
+		Convey("Get all versions for an updated dashboard", func() {
+			updateTestDashboard(savedDash, map[string]interface{}{
+				"tags": "different-tag",
+			})
+
+			query := m.GetDashboardVersionsQuery{DashboardId: savedDash.Id, OrgId: 1}
+			err := GetDashboardVersions(&query)
+
+			So(err, ShouldBeNil)
+			So(len(query.Result), ShouldEqual, 2)
+		})
+	})
+}

+ 9 - 18
pkg/services/sqlstore/logger.go

@@ -23,67 +23,59 @@ func NewXormLogger(level glog.Lvl, grafanaLog glog.Logger) *XormLogger {
 }
 
 // Error implement core.ILogger
-func (s *XormLogger) Err(v ...interface{}) error {
+func (s *XormLogger) Error(v ...interface{}) {
 	if s.level <= glog.LvlError {
 		s.grafanaLog.Error(fmt.Sprint(v...))
 	}
-	return nil
 }
 
 // Errorf implement core.ILogger
-func (s *XormLogger) Errf(format string, v ...interface{}) error {
+func (s *XormLogger) Errorf(format string, v ...interface{}) {
 	if s.level <= glog.LvlError {
 		s.grafanaLog.Error(fmt.Sprintf(format, v...))
 	}
-	return nil
 }
 
 // Debug implement core.ILogger
-func (s *XormLogger) Debug(v ...interface{}) error {
+func (s *XormLogger) Debug(v ...interface{}) {
 	if s.level <= glog.LvlDebug {
 		s.grafanaLog.Debug(fmt.Sprint(v...))
 	}
-	return nil
 }
 
 // Debugf implement core.ILogger
-func (s *XormLogger) Debugf(format string, v ...interface{}) error {
+func (s *XormLogger) Debugf(format string, v ...interface{}) {
 	if s.level <= glog.LvlDebug {
 		s.grafanaLog.Debug(fmt.Sprintf(format, v...))
 	}
-	return nil
 }
 
 // Info implement core.ILogger
-func (s *XormLogger) Info(v ...interface{}) error {
+func (s *XormLogger) Info(v ...interface{}) {
 	if s.level <= glog.LvlInfo {
 		s.grafanaLog.Info(fmt.Sprint(v...))
 	}
-	return nil
 }
 
 // Infof implement core.ILogger
-func (s *XormLogger) Infof(format string, v ...interface{}) error {
+func (s *XormLogger) Infof(format string, v ...interface{}) {
 	if s.level <= glog.LvlInfo {
 		s.grafanaLog.Info(fmt.Sprintf(format, v...))
 	}
-	return nil
 }
 
 // Warn implement core.ILogger
-func (s *XormLogger) Warning(v ...interface{}) error {
+func (s *XormLogger) Warn(v ...interface{}) {
 	if s.level <= glog.LvlWarn {
 		s.grafanaLog.Warn(fmt.Sprint(v...))
 	}
-	return nil
 }
 
 // Warnf implement core.ILogger
-func (s *XormLogger) Warningf(format string, v ...interface{}) error {
+func (s *XormLogger) Warnf(format string, v ...interface{}) {
 	if s.level <= glog.LvlWarn {
 		s.grafanaLog.Warn(fmt.Sprintf(format, v...))
 	}
-	return nil
 }
 
 // Level implement core.ILogger
@@ -103,8 +95,7 @@ func (s *XormLogger) Level() core.LogLevel {
 }
 
 // SetLevel implement core.ILogger
-func (s *XormLogger) SetLevel(l core.LogLevel) error {
-	return nil
+func (s *XormLogger) SetLevel(l core.LogLevel) {
 }
 
 // ShowSQL implement core.ILogger

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

@@ -0,0 +1,61 @@
+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]))
+
+	// before new dashboards where created with version 0, now they are always inserted with version 1
+	const setVersionTo1WhereZeroSQL = `UPDATE dashboard SET version = 1 WHERE version = 0`
+	mg.AddMigration("Set dashboard version to 1 where 0", new(RawSqlMigration).
+		Sqlite(setVersionTo1WhereZeroSQL).
+		Postgres(setVersionTo1WhereZeroSQL).
+		Mysql(setVersionTo1WhereZeroSQL))
+
+	const rawSQL = `INSERT INTO dashboard_version
+(
+	dashboard_id,
+	version,
+	parent_version,
+	restored_from,
+	created,
+	created_by,
+	message,
+	data
+)
+SELECT
+	dashboard.id,
+	dashboard.version,
+	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) {

+ 2 - 1
public/app/core/components/switch.ts

@@ -7,7 +7,7 @@ import coreModule from 'app/core/core_module';
 import Drop from 'tether-drop';
 
 var template = `
-<label for="check-{{ctrl.id}}" class="gf-form-label {{ctrl.labelClass}} pointer">
+<label for="check-{{ctrl.id}}" class="gf-form-label {{ctrl.labelClass}} pointer" ng-show="ctrl.label">
   {{ctrl.label}}
   <info-popover mode="right-normal" ng-if="ctrl.tooltip" position="top center">
     {{ctrl.tooltip}}
@@ -24,6 +24,7 @@ export class SwitchCtrl {
   checked: any;
   show: any;
   id: any;
+  label: string;
 
   /** @ngInject */
   constructor($scope, private $timeout) {

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

@@ -15,6 +15,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';

+ 41 - 28
public/app/core/directives/dash_edit_link.js

@@ -10,7 +10,9 @@ function ($, angular, coreModule) {
     'settings':    { src: 'public/app/features/dashboard/partials/settings.html'},
     'annotations': { src: 'public/app/features/annotations/partials/editor.html'},
     'templating':  { src: 'public/app/features/templating/partials/editor.html'},
-    'import':      { src: '<dash-import></dash-import>' }
+    'history':     { html: '<gf-dashboard-history dashboard="dashboard"></gf-dashboard-history>'},
+    'timepicker':  { src: 'public/app/features/dashboard/timepicker/dropdown.html' },
+    'import':      { html: '<dash-import></dash-import>' }
   };
 
   coreModule.default.directive('dashEditorView', function($compile, $location, $rootScope) {
@@ -18,48 +20,53 @@ function ($, angular, coreModule) {
       restrict: 'A',
       link: function(scope, elem) {
         var editorScope;
-        var lastEditor;
+        var lastEditView;
 
-        function hideEditorPane() {
+        function hideEditorPane(hideToShowOtherView) {
           if (editorScope) {
-            scope.appEvent('dash-editor-hidden', lastEditor);
-            editorScope.dismiss();
+            editorScope.dismiss(hideToShowOtherView);
+            scope.appEvent('dash-editor-hidden');
           }
         }
 
-        function showEditorPane(evt, payload, editview) {
-          if (editview) {
-            scope.contextSrv.editview = editViewMap[editview];
-            payload.src = scope.contextSrv.editview.src;
+        function showEditorPane(evt, options) {
+          if (options.editview) {
+            options.src = editViewMap[options.editview].src;
+            options.html = editViewMap[options.editview].html;
           }
 
-          if (lastEditor === payload.src) {
-            hideEditorPane();
+          if (lastEditView === options.editview) {
+            hideEditorPane(false);
             return;
           }
 
-          hideEditorPane();
+          hideEditorPane(true);
 
-          lastEditor = payload.src;
-          editorScope = payload.scope ? payload.scope.$new() : scope.$new();
+          lastEditView = options.editview;
+          editorScope = options.scope ? options.scope.$new() : scope.$new();
 
-          editorScope.dismiss = function() {
+          editorScope.dismiss = function(hideToShowOtherView) {
             editorScope.$destroy();
-            elem.empty();
-            lastEditor = null;
+            lastEditView = null;
             editorScope = null;
             elem.removeClass('dash-edit-view--open');
 
-            if (editview) {
+            if (!hideToShowOtherView) {
+              setTimeout(function() {
+                elem.empty();
+              }, 250);
+            }
+
+            if (options.editview) {
               var urlParams = $location.search();
-              if (editview === urlParams.editview) {
+              if (options.editview === urlParams.editview) {
                 delete urlParams.editview;
                 $location.search(urlParams);
               }
             }
           };
 
-          if (editview === 'import') {
+          if (options.editview === 'import') {
             var modalScope = $rootScope.$new();
             modalScope.$on("$destroy", function() {
               editorScope.dismiss();
@@ -74,15 +81,20 @@ function ($, angular, coreModule) {
             return;
           }
 
-          var view = payload.src;
-          if (view.indexOf('.html') > 0)  {
+          var view;
+          if (options.src)  {
+            view = angular.element(document.createElement('div'));
+            view.html('<div class="tabbed-view" ng-include="' + "'" + options.src + "'" + '"></div>');
+          } else {
             view = angular.element(document.createElement('div'));
-            view.append($('<div class="tabbed-view" ng-include="' + "'" + payload.src + "'" + '"></div>'));
+            view.addClass('tabbed-view');
+            view.html(options.html);
           }
 
           $compile(view)(editorScope);
 
           setTimeout(function() {
+            elem.empty();
             elem.append(view);
             setTimeout(function() {
               elem.addClass('dash-edit-view--open');
@@ -92,18 +104,19 @@ function ($, angular, coreModule) {
 
         scope.$watch("dashboardViewState.state.editview", function(newValue, oldValue) {
           if (newValue) {
-            showEditorPane(null, {}, newValue);
+            showEditorPane(null, {editview: newValue});
           } else if (oldValue) {
-            scope.contextSrv.editview = null;
-            if (lastEditor === editViewMap[oldValue]) {
+            if (lastEditView === oldValue) {
               hideEditorPane();
             }
           }
         });
 
-        scope.contextSrv.editview = null;
         scope.$on("$destroy", hideEditorPane);
-        scope.onAppEvent('hide-dash-editor', hideEditorPane);
+        scope.onAppEvent('hide-dash-editor', function() {
+          hideEditorPane(false);
+        });
+
         scope.onAppEvent('show-dash-editor', showEditorPane);
       }
     };

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

@@ -0,0 +1,77 @@
+///<reference path="../../headers/common.d.ts" />
+
+import angular from 'angular';
+import coreModule from '../core_module';
+
+export class DeltaCtrl {
+  observer: any;
+
+  /** @ngInject */
+  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: '&',
+    },
+    template: `<a class="diff-linenum btn btn-inverse btn-small" ng-click="ctrl.goToLine(link)">Line {{ line }}</a>`
+  };
+}
+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' },

+ 8 - 0
public/app/core/nav_model_srv.ts

@@ -167,6 +167,14 @@ export class NavModelSrv {
         clickHandler: () => dashNavCtrl.openEditView('annotations')
       });
 
+      if (!dashboard.meta.isHome) {
+        menu.push({
+          title: 'Version history',
+          icon: 'fa fa-fw fa-history',
+          clickHandler: () => dashNavCtrl.openEditView('history')
+        });
+      }
+
       menu.push({
         title: 'View JSON',
         icon: 'fa fa-fw fa-eye',

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

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

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

@@ -1,16 +1,19 @@
 define([
   './dashboard_ctrl',
   './alerting_srv',
+  './history/history',
   './dashboardLoaderSrv',
   './dashnav/dashnav',
   './submenu/submenu',
-  './saveDashboardAsCtrl',
+  './save_as_modal',
+  './save_modal',
   './shareModalCtrl',
   './shareSnapshotCtrl',
   './dashboard_srv',
   './viewStateSrv',
   './time_srv',
   './unsavedChangesSrv',
+  './unsaved_changes_modal',
   './timepicker/timepicker',
   './graphiteImportCtrl',
   './impression_store',
@@ -18,7 +21,6 @@ define([
   './import/dash_import',
   './export/export_modal',
   './export_data/export_data_modal',
-  './dash_list_ctrl',
   './ad_hoc_filters',
   './row/row_ctrl',
   './repeat_option/repeat_option',

+ 0 - 11
public/app/features/dashboard/dash_list_ctrl.ts

@@ -1,11 +0,0 @@
-///<reference path="../../headers/common.d.ts" />
-
-import coreModule from 'app/core/core_module';
-
-export class DashListCtrl {
-  /** @ngInject */
-  constructor() {
-  }
-}
-
-coreModule.controller('DashListCtrl', DashListCtrl);

+ 52 - 32
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.save(clone, {overwrite: true});
         }
       });
     }
@@ -74,7 +49,7 @@ export class DashboardSrv {
         yesText: "Save & Overwrite",
         icon: "fa-warning",
         onConfirm: () => {
-          this.saveDashboard({overwrite: true});
+          this.save(clone, {overwrite: true});
         }
       });
     }
@@ -90,28 +65,73 @@ export class DashboardSrv {
         icon: "fa-warning",
         altActionText: "Save As",
         onAltAction: () => {
-          this.saveDashboardAs();
+          this.showSaveAsModal();
         },
         onConfirm: () => {
-          this.saveDashboard({overwrite: true});
+          this.save(clone, {overwrite: true});
         }
       });
     }
   }
 
-  saveDashboardAs() {
+  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.showSaveAsModal();
+    }
+
+    if (this.dash.version > 0) {
+      return this.showSaveModal();
+    }
+
+    return this.save(this.dash.getSaveModelClone(), options);
+  }
+
+  showSaveAsModal() {
     var newScope = this.$rootScope.$new();
     newScope.clone = this.dash.getSaveModelClone();
     newScope.clone.editable = true;
     newScope.clone.hideControls = false;
 
     this.$rootScope.appEvent('show-modal', {
-      src: 'public/app/features/dashboard/partials/saveDashboardAs.html',
+      templateHtml: '<save-dashboard-as-modal dismiss="dismiss()"></save-dashboard-as-modal>',
       scope: newScope,
       modalClass: 'modal--narrow'
     });
   }
 
+  showSaveModal() {
+    this.$rootScope.appEvent('show-modal', {
+      templateHtml: '<save-dashboard-modal dismiss="dismiss()"></save-dashboard-modal>',
+      scope: this.$rootScope.$new(),
+      modalClass: 'modal--narrow'
+    });
+  }
 }
 
 coreModule.service('dashboardSrv', DashboardSrv);

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

@@ -44,7 +44,7 @@
 	<li ng-show="::ctrl.dashboard.meta.canSave">
 		<a ng-click="ctrl.saveDashboard()" bs-tooltip="'Save dashboard <br> CTRL+S'" data-placement="bottom"><i class="fa fa-save"></i></a>
 	</li>
-	<li ng-if="ctrl.dashboard.snapshot.originalUrl">
+	<li ng-if="::ctrl.dashboard.snapshot.originalUrl">
 		<a ng-href="{{ctrl.dashboard.snapshot.originalUrl}}" bs-tooltip="'Open original dashboard'" data-placement="bottom"><i class="fa fa-link"></i></a>
 	</li>
 </ul>

+ 3 - 3
public/app/features/dashboard/dashnav/dashnav.ts

@@ -87,8 +87,8 @@ export class DashNavCtrl {
       this.$rootScope.appEvent('panel-change-view', {fullscreen: false, edit: false});
     }
 
-    saveDashboard(options) {
-      return this.dashboardSrv.saveDashboard(options);
+    saveDashboard() {
+      return this.dashboardSrv.saveDashboard();
     }
 
     deleteDashboard() {
@@ -126,7 +126,7 @@ export class DashNavCtrl {
     }
 
     saveDashboardAs() {
-      return this.dashboardSrv.saveDashboardAs();
+      return this.dashboardSrv.showSaveAsModal();
     }
 
     viewJson() {

+ 146 - 0
public/app/features/dashboard/history/history.html

@@ -0,0 +1,146 @@
+<div class="tabbed-view-header">
+	<h2 class="tabbed-view-title">
+		Version history
+	</h2>
+
+	<ul class="gf-tabs">
+		<li class="gf-tabs-item" >
+			<a class="gf-tabs-link" ng-click="ctrl.switchMode('list');" ng-class="{active: ctrl.mode === 'list'}">
+				List
+			</a>
+		</li>
+		<li class="gf-tabs-item" ng-show="ctrl.mode === 'compare'">
+			<span class="active gf-tabs-link">
+				Version Comparison
+			</span>
+		</li>
+	</ul>
+
+	<button class="tabbed-view-close-btn" ng-click="ctrl.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 history list&hellip;</em>
+		</div>
+
+		<div ng-if="!ctrl.loading">
+      <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 class="filter-table__switch-cell" bs-tooltip="!revision.checked && ctrl.canCompare ? 'You can only compare 2 versions at a time' : ''" data-placement="right">
+                <gf-form-switch switch-class="gf-form-switch--table-cell"
+                                checked="revision.checked"
+                                on-change="ctrl.revisionSelectionChanged()"
+																ng-disabled="!revision.checked && ctrl.canCompare">
+                </gf-form-switch>
+              </td>
+              <td class="text-center">{{revision.version}}</td>
+              <td>{{revision.createdDateString}}</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-history"></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;Latest
+                </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">
+            <button	type="button"
+                class="btn gf-form-button btn-secondary"
+                ng-if="ctrl.revisions.length > 1"
+                ng-disabled="!ctrl.canCompare"
+                ng-click="ctrl.getDiff(ctrl.diff)"
+								bs-tooltip="ctrl.canCompare ? '' : 'Select 2 versions to start comparing'" data-placement="bottom">
+              <i class="fa fa-code-fork" ></i>&nbsp;&nbsp;Compare versions
+            </button>
+            <button  type="button"
+                class="btn gf-form-button btn-inverse"
+                ng-if="ctrl.revisions.length >= ctrl.limit"
+                ng-click="ctrl.addToLog()"
+                ng-disabled="ctrl.isLastPage()">
+              Show more versions
+            </button>
+          </div>
+        </div>
+      </div>
+		</div>
+	</div>
+
+	<div class="edit-tab-with-sidemenu" ng-if="ctrl.mode === 'compare'">
+    <aside class="edit-sidemenu-aside">
+      <ul class="edit-sidemenu">
+        <li ng-class="{active: ctrl.diff === 'basic'}"><a ng-click="ctrl.getDiff('basic')" href="">Change Summary</a></li>
+        <li ng-class="{active: ctrl.diff === 'html'}"><a ng-click="ctrl.getDiff('json')" href="">JSON Diff</a></li>
+      </ul>
+    </aside>
+
+    <div class="edit-tab-content">
+      <div ng-if="ctrl.loading">
+        <i class="fa fa-spinner fa-spin"></i>
+        <em>Fetching changes&hellip;</em>
+      </div>
+
+      <div ng-if="!ctrl.loading">
+        <a  type="button"
+            class="btn gf-form-button btn-secondary pull-right"
+            ng-click="ctrl.restore(ctrl.baseInfo.version)"
+            ng-if="ctrl.isNewLatest">
+          <i class="fa fa-history" ></i>&nbsp;&nbsp;Restore to version {{ctrl.baseInfo.version}}
+        </a>
+        <h4>
+          Comparing Version {{ctrl.baseInfo.version}}
+          <i class="fa fa-arrows-h"></i>
+					Version {{ctrl.newInfo.version}}
+          <cite class="muted" ng-if="ctrl.isNewLatest">(Latest)</cite>
+        </h4>
+        <section>
+          <p class="small muted">
+          <strong>Version {{ctrl.newInfo.version}}</strong> updated by
+          <span>{{ctrl.newInfo.createdBy}} </span>
+          <span>{{ctrl.newInfo.ageString}}</span>
+          <span> - {{ctrl.newInfo.message}}</span>
+          </p>
+          <p class="small muted">
+          <strong>Version {{ctrl.baseInfo.version}}</strong> updated by
+          <span>{{ctrl.baseInfo.createdBy}} </span>
+          <span>{{ctrl.baseInfo.ageString}}</span>
+          <span> - {{ctrl.baseInfo.message}}</span>
+          </p>
+        </section>
+        <div id="delta" diff-delta>
+          <div class="delta-basic" ng-show="ctrl.diff === 'basic'" compile="ctrl.delta.basic"></div>
+          <div class="delta-html" ng-show="ctrl.diff === 'json'" compile="ctrl.delta.json"></div>
+        </div>
+      </div>
+    </div>
+  </div>
+</div>

+ 203 - 0
public/app/features/dashboard/history/history.ts

@@ -0,0 +1,203 @@
+///<reference path="../../../headers/common.d.ts" />
+
+import './history_srv';
+
+import _ from 'lodash';
+import angular from 'angular';
+import moment from 'moment';
+
+import {DashboardModel} from '../model';
+import {HistoryListOpts, RevisionsModel, CalculateDiffOptions, HistorySrv} from './history_srv';
+
+export class HistoryListCtrl {
+  appending: boolean;
+  dashboard: DashboardModel;
+  delta: { basic: string; json: string; };
+  diff: string;
+  limit: number;
+  loading: boolean;
+  max: number;
+  mode: string;
+  revisions: RevisionsModel[];
+  start: number;
+  newInfo: RevisionsModel;
+  baseInfo: RevisionsModel;
+  canCompare: boolean;
+  isNewLatest: boolean;
+
+  /** @ngInject */
+  constructor(private $scope,
+              private $rootScope,
+              private $location,
+              private $window,
+              private $timeout,
+              private $q,
+              private historySrv: HistorySrv) {
+
+    this.appending = false;
+    this.diff = 'basic';
+    this.limit = 10;
+    this.loading = false;
+    this.max = 2;
+    this.mode = 'list';
+    this.start = 0;
+    this.canCompare = false;
+
+    this.$rootScope.onAppEvent('dashboard-saved', this.onDashboardSaved.bind(this), $scope);
+    this.resetFromSource();
+  }
+
+  onDashboardSaved() {
+    this.resetFromSource();
+  }
+
+  switchMode(mode: string) {
+    this.mode = mode;
+    if (this.mode === 'list') {
+      this.reset();
+    }
+  }
+
+  dismiss() {
+    this.$rootScope.appEvent('hide-dash-editor');
+  }
+
+  addToLog() {
+    this.start = this.start + this.limit;
+    this.getLog(true);
+  }
+
+  revisionSelectionChanged() {
+    let selected = _.filter(this.revisions, {checked: true}).length;
+    this.canCompare = selected === 2;
+  }
+
+  formatDate(date) {
+    return this.dashboard.formatDate(date);
+  }
+
+  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) {
+    this.diff = diff;
+    this.mode = 'compare';
+
+    // have it already been fetched?
+    if (this.delta[this.diff]) {
+      return this.$q.when(this.delta[this.diff]);
+    }
+
+    const selected = _.filter(this.revisions, {checked: true});
+
+    this.newInfo = selected[0];
+    this.baseInfo = selected[1];
+    this.isNewLatest = this.newInfo.version === this.dashboard.version;
+
+    this.loading = true;
+    const options: CalculateDiffOptions = {
+      new: {
+        dashboardId: this.dashboard.id,
+        version: this.newInfo.version,
+      },
+      base: {
+        dashboardId: this.dashboard.id,
+        version: this.baseInfo.version,
+      },
+      diffType: diff,
+    };
+
+    return this.historySrv.calculateDiff(options).then(response => {
+      this.delta[this.diff] = response;
+    }).catch(() => {
+      this.mode = 'list';
+    }).finally(() => {
+      this.loading = false;
+    });
+  }
+
+  getLog(append = false) {
+    this.loading = !append;
+    this.appending = append;
+    const options: HistoryListOpts = {
+      limit: this.limit,
+      start: this.start,
+    };
+
+    return this.historySrv.getHistoryList(this.dashboard, options).then(revisions => {
+      // set formated dates & default values
+      for (let rev of revisions) {
+        rev.createdDateString = this.formatDate(rev.created);
+        rev.ageString = this.formatBasicDate(rev.created);
+        rev.checked = false;
+      }
+
+      this.revisions = append ? this.revisions.concat(revisions) : revisions;
+
+    }).catch(err => {
+      this.loading = false;
+    }).finally(() => {
+      this.loading = false;
+      this.appending = false;
+    });
+  }
+
+  isLastPage() {
+    return _.find(this.revisions, rev => rev.version === 1);
+  }
+
+  reset() {
+    this.delta = { basic: '', json: '' };
+    this.diff = 'basic';
+    this.mode = 'list';
+    this.revisions = _.map(this.revisions, rev => _.extend({}, rev, { checked: false }));
+    this.canCompare = false;
+    this.start = 0;
+    this.isNewLatest = false;
+  }
+
+  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-history',
+      yesText: `Yes, restore to version ${version}`,
+      onConfirm: this.restoreConfirm.bind(this, version),
+    });
+  }
+
+  restoreConfirm(version: number) {
+    this.loading = true;
+    return this.historySrv.restoreDashboard(this.dashboard, version).then(response => {
+      this.$location.path('dashboard/db/' + response.slug);
+      this.$rootScope.appEvent('alert-success', ['Dashboard restored', 'Restored from version ' + version]);
+    }).catch(() => {
+      this.mode = 'list';
+      this.loading = false;
+    });
+  }
+}
+
+export function dashboardHistoryDirective() {
+  return {
+    restrict: 'E',
+    templateUrl: 'public/app/features/dashboard/history/history.html',
+    controller: HistoryListCtrl,
+    bindToController: true,
+    controllerAs: 'ctrl',
+    scope: {
+      dashboard: "="
+    }
+  };
+}
+
+angular.module('grafana.directives').directive('gfDashboardHistory', dashboardHistoryDirective);

+ 55 - 0
public/app/features/dashboard/history/history_srv.ts

@@ -0,0 +1,55 @@
+///<reference path="../../../headers/common.d.ts" />
+
+import _ from 'lodash';
+import coreModule from 'app/core/core_module';
+import {DashboardModel} from '../model';
+
+export interface HistoryListOpts {
+  limit: number;
+  start: number;
+}
+
+export interface RevisionsModel {
+  id: number;
+  checked: boolean;
+  dashboardId: number;
+  parentVersion: number;
+  version: number;
+  created: Date;
+  createdBy: string;
+  message: string;
+}
+
+export interface CalculateDiffOptions {
+  new: DiffTarget;
+  base: DiffTarget;
+  diffType: string;
+}
+
+export interface DiffTarget {
+  dashboardId: number;
+  version: number;
+  unsavedDashboard?: DashboardModel; // when doing diffs against unsaved dashboard version
+}
+
+export class HistorySrv {
+  /** @ngInject */
+  constructor(private backendSrv, private $q) {}
+
+  getHistoryList(dashboard: DashboardModel, options: HistoryListOpts) {
+    const id = dashboard && dashboard.id ? dashboard.id : void 0;
+    return id ? this.backendSrv.get(`api/dashboards/id/${id}/versions`, options) : this.$q.when([]);
+  }
+
+  calculateDiff(options: CalculateDiffOptions) {
+    return this.backendSrv.post('api/dashboards/calculate-diff', options);
+  }
+
+  restoreDashboard(dashboard: DashboardModel, version: number) {
+    const id = dashboard && dashboard.id ? dashboard.id : void 0;
+    const url = `api/dashboards/id/${id}/restore`;
+    return id && _.isNumber(version) ? this.backendSrv.post(url, { version }) : this.$q.when({});
+  }
+}
+
+coreModule.service('historySrv', HistorySrv);

+ 1 - 1
public/app/features/dashboard/model.ts

@@ -244,7 +244,7 @@ export class DashboardModel {
     return newPanel;
   }
 
-  formatDate(date, format) {
+  formatDate(date, format?) {
     date = moment.isMoment(date) ? date : moment(date);
     format = format || 'YYYY-MM-DD HH:mm:ss';
     this.timezone = this.getTimezone();

+ 0 - 10
public/app/features/dashboard/partials/dash_list.html

@@ -1,10 +0,0 @@
-<navbar title="Dashboards" title-url="dashboards" icon="icon-gf icon-gf-dashboard">
-</navbar>
-
-<div class="page-container">
-  <div class="page-header">
-		<h1>Dashboards</h1>
-	</div>
-</div>
-
-

+ 0 - 35
public/app/features/dashboard/partials/graphiteImport.html

@@ -1,35 +0,0 @@
-<div ng-controller="GraphiteImportCtrl" ng-init="init()">
-
-	<div ng-if="datasources.length > 0">
-		<h2 class="page-heading">Load dashboard from Graphite-Web</h2>
-
-		<div class="gf-form-group">
-			<div class="gf-form-inline">
-				<div class="gf-form">
-					<span class="gf-form-label width-10">Data source</span>
-				</div>
-				<div class="gf-form">
-					<div class="gf-form-select-wrapper">
-						<select type="text" ng-model="options.sourceName" class="gf-form-input gf-size-auto" ng-options="f for f in datasources">
-						</select>
-					</div>
-				</div>
-				<div class="gf-form">
-					<button class="btn btn-success pull-right" ng-click="listAll()">List dashboards</button>
-				</div>
-			</div>
-		</div>
-
-		<table class="grafana-options-table" style="margin-top: 20px;">
-			<tr ng-repeat="dash in dashboards">
-				<td style="">{{dash.name}}</td>
-				<td>
-					<button class="btn btn-inverse pull-right" ng-click="import(dash.name)">
-						Load
-					</button>
-				</td>
-			</tr>
-		</table>
-
-	</div>
-</div>

+ 0 - 27
public/app/features/dashboard/partials/saveDashboardAs.html

@@ -1,27 +0,0 @@
-<div class="modal-body" ng-controller="SaveDashboardAsCtrl" ng-init="init();">
-	<div class="modal-header">
-		<h2 class="modal-header-title">
-			<i class="fa fa-copy"></i>
-			<span class="p-l-1">Save As...</span>
-		</h2>
-
-		<a class="modal-header-close" ng-click="dismiss();">
-			<i class="fa fa-remove"></i>
-		</a>
-	</div>
-
-	<div class="modal-content">
-		<div class="p-t-2">
-			<div class="gf-form">
-				<label class="gf-form-label">New name</label>
-				<input type="text" class="gf-form-input" ng-model="clone.title" give-focus="true" ng-keydown="keyDown($event)">
-			</div>
-		</div>
-
-		<div class="gf-form-button-row text-center">
-			<a class="btn btn-success" ng-click="saveClone();">Save</a>
-			<a class="btn-text" ng-click="dismiss();">Cancel</a>
-		</div>
-	</div>
-</div>
-

+ 0 - 64
public/app/features/dashboard/saveDashboardAsCtrl.js

@@ -1,64 +0,0 @@
-define([
-  'angular',
-],
-function (angular) {
-  'use strict';
-
-  var module = angular.module('grafana.controllers');
-
-  module.controller('SaveDashboardAsCtrl', function($scope, backendSrv, $location) {
-
-    $scope.init = function() {
-      $scope.clone.id = null;
-      $scope.clone.editable = true;
-      $scope.clone.title = $scope.clone.title + " Copy";
-
-      // remove alerts
-      $scope.clone.rows.forEach(function(row) {
-        row.panels.forEach(function(panel) {
-          delete panel.alert;
-        });
-      });
-
-      // remove auto update
-      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();
-      }
-    };
-
-    $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});
-            }
-          });
-        }
-      });
-    };
-  });
-
-});

+ 79 - 0
public/app/features/dashboard/save_as_modal.ts

@@ -0,0 +1,79 @@
+///<reference path="../../headers/common.d.ts" />
+
+import coreModule from 'app/core/core_module';
+
+const  template = `
+<div class="modal-body">
+	<div class="modal-header">
+		<h2 class="modal-header-title">
+			<i class="fa fa-copy"></i>
+			<span class="p-l-1">Save As...</span>
+		</h2>
+
+		<a class="modal-header-close" ng-click="ctrl.dismiss();">
+			<i class="fa fa-remove"></i>
+		</a>
+	</div>
+
+	<form name="ctrl.saveForm" ng-submit="ctrl.save()" class="modal-content" novalidate>
+		<div class="p-t-2">
+			<div class="gf-form">
+				<label class="gf-form-label">New name</label>
+				<input type="text" class="gf-form-input" ng-model="ctrl.clone.title" give-focus="true" required>
+			</div>
+		</div>
+
+		<div class="gf-form-button-row text-center">
+			<button type="submit" class="btn btn-success" ng-disabled="ctrl.saveForm.$invalid">Save</button>
+			<a class="btn-text" ng-click="ctrl.dismiss();">Cancel</a>
+		</div>
+	</form>
+</div>
+`;
+
+export class SaveDashboardAsModalCtrl {
+  clone: any;
+  dismiss: () => void;
+
+  /** @ngInject */
+  constructor(private $scope, private dashboardSrv) {
+    var dashboard = this.dashboardSrv.getCurrent();
+    this.clone = dashboard.getSaveModelClone();
+    this.clone.id = null;
+    this.clone.title += ' Copy';
+    this.clone.editable = true;
+    this.clone.hideControls = false;
+
+    // remove alerts
+    this.clone.rows.forEach(row => {
+      row.panels.forEach(panel => {
+        delete panel.alert;
+      });
+    });
+
+    delete this.clone.autoUpdate;
+  }
+
+  save() {
+    return this.dashboardSrv.save(this.clone).then(this.dismiss);
+  }
+
+  keyDown(evt) {
+    if (evt.keyCode === 13) {
+      this.save();
+    }
+  }
+}
+
+export function saveDashboardAsDirective() {
+  return {
+    restrict: 'E',
+    template: template,
+    controller: SaveDashboardAsModalCtrl,
+    bindToController: true,
+    controllerAs: 'ctrl',
+    scope: {dismiss: "&"}
+  };
+}
+
+coreModule.directive('saveDashboardAsModal',  saveDashboardAsDirective);

+ 88 - 0
public/app/features/dashboard/save_modal.ts

@@ -0,0 +1,88 @@
+///<reference path="../../headers/common.d.ts" />
+
+import coreModule from 'app/core/core_module';
+
+const  template = `
+<div class="modal-body">
+	<div class="modal-header">
+		<h2 class="modal-header-title">
+			<i class="fa fa-save"></i>
+			<span class="p-l-1">Save changes</span>
+		</h2>
+
+		<a class="modal-header-close" ng-click="ctrl.dismiss();">
+			<i class="fa fa-remove"></i>
+		</a>
+	</div>
+
+	<form name="ctrl.saveForm" ng-submit="ctrl.save()" class="modal-content" novalidate>
+		<h6 class="text-center">Add a note to describe your changes</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="ctrl.message"
+						ng-model-options="{allowInvalid: true}"
+						ng-maxlength="this.max"
+						autocomplete="off"
+						required />
+					<small class="gf-form-hint-text muted" ng-cloak>
+						<span ng-class="{'text-error': ctrl.saveForm.message.$invalid && ctrl.saveForm.message.$dirty }">
+							{{ctrl.message.length || 0}}
+						</span>
+						/ {{ctrl.max}} characters
+					</small>
+				</label>
+			</div>
+		</div>
+
+		<div class="gf-form-button-row text-center">
+			<button type="submit" class="btn btn-success" ng-disabled="ctrl.saveForm.$invalid">Save</button>
+			<button class="btn btn-inverse" ng-click="ctrl.dismiss();">Cancel</button>
+		</div>
+	</form>
+</div>
+`;
+
+export class SaveDashboardModalCtrl {
+  message: string;
+  max: number;
+  saveForm: any;
+  dismiss: () => void;
+
+  /** @ngInject */
+  constructor(private $scope, private dashboardSrv) {
+    this.message = '';
+    this.max = 64;
+  }
+
+  save() {
+    if (!this.saveForm.$valid) {
+      return;
+    }
+
+    var dashboard = this.dashboardSrv.getCurrent();
+    var saveModel = dashboard.getSaveModelClone();
+    var options = {message: this.message};
+
+    return this.dashboardSrv.save(saveModel, options).then(this.dismiss);
+  }
+}
+
+export function saveDashboardModalDirective() {
+  return {
+    restrict: 'E',
+    template: template,
+    controller: SaveDashboardModalCtrl,
+    bindToController: true,
+    controllerAs: 'ctrl',
+    scope: {dismiss: "&"}
+  };
+}
+
+coreModule.directive('saveDashboardModal',  saveDashboardModalDirective);

+ 315 - 0
public/app/features/dashboard/specs/history_ctrl_specs.ts

@@ -0,0 +1,315 @@
+import {describe, beforeEach, it, sinon, expect, angularMocks} from 'test/lib/common';
+
+import _ from 'lodash';
+import {HistoryListCtrl} from 'app/features/dashboard/history/history';
+import { versions, compare, restore } from 'test/mocks/history-mocks';
+import config from 'app/core/config';
+
+describe('HistoryListCtrl', 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 historySrv;
+  var $rootScope;
+  beforeEach(function() {
+    historySrv = {
+      getHistoryList: sinon.stub(),
+      calculateDiff: sinon.stub(),
+      restoreDashboard: sinon.stub(),
+    };
+    $rootScope = {
+      appEvent: sinon.spy(),
+      onAppEvent: sinon.spy(),
+    };
+  });
+
+  describe('when the history list component is loaded', function() {
+    var deferred;
+
+    beforeEach(angularMocks.inject(($controller, $q) => {
+      deferred = $q.defer();
+      historySrv.getHistoryList.returns(deferred.promise);
+      ctx.ctrl = $controller(HistoryListCtrl, {
+        historySrv,
+        $rootScope,
+        $scope: ctx.scope,
+      }, {
+        dashboard: {
+          id: 2,
+          version: 3,
+          formatDate: sinon.stub().returns('date'),
+        }
+      });
+    }));
+
+    it('should immediately attempt to fetch the history list', function() {
+      expect(historySrv.getHistoryList.calledOnce).to.be(true);
+    });
+
+    describe('and the history list 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: '', json: '' });
+        expect(ctx.ctrl.canCompare).to.be(false);
+        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.reset();
+        var actual = _.filter(ctx.ctrl.revisions, rev => !rev.checked);
+        expect(actual.length).to.be(4);
+      });
+
+    });
+
+    describe('and fetching the history list fails', function() {
+      beforeEach(function() {
+        deferred.reject(new Error('HistoryListError'));
+        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: '', json: '' });
+        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 have an empty revisions list', function() {
+        expect(ctx.ctrl.revisions).to.eql([]);
+      });
+    });
+
+    describe('should update the history list 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);
+      });
+    });
+  });
+
+  describe('when the user wants to compare two revisions', function() {
+    var deferred;
+
+    beforeEach(angularMocks.inject(($controller, $q) => {
+      deferred = $q.defer();
+      historySrv.getHistoryList.returns($q.when(versionsResponse));
+      historySrv.calculateDiff.returns(deferred.promise);
+      ctx.ctrl = $controller(HistoryListCtrl, {
+        historySrv,
+        $rootScope,
+        $scope: ctx.scope,
+      }, {
+        dashboard: {
+          id: 2,
+          version: 3,
+          formatDate: sinon.stub().returns('date'),
+        }
+      });
+
+      ctx.ctrl.$scope.onDashboardSaved = sinon.spy();
+      ctx.ctrl.$scope.$apply();
+    }));
+
+    it('should have already fetched the history list', function() {
+      expect(historySrv.getHistoryList.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.canCompare).to.be(false);
+
+      // single value
+      ctx.ctrl.revisions = [{checked: true}];
+      ctx.ctrl.revisionSelectionChanged();
+      expect(ctx.ctrl.canCompare).to.be(false);
+
+      // both values in range
+      ctx.ctrl.revisions = [{checked: true}, {checked: true}];
+      ctx.ctrl.revisionSelectionChanged();
+      expect(ctx.ctrl.canCompare).to.be(true);
+    });
+
+    describe('and the basic diff is successfully fetched', function() {
+      beforeEach(function() {
+        deferred.resolve(compare('basic'));
+        ctx.ctrl.revisions[1].checked = true;
+        ctx.ctrl.revisions[3].checked = true;
+        ctx.ctrl.getDiff('basic');
+        ctx.ctrl.$scope.$apply();
+      });
+
+      it('should fetch the basic diff if two valid versions are selected', function() {
+        expect(historySrv.calculateDiff.calledOnce).to.be(true);
+        expect(ctx.ctrl.delta.basic).to.be('<div></div>');
+        expect(ctx.ctrl.delta.json).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('json'));
+        ctx.ctrl.revisions[1].checked = true;
+        ctx.ctrl.revisions[3].checked = true;
+        ctx.ctrl.getDiff('json');
+        ctx.ctrl.$scope.$apply();
+      });
+
+      it('should fetch the json diff if two valid versions are selected', function() {
+        expect(historySrv.calculateDiff.calledOnce).to.be(true);
+        expect(ctx.ctrl.delta.basic).to.be('');
+        expect(ctx.ctrl.delta.json).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('json');
+      });
+
+      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.revisions[3].checked = true;
+        ctx.ctrl.revisions[1].checked = true;
+        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(historySrv.calculateDiff.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.revisions[3].checked = true;
+        ctx.ctrl.revisions[1].checked = true;
+        ctx.ctrl.getDiff('basic');
+        ctx.ctrl.$scope.$apply();
+      });
+
+      it('should fetch the diff if two valid versions are selected', function() {
+        expect(historySrv.calculateDiff.calledOnce).to.be(true);
+      });
+
+      it('should return to the history list 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 have an empty delta/changeset', function() {
+        expect(ctx.ctrl.delta).to.eql({ basic: '', json: '' });
+      });
+    });
+  });
+
+  describe('when the user wants to restore a revision', function() {
+    var deferred;
+
+    beforeEach(angularMocks.inject(($controller, $q) => {
+      deferred = $q.defer();
+      historySrv.getHistoryList.returns($q.when(versionsResponse));
+      historySrv.restoreDashboard.returns(deferred.promise);
+      ctx.ctrl = $controller(HistoryListCtrl, {
+        historySrv,
+        contextSrv: { user: { name: 'Carlos' }},
+        $rootScope,
+        $scope: ctx.scope,
+      });
+      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('and restore fails to fetch', function() {
+      beforeEach(function() {
+        deferred.reject(new Error('RestoreError'));
+        ctx.ctrl.restoreConfirm(RESTORE_ID);
+        try {
+          // this throws error, due to promise rejection
+          ctx.ctrl.$scope.$apply();
+        } catch (e) {}
+      });
+
+      it('should indicate loading has finished', function() {
+        expect(ctx.ctrl.loading).to.be(false);
+      });
+
+    });
+  });
+});

+ 70 - 0
public/app/features/dashboard/specs/history_srv_specs.ts

@@ -0,0 +1,70 @@
+import {describe, beforeEach, it, sinon, expect, angularMocks} from 'test/lib/common';
+
+import helpers from 'test/specs/helpers';
+import HistorySrv from '../history/history_srv';
+import { versions, compare, restore } from 'test/mocks/history-mocks';
+
+describe('historySrv', function() {
+  var ctx = new helpers.ServiceTestContext();
+
+  var versionsResponse = versions();
+  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/id/:id/versions').respond(versionsResponse);
+    $httpBackend.whenRoute('POST', 'api/dashboards/id/:id/restore')
+      .respond(function(method, url, data, headers, params) {
+        const parsedData = JSON.parse(data);
+        return [200, restoreResponse(parsedData.version)];
+      });
+  }));
+  beforeEach(ctx.createService('historySrv'));
+
+  describe('getHistoryList', function() {
+    it('should return a versions array for the given dashboard id', function(done) {
+      ctx.service.getHistoryList({ 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.getHistoryList({ }).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.getHistoryList().then(function(versions) {
+        expect(versions).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();
+    });
+  });
+});

+ 1 - 2
public/app/features/dashboard/timepicker/timepicker.ts

@@ -34,7 +34,6 @@ export class TimePickerCtrl {
     $rootScope.onAppEvent('shift-time-backward', () => this.move(-1), $scope);
     $rootScope.onAppEvent('refresh', () => this.init(), $scope);
     $rootScope.onAppEvent('dash-editor-hidden', () => this.isOpen = false, $scope);
-
     this.init();
   }
 
@@ -114,7 +113,7 @@ export class TimePickerCtrl {
     this.refresh.options.unshift({text: 'off'});
 
     this.$rootScope.appEvent('show-dash-editor', {
-      src: 'public/app/features/dashboard/timepicker/dropdown.html',
+      editview: 'timepicker',
       scope: this.$scope,
       cssClass: 'gf-timepicker-dropdown',
     });

+ 22 - 24
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;
@@ -134,34 +134,31 @@ function(angular, _) {
       return currentJson !== originalJson;
     };
 
-    p.open_modal = function() {
-      var tracker = this;
+    p.discardChanges = function() {
+      this.original = null;
+      this.gotoNext();
+    };
 
-      var modalScope = this.scope.$new();
-      modalScope.ignore = function() {
-        tracker.original = null;
-        tracker.goto_next();
-      };
+    p.open_modal = function() {
+      $rootScope.appEvent('show-modal', {
+        templateHtml: '<unsaved-changes-modal dismiss="dismiss()"></unsaved-changes-modal>',
+        modalClass: 'modal--narrow confirm-modal'
+      });
+    };
 
-      modalScope.save = function() {
-        var cancel = $rootScope.$on('dashboard-saved', function() {
-          cancel();
-          $timeout(function() {
-            tracker.goto_next();
-          });
+    p.saveChanges = function() {
+      var self = this;
+      var cancel = $rootScope.$on('dashboard-saved', function() {
+        cancel();
+        $timeout(function() {
+          self.gotoNext();
         });
-
-        $rootScope.$emit('save-dashboard');
-      };
-
-      $rootScope.appEvent('show-modal', {
-        src: 'public/app/partials/unsaved-changes.html',
-        modalClass: 'confirm-modal',
-        scope: modalScope,
       });
+
+      $rootScope.appEvent('save-dashboard');
     };
 
-    p.goto_next = function() {
+    p.gotoNext = function() {
       var baseLen = $location.absUrl().length - $location.url().length;
       var nextUrl = this.next.substring(baseLen);
       $location.url(nextUrl);
@@ -169,7 +166,8 @@ function(angular, _) {
 
     this.Tracker = Tracker;
     this.init = function(dashboard, scope) {
-      return new Tracker(dashboard, scope, 1000);
+      this.tracker = new Tracker(dashboard, scope, 1000);
+      return this.tracker;
     };
   });
 });

+ 63 - 0
public/app/features/dashboard/unsaved_changes_modal.ts

@@ -0,0 +1,63 @@
+///<reference path="../../headers/common.d.ts" />
+
+import coreModule from 'app/core/core_module';
+
+const  template = `
+<div class="modal-body">
+  <div class="modal-header">
+    <h2 class="modal-header-title">
+      <i class="fa fa-exclamation"></i>
+      <span class="p-l-1">Unsaved changes</span>
+    </h2>
+
+    <a class="modal-header-close" ng-click="dismiss();">
+      <i class="fa fa-remove"></i>
+    </a>
+  </div>
+
+  <div class="modal-content text-center">
+
+    <div class="confirm-modal-text">
+      Do you want to save you changes?
+    </div>
+
+    <div class="confirm-modal-buttons">
+      <button type="button" class="btn btn-inverse" ng-click="ctrl.dismiss()">Cancel</button>
+      <button type="button" class="btn btn-danger" ng-click="ctrl.discard()">Discard</button>
+      <button type="button" class="btn btn-success" ng-click="ctrl.save()">Save</button>
+    </div>
+  </div>
+</div>
+`;
+
+export class UnsavedChangesModalCtrl {
+  clone: any;
+  dismiss: () => void;
+
+  /** @ngInject */
+  constructor(private $rootScope, private unsavedChangesSrv) {
+  }
+
+  discard() {
+    this.dismiss();
+    this.unsavedChangesSrv.tracker.discardChanges();
+  }
+
+  save() {
+    this.dismiss();
+    this.unsavedChangesSrv.tracker.saveChanges();
+  }
+}
+
+export function unsavedChangesModalDirective() {
+  return {
+    restrict: 'E',
+    template: template,
+    controller: UnsavedChangesModalCtrl,
+    bindToController: true,
+    controllerAs: 'ctrl',
+    scope: {dismiss: "&"}
+  };
+}
+
+coreModule.directive('unsavedChangesModal', unsavedChangesModalDirective);

+ 0 - 27
public/app/partials/unsaved-changes.html

@@ -1,27 +0,0 @@
-<div class="modal-body">
-	<div class="modal-header">
-		<h2 class="modal-header-title">
-		<i class="fa fa-exclamation"></i>
-			<span class="p-l-1">Unsaved changes</span>
-		</h2>
-
-		<a class="modal-header-close" ng-click="dismiss();">
-			<i class="fa fa-remove"></i>
-		</a>
-	</div>
-
-	<div class="modal-content text-center">
-
-		<div class="confirm-modal-text">
-			What do you want to do?
-		</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>
-	</div>
-
-</div>
-

+ 1 - 1
public/dashboards/home.json

@@ -101,6 +101,6 @@
     "list": []
   },
   "schemaVersion": 12,
-  "version": 2,
+  "version": 0,
   "links": []
 }

+ 1 - 0
public/sass/_grafana.scss

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

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

@@ -280,3 +280,25 @@ $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-group-bg:         $dark-4;
+$diff-arrow-color:      $white;
+
+$diff-json-bg:          $dark-4;
+$diff-json-fg:          $gray-5;
+
+$diff-json-added:       #457740;
+$diff-json-deleted:     #a04338;
+
+$diff-json-old:         #a04338;
+$diff-json-new:         #457740;
+
+$diff-json-changed-fg:  $gray-5;
+$diff-json-changed-num: $text-color;
+
+$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;

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

@@ -41,6 +41,7 @@
   }
 
   &.disabled,
+  &[disabled],
   &:disabled {
     cursor: $cursor-disabled;
     opacity: .65;
@@ -118,5 +119,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;
+  }
+}
 
 

+ 8 - 9
public/sass/components/_filter-table.scss

@@ -19,24 +19,21 @@
 
 .filter-table tr {
   background: $grafanaListBackground;
-  border-bottom: 2px solid $page-bg;
+  border-bottom: 3px solid $page-bg;
 }
 
 .filter-table th {
   width: auto;
-  padding: 10px 15px 10px 0;
+  padding: $table-cell-padding;
   text-align: left;
-
-  &:first-child {
-    padding-left: 15px;
-  }
 }
 
 .filter-table td {
-  padding: 15px 15px 15px 0;
+  padding: $table-cell-padding;
 
-  &:first-child {
-    padding-left: 15px;
+  &.filter-table__switch-cell {
+    padding: 0;
+    border-right: 3px solid $page-bg;
   }
 }
 
@@ -55,3 +52,5 @@
 .filter-table .expanded > td {
   padding-bottom: 0;
 }
+
+

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

@@ -163,6 +163,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;
@@ -222,10 +232,6 @@ $gf-form-margin: 0.25rem;
   flex-grow: 0;
 }
 
-.gf-form-switch {
-  margin-right: $gf-form-margin;
-}
-
 .natural-language-input {
   &input[type="number"] {
     font-size: $font-size-base;

+ 16 - 1
public/sass/components/_switch.scss

@@ -11,6 +11,7 @@ $switch-height: 1.5rem;
   max-width: 4.5rem;
   flex-grow: 1;
   min-width: 4.0rem;
+  margin-right: $gf-form-margin;
 
   input {
     position: absolute;
@@ -42,8 +43,10 @@ $switch-height: 1.5rem;
     color: #fff;
     font-size: $font-size-sm;
     text-align: center;
-    line-height: 2.8rem;
     font-size: 150%;
+    display: flex;
+    flex-direction: column;
+    justify-content: center;
   }
 
   &:hover {
@@ -89,6 +92,14 @@ $switch-height: 1.5rem;
     transform: rotateY(0);
   }
 
+  &--table-cell {
+    margin-bottom: 0;
+    margin-right: 0;
+
+    input + label {
+      height: 3.6rem;
+    }
+  }
 }
 
 gf-form-switch[disabled]  {
@@ -96,5 +107,9 @@ gf-form-switch[disabled]  {
   .gf-form-switch input + label {
     cursor: default;
     pointer-events: none !important;
+    &::before {
+      color: $text-color-faint;
+      text-shadow: none;
+    }
   }
 }

+ 0 - 1
public/sass/components/edit_sidemenu.scss

@@ -10,7 +10,6 @@
 }
 
 .edit-sidemenu-aside {
-  min-width: 6rem;
   margin-right: $spacer*2;
 }
 

+ 182 - 0
public/sass/pages/_history.scss

@@ -0,0 +1,182 @@
+// 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,
+.diff-json-deleted,
+.diff-json-added,  {
+  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-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;
+}

+ 197 - 0
public/test/mocks/history-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: 'history-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: 'history-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 history list',
+            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: 'History 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

@@ -458,6 +458,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",
@@ -500,6 +506,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",