aboutsummaryrefslogtreecommitdiffstats
path: root/modules/home/zsh.nix
blob: a7817f9100768f1174c2e33a1ae8ca6e77258702 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
{ pkgs, lib, ... }:

let
  # Pinned to commits, not branch names: a branch ref keeps moving while the
  # hash stays put, so every upstream push breaks the build with a mismatch.
  # To update: bump rev, then `nix flake prefetch github:<owner>/<repo>/<rev>`.
  zsh-autocomplete = pkgs.fetchFromGitHub {
    owner = "marlonrichert";
    repo = "zsh-autocomplete";
    rev = "027cdab14451e98c9d36d72b1f79d9488ac88e46";
    hash = "sha256-lnQJqbQJXz6rzClPHc9DMLbwxesvsH5tZronkG/QgJE=";
  };
  zsh-autosuggestions = pkgs.fetchFromGitHub {
    owner = "zsh-users";
    repo = "zsh-autosuggestions";
    rev = "85919cd1ffa7d2d5412f6d3fe437ebdbeeec4fc5";
    hash = "sha256-KmkXgK1J6iAyb1FtF/gOa0adUnh1pgFsgQOUnNngBaE=";
  };
  zsh-vi-mode = pkgs.fetchFromGitHub {
    owner = "jeffreytse";
    repo = "zsh-vi-mode";
    rev = "91cafe4a09b6670cb8e761aa413e5f7b9e00816f";
    hash = "sha256-5ZYcxl5sjfn1XfQ7D28Si4OXwCHHapAJSboJfNgl/5A=";
  };
in
{
  home.file = {
    ".zsh_repos/marlonrichert/zsh-autocomplete".source = zsh-autocomplete;
    ".zsh_repos/zsh-users/zsh-autosuggestions".source = zsh-autosuggestions;
    ".zsh_repos/jeffreytse/zsh-vi-mode".source = zsh-vi-mode;
    ".zshenv".text = ''
      ##!/bin/zsh
      #
      # .zshenv - Zsh environment file, loaded always.
      #

      # Set ZDOTDIR if you want to re-home Zsh.
      export XDG_CONFIG_HOME=''${XDG_CONFIG_HOME:-$HOME/.config}
      export XDG_DATA_HOME=''${XDG_DATA_HOME:-$HOME/.local/share}
      export XDG_CACHE_HOME=''${XDG_CACHE_HOME:-$HOME/.cache}
      export ZDOTDIR=''${ZDOTDIR:-$XDG_CONFIG_HOME/zsh}

      # Ensure path arrays do not contain duplicates.
      typeset -gU path fpath

      # Cached zsh completions generated on rebuild (see home.activation in zsh.nix).
      fpath=($HOME/.zsh_completions $fpath)

      # Set the list of directories that zsh searches for commands.
      path=(
        $HOME/{,s}bin(N)
        $HOME/.local/{,s}bin(N)
        $HOME/.cargo/bin(N)
        $HOME/go/bin(N)
        /Library/Frameworks/Firebird.framework/Resources/bin(N)
        /opt/homebrew/opt/libpq/bin(N)
        /opt/homebrew/opt/rustup/bin(N)
        /opt/{homebrew,local}/{,s}bin(N)
        /usr/local/{,s}bin(N)
        $path
      )
    '' + (
      if pkgs.stdenv.isDarwin then ''
        eval "$(/opt/homebrew/bin/brew shellenv)"
      '' else ""
    ) + ''
    '';

    ".hushlogin".text = "";

    ".config/zsh/.zshrc".text = ''
      #!/bin/bash
      #      ^----- get shellcheck hints based on bash
      # https://github.com/koalaman/shellcheck/issues/809
      # shellcheck disable=SC1090 # sourced filenames with variables

      # Remove stale compiled zsh files that shadow nix-managed configs
      rm -f ~/.config/zsh/.zshrc.zwc ~/.config/zsh/{aliases,extras}.zwc

      function set_terminal_title() {
        printf '\033]0;%s@%s:%s\033\\' "$USER" "''${HOST%%.*}" "''${PWD/#$HOME/~}"
      }
      autoload -Uz add-zsh-hook
      add-zsh-hook precmd set_terminal_title

      eval "$(starship init zsh)"

      source ~/.zsh_repos/marlonrichert/zsh-autocomplete/zsh-autocomplete.plugin.zsh
      source ~/.zsh_repos/zsh-users/zsh-autosuggestions/zsh-autosuggestions.plugin.zsh
      # zsh-vi-mode clobbers all keybindings on init, so anything
      # that needs to survive (fzf, autosuggest) goes in zvm_after_init.
      function zvm_after_init() {
        eval "$(fzf --zsh)"
        bindkey '^I^I' autosuggest-accept
      }

      source ~/.zsh_repos/jeffreytse/zsh-vi-mode/zsh-vi-mode.plugin.zsh

      for file in ~/.config/zsh/{aliases,extras}; do
          if [[ -r "$file" ]] && [[ -f "$file" ]]; then
              # shellcheck source=/dev/null
              source "$file"
          fi
      done

      command -v twm &>/dev/null && eval "$(twm --print-zsh-completion)"
    '';

    ".config/zsh/aliases".text = ''
      # Git aliases
      alias git-unpushed='git log --branches --not --remotes --no-walk --decorate --oneline'
      alias gb='git checkout -b'
      alias gfr='git fetch upstream && git rebase upstream/main'
      alias git-undo='git reset --soft HEAD~1'
      alias git-clean-branches="git for-each-ref --format '%(refname:short)' refs/heads | grep -v 'master\|main' | xargs git branch -D"
      alias :q='exit'
      alias ls='ls --color'
    '' + (if pkgs.stdenv.isDarwin then ''
      alias tailscale='/Applications/Tailscale.app/Contents/MacOS/Tailscale'
      alias rebuild='sudo darwin-rebuild switch --flake ~/ghq/simenandre.no/dotfiles#default'
      alias update='nix flake update --flake ~/ghq/simenandre.no/dotfiles && sudo darwin-rebuild switch --flake ~/ghq/simenandre.no/dotfiles#default'
      alias nix-gc='sudo nix-collect-garbage --delete-older-than 14d && nix-collect-garbage --delete-older-than 14d && nix store gc'
    '' else "") + ''

      # Generic / Random / Utility
      alias rg="rg --hidden --glob '!.git' --glob '!node_modules'"
      alias r='cd $REPOS/github.com/'
      alias c='clear'
    '' + (if pkgs.stdenv.isDarwin then ''
      alias afk='pmset displaysleepnow'
    '' else "") + ''
      alias dl="cd ~/Downloads"
      alias l='ls -l'
      alias todo='nt'
      alias tasks="open 'obsidian://open?file=-%20Oppgaver'"
      alias todos="mt ~/ghq/github.com/simenandre/notes/"
      alias today="open 'obsidian://advanced-uri?daily=true'"
      alias tre="tree -I '.git|node_modules'"
      alias timeliste="open 'https://tripletex.no/execute/updateHourlist?contextId=11208568'"
      alias t="open 'https://tripletex.no/execute/updateHourlist?contextId=11208568'"
      alias fork-cleaner="fork-cleaner --token \$(cat ~/.secrets/github-token 2>/dev/null)"
      alias vi="nvim"
      alias vim="nvim"
      alias v="nvim"

      function claude() {
        if [[ -n "$TMUX" ]]; then
          tmux rename-window "claude"
          command claude "$@"
          tmux set-window-option automatic-rename on
        else
          command claude "$@"
        fi
      }

      alias dump-issues="getBjerkIssues > ~/Downloads/issues-$(date -I).json"
    '';

    ".config/zsh/extras".text = ''
      if [[ "$(uname)" == "Darwin" ]]; then
        export DOCKER_HOST="unix://$HOME/.colima/default/docker.sock"
        export TESTCONTAINERS_DOCKER_SOCKET_OVERRIDE=/var/run/docker.sock
      fi

      NOTES_DIR=$HOME/ghq/github.com/simenandre/notes/
      function note() {
        if [ $1 ]; then
          FILE=$NOTES_DIR/$(date +%Y-%m-%d).md

          if [ $2 ]; then
            FILE=$2
          fi

          echo $1 >> $FILE
        fi
      }

      function nt() {
        if [ $1 ]; then
          CONTENT="- [ ] $1"
          note $CONTENT $2
        fi
      }

      function getBjerkIssues() {
        gh issue list --repo bjerkio/internal \
          --search "-label:backlog -label:kind/system" \
          --json title,body,url,createdAt,assignees,number,labels,comments \
          --jq 'map({url, createdAt, title, labels: [.labels[].name], assignees: [.assignees[].login], body, number: "#\(.number)", comments: .comments | map({ body: .body, createdAt: .createdAt })})'
      }

      function g() {
        export GOOGLE_CLOUD_PROJECT="sokkel-sandbox"
        export GOOGLE_CLOUD_LOCATION="europe-north1"
        export GOOGLE_GENAI_USE_VERTEXAI=true

        gemini
      }
    '';
  };

  home.activation.generateZshCompletions = lib.hm.dag.entryAfter [ "writeBoundary" ] ''
    COMPDIR="$HOME/.zsh_completions"
    $DRY_RUN_CMD mkdir -p "$COMPDIR"

    # Make brew-installed binaries discoverable during activation.
    export PATH="/opt/homebrew/bin:/opt/homebrew/sbin:$HOME/.cargo/bin:$HOME/go/bin:$PATH"

    generate() {
      local name="$1"
      local bin="$2"
      shift 2
      if command -v "$bin" >/dev/null 2>&1; then
        if "$bin" "$@" > "$COMPDIR/_$name.tmp" 2>/dev/null && [ -s "$COMPDIR/_$name.tmp" ]; then
          mv "$COMPDIR/_$name.tmp" "$COMPDIR/_$name"
        else
          rm -f "$COMPDIR/_$name.tmp"
          echo "  warning: failed to generate _$name (does '$bin' support 'completion zsh'?)"
        fi
      fi
    }

    generate gh          gh       completion -s zsh
    generate kubectl     kubectl  completion zsh
    generate helm        helm     completion zsh
    generate pulumi      pulumi   gen-completion zsh
    generate pnpm        pnpm     completion zsh
    generate deno        deno     completions zsh
    generate flyctl      flyctl   completion zsh
    generate rustup      rustup   completions zsh
    generate cargo       rustup   completions zsh cargo
    generate robin       robin    completion zsh
    generate bobbin      bobbin   completion zsh
    generate dina        dina     completion zsh
    generate so          so       completion zsh
    generate dinactl     dinactl  completion zsh
    generate identityctl identityctl completion zsh
  '';
}