瀏覽代碼

Merge branch 'devel'

Edvinas Valatka 10 年之前
父節點
當前提交
af0311066f
共有 2 個文件被更改,包括 49 次插入39 次删除
  1. 28 18
      main.go
  2. 21 21
      utils.go

+ 28 - 18
main.go

@@ -1,27 +1,37 @@
 package main
 
 import (
-    "bufio"
-    "os"
-    "strings"
+	"bufio"
+	"os"
+	"strings"
 )
 
 var history = make(map[string]int)
 
 func main() {
-    histfile, _ := os.Open(gethistfile())
-    scanner := bufio.NewScanner(histfile)
-    for scanner.Scan() {
-        line := scanner.Text()
-        history[strings.TrimSpace(line)] = 0
-    }
-    defer histfile.Close()
-    newhistfile, _ := os.OpenFile(mktmpfile(), os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0600)
-    newhistfile.Truncate(0)
-    for key, _ := range history {
-        newhistfile.WriteString(key + "\n")
-    }
-    newhistfile.Sync()
-    CopyFile(mktmpfile(), gethistfile())
-    defer newhistfile.Close()
+	histfile, _ := os.Open(gethistfile())
+	scanner := bufio.NewScanner(histfile)
+	var i = 0
+	for scanner.Scan() {
+		history[strings.TrimSpace(scanner.Text())] = i
+		i++
+	}
+
+	defer histfile.Close()
+
+	var ah = make([]string, i)
+	for key, val := range history {
+		ah[val] = key
+	}
+
+	newhistfile, _ := os.OpenFile(mktmpfile(), os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0600)
+	newhistfile.Truncate(0)
+	for _, key := range ah {
+		if len(strings.TrimSpace(key)) > 0 {
+			newhistfile.WriteString(key + "\n")
+		}
+	}
+	newhistfile.Sync()
+	CopyFile(mktmpfile(), gethistfile())
+	defer newhistfile.Close()
 }

+ 21 - 21
utils.go

@@ -2,37 +2,37 @@
 package main
 
 import (
-    "io"
-    "os"
-    "os/user"
-    "path"
+	"io"
+	"os"
+	"os/user"
+	"path"
 )
 
 func gethomedir() string {
-    u, _ := user.Current()
-    return u.HomeDir
+	u, _ := user.Current()
+	return u.HomeDir
 }
 
 func gethistfile() string {
-    const fname = ".bash_history"
-    return path.Join(gethomedir(), fname)
+	const fname = ".bash_history"
+	return path.Join(gethomedir(), fname)
 }
 
 func mktmpfile() string {
-    const fname = ".bash_history"
-    return path.Join("/tmp", fname)
+	const fname = ".bash_history"
+	return path.Join("/tmp", fname)
 }
 
 func CopyFile(src, dst string) (int64, error) {
-    sf, err := os.Open(src)
-    if err != nil {
-        return 0, err
-    }
-    defer sf.Close()
-    df, err := os.Create(dst)
-    if err != nil {
-        return 0, err
-    }
-    defer df.Close()
-    return io.Copy(df, sf)
+	sf, err := os.Open(src)
+	if err != nil {
+		return 0, err
+	}
+	defer sf.Close()
+	df, err := os.Create(dst)
+	if err != nil {
+		return 0, err
+	}
+	defer df.Close()
+	return io.Copy(df, sf)
 }