Skip to content

Commit a0f5105

Browse files
authored
refactor(nu-hooks/startup-times): Better performance and UX (#1136)
- Use attr based examples. - Hook removes itself after running, rather than staying loaded. - Switch to tsv as storage format to allow adding new logs without loading the file into memory.
1 parent 598ff1a commit a0f5105

File tree

1 file changed

+34
-34
lines changed

1 file changed

+34
-34
lines changed

nu-hooks/nu-hooks/startup-times.nu

Lines changed: 34 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,39 @@
1-
# setup a hook that will log startup times
2-
#
3-
# # Example
4-
# ```nushell
5-
# $env.config.hooks.env_change.PWD = (
6-
# $env.config.hooks.env_change.PWD | append (
7-
# use nu-hooks/startup-times.nu;
8-
# startup-times setup
9-
# )
10-
# )
11-
# ```
12-
export def setup [
13-
dir: path = $nu.data-dir, # the path where to store the "startup times" file
14-
]: [ nothing -> closure ] {
15-
{|before, _|
16-
if $before == null {
17-
let file = $dir | path join "startup-times.nuon"
18-
if not ($file | path exists) {
19-
mkdir ($file | path dirname)
20-
touch $file
21-
}
1+
alias startup-times = main
2+
3+
# A hook for logging startup times
4+
@example "Setting it up is simple, calling the command adds the hook automatically" { startup-times }
5+
@example "Setting it up with a custom path" {
6+
$env.config.hooks.pre_prompt ++= (startup-times "~/startup-times.tsv")
7+
}
8+
export def --env main [
9+
file: path = ($nu.data-dir | path join "startup-times.tsv"), # the file to log the startup times
10+
]: nothing -> nothing {
11+
$env.config.hooks.pre_prompt = [
12+
{
13+
remove: true
14+
code: {
15+
let version = (version)
16+
let times = {
17+
date: (date now)
18+
time: $nu.startup-time
19+
build: $version.build_rust_channel
20+
allocator: $version.allocator
21+
version: $version.version
22+
commit: $version.commit_hash
23+
build_time: $version.build_time
24+
}
2225

23-
let version = (version)
26+
if not ($file | path exists) {
27+
mkdir ($file | path dirname)
28+
$times | to tsv | save $file
29+
} else {
30+
$times | to tsv --noheaders | save --append $file
31+
}
2432

25-
# NOTE: this binding is required as per
26-
# https://github.com/nushell/nushell/pull/12601#issuecomment-2069167555
27-
let startup_times = open $file | append {
28-
date: (date now)
29-
time: $nu.startup-time
30-
build: $version.build_rust_channel
31-
allocator: $version.allocator
32-
version: $version.version
33-
commit: $version.commit_hash
34-
build_time: $version.build_time
33+
# Remove self
34+
$env.config.hooks.pre_prompt = $env.config.hooks.pre_prompt
35+
| where not (try { $it.remove == true } catch { false })
3536
}
36-
$startup_times | save --force $file
3737
}
38-
}
38+
]
3939
}

0 commit comments

Comments
 (0)