本文整理汇总了Golang中github.com/sergi/go-diff/diffmatchpatch.New函数的典型用法代码示例。如果您正苦于以下问题:Golang New函数的具体用法?Golang New怎么用?Golang New使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了New函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Edit
func Edit(db *gorp.DbMap, w WikiPage) (WikiPage, bool) {
if w.Id == 0 {
db.Insert(&w)
} else {
wOld, ok := GetBySlug(db, w.Title)
if !ok {
return WikiPage{}, false
}
textOld := string(wOld.Body)
textNew := string(w.Body)
d := diffmatchpatch.New()
b := d.DiffMain(textNew, textOld, false)
dl := d.DiffToDelta(b)
delta := WikiDelta{
ItemId: w.Id,
PrevDelta: w.PrevDelta,
Delta: []byte(dl),
}
db.Insert(&delta)
w.PrevDelta = delta.Id
db.Update(&w)
}
return w, true
}
示例2: writeDiffHTML
func writeDiffHTML(out *bytes.Buffer, from, to, header string) {
dmp := diffmatchpatch.New()
diff := dmp.DiffMain(from, to, true)
diff = dmp.DiffCleanupSemantic(diff)
out.WriteString("<h1>" + html.EscapeString(header) + "</h1>\n<pre>")
// write the diff
for _, chunk := range diff {
txt := html.EscapeString(chunk.Text)
txt = strings.Replace(txt, "\n", "↩\n", -1)
switch chunk.Type {
case diffmatchpatch.DiffInsert:
out.WriteString(`<ins style="background:#e6ffe6;">`)
out.WriteString(txt)
out.WriteString(`</ins>`)
case diffmatchpatch.DiffDelete:
out.WriteString(`<del style="background:#ffe6e6;">`)
out.WriteString(txt)
out.WriteString(`</del>`)
case diffmatchpatch.DiffEqual:
out.WriteString(`<span>`)
out.WriteString(txt)
out.WriteString(`</span>`)
}
}
if out.Len() > MaxDetailsLen {
out.Truncate(MaxDetailsLen)
out.WriteString("\n\n[TRUNCATED]")
}
out.WriteString("</pre>")
}
示例3: CompareGotExpected
func CompareGotExpected(t *testing.T, err error, got, expected interface{}) {
if reflect.DeepEqual(got, expected) {
return
}
t.Logf("got:\n%v", got)
t.Logf("expected:\n%v", expected)
differ := diffmatchpatch.New()
diff := differ.DiffMain(fmt.Sprintf("%+v", expected),
fmt.Sprintf("%+v", got), true)
var diffout string
for _, line := range diff {
switch line.Type {
case diffmatchpatch.DiffDelete:
diffout += fmt.Sprintf("\033[32m%v\033[0m", line.Text)
case diffmatchpatch.DiffInsert:
diffout += fmt.Sprintf("\033[31m%v\033[0m", line.Text)
default:
diffout += line.Text
}
}
t.Logf("diff:\n%v", diffout)
t.Fatal("got is not like expected")
}
示例4: Do
// Do computes the (line oriented) modifications needed to turn the src
// string into the dst string.
func Do(src, dst string) (diffs []diffmatchpatch.Diff) {
dmp := diffmatchpatch.New()
wSrc, wDst, warray := dmp.DiffLinesToChars(src, dst)
diffs = dmp.DiffMain(wSrc, wDst, false)
diffs = dmp.DiffCharsToLines(diffs, warray)
return diffs
}
示例5: lineDiff
func lineDiff(src1, src2 *string) []diffmatchpatch.Diff {
dmp := diffmatchpatch.New()
a, b, c := dmp.DiffLinesToChars(*src1, *src2)
diffs := dmp.DiffMain(a, b, false)
result := dmp.DiffCharsToLines(diffs, c)
return result
}
示例6: Update
func (this *highlightedDiff) Update() {
left := this.GetSources()[0].(caret.MultilineContentI)
right := this.GetSources()[1].(caret.MultilineContentI)
dmp := diffmatchpatch.New()
diffs := dmp.DiffMain(left.Content(), right.Content(), true)
for side := range this.segments {
this.segments[side] = nil
offset := uint32(0)
for _, diff := range diffs {
if side == 0 && diff.Type == -1 {
this.segments[side] = append(this.segments[side], highlightSegment{offset: offset, color: mediumRedColor})
offset += uint32(len(diff.Text))
}
if side == 1 && diff.Type == +1 {
this.segments[side] = append(this.segments[side], highlightSegment{offset: offset, color: mediumGreenColor})
offset += uint32(len(diff.Text))
}
if diff.Type == 0 {
this.segments[side] = append(this.segments[side], highlightSegment{offset: offset})
offset += uint32(len(diff.Text))
}
}
// HACK: Fake last element.
if side == 0 {
this.segments[side] = append(this.segments[side], highlightSegment{offset: uint32(left.LenContent())})
} else {
this.segments[side] = append(this.segments[side], highlightSegment{offset: uint32(right.LenContent())})
}
}
}
示例7: save
func (p *CowyoData) save(newText string) error {
if !open {
return fmt.Errorf("db must be opened before saving")
}
err := db.Update(func(tx *bolt.Tx) error {
bucket, err := tx.CreateBucketIfNotExists([]byte("datas"))
if err != nil {
return fmt.Errorf("create bucket: %s", err)
}
// find diffs
dmp := diffmatchpatch.New()
diffs := dmp.DiffMain(p.CurrentText, newText, true)
delta := dmp.DiffToDelta(diffs)
p.CurrentText = newText
p.Timestamps = append(p.Timestamps, time.Now().Format(time.ANSIC))
p.Diffs = append(p.Diffs, delta)
enc, err := p.encode()
if err != nil {
return fmt.Errorf("could not encode CowyoData: %s", err)
}
err = bucket.Put([]byte(p.Title), enc)
return err
})
return err
}
示例8: main
func main() {
// Read whole file as string
inbyte, err := ioutil.ReadFile("text1.txt")
if err != nil {
panic(err)
}
text1 := string(inbyte[:])
inbyte, err = ioutil.ReadFile("text2.txt")
if err != nil {
panic(err)
}
text2 := string(inbyte[:])
// Check diffs
dmp := diffmatchpatch.New()
diffs := dmp.DiffMain(text1, text2, false)
// Make patch
patch := dmp.PatchMake(text1, diffs)
// Print patch to see the results before they're applied
fmt.Println(dmp.PatchToText(patch))
// Apply patch
text3, _ := dmp.PatchApply(patch, text1)
// Write the patched text to a new file
err = ioutil.WriteFile("text3.txt", []byte(text3), 0644)
if err != nil {
panic(err)
}
}
示例9: diffBackup
func diffBackup(store configstore.Store, w http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
t1, err := time.Parse(file.DefaultDateFormat, vars["date1"])
if err != nil {
log.Printf("Error: %s", err)
http.Error(w, "error :(", 500)
return
}
t2, err := time.Parse(file.DefaultDateFormat, vars["date2"])
if err != nil {
log.Printf("Error: %s", err)
http.Error(w, "error :(", 500)
return
}
e1 := configstore.Entry{
Name: vars["hostname"],
Date: t1,
}
e2 := configstore.Entry{
Name: vars["hostname"],
Date: t2,
}
err = store.Get(&e1)
if err != nil {
log.Printf("Error: %s", err)
http.Error(w, "error :(", 500)
return
}
err = store.Get(&e2)
if err != nil {
log.Printf("Error: %s", err)
http.Error(w, "error :(", 500)
return
}
dmp := diffmatchpatch.New()
diffs := dmp.DiffMain(e1.Content.String(), e2.Content.String(), true)
em := struct {
Hostname string
Date1 time.Time
Date2 time.Time
Diff string
}{
vars["hostname"],
t1,
t2,
dmp.DiffPrettyHtml(diffs),
}
io.WriteString(w, mustache.RenderFileInLayout("templates/diff.html.mustache", "templates/layout.html.mustache", em))
}
示例10: diff
func diff(a, b string) []diffmatchpatch.Diff {
dmp := diffmatchpatch.New()
diffs := dmp.DiffMain(a, b, true)
if len(diffs) > 2 {
diffs = dmp.DiffCleanupSemantic(diffs)
diffs = dmp.DiffCleanupEfficiency(diffs)
}
return diffs
}
示例11: main
func main() {
var text1 string = "hej"
var text2 string = "hejj"
var dmp = diffmatchpatch.New()
var diffs = dmp.DiffMain(text1, text2, false)
fmt.Println("%s", diffs)
}
示例12: TestDiffShow
func (self *SanityTest) TestDiffShow(c *Case) {
state := dmp.New()
diffs := state.DiffMain("aaabdef", "aaacdef1", false)
c.AssertEquals(dmp.Diff{dmp.DiffEqual, "aaa"}, diffs[0])
c.AssertEquals(dmp.Diff{dmp.DiffDelete, "b"}, diffs[1])
c.AssertEquals(dmp.Diff{dmp.DiffInsert, "c"}, diffs[2])
c.AssertEquals(dmp.Diff{dmp.DiffEqual, "def"}, diffs[3])
c.AssertEquals(dmp.Diff{dmp.DiffInsert, "1"}, diffs[4])
}
示例13: getImportantVersions
func getImportantVersions(p CowyoData) []versionsInfo {
m := map[int]int{}
dmp := diffmatchpatch.New()
lastText := ""
lastTime := time.Now().AddDate(0, -1, 0)
for i, diff := range p.Diffs {
seq1, _ := dmp.DiffFromDelta(lastText, diff)
texts_linemode := diffRebuildtexts(seq1)
rebuilt := texts_linemode[len(texts_linemode)-1]
parsedTime, _ := time.Parse(time.ANSIC, p.Timestamps[i])
duration := parsedTime.Sub(lastTime)
m[i] = int(duration.Seconds())
if i > 0 {
m[i-1] = m[i]
}
// On to the next one
lastText = rebuilt
lastTime = parsedTime
}
// Sort in order of decreasing diff times
n := map[int][]int{}
var a []int
for k, v := range m {
n[v] = append(n[v], k)
}
for k := range n {
a = append(a, k)
}
sort.Sort(sort.Reverse(sort.IntSlice(a)))
// Get the top 4 biggest diff times
var importantVersions []int
var r []versionsInfo
for _, k := range a {
for _, s := range n[k] {
if s != 0 && s != len(n) {
fmt.Printf("%d, %d\n", s, k)
importantVersions = append(importantVersions, s)
if len(importantVersions) > 10 {
sort.Ints(importantVersions)
for _, nn := range importantVersions {
r = append(r, versionsInfo{p.Timestamps[nn], nn})
}
return r
}
}
}
}
sort.Ints(importantVersions)
for _, nn := range importantVersions {
r = append(r, versionsInfo{p.Timestamps[nn], nn})
}
return r
}
示例14: reportOnFileWatch
func reportOnFileWatch(fw *FileWatch) {
file, err := os.Open(fw.Source)
if err != nil {
//TODO report that the file is not there
} else {
changes := []Change{}
fileInfo, _ := file.Stat()
// If the cached size is greater than the live size
// it means the file has lost content. This is not common behavior
// for a log file, and that iss what we are concerned about. So... (for now at least)
// we are going to reset the cached content. Meaning that the diff will include all that
// is in the file.
if fw.Size() > fileInfo.Size() {
fw.SetContent([]byte{})
}
if fw.Size() != fileInfo.Size() {
fileBytes := GatherBytes(fw.Source)
dmp := diffmatchpatch.New()
diffs := dmp.DiffMain(string(fw.Content()), string(fileBytes), true)
for _, x := range diffs {
if x.Type == 1 {
if fw.Lines {
for _, i := range SplitByLine(x.Text) {
changes = append(changes, NewChange(fw, i))
}
} else {
changes = append(changes, NewChange(fw, x.Text))
}
}
}
fw.SetContent(fileBytes)
}
fw.SetSize(fileInfo.Size())
for _, i := range changes {
if strings.Trim(i.Content, trimset) != "" {
jsondChange, err := json.Marshal(i)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(string(jsondChange))
}
}
}
}
}
示例15: rebuildTextsToDiffN
func rebuildTextsToDiffN(p WikiData, n int) string {
dmp := diffmatchpatch.New()
lastText := ""
for i, diff := range p.Diffs {
seq1, _ := dmp.DiffFromDelta(lastText, diff)
textsLinemode := diffRebuildtexts(seq1)
rebuilt := textsLinemode[len(textsLinemode)-1]
if i == n {
return rebuilt
}
lastText = rebuilt
}
return "ERROR"
}