elvish/store/dir_hist.go

78 lines
1.7 KiB
Go
Raw Normal View History

2015-02-25 23:40:48 +08:00
package store
import "database/sql"
2016-02-08 06:23:16 +08:00
// Dir is an entry in the directory history.
2015-02-25 23:40:48 +08:00
type Dir struct {
Path string
Score float64
}
const (
2016-02-08 06:23:16 +08:00
scoreIncrement = 10
2015-02-25 23:40:48 +08:00
)
func init() {
initTable["dir"] = func(db *sql.DB) error {
_, err := db.Exec(`create table if not exists dir (path text unique primary key, score real default 0)`)
return err
}
2015-02-25 23:40:48 +08:00
}
2016-02-08 06:23:16 +08:00
// AddDir adds a directory to the directory history.
2015-02-25 23:40:48 +08:00
func (s *Store) AddDir(d string) error {
tx, err := s.db.Begin()
if err != nil {
return err
}
defer tx.Commit()
// Insert when the path does not already exist
_, err = tx.Exec("insert or ignore into dir (path) values(?)", d)
if err != nil {
return err
}
// Increment score
2016-02-08 06:23:16 +08:00
_, err = tx.Exec("update dir set score = score + ? where path = ?", scoreIncrement, d)
2015-02-25 23:40:48 +08:00
return err
}
func convertDirs(rows *sql.Rows) ([]Dir, error) {
var (
dir Dir
dirs []Dir
)
for rows.Next() {
rows.Scan(&dir.Path, &dir.Score)
dirs = append(dirs, dir)
}
if err := rows.Err(); err != nil {
return nil, err
}
return dirs, nil
}
2016-02-08 06:23:16 +08:00
// FindDirs finds directories containing a given substring. The results are
// ordered by scores in descending order.
2015-02-25 23:40:48 +08:00
func (s *Store) FindDirs(p string) ([]Dir, error) {
rows, err := s.db.Query(
"select path, score from dir where instr(path, ?) > 0 order by score desc", p)
if err != nil {
return nil, err
}
return convertDirs(rows)
}
2016-02-08 06:23:16 +08:00
// ListDirs lists all directories in the directory history. The results are
// ordered by scores in descending order.
2015-02-25 23:40:48 +08:00
func (s *Store) ListDirs() ([]Dir, error) {
rows, err := s.db.Query(
"select path, score from dir order by score desc")
if err != nil {
return nil, err
}
return convertDirs(rows)
}