Skip to content

Commit

Permalink
单独存放 scripts
Browse files Browse the repository at this point in the history
  • Loading branch information
lollipopkit committed Oct 27, 2022
1 parent 1a7b9dd commit 7ecf40d
Show file tree
Hide file tree
Showing 4 changed files with 117 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
## 📄 语法
#### 详细
- **Step by step**[LANG.md](LANG.md)
- **By examples**[测试集](test)
- **By examples**[脚本](scripts) or [测试集](test)

#### 速览
```js
Expand Down
File renamed without changes.
File renamed without changes.
116 changes: 116 additions & 0 deletions scripts/zsh_history_tidy.lk
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
cmd_prefix := 'lk zsh_history_tidy.lk'

args := os.args

modes := {
"duplicate": fn(line, _, cmd) {
have := false
for _, v in lines_result {
if strs.contains(v, cmd) {
have = true
break
}
}
if not have {
lines_result[#lines_result] = line
}
},
"old": fn(line, time, _) {
if time_limit == nil {
time_limit = now - int(args[3])
}

if time >= time_limit {
lines_result[#lines_result] = line
}
},
'key': fn(line, _, cmd) {
if not re.find(args[3], cmd) {
lines_result[#lines_result] = line
}
}
}
helps := {
"duplicate": fmt('清理重复的命令历史,eg: %s duplicate', cmd_prefix),
'old': fmt('清理过期的历史,eg: %s old 86400 -> 清理一天前的历史, 86400 = 60 * 70 * 24', cmd_prefix),
'key': fmt('正则匹配,eg: %s key "cd [A-Z]" -> 符合正则的行会被清理', cmd_prefix)
}
checks := {
'duplicate': fn() {
rt true
},
'old': fn() {
if #args != 4 {
print(fmt('参数过少: \n%s', helps['old']))
rt false
}
if not re.have('^[0-9]+$', args[3]) {
print('参数错误,只能为数字:\n' + helps['old'])
rt false
}
rt true
} ,
'key': fn() {
pass := #args == 4
if not pass {
print(fmt('参数过少: \n%s', helps['key']))
}
rt pass
},
}

if #args < 3 {
print(fmt("Usage: %s <mode> [options]\n", cmd_prefix))
help_str := ''
for k, v in helps {
help_str += fmt('<%s> : \n%s\n', k, v)
}
print('以下是可选的模式:\n'+help_str)
os.exit()
}

mode := args[2]
if modes[mode] == nil {
print('Unkown mode: '+mode)
}
if not checks[mode]() {
os.exit()
}

func := modes[args[2]]

now = os.time() / 1000
zsh_history_path := os.get_env('HOME') + '/.zsh_history'
err := os.cp(zsh_history_path, zsh_history_path + '.bak')
if err != nil {
print('备份失败, 是否继续?(y/n)')
continue := input()
if continue != 'y' {
os.exit()
}
}

histories, err := os.read(zsh_history_path)
if err != nil {
print(err)
os.exit(1)
}

lines := strs.split(histories, '\n')
lines_result = {}
for _, line in lines {
results := re.find(`: ([0-9]+):[0-9]+;([ \S]+)`, line)
if results != nil {
time := int(results[1])
cmd := results[2]
func(line, time, cmd)
}
}

err := os.write(zsh_history_path, strs.join(lines_result, '\n'))
if err != nil {
print(err)
os.exit(1)
} else {
print(fmt('清理完成,原有 %d 条,现有 %d 条,共清理 %d 条历史', #lines, #lines_result, #lines - #lines_result))
}

0 comments on commit 7ecf40d

Please sign in to comment.