Skip to content

Commit df57033

Browse files
committed
refactor(nu-hooks/startup-times): Better performance and UX
- 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 32cdc96 commit df57033

File tree

1 file changed

+39
-34
lines changed

1 file changed

+39
-34
lines changed

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

Lines changed: 39 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,44 @@
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
222

23-
let version = (version)
3+
# A hook for logging startup times
4+
@example "Setting it up" {
5+
$env.config.hooks.pre_prompt ++= (startup-times)
6+
}
7+
@example "Setting it up with a custom path" {
8+
$env.config.hooks.pre_prompt ++= (startup-times "~/startup-times.tsv")
9+
}
10+
export def main [
11+
file: path = ($nu.data-dir | path join "startup-times.tsv"), # the file to log the startup times
12+
]: nothing -> list {
13+
[
14+
{
15+
remove: true
16+
code: {
17+
let version = (version)
18+
let times = {
19+
date: (date now)
20+
time: $nu.startup-time
21+
build: $version.build_rust_channel
22+
allocator: $version.allocator
23+
version: $version.version
24+
commit: $version.commit_hash
25+
build_time: $version.build_time
26+
}
2427

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
28+
if not ($file | path exists) {
29+
mkdir ($file | path dirname)
30+
$times | to tsv | save $file
31+
} else {
32+
$times | to tsv --noheaders | save --append $file
33+
}
3534
}
36-
$startup_times | save --force $file
3735
}
38-
}
36+
{
37+
# The hook removes itself, making it run just once
38+
# NOTE: We need a separate string hook, modifying `$env.config` in
39+
# a closure hook does not take effect
40+
remove: true
41+
code: '$env.config.hooks.pre_prompt = $env.config.hooks.pre_prompt | where not (try { $it.remove == true } catch { false })'
42+
}
43+
]
3944
}

0 commit comments

Comments
 (0)