Compare commits

..

31 Commits
master ... lean

Author SHA1 Message Date
pegasust ceb5f8d983 feat(nvim): favor PATH for ungrammar_lsp for faster development cycle 2023-08-13 00:25:50 -07:00
pegasust f012f26d28 fix(nvim): change to personal git for fast iteration 2023-08-06 13:21:26 -07:00
pegasust f9cf4bcf93 feat(nvim): add dev ungrammar_lsp 2023-08-06 13:04:42 -07:00
pegasust bf812d1e88 leaner 2023-08-01 19:32:21 -07:00
pegasust 41b41d5939 lean 2023-08-01 18:54:41 -07:00
pegasust f969912c08 flake lock 2023-08-01 00:36:14 -07:00
pegasust 7b5a6cfa94 feat(pixi): some repl around, cannot match heic with mov 2023-08-01 00:35:06 -07:00
htran 8ba20cbc56 fix: gh ssh hostname 2023-07-29 16:28:00 -07:00
htran 6ba1836a03 add gh shortform 2023-07-29 16:23:31 -07:00
htran c87dba3422 patch latest 2023-07-25 13:26:29 -07:00
pegasust fd4ff2cbbc plugin intelligence 2023-07-25 13:24:49 -07:00
pegasust 7914c40d91 gopls 2023-07-22 01:37:24 -07:00
pegasust 5f5439d793 forgorr to invoke lspconfig 2023-07-21 00:56:04 -07:00
pegasust 4ae426dbad forgorr to add setup logic 2023-07-21 00:51:35 -07:00
pegasust b83f698dc4 add gopls please 2023-07-21 00:49:04 -07:00
pegasust 7c4b7d0db6 fix(nvim): nil_ls uses lspconfig instead of mason-lspconfig 2023-07-10 02:08:36 -07:00
htran 22a78899ed feat: add nix configs for data collections 2023-07-08 20:43:20 -07:00
htran 5b61ab39f9 feat(nvim): nil_ls is now registered, but not ensure_installed from mason 2023-07-08 18:28:13 -07:00
htran e13cd11a68 untested - rclone 2023-07-07 00:43:18 -07:00
htran 187890cc9b add keepassxc 2023-07-07 00:43:14 -07:00
htran b8abf4e3dd bump 2023-07-04 01:43:44 -07:00
htran a2619bf71a fix: ssh looks at me funny and says 'i dont know what xterm-kitty is' 2023-06-23 09:44:02 -07:00
htran 74a0ef58c4 feat: more ssh 2023-06-23 01:29:26 -07:00
htran 0208a946f2 feat: real tab title template hacker mode 2023-06-23 01:13:06 -07:00
htran c2b5908fa5 kitty as my main terminal now 2023-06-22 23:36:52 -07:00
htran 83c2b01570 ^std breaking change 2023-06-22 20:52:40 -07:00
htran ab8e04f3a0 add sg-nvim (cody!) 2023-06-22 10:34:20 -07:00
htran eb91f32d53 move 2023-06-20 14:10:00 -07:00
htran 0dd6558770 doc: reason for removal of mickael-menu/zk 2023-06-18 04:37:00 -07:00
htran f04fea60d2 remove mickael-menu/zk 2023-06-18 04:22:11 -07:00
htran 024e8530d0 alejandra fmt and some cleanup 2023-06-18 02:51:33 -07:00
176 changed files with 2388 additions and 9598 deletions

19
.envrc
View File

@ -1,16 +1,11 @@
#!/bin/sh #!/bin/sh
source "$( # first time
nix eval \ if [[ ! -d $(nix store add-path --name source --dry-run .) ]]; then
--no-update-lock-file \ nix store add-path --name source .
--no-write-lock-file \ fi
--no-warn-dirty \
--accept-flake-config \
.#__std.direnv_lib 2>/dev/null \
|| nix eval .#__std.direnv_lib # show the errors
)"
# FIXME: This should check if $USER is in userShells, if not,
# fall back to `use nix`
use std nix "//repo/userShells:${USER}"
# shellcheck disable=SC1090
. "$(fetchurl "https://raw.githubusercontent.com/paisano-nix/direnv/bd36f51b9d566d8a36e230dab638abf3074625c3/lib" "sha256-IgQhKK7UHL1AfCUntJO2KCaIDJQotRnK2qC4Daxk+wI=")"
use envreload "//repo/userShells/${USER}" //repo/userShells/default //repo/userShells

1
.gitignore vendored
View File

@ -1,2 +1,3 @@
result result
.direnv .direnv
.data

View File

@ -1,16 +0,0 @@
keys:
- &htran-mbp age1jpm9mtxz6n8vncrk6pk7dppj3r7qxfj5hsgvcdulmp3lxvxez94qvxlgay
- &htran age1jw958shpwu7st8sc4z0fufuswmfpxfc9wl3df9g3f3y57m45j92syr0mng
- &bao age1umzkd4k0xt6uv5de85fpc4uztrph86nsd79h5f8cpuvtpy8n6adss7q2fv
- &root_bao age1vx7e6vz9zptwqd0cakjj8erqv58cstddama8zcrppc36rqqmlvjs53x9u0
- &htran1 age1vkd39dmrft3uk5wnfqppharn38dhrh78ev6pl85u005jhcge5e9qz4lt79
creation_rules:
- path_regex: .*
key_groups:
- age:
- *htran
- *htran-mbp
- *bao
- *root_bao
- *htran1

View File

@ -9,6 +9,25 @@ a bit more experiment on NixOS, I'll keep this repository as simple as possible.
([`init.lua`](./native_configs/neovim/init.lua), [`sshconfig`](./native_configs/ssh/config),...) ([`init.lua`](./native_configs/neovim/init.lua), [`sshconfig`](./native_configs/ssh/config),...)
to be idempotent for Nix and non-Nix targets. to be idempotent for Nix and non-Nix targets.
## Bleed-first development
NOTE: this is extremely bleeding edge with many different branches that are probably
stale. This is because I'm breaking all the time and wanted my `master` branch
to be simply "minimally" available, regardless of what features I implemented later
on.
Currently, `master` is probably not as stable as we all want it to be.
`bleed` was created as I moved onto using [`gh:divnix/std`](https://github.com/divnix/std)
which introduced more explorations to make it backward compatible
`lean` was created in the process of merging `bleed` back onto `master`. Couple
of my infra on Linode are spun down due to Akamai's increased cost, so I try
to keep everything lean, while having an available branch (`bleed`) to look
back to if I need to do anything fancy. `lean` here means it's minimal to the
best of its ability by having only functional code.
## Nix ## Nix
Monorepo that contains my commonly used personal environments. Monorepo that contains my commonly used personal environments.
@ -53,6 +72,9 @@ via writing and typing.
I am in the process of moving away from Obsidian so that I can write ZK notes I am in the process of moving away from Obsidian so that I can write ZK notes
text-editor agnostically. text-editor agnostically.
#### mickael-menu/zk
- Config file: `zk/config.toml` - Config file: `zk/config.toml`
- Command: `ln [-s] $PWD/zk/config.toml ~/.config/zk/config.toml` - Command: `ln [-s] $PWD/zk/config.toml ~/.config/zk/config.toml`
@ -62,6 +84,18 @@ text-editor agnostically.
Note (2023-06-07): I'm now using a mix of nvim-zk with Notion. I'm still figuring out Note (2023-06-07): I'm now using a mix of nvim-zk with Notion. I'm still figuring out
a centralize place to put my notes and use it to do some knowledge graph magic a centralize place to put my notes and use it to do some knowledge graph magic
NOTE (2023-06-18): I used `mickael-menu/zk` for some time, but have found myself
resort to notion due to the need for easier linking (just copy-paste onto
selected note) where as I need to:
- `cS]` to encapsulate the selection with `[]`, then do `(<C-v>`. Too many keystrokes.
On retrospect, I could probably remap this workflow to `<LocalLeader>el"`:
Though, I want to just develop my own solution with
[`nucliadb`](https://github.com/nuclia/nucliadb) and
[`h2ogpt`](https://github.com/h2oai/h2ogpt)
## Troubleshoots ## Troubleshoots
### My MacOS just updated, `nix` is no-longer here ### My MacOS just updated, `nix` is no-longer here

View File

@ -1,30 +0,0 @@
# Ideally, this should contain the barebone necessary for building/interacting
# with tech used in this project
#
# Should also incorporate shortcuts like scripts/{hm-switch,conf-sysnix}.sh in here instead
#
# It should not contain PDE
{
pkgs ? import <nixpkgs> {},
lib,
...
}:
pkgs.mkShell {
# mkShell doesn't care about the differences across nativeBuildInputs,
# buildInputs, or packages
buildInputs = [
# shell scripts
pkgs.rust4cargo
pkgs.sops
pkgs.ssh-to-age
pkgs.go
pkgs.gopls
];
shellHook = ''
# Since we need late dispatch of ~, we have to put this in shellHook.
export SOPS_AGE_KEY_FILE=~/.config/sops/age/keys.txt
'';
# env vars
lol = "hello world";
}

1
dev/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
__pycache__

101
dev/pixi/poetry.lock generated Normal file
View File

@ -0,0 +1,101 @@
# This file is automatically @generated by Poetry 1.5.1 and should not be changed by hand.
[[package]]
name = "colorama"
version = "0.4.6"
description = "Cross-platform colored terminal text."
optional = false
python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7"
files = [
{file = "colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6"},
{file = "colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44"},
]
[[package]]
name = "exceptiongroup"
version = "1.1.2"
description = "Backport of PEP 654 (exception groups)"
optional = false
python-versions = ">=3.7"
files = [
{file = "exceptiongroup-1.1.2-py3-none-any.whl", hash = "sha256:e346e69d186172ca7cf029c8c1d16235aa0e04035e5750b4b95039e65204328f"},
{file = "exceptiongroup-1.1.2.tar.gz", hash = "sha256:12c3e887d6485d16943a309616de20ae5582633e0a2eda17f4e10fd61c1e8af5"},
]
[package.extras]
test = ["pytest (>=6)"]
[[package]]
name = "iniconfig"
version = "2.0.0"
description = "brain-dead simple config-ini parsing"
optional = false
python-versions = ">=3.7"
files = [
{file = "iniconfig-2.0.0-py3-none-any.whl", hash = "sha256:b6a85871a79d2e3b22d2d1b94ac2824226a63c6b741c88f7ae975f18b6778374"},
{file = "iniconfig-2.0.0.tar.gz", hash = "sha256:2d91e135bf72d31a410b17c16da610a82cb55f6b0477d1a902134b24a455b8b3"},
]
[[package]]
name = "packaging"
version = "23.1"
description = "Core utilities for Python packages"
optional = false
python-versions = ">=3.7"
files = [
{file = "packaging-23.1-py3-none-any.whl", hash = "sha256:994793af429502c4ea2ebf6bf664629d07c1a9fe974af92966e4b8d2df7edc61"},
{file = "packaging-23.1.tar.gz", hash = "sha256:a392980d2b6cffa644431898be54b0045151319d1e7ec34f0cfed48767dd334f"},
]
[[package]]
name = "pluggy"
version = "1.2.0"
description = "plugin and hook calling mechanisms for python"
optional = false
python-versions = ">=3.7"
files = [
{file = "pluggy-1.2.0-py3-none-any.whl", hash = "sha256:c2fd55a7d7a3863cba1a013e4e2414658b1d07b6bc57b3919e0c63c9abb99849"},
{file = "pluggy-1.2.0.tar.gz", hash = "sha256:d12f0c4b579b15f5e054301bb226ee85eeeba08ffec228092f8defbaa3a4c4b3"},
]
[package.extras]
dev = ["pre-commit", "tox"]
testing = ["pytest", "pytest-benchmark"]
[[package]]
name = "pytest"
version = "7.4.0"
description = "pytest: simple powerful testing with Python"
optional = false
python-versions = ">=3.7"
files = [
{file = "pytest-7.4.0-py3-none-any.whl", hash = "sha256:78bf16451a2eb8c7a2ea98e32dc119fd2aa758f1d5d66dbf0a59d69a3969df32"},
{file = "pytest-7.4.0.tar.gz", hash = "sha256:b4bf8c45bd59934ed84001ad51e11b4ee40d40a1229d2c79f9c592b0a3f6bd8a"},
]
[package.dependencies]
colorama = {version = "*", markers = "sys_platform == \"win32\""}
exceptiongroup = {version = ">=1.0.0rc8", markers = "python_version < \"3.11\""}
iniconfig = "*"
packaging = "*"
pluggy = ">=0.12,<2.0"
tomli = {version = ">=1.0.0", markers = "python_version < \"3.11\""}
[package.extras]
testing = ["argcomplete", "attrs (>=19.2.0)", "hypothesis (>=3.56)", "mock", "nose", "pygments (>=2.7.2)", "requests", "setuptools", "xmlschema"]
[[package]]
name = "tomli"
version = "2.0.1"
description = "A lil' TOML parser"
optional = false
python-versions = ">=3.7"
files = [
{file = "tomli-2.0.1-py3-none-any.whl", hash = "sha256:939de3e7a6161af0c887ef91b7d41a53e7c5a1ca976325f429cb46ea9bc30ecc"},
{file = "tomli-2.0.1.tar.gz", hash = "sha256:de526c12914f0c550d15924c62d72abc48d6fe7364aa87328337a31007fe8a4f"},
]
[metadata]
lock-version = "2.0"
python-versions = "^3.10"
content-hash = "1cf751550a88abe6c6ea8896fe41073f08488ebbd3fb959572a2038d4d944ebc"

20
dev/pixi/pyproject.toml Normal file
View File

@ -0,0 +1,20 @@
[tool.poetry]
name = "pixi"
version = "0.0.1"
description = "Toy project to investigate about apple photos synced iphone -> mac"
authors = ["Pegasust <pegasucksgg@gmail.com>"]
readme = "README.md"
[tool.poetry.dependencies]
python = "^3.10"
[tool.poetry.group.dev.dependencies]
pytest = "^7.3.1"
[[tool.poetry.packages]]
include = "repl"
[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"

View File

@ -0,0 +1,118 @@
#!/usr/bin/env python
"""
REPL-friendly python mono-module for importing and execution singleton
"""
import os
from dataclasses import dataclass
from itertools import groupby
from typing import Iterable
mac_photos = os.getenv("MAC_PHOTOS_PATH", default="mac_photos")
@dataclass(slots=True, frozen=True)
class PhotosKExt:
name: str
parent: tuple[str, ...]
exts_lowered: tuple[str, ...]
@classmethod
def from_root_file(cls, root: str, filename: str):
ext_elems = filename.split('.')
return cls(
name=ext_elems[0],
parent=os.path.split(root),
exts_lowered=tuple(
ext.lower() for ext in ext_elems[1:]
)
)
@dataclass(slots=True, frozen=True)
class PhotosKey:
filename: str
parent: tuple[str, ...]
@classmethod
def from_key_ext(cls, ext: PhotosKExt):
return cls(filename=ext.name, parent=ext.parent)
@dataclass(slots=True)
class PhotosValue:
exts: dict[str, list[str]]
def heic_paths(self) -> list[str]:
return self.exts.get("heic", list())
def mov_paths(self) -> list[str]:
return self.exts.get("mov", list())
def candidate_exts(file_exts: Iterable[PhotosKExt]):
"""
>>> {ext: len(files)for ext, files in cexts.items()}
stdout> {... 'mov': 2769, 'heic': 2354 ...}
We could make a bold guess that iPhone 11 stores both `heic` and `mov`
for materialized best capture and live movie for live capture.
"""
exts_rv: dict[str, list[PhotosKExt]] = dict()
for file in file_exts:
for ext in file.exts_lowered:
exts_rv.setdefault(ext, list()).append(file)
return exts_rv
def file_exts(photos_dir: str = mac_photos):
return {
PhotosKExt.from_root_file(filename=file, root=root)
for root, _, files in os.walk(photos_dir, followlinks=True)
for file in files
}
def photos_exts(files_with_ext: Iterable[PhotosKExt]):
return {
k: list(v)
for k, v in groupby(files_with_ext, key=lambda x: (x.name, x.parent))
}
def main():
fexts = file_exts()
cexts = candidate_exts(fexts)
print(f"{photos_exts(fexts)=}")
print(f"{cexts=}")
ext_counts = {ext: len(files)for ext, files in cexts.items()}
print(ext_counts)
# stdout>
"""
{'jpeg': 6023, 'mov': 2769, 'heic': 2354, 'thm': 197, 'png': 168, 'plist': 163,
'log': 1, 'aae': 102, 'kgdb': 3, 'mp4': 26, 'data': 3, 'db': 3, 'xml': 26,
'cmap': 2, 'plj': 16, 'kgdb-wal': 3, 'sqlite-shm': 11, 'cloudphotodb-wal': 1,
'kgdb-shm': 3, '00001]': 1, 'frag': 2, 'ithmb': 3, 'sqlite': 15, 'lock': 1,
'sqlite-wal': 11, 'aoi': 3, '0': 1,
'm3u8-8f37dbfb-b3a6-4d52-beca-d17aaed01606': 2, 'jpg': 2, 'roi': 3, 'poi': 3,
'db-shm': 1, 'm3u8-37f64716-0b2d-4a82-854a-5a6c78ce505a': 1, 'descriptor': 3,
'bin': 2, 'm3u8': 5, 'cloudphotodb': 1, 'db-wal': 1, 'nature': 3,
'm3u8-d8faad08-4fcc-4161-a600-1562d755c97b': 1, 'initfrag': 2, '20201]': 1,
'cloudphotodb-shm': 1}
"""
movs = cexts['mov']
heics = cexts['heic']
heic_name_set = {heic.name.lower() for heic in heics}
mov_name_set = {mov.name.lower() for mov in movs}
print(len(heic_name_set - mov_name_set) - len(heic_name_set))
# stdout> (not 0)
# Hence, we are not able to match `.heic` with its `.mov` with just names
# Could it be that the `.heic` also contains the high-quality live?
if __name__ == "__main__":
main()

View File

@ -34,3 +34,28 @@ documentations and defaults
- `mkShell` doesn't care about `packages`, `nativeBuildInputs`, `buildInputs` - `mkShell` doesn't care about `packages`, `nativeBuildInputs`, `buildInputs`
## Archive a branch
Very common to see branches getting stale. We either want to have them become
PR or just have them stale and not deleted (for maximal data collection if
needed)
Hence, here's the aspect of archiving a branch, that also reflects remote branch
```bash
# archive. Feel free to just rename the BRANCH_NAME here
BRANCH_NAME="boost"
git tag "archive/$BRANCH_NAME" $BRANCH_NAME
git branch -D $BRANCH_NAME
# Now delete at origin
git branch -d -r "origin/$BRANCH_NAME"
git push --tags
git push origin :$BRANCH_NAME
# restore
BRANCH_NAME="hello_world"
git fetch origin
git checkout -b "$BRANCH_NAME" "archive/$BRANCH_NAME"
```

View File

@ -0,0 +1,9 @@
# Local nixlib in `nix repl`
Pretty useful for airplane-driven development
```console
nixlib = import <nixpkgs/lib>
nix-repl> nixlib.genAttrs
«lambda @ /nix/var/nix/profiles/per-user/root/channels/nixpkgs/lib/attrsets.nix:619:5»
```

View File

@ -3,7 +3,7 @@
The current [`scripts/vim.dsl`](../scripts/vim.dsl) grabs the upstream supported vim plugins The current [`scripts/vim.dsl`](../scripts/vim.dsl) grabs the upstream supported vim plugins
onto a sqlite database to be stored in memory. We could perform some data exploration via this database onto a sqlite database to be stored in memory. We could perform some data exploration via this database
## Explore which plugins should be added to `neovim.nix` ## Example: Explore which plugins should be added to `neovim.nix`
Gather list of plugins need to be added. This can be done simply by adding Gather list of plugins need to be added. This can be done simply by adding
a print statement on `WPlug` in `../native_configs/neovim/init.lua` then run neovim a print statement on `WPlug` in `../native_configs/neovim/init.lua` then run neovim

1235
flake.lock

File diff suppressed because it is too large Load Diff

View File

@ -8,8 +8,11 @@
inputs = { inputs = {
nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable"; nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
nixpkgs-latest.url = "github:nixos/nixpkgs"; nixpkgs-latest.url = "github:nixos/nixpkgs";
deploy-rs.url = "github:serokell/deploy-rs"; # deploy-rs.url = "github:serokell/deploy-rs";
std.url = "github:divnix/std"; std = {
url = "github:divnix/std";
inputs.devshell.url = "github:numtide/devshell";
};
home-manager = { home-manager = {
url = "github:nix-community/home-manager"; url = "github:nix-community/home-manager";
inputs.nixpkgs.follows = "nixpkgs"; inputs.nixpkgs.follows = "nixpkgs";
@ -17,6 +20,8 @@
neovim-nightly-overlay = { neovim-nightly-overlay = {
# need to pin this until darwin build is successful again. # need to pin this until darwin build is successful again.
url = "github:nix-community/neovim-nightly-overlay?rev=88a6c749a7d126c49f3374f9f28ca452ea9419b8"; url = "github:nix-community/neovim-nightly-overlay?rev=88a6c749a7d126c49f3374f9f28ca452ea9419b8";
# url = "github:nix-community/neovim-nightly-overlay";
inputs.nixpkgs.follows = "nixpkgs"; inputs.nixpkgs.follows = "nixpkgs";
}; };
nix-boost = { nix-boost = {
@ -31,21 +36,29 @@
# Should show the latest nixpkgs whenever possible # Should show the latest nixpkgs whenever possible
inputs.nixpkgs.follows = "nixpkgs-latest"; inputs.nixpkgs.follows = "nixpkgs-latest";
}; };
sg-nvim = {
url = "git+https://github.com/pegasust/sg.nvim?ref=sg-cody-discover";
};
}; };
outputs = {self, std, ...} @ inputs: outputs = {
self,
std,
...
} @ inputs:
std.growOn std.growOn
{ {
# boilerplate # boilerplate
inherit inputs; inherit inputs;
# All cell blocks are under ./nix/cells/<cell>/<cellblock> as `<cellblock>.nix` # All cell blocks are under ./nix/<cell>/<cellblock> as `<cellblock>.nix`
# or `<cellblock/default.nix` # or `<cellblock/default.nix`
cellsFrom = ./nix/cells; cellsFrom = ./nix;
# modules = ./nix/modules; # modules = ./nix/modules;
cellBlocks = let cellBlocks = let
inherit (std.blockTypes) devshells functions anything installables; inherit (std.blockTypes) devshells functions anything installables runnables;
in [ in [
(installables "shells")
(devshells "devshells") (devshells "devshells")
(devshells "userShells") (devshells "userShells")
(functions "home-profiles") (functions "home-profiles")
@ -53,18 +66,21 @@
(anything "home-configs") (anything "home-configs")
(installables "packages") (installables "packages")
(anything "lib") (anything "lib")
(runnables "formatter")
]; ];
} }
{ {
devShells = std.harvest self [["dotfiles" "devshells"]]; devShells = std.harvest self [["dotfiles" "devshells"] ["dev" "shells"]];
# nixosConfigurations = std.pick [ [ "dotfiles" "nixos" ] ];
# homeConfigurations = std.pick [ [ "dotfiles" "home" ] ];
homeModules = std.pick self [["repo" "home-modules"]]; homeModules = std.pick self [["repo" "home-modules"]];
packages = std.harvest self [["repo" "packages"]]; packages = std.harvest self [
["repo" "packages"]
["dev" "packages"]
];
legacyPackages = std.harvest self [["repo" "home-configs"]]; legacyPackages = std.harvest self [["repo" "home-configs"]];
lib = std.pick self [["repo" "lib"]]; lib = std.pick self [["repo" "lib"]];
# TODO: Debug only # TODO: Debug only
homeProfiles = std.pick self [["repo" "home-profiles"]]; homeProfiles = std.pick self [["repo" "home-profiles"]];
formatter = std.harvest self [["repo" "formatter"]];
}; };
} }

View File

@ -1,81 +0,0 @@
# Do not modify this file! It was generated by nixos-generate-config
# and may be overwritten by future invocations. Please make changes
# to /etc/nixos/configuration.nix instead.
{
config,
lib,
pkgs,
modulesPath,
...
}: {
imports = [];
boot.initrd.availableKernelModules = [];
boot.initrd.kernelModules = [];
boot.kernelModules = [];
boot.extraModulePackages = [];
## NOTE: These filesystems are mounted by a wrapper script from nix-wsl
# fileSystems."/" =
# {
# device = "/dev/sdc";
# fsType = "ext4";
# };
#
# fileSystems."/mnt/wsl" =
# {
# device = "tmpfs";
# fsType = "tmpfs";
# };
#
# fileSystems."/mnt/wsl/docker-desktop/shared-sockets/guest-services" =
# {
# device = "none";
# fsType = "tmpfs";
# };
#
# fileSystems."/usr/lib/wsl/drivers" =
# {
# device = "drivers";
# fsType = "drvfs";
# };
#
# fileSystems."/usr/lib/wsl/lib" =
# {
# device = "lib";
# fsType = "drvfs";
# };
fileSystems."/mnt/c" = {
device = "C:";
fsType = "drvfs";
};
fileSystems."/mnt/d" = {
device = "D:";
fsType = "drvfs";
};
fileSystems."/mnt/f" = {
device = "F:";
fsType = "drvfs";
};
swapDevices = [];
# Enables DHCP on each ethernet and wireless interface. In case of scripted networking
# (the default) this is the recommended approach. When using systemd-networkd it's
# still possible to use this option, but it's recommended to use it in conjunction
# with explicit per-interface declarations with `networking.interfaces.<interface>.useDHCP`.
networking.useDHCP = lib.mkDefault true;
# networking.interfaces.bond0.useDHCP = lib.mkDefault true;
# networking.interfaces.bonding_masters.useDHCP = lib.mkDefault true;
# networking.interfaces.dummy0.useDHCP = lib.mkDefault true;
# networking.interfaces.eth0.useDHCP = lib.mkDefault true;
# networking.interfaces.sit0.useDHCP = lib.mkDefault true;
# networking.interfaces.tunl0.useDHCP = lib.mkDefault true;
nixpkgs.hostPlatform = lib.mkDefault "x86_64-linux";
hardware.cpu.intel.updateMicrocode = lib.mkDefault config.hardware.enableRedistributableFirmware;
}

View File

@ -1,12 +0,0 @@
{
nixpkgs,
agenix,
home-manager,
flake-utils,
nixgl,
rust-overlay,
flake-compat,
pkgs,
lib,
proj_root,
}: {}

View File

@ -1,48 +0,0 @@
# Do not modify this file! It was generated by nixos-generate-config
# and may be overwritten by future invocations. Please make changes
# to /etc/nixos/configuration.nix instead.
{
config,
lib,
pkgs,
modulesPath,
...
}: {
imports = [
(modulesPath + "/installer/scan/not-detected.nix")
];
boot.loader.systemd-boot.enable = true;
boot.initrd.availableKernelModules = ["xhci_pci" "ahci" "nvme" "usbhid" "usb_storage" "sd_mod"];
# boot.initrd.kernelModules = [ "amdgpu" ];
boot.initrd.kernelModules = [];
boot.kernelModules = ["kvm-amd" "coretemp"];
boot.extraModulePackages = [];
fileSystems."/" =
# Might be wise to use /dev/nvme0p1 instead
{
device = "/dev/disk/by-uuid/27fc09b3-e3b7-4883-94a0-c313a0e0abe2";
fsType = "ext4";
};
fileSystems."/boot" =
# Might be wise to use /dev/nvme0p2 instead
{
device = "/dev/disk/by-uuid/EBA6-394D";
fsType = "vfat";
};
swapDevices = [];
# Enables DHCP on each ethernet and wireless interface. In case of scripted networking
# (the default) this is the recommended approach. When using systemd-networkd it's
# still possible to use this option, but it's recommended to use it in conjunction
# with explicit per-interface declarations with `networking.interfaces.<interface>.useDHCP`.
networking.useDHCP = lib.mkDefault true;
# networking.interfaces.enp5s0.useDHCP = lib.mkDefault true;
# networking.interfaces.wlp4s0.useDHCP = lib.mkDefault true;
nixpkgs.hostPlatform = lib.mkDefault "x86_64-linux";
hardware.cpu.amd.updateMicrocode = lib.mkDefault config.hardware.enableRedistributableFirmware;
}

View File

@ -1,91 +0,0 @@
{
nixpkgs,
agenix,
home-manager,
flake-utils,
nixgl,
rust-overlay,
flake-compat,
pkgs,
lib,
proj_root,
nixosDefaultVersion ? "22.05",
defaultSystem ? "x86_64-linux",
...
} @ finalInputs: let
config = {
bao.metadata = {
# req
hostName = "bao";
# opts
ssh_pubkey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIIBuAaAE7TiQmMH300VRj/pYCri1qPmHjd+y9aX2J0Fs";
nixosVersion = "22.11";
system = "x86_64-linux";
preset = "base";
};
# TODO: add override so that we can add wsl config on top
bao.nixosConfig = {
modules = [
(import ../modules/nvgpu.sys.nix)
(import ../modules/kde.sys.nix)
(import ../modules/pulseaudio.sys.nix)
(import ../modules/storage.perso.sys.nix)
];
};
};
propagate = hostConfig @ {
metadata,
nixosConfig,
}: let
# req
inherit (metadata) hostName;
# opts
ssh_pubkey = lib.attrByPath ["ssh_pubkey"] null metadata; # metadata.ssh_pubkey??undefined
users = lib.attrByPath ["users"] {} metadata;
nixosVersion = lib.attrByPath ["nixosVersion"] nixosDefaultVersion metadata;
system = lib.attrByPath ["system"] defaultSystem metadata;
preset = lib.attrByPath ["preset"] "base" metadata;
# infer
hardwareConfig = import "${proj_root.hosts.path}/${hostName}/hardware-configuration.nix";
# alias to prevent infinite recursion
_nixosConfig = nixosConfig;
in {
inherit hostName ssh_pubkey users nixosVersion system preset hardwareConfig;
nixosConfig =
_nixosConfig
// {
inherit system;
modules =
[
{
config._module.args = {
inherit proj_root;
my-lib = finalInputs.lib;
};
}
hardwareConfig
{
system.stateVersion = nixosVersion;
networking.hostName = hostName;
users.users = users;
}
{
imports = [agenix.nixosModule];
environment.systemPackages = [agenix.defaultPackage.x86_64-linux];
}
(import "${proj_root.modules.path}/secrets.nix")
(import "${proj_root.modules.path}/${preset}.sys.nix")
]
++ _nixosConfig.modules;
};
};
# we are blessed by the fact that we engulfed nixpkgs.lib.* at top level
mkHostFromPropagated = propagatedHostConfig @ {nixosConfig, ...}: nixpkgs.lib.nixosSystem nixosConfig;
mkHost = hostConfig: (lib.pipe [propagate mkHostFromPropagated] hostConfig);
trimNull = lib.filterAttrsRecursive (name: value: value != null);
flattenPubkey = lib.mapAttrs (hostName: meta_config: meta_config.metadata.ssh_pubkey);
in {
nixosConfigurations = lib.mapAttrs (name: hostConfig: mkHost hostConfig) config;
# {bao = "ssh-ed25519 ..."; another_host = "ssh-rsa ...";}
pubKeys = lib.getPubkey config;
}

View File

@ -1,44 +0,0 @@
# Do not modify this file! It was generated by nixos-generate-config
# and may be overwritten by future invocations. Please make changes
# to /etc/nixos/configuration.nix instead.
{
config,
lib,
pkgs,
modulesPath,
...
}: {
imports = [
(modulesPath + "/profiles/qemu-guest.nix")
];
boot.initrd.availableKernelModules = ["virtio_pci" "virtio_scsi" "ahci" "sd_mod"];
boot.initrd.kernelModules = [];
boot.kernelParams = ["console=ttyS0,19200n8"];
boot.loader.grub.extraConfig = ''
serial --speed=19200 --unit=0 --word=8 --parity=no --stop=1
terminal_input serial;
terminal_output serial
'';
boot.loader.grub.forceInstall = true;
boot.loader.grub.device = "nodev";
boot.loader.timeout = 10;
boot.kernelModules = [];
boot.extraModulePackages = [];
fileSystems."/" = {
device = "/dev/sda";
fsType = "ext4";
};
swapDevices = [{device = "/dev/sdb";}];
# Enables DHCP on each ethernet and wireless interface. In case of scripted networking
# (the default) this is the recommended approach. When using systemd-networkd it's
# still possible to use this option, but it's recommended to use it in conjunction
# with explicit per-interface declarations with `networking.interfaces.<interface>.useDHCP`.
networking.useDHCP = lib.mkDefault true;
# networking.interfaces.enp0s5.useDHCP = lib.mkDefault true;
hardware.cpu.amd.updateMicrocode = lib.mkDefault config.hardware.enableRedistributableFirmware;
}

View File

@ -1,44 +0,0 @@
# Do not modify this file! It was generated by nixos-generate-config
# and may be overwritten by future invocations. Please make changes
# to /etc/nixos/configuration.nix instead.
{
config,
lib,
pkgs,
modulesPath,
...
}: {
imports = [
(modulesPath + "/profiles/qemu-guest.nix")
];
boot.initrd.availableKernelModules = ["virtio_pci" "virtio_scsi" "ahci" "sd_mod"];
boot.initrd.kernelModules = [];
boot.kernelParams = ["console=ttyS0,19200n8"];
boot.loader.grub.extraConfig = ''
serial --speed=19200 --unit=0 --word=8 --parity=no --stop=1
terminal_input serial;
terminal_output serial
'';
boot.loader.grub.forceInstall = true;
boot.loader.grub.device = "nodev";
boot.loader.timeout = 10;
boot.kernelModules = [];
boot.extraModulePackages = [];
fileSystems."/" = {
device = "/dev/sda";
fsType = "ext4";
};
swapDevices = [{device = "/dev/sdb";}];
# Enables DHCP on each ethernet and wireless interface. In case of scripted networking
# (the default) this is the recommended approach. When using systemd-networkd it's
# still possible to use this option, but it's recommended to use it in conjunction
# with explicit per-interface declarations with `networking.interfaces.<interface>.useDHCP`.
networking.useDHCP = lib.mkDefault true;
# networking.interfaces.enp0s5.useDHCP = lib.mkDefault true;
hardware.cpu.amd.updateMicrocode = lib.mkDefault config.hardware.enableRedistributableFirmware;
}

View File

@ -1,12 +0,0 @@
{
nixpkgs,
agenix,
home-manager,
flake-utils,
nixgl,
rust-overlay,
flake-compat,
pkgs,
lib,
proj_root,
}: {}

View File

@ -1,51 +0,0 @@
# Do not modify this file! It was generated by nixos-generate-config
# and may be overwritten by future invocations. Please make changes
# to /etc/nixos/configuration.nix instead.
{
config,
lib,
pkgs,
modulesPath,
...
}: {
imports = [
(modulesPath + "/profiles/qemu-guest.nix")
];
boot.initrd.availableKernelModules = ["virtio_pci" "virtio_scsi" "ahci" "sd_mod"];
boot.initrd.kernelModules = [];
boot.kernelParams = ["console=ttyS0,19200n8"];
boot.loader.grub.extraConfig = ''
serial --speed=19200 --unit=0 --word=8 --parity=no --stop=1
terminal_input serial;
terminal_output serial
'';
boot.loader.grub.forceInstall = true;
boot.loader.grub.device = "nodev";
boot.loader.timeout = 10;
boot.kernelModules = [];
boot.extraModulePackages = [];
fileSystems = {
"/" = {
device = "/dev/sda";
fsType = "ext4";
};
# Assume Linode volume "gitea" exists, mount it to '/gitea"'
"/gitea" = {
device = "/dev/disk/by-id/scsi-0Linode_Volume_gitea";
fsType = "ext4";
};
};
swapDevices = [{device = "/dev/sdb";}];
# Enables DHCP on each ethernet and wireless interface. In case of scripted networking
# (the default) this is the recommended approach. When using systemd-networkd it's
# still possible to use this option, but it's recommended to use it in conjunction
# with explicit per-interface declarations with `networking.interfaces.<interface>.useDHCP`.
networking.useDHCP = lib.mkDefault true;
# networking.interfaces.enp0s5.useDHCP = lib.mkDefault true;
hardware.cpu.amd.updateMicrocode = lib.mkDefault config.hardware.enableRedistributableFirmware;
}

View File

@ -1,44 +0,0 @@
# Do not modify this file! It was generated by nixos-generate-config
# and may be overwritten by future invocations. Please make changes
# to /etc/nixos/configuration.nix instead.
{
config,
lib,
pkgs,
modulesPath,
...
}: {
imports = [
(modulesPath + "/profiles/qemu-guest.nix")
];
boot.initrd.availableKernelModules = ["virtio_pci" "virtio_scsi" "ahci" "sd_mod"];
boot.initrd.kernelModules = [];
boot.kernelModules = [];
boot.extraModulePackages = [];
boot.kernelParams = ["console=ttyS0,19200n8"];
boot.loader.grub.extraConfig = ''
serial --speed=19200 --unit=0 --word=8 --parity=no --stop=1
terminal_input serial;
terminal_output serial;
'';
boot.loader.grub.forceInstall = true;
boot.loader.grub.device = "nodev";
boot.loader.timeout = 10;
fileSystems."/" = {
device = "/dev/sda";
fsType = "ext4";
};
swapDevices = [{device = "/dev/sdb";}];
# Enables DHCP on each ethernet and wireless interface. In case of scripted networking
# (the default) this is the recommended approach. When using systemd-networkd it's
# still possible to use this option, but it's recommended to use it in conjunction
# with explicit per-interface declarations with `networking.interfaces.<interface>.useDHCP`.
networking.useDHCP = lib.mkDefault true;
# networking.interfaces.enp0s5.useDHCP = lib.mkDefault true;
hardware.cpu.amd.updateMicrocode = lib.mkDefault config.hardware.enableRedistributableFirmware;
}

View File

@ -1 +0,0 @@

1
mac_photos Symbolic link
View File

@ -0,0 +1 @@
/Users/hungtran/Pictures/Photos Library.photoslibrary

View File

@ -1,6 +0,0 @@
{
imports = [./gpu.sys.nix];
boot.initrd.kernelModules = ["amdgpu"];
services.xserver.enable = true;
services.xserver.videoDrivers = ["amdgpu"];
}

View File

@ -1,15 +0,0 @@
{
pkgs,
lib,
proj_root,
...
}: {
imports = [
./minimal.sys.nix
./mosh.sys.nix
./tailscale.sys.nix
./ssh.sys.nix
];
environment.systemPackages = [pkgs.lm_sensors];
time.timeZone = "America/Phoenix";
}

View File

@ -1 +0,0 @@
inputs: {}

View File

@ -1,12 +0,0 @@
{pkgs, ...}: {
environment.systemPackages = [pkgs.clinfo pkgs.lshw pkgs.glxinfo pkgs.pciutils pkgs.vulkan-tools];
hardware.opengl = {
enable = true;
extraPackages = [pkgs.rocm-opencl-icd pkgs.rocm-opencl-runtime];
# Vulkan
driSupport = true;
driSupport32Bit = true;
package = pkgs.mesa.drivers;
package32 = pkgs.pkgsi686Linux.mesa.drivers;
};
}

View File

@ -1,30 +0,0 @@
{
pkgs,
my-lib,
...
}: {
environment.noXlibs = my-lib.mkForce false;
# TODO: wireless networking
# Enable the X11 windowing system.
services.xserver.enable = true;
# KDE & Plasma 5
services.xserver.displayManager.sddm.enable = true;
services.xserver.desktopManager.plasma5 = {
enable = true;
excludePackages = let
plasma5 = pkgs.libsForQt5;
in [
plasma5.elisa # audio viewer
plasma5.konsole # I use alacritty instaed
plasma5.plasma-browser-integration
plasma5.print-manager # will enable if I need
plasma5.khelpcenter # why not just write manpages instead :(
# plasma5.ksshaskpass # pls just put prompts on my dear terminal
];
};
# disables KDE's setting of askpassword
programs.ssh.askPassword = "";
programs.ssh.enableAskPassword = false;
}

View File

@ -1,31 +0,0 @@
{
pkgs,
lib,
proj_root,
modulesPath,
...
}: {
imports = ["${modulesPath}/profiles/minimal.nix"];
# prune old builds after a while
nix.settings.auto-optimise-store = true;
nix.package = pkgs.nixFlakes; # nix flakes
nix.extraOptions = ''
experimental-features = nix-command flakes
'';
programs.neovim = {
enable = true;
defaultEditor = true;
};
programs.git.enable = true;
environment.systemPackages = [
pkgs.gnumake
pkgs.wget
pkgs.inetutils # network diag
pkgs.mtr # network diag
pkgs.sysstat # sys diag
];
users.users.root = {
# openssh runs in root, no? This is because port < 1024 requires root.
openssh.authorizedKeys.keys = lib.strings.splitString "\n" (builtins.readFile "${proj_root.configs.path}/ssh/authorized_keys");
};
}

View File

@ -1,28 +0,0 @@
{
pkgs,
lib,
config,
...
}: let
cfg = config.mod.mosh;
in {
options.mod.mosh = {
enable = lib.mkOption {
type = lib.types.bool;
description = "enable mosh";
default = true;
example = false;
};
};
config = lib.mkIf cfg.enable {
environment.systemPackages = [pkgs.mosh];
networking.firewall = lib.mkIf config.networking.firewall.enable {
allowedUDPPortRanges = [
{
from = 60000;
to = 61000;
} # mosh
];
};
};
}

View File

@ -1,7 +0,0 @@
{config, ...}: {
imports = [./gpu.sys.nix];
nixpkgs.config.allowUnfree = true;
services.xserver.enable = true;
services.xserver.videoDrivers = ["nvidia"];
hardware.nvidia.package = config.boot.kernelPackages.nvidiaPackages.stable;
}

View File

@ -1,23 +0,0 @@
{
config,
pkgs,
lib,
}: let
gpu_pkgs = [pkgs.clinfo pkgs.lshw pkgs.glxinfo pkgs.pciutils pkgs.vulkan-tools];
gpu_conf = {
# openCL
hardware.opengl = {
enable = true;
extraPackages = let
inherit (pkgs) rocm-opencl-icd rocm-opencl-runtime;
in [rocm-opencl-icd rocm-opencl-runtime];
# Vulkan
driSupport = true;
driSupport32Bit = true;
package = pkgs.mesa.drivers;
package32 = pkgs.pkgsi686Linux.mesa.drivers;
};
environment.systemPackages = gpu_pkgs;
};
in
gpu_conf

View File

@ -1,15 +0,0 @@
{
# Sound: pipewire
sound.enable = false;
hardware.pulseaudio.enable = false;
services.pipewire = {
enable = true;
alsa.enable = true;
alsa.support32Bit = true;
pulse.enable = true;
# Might want to use JACK in the future
jack.enable = true;
};
security.rtkit.enable = true;
}

View File

@ -1,9 +0,0 @@
{
# Enable sound. (pulse audio)
sound.enable = true;
programs.dconf.enable = true;
hardware.pulseaudio.enable = true;
hardware.pulseaudio.support32Bit = true;
nixpkgs.config.pulseaudio = true;
hardware.pulseaudio.extraConfig = "load-module module-combine-sink";
}

View File

@ -1,18 +0,0 @@
{proj_root, ...}: {
age.secrets.s3fs = {
file = "${proj_root.secrets.path}/s3fs.age";
# mode = "600"; # owner + group only
# owner = "hungtr";
# group = "users";
};
age.secrets."s3fs.digital-garden" = {
file = "${proj_root.secrets.path}/s3fs.digital-garden.age";
};
age.secrets._nhitrl_cred = {
file = "${proj_root.secrets.path}/_nhitrl.age";
};
age.secrets."wifi.env" = {
file = "${proj_root.secrets.path}/wifi.env.age";
};
# environment.systemPackages = [agenix.defaultPackage.x86_64-linux];
}

View File

@ -1,6 +0,0 @@
{
services.openssh = {
enable = true;
permitRootLogin = "no";
};
}

View File

@ -1,94 +0,0 @@
# Personal configuration on storage solution
{
pkgs,
config,
lib,
...
}: {
environment.systemPackages = [
pkgs.s3fs
pkgs.cifs-utils
];
# Sadly, autofs uses systemd, so we can't put it in home-manager
# HACK: need to store secret somewhere so that root can access this
# because autofs may run as root for now, we enforce putting the secret in this monorepo
# TODO: make this configuration nix-less to show that it's 100% data
services.autofs = let
# confToBackendArg {lol="what"; empty=""; name_only=null;} -> "lol=what,empty=,name_only"
# TODO: change null -> true/false. This allows overriding & better self-documentation
confToBackendArg = conf: (lib.concatStringsSep ","
(lib.mapAttrsToList (name: value: "${name}${lib.optionalString (value != null) "=${value}"}") conf));
# mount_dest: path ("wow")
# backend_args: nix attrs representing the arguments to be passed to s3fs
# ({"-fstype" = "fuse"; "use_cache" = "/tmp";})
# bucket: bucket name (hungtr-hot)
# NOTE: s3 custom provider will be provided inside
# backend_args, so just put the bucket name here
#
#-> "${mount_dest} ${formatted_args} ${s3fs-bin}#${bucket}"
autofs-s3fs_entry = {
mount_dest,
backend_args ? {"-fstype" = "fuse";},
bucket,
} @ inputs: let
s3fs-exec = "${pkgs.s3fs}/bin/s3fs";
in "${mount_dest} ${confToBackendArg backend_args} :${s3fs-exec}\#${bucket}";
personalStorage = [
(autofs-s3fs_entry {
mount_dest = "garden";
backend_args = {
"-fstype" = "fuse";
use_cache = "/tmp";
del_cache = null;
allow_other = null;
url = "https://v5h5.la11.idrivee2-14.com";
passwd_file = config.age.secrets."s3fs.digital-garden".path;
dbglevel = "debug"; # enable this for better debugging info in journalctl
uid = "1000"; # default user
gid = "100"; # users
umask = "003"; # others read only, fully shared for users group
};
bucket = "digital-garden";
})
(
let
args = {
"-fstype" = "cifs";
credentials = config.age.secrets._nhitrl_cred.path;
user = null;
uid = "1001";
gid = "100";
dir_mode = "0777";
file_mode = "0777";
};
in "felia_d ${confToBackendArg args} ://felia.coati-celsius.ts.net/d"
)
(
let
args = {
"-fstype" = "cifs";
credentials = config.age.secrets._nhitrl_cred.path;
user = null;
uid = "1001";
gid = "100";
dir_mode = "0777";
file_mode = "0777";
};
in "felia_f ${confToBackendArg args} ://felia.coati-celsius.ts.net/f"
)
];
persoConf = pkgs.writeText "auto.personal" (builtins.concatStringsSep "\n" personalStorage);
in {
enable = true;
# Creates /perso directory with every subdirectory declared by ${personalStorage}
# as of now (might be stale), /perso/hot is the only mount accessible
# that is also managed by s3fs
autoMaster = ''
/perso file:${persoConf}
'';
timeout = 30; # default: 600, 600 seconds (10 mins) of inactivity => unmount
# debug = true; # writes to more to journalctl
};
}

View File

@ -1,57 +0,0 @@
{
pkgs,
config,
lib,
...
}: let
cfg = config.mod.tailscale;
in {
options.mod.tailscale = {
enable = lib.mkEnableOption "tailscale";
};
config = lib.mkIf cfg.enable {
environment.systemPackages = [pkgs.tailscale];
services.tailscale.enable = true;
systemd.services.tailscale-autoconnect = {
description = "Automatically connects to Tailscale";
# make sure tailscale is running before trying to connect to tailscale
after = ["network-pre.target" "tailscale.service"];
wants = ["network-pre.target" "tailscale.service"];
wantedBy = ["multi-user.target"];
# set this service as a oneshot job
serviceConfig.Type = "oneshot";
# have the job run this shell script
script = ''
# wait for tailscaled to settle
sleep 2
# check if we are already authenticated to tailscale
status="$(${pkgs.tailscale}/bin/tailscale status -json | ${pkgs.jq}/bin/jq -r .BackendState)"
if [ $status = "Running" ]; then # if so, then do nothing
exit 0
fi
# ${pkgs.tailscale}/bin/tailscale up # blocks, doesn't give url
# This time, configure device auth so that we authenticate from portal
# https://tailscale.com/kb/1099/device-authorization/#enable-device-authorization-for-your-network
${pkgs.tailscale}/bin/tailscale up -authkey tskey-auth-kJcgTG5CNTRL-PUVFkk31z1bThHpfq3FC5b1jcMmkW2EYW
'';
};
networking.firewall = lib.mkIf config.networking.firewall.enable {
trustedInterfaces = [
"tailscale0"
];
allowedUDPPorts = [
config.services.tailscale.port
];
allowedTCPPorts = [
22
];
checkReversePath = "loose";
};
};
}

View File

@ -1,8 +0,0 @@
{config, ...}: {
networking.wireless.enable = true;
networking.wireless.environmentFile = config.age.secrets."wifi.env";
networking.wireless.networks = {
"Hoang Sa".psk = "@DESERT_PSK@";
"Truong Sa".psk = "@DESERT_PSK@";
};
}

View File

@ -120,7 +120,6 @@ font:
# - (Linux/BSD) monospace # - (Linux/BSD) monospace
# - (Windows) Consolas # - (Windows) Consolas
family: DroidSansMono NF family: DroidSansMono NF
# The `style` can be specified to pick a specific face. # The `style` can be specified to pick a specific face.
#style: Regular #style: Regular
@ -159,7 +158,6 @@ font:
# Point size # Point size
size: 7.0 size: 7.0
# Offset is the extra space around each character. `offset.y` can be thought # Offset is the extra space around each character. `offset.y` can be thought
# of as modifying the line spacing, and `offset.x` as modifying the letter # of as modifying the line spacing, and `offset.x` as modifying the letter
# spacing. # spacing.
@ -771,7 +769,12 @@ key_bindings:
# Vi Mode # Vi Mode
#- { key: Space, mods: Shift|Control, mode: ~Search, action: ToggleViMode } #- { key: Space, mods: Shift|Control, mode: ~Search, action: ToggleViMode }
- { key: Escape, mods: Shift, mode: ~Search, action: ToggleViMode } - {
key: Escape,
mods: Shift,
mode: ~Search,
action: ToggleViMode
}
#- { key: Space, mods: Shift|Control, mode: Vi|~Search, action: ScrollToBottom } #- { key: Space, mods: Shift|Control, mode: Vi|~Search, action: ScrollToBottom }
#- { key: Escape, mode: Vi|~Search, action: ClearSelection } #- { key: Escape, mode: Vi|~Search, action: ClearSelection }
#- { key: I, mode: Vi|~Search, action: ToggleViMode } #- { key: I, mode: Vi|~Search, action: ToggleViMode }
@ -836,7 +839,7 @@ key_bindings:
# (Windows, Linux, and BSD only) # (Windows, Linux, and BSD only)
- { key: V, mods: Control|Shift, mode: ~Vi, action: Paste } - { key: V, mods: Control|Shift, mode: ~Vi, action: Paste }
- { key: C, mods: Control|Shift, action: Copy } - { key: C, mods: Control|Shift, action: Copy }
- { key: Return, mods: Alt, action: ToggleFullscreen } # - { key: Return, mods: Alt, action: ToggleFullscreen }
#- { key: F, mods: Control|Shift, mode: ~Search, action: SearchForward } #- { key: F, mods: Control|Shift, mode: ~Search, action: SearchForward }
#- { key: B, mods: Control|Shift, mode: ~Search, action: SearchBackward } #- { key: B, mods: Control|Shift, mode: ~Search, action: SearchBackward }
#- { key: C, mods: Control|Shift, mode: Vi|~Search, action: ClearSelection } #- { key: C, mods: Control|Shift, mode: Vi|~Search, action: ClearSelection }
@ -866,7 +869,9 @@ key_bindings:
#- { key: Q, mods: Command, action: Quit } #- { key: Q, mods: Command, action: Quit }
#- { key: W, mods: Command, action: Quit } #- { key: W, mods: Command, action: Quit }
#- { key: N, mods: Command, action: SpawnNewInstance } #- { key: N, mods: Command, action: SpawnNewInstance }
- { key: Return, mods: Command, action: ToggleFullscreen } # NOTE: Use Command + Control + F
#
# - { key: Return, mods: Command, action: ToggleFullscreen }
#- { key: F, mods: Command, mode: ~Search, action: SearchForward } #- { key: F, mods: Command, mode: ~Search, action: SearchForward }
#- { key: B, mods: Command, mode: ~Search, action: SearchBackward } #- { key: B, mods: Command, mode: ~Search, action: SearchBackward }

View File

@ -0,0 +1,129 @@
# Font configuration
font_family Hack Nerd Font Mono
bold_font Hack Nerd Font Mono Bold
italic_font Hack Nerd Font Mono Italic
bold_italic_font Hack Nerd Font Mono Bold Italic
font_size 11.0
sync_to_monitor no
disable_ligatures never
# NO BELLS!
enable_audio_bell no
# theme gruvbox_dark
# include /themes/gruvbox_dark.conf
# window_margin_width 5.0
# window_padding_width 5.0
# I'm on Prime's team here, blinking cursor is too distracting
cursor_blink_interval 0
background #282c34
dynamic_background_opacity true
background_opacity 0.97
macos_traditional_fullscreen no
# from nvim-nonicons
# symbol_map U+f101-U+f208 nonicon regular
# No creating windows
map ctrl+shift+enter no_op
map cmd+enter no_op
# I don't understand why some of these have remaps on MacOS
# new_os_window
map ctrl+shift+n no_op
# new_os_window
map cmd+n no_op
map ctrl+shift+w close_window
map shft+cmd+d no_op # just disable any apple-linux segregation
# tabs
## Tab creation
map ctrl+shift+t combine | new_tab | set_tab_title _
map cmd+t no_op
map ctrl+, set_tab_title _
## No tab destruction
map ctrl+shift+q no_op
map ctrl+shift+w no_op
# close_tab 🍎
map cmd+w no_op
## No tab iteration
# next_tab
map ctrl+shift+right no_op
# next_tab 🍎
map shift+cmd+] no_op
# next_tab
map ctrl+tab no_op
# previous_tab
map ctrl+shift+left no_op
# previous_tab 🍎
map shift+cmd+[ no_op
# previous_tab
map ctrl+shift+tab no_op
# move_tab_forward
map ctrl+shift+. no_op
## Tab linear jumping
map ctrl+1 goto_tab 1
map ctrl+2 goto_tab 2
map ctrl+3 goto_tab 3
map ctrl+4 goto_tab 4
map ctrl+5 goto_tab 5
map ctrl+6 goto_tab 6
map ctrl+7 goto_tab 7
map ctrl+8 goto_tab 8
map ctrl+9 goto_tab 9
map ctrl+0 goto_tab 10
### A bit ergonomics for mac
map cmd+1 goto_tab 1
map cmd+2 goto_tab 2
map cmd+3 goto_tab 3
map cmd+4 goto_tab 4
map cmd+5 goto_tab 5
map cmd+6 goto_tab 6
map cmd+7 goto_tab 7
map cmd+8 goto_tab 8
map cmd+9 goto_tab 9
map cmd+0 goto_tab 10
## Just disable all iteration of tab - use linear mapping
map ctrl+shift+right no_op
map shift+cmd+] no_op
map ctrl+tab no_op
map ctrl+shift+left no_op
map shift+cmd+[ no_op
map ctrl+shift+tab no_op
## Titles
tab_bar_edge top
tab_fade 0.6 1
tab_title_template "{fmt.fg.red}{bell_symbol}{activity_symbol}{fmt.fg.tab}{index}|{title}{(lambda parts: '/'.join([p if len(p) <= 2 else p[:2]+'…' for p in parts[:-1]] + [parts[-1]]))(tab.active_wd.split('/'))}"
active_tab_font_style bold
active_tab_foreground #000
active_tab_background #eee
inactive_tab_foreground #444
inactive_tab_background #999
map ctrl+shift+, set_tab_title
# set_tab_title
map ctrl+shift+alt+t no_op
# set_tab_title
map shift+cmd+i no_op
# map ctrl+shift+p>n kitten hints --type=linenum --linenum-action=tab nvim +{line} {path}
# I don't really have good way to ever press F1
# map f1 kitten hints --customize-processing hint_define_word.py

View File

@ -18,12 +18,13 @@ endif
local Plug = vim.fn['plug#'] local Plug = vim.fn['plug#']
-- prepare a list of installed plugins from rtp -- prepare a list of installed plugins from rtp
--- @type table<string, boolean>
local installed_plugins = {} local installed_plugins = {}
-- NOTE: nvim_list_runtime_paths will expand wildcard paths for us. -- NOTE: nvim_list_runtime_paths will expand wildcard paths for us.
for _, path in ipairs(vim.api.nvim_list_runtime_paths()) do for _, path in ipairs(vim.api.nvim_list_runtime_paths()) do
local last_folder_start = path:find("/[^/]*$") local last_folder_start = path:find("/[^/]*$")
if last_folder_start then if last_folder_start then
local plugin_name = path:sub(last_folder_start + 1) local plugin_name = string.lower(path:sub(last_folder_start + 1))
installed_plugins[plugin_name] = true installed_plugins[plugin_name] = true
end end
end end
@ -31,17 +32,29 @@ end
local wplug_log = require('plenary.log').new({ plugin = 'wplug_log', level = 'debug', use_console = false }) local wplug_log = require('plenary.log').new({ plugin = 'wplug_log', level = 'debug', use_console = false })
-- Do Plug if plugin not yet linked in `rtp`. This takes care of Nix-compatibility -- Do Plug if plugin not yet linked in `rtp`. This takes care of Nix-compatibility
local function WPlug(plugin_path, ...) local function WPlug(plugin_path, ...)
-- hrsh7th/cmp-nvim -> cmp-nvim
local plugin_name = string.lower(plugin_path:match("/([^/]+)$")) local plugin_name = string.lower(plugin_path:match("/([^/]+)$"))
if not installed_plugins[plugin_name] then if not installed_plugins[plugin_name] then
wplug_log.info("Plugging " .. plugin_path) wplug_log.info("Missing in rtp: " .. plugin_name .. " path: " .. plugin_path)
Plug(plugin_path, ...) Plug(plugin_path, ...)
end end
installed_plugins[plugin_name] = false
end end
-- Borked, reason unknown
-- for plugin, plugged in pairs(installed_plugins) do
-- if plugged ~= false then
-- wplug_log.info("Plugin " .. plugin .. " added to rtp but not WPlug-ed")
-- end
-- end
vim.call('plug#begin') vim.call('plug#begin')
-- libs and dependencies -- libs and dependencies
-- Plug('nvim-lua/plenary.nvim') -- The base of all plugins WPlug('nvim-lua/plenary.nvim') -- The base of all plugins
WPlug('MunifTanjim/nui.nvim') -- For some .so or .dylib neovim UI action
-- plugins -- plugins
WPlug('tjdevries/nlua.nvim') -- adds symbols of vim stuffs in init.lua WPlug('tjdevries/nlua.nvim') -- adds symbols of vim stuffs in init.lua
@ -94,6 +107,7 @@ WPlug('radenling/vim-dispatch-neovim') -- Add support for neovim's terminal
WPlug('gennaro-tedesco/nvim-jqx') -- JSON formatter (use :Jqx*) WPlug('gennaro-tedesco/nvim-jqx') -- JSON formatter (use :Jqx*)
WPlug('kylechui/nvim-surround') -- surrounds with tags/parenthesis WPlug('kylechui/nvim-surround') -- surrounds with tags/parenthesis
WPlug('simrat39/rust-tools.nvim') -- config rust-analyzer and nvim integration WPlug('simrat39/rust-tools.nvim') -- config rust-analyzer and nvim integration
WPlug('tjdevries/sg.nvim') -- Cody and other cool sourcegraph stuffs
-- UI & colorscheme -- UI & colorscheme
WPlug('simrat39/inlay-hints.nvim') -- type-hints with pseudo-virtual texts WPlug('simrat39/inlay-hints.nvim') -- type-hints with pseudo-virtual texts
@ -111,7 +125,6 @@ WPlug('nvim-treesitter/nvim-treesitter-context') -- Top one-liner context of fun
WPlug('nvim-treesitter/playground') -- Sees Treesitter AST - less hair pulling, more PRs WPlug('nvim-treesitter/playground') -- Sees Treesitter AST - less hair pulling, more PRs
WPlug('saadparwaiz1/cmp_luasnip') -- snippet engine WPlug('saadparwaiz1/cmp_luasnip') -- snippet engine
WPlug('L3MON4D3/LuaSnip') -- snippet engine WPlug('L3MON4D3/LuaSnip') -- snippet engine
WPlug('mickael-menu/zk-nvim') -- Zettelkasten
WPlug('folke/neodev.nvim') -- Neovim + lua development setup WPlug('folke/neodev.nvim') -- Neovim + lua development setup
-- Switch cases: -- Switch cases:
-- `gsp` -> PascalCase (classes), `gsc` -> camelCase (Java), `gs_` -> snake_case (C/C++/Rust) -- `gsp` -> PascalCase (classes), `gsc` -> camelCase (Java), `gs_` -> snake_case (C/C++/Rust)
@ -209,8 +222,8 @@ vim.opt.completeopt = { "menu", "menuone", "noselect", "noinsert" }
-- vim.opt.clipboard = "unnamedplus" -- vim.opt.clipboard = "unnamedplus"
-- more aggressive swap file writing. ThePrimeagen believes higher number
-- leads to low DX -- more aggressive swap file writing. ThePrimeagen believes higher number leads to low DX
vim.opt.updatetime = 50 vim.opt.updatetime = 50
vim.g.mapleader = ' ' vim.g.mapleader = ' '
@ -438,16 +451,6 @@ remap('n', '<leader>fd', function()
require('telescope.builtin').diagnostics() require('telescope.builtin').diagnostics()
end, { desc = '[F]ind [D]iagnostics' }) end, { desc = '[F]ind [D]iagnostics' })
-- ZK remap stuffs
remap('n', '<leader>zf', function()
-- vim.cmd([[:ZkNotes]])
require('zk').edit({}, { multi_select = false })
end, { desc = '[Z]ettelkasten [F]iles' })
remap('n', '<leader>zg', function()
vim.cmd(":ZkGrep")
end, { desc = '[Z]ettelkasten [G]rep' })
-- tab management {{{ -- tab management {{{
-- Jump to specific tab with <C-t>[number] -- Jump to specific tab with <C-t>[number]
@ -581,7 +584,7 @@ for i = 1, 10 do
-- harpoon: navigate terms by numbers -- harpoon: navigate terms by numbers
remap('n', '<leader>t' .. tostring(i % 10), function() remap('n', '<leader>t' .. tostring(i % 10), function()
require('harpoon.term').gotoTerminal(i) require('harpoon.term').gotoTerminal(i)
end) end, { desc = "Terminal " .. i })
end end
-- neogit: easy-to-see git status. Provides only productivity on staging/unstage -- neogit: easy-to-see git status. Provides only productivity on staging/unstage
@ -678,6 +681,10 @@ local on_attach = function(client, bufnr)
-- enable inlay hints if available -- enable inlay hints if available
require('inlay-hints').on_attach(client, bufnr) require('inlay-hints').on_attach(client, bufnr)
end end
require("sg").setup {
on_attach = on_attach,
}
-- nvim-cmp -- nvim-cmp
local cmp = require 'cmp' local cmp = require 'cmp'
@ -887,6 +894,41 @@ cmp.setup.cmdline(':', {
-- nvim-cmp supports additional completion capabilities -- nvim-cmp supports additional completion capabilities
local capabilities = require('cmp_nvim_lsp').default_capabilities() local capabilities = require('cmp_nvim_lsp').default_capabilities()
-- NOTE: extend nvim-lspconfig locally for development
local function ensure_ungrammar_lspconfig()
local lspconfig = require('lspconfig')
local configs = require('lspconfig.configs')
if not configs['ungrammar_lsp'] then
configs['ungrammar_lsp'] = {
default_config = {
cmd = {
"ungrammar_lsp"
},
filetypes = { "ungrammar", "ungram" },
root_dir = lspconfig.util.root_pattern(".git", ".ungram"),
settings = {
-- Your LSP-specific settings
},
},
}
end
end
ensure_ungrammar_lspconfig()
local function setup_ungrammar_handler()
-- NOTE: requires `lspconfig.configs.ungrammar_lsp.default_config` to exists
require('lspconfig').ungrammar_lsp.setup {
on_attach = on_attach,
capabilities = capabilities,
settings = {
-- ungrammar lsp settings to be determined
},
}
end
-- local tabnine = require('cmp_tabnine.config') -- local tabnine = require('cmp_tabnine.config')
-- tabnine.setup({ -- tabnine.setup({
-- max_lines = 1000, -- max_lines = 1000,
@ -937,6 +979,58 @@ local inlay_hint_tsjs = {
includeInlayVariableTypeHints = true, includeInlayVariableTypeHints = true,
}; };
local setup = {
["nil_ls"] = function()
require('lspconfig').nil_ls.setup {
on_attach = on_attach,
capabilities = capabilities,
--- refer to https://github.com/oxalica/nil/blob/main/docs/configuration.md
--- for the list of configurations available for `nil_ls`
settings = {
["nil"] = {
formatting = {
-- NOTE: nil_ls automatically adds the specific path to the filename
-- at the end, so we couldn't really have a fallback mechanism without
-- wrapping.
command = {
"nix", "run", "nixpkgs#alejandra"
},
},
nix = {
flake = {
-- calls `nix flake archive` to put a flake and its output to store
autoArchive = true,
-- auto eval flake inputs for improved completion
autoEvalInputs = true,
},
},
},
},
}
end,
["gopls"] = function()
local lspconfig = require('lspconfig')
lspconfig.gopls.setup {
cmd = { "gopls" },
settings = {
gopls = {
analyses = {
unusedparams = true,
},
staticcheck = true,
},
},
root_dir = lspconfig.util.root_pattern('.git', 'go.mod'),
on_attach = on_attach,
capabilities = capabilities,
}
end,
}
setup_ungrammar_handler()
require('mason-lspconfig').setup_handlers({ require('mason-lspconfig').setup_handlers({
-- default handler -- default handler
function(server_name) function(server_name)
@ -1043,30 +1137,10 @@ require('mason-lspconfig').setup_handlers({
}, },
} }
end, end,
["nil_ls"] = function()
require('lspconfig').nil_ls.setup {
on_attach = on_attach,
capabilities = capabilities,
--- refer to https://github.com/oxalica/nil/blob/main/docs/configuration.md
--- for the list of configurations available for `nil_ls`
settings = {
["nil"] = {
formatting = {
command = { "nix", "run", "nixpkgs#alejandra" },
},
nix = {
flake = {
-- calls `nix flake archive` to put a flake and its output to store
autoArchive = true,
-- auto eval flake inputs for improved completion
autoEvalInputs = true,
},
},
},
},
}
end,
}) })
setup["nil_ls"]()
setup["gopls"]()
require("rust-tools").setup { require("rust-tools").setup {
tools = { tools = {
-- rust-tools options -- rust-tools options
@ -1253,49 +1327,6 @@ require("rust-tools").setup {
}, },
} }
require('zk').setup({
picker = "telescope",
lsp = {
config = {
cmd = { "zk", "lsp" },
name = "zk",
on_attach = on_attach,
},
auto_attach = {
enable = true,
filetypes = { "markdown" }
},
},
})
-- Custom ZkOrphans that determines unlinked notes
-- `:ZkOrphans {tags = {"work"}}`
require('zk.commands').add("ZkOrphans", function(options)
options = vim.tbl_extend("force", { orphan = true }, options or {})
-- zk.edit opens notes picker
require('zk').edit(options, { title = "Zk Orphans (unlinked notes)" })
end)
--
-- ZkGrep: opens file picker
-- In the case where `match_ctor` is falsy, create a prompt.
-- This is so that we distinguish between ZkGrep and ZkNotes
-- Params:
-- match_ctor: string | {match= :string,...} | "" | nil
require('zk.commands').add("ZkGrep", function(match_ctor)
-- handle polymorphic `match_ctor`
local grep_str = match_ctor
local match
if match_ctor == nil or match_ctor == '' then
vim.fn.inputsave()
grep_str = vim.fn.input('Grep string: >')
match = { match = grep_str }
elseif type(match_ctor) == 'string' then
match = { match = grep_str }
end
require('zk').edit(match, { title = "Grep: '" .. grep_str .. "'", mutli_select = false })
end)
-- Gitsigns -- Gitsigns
require('gitsigns').setup { require('gitsigns').setup {
signs = { signs = {

View File

@ -5,3 +5,4 @@ ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDFQN5Ia8rTalnQgcvdxH2n7UNNT1Tq9UvNdJeg9ziJ
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCgmng5xL/auvI2F8ufFAfId2Ey55ONHjgnKKSEWLVWkPMutXT3BCnSglNAuEVRLX2zfzg3beQd80AHTow+qro5QWI/rYfeL1QPNEwoThbRFcvtWLTlgzBGA4ejjpIF9sCPNp0sXrrQRfxRP7w4b23BcRJQcsDoaEtKGKJZ2GQIoOafkYypwcunANb54EAouZTfHEPKDr26Gfw8usc2Sae32G/80QLBF2jGabyexJjNE3F6hdJTwq5iiqIVdSr4ue82zo3M8jBdtCMDGaOliI5RWSa9iuX9o2scCGDU69Gkw7ma+JHOP/e9Z8sUz03TkjPbEnGi3EC3YAHEoDzmwqTi07hppCuzacLB5NZ9UZ1g5PzBIZR8TJTONngT08EQyGrkNv2sUnn0dtBqve5tHR04NuXy65ym7Iwl2DDVbAL0NlM4gKWzOGZ2CnSLT0WmkG2sQKU37NmS2pBJ8RXJBatUFe4vQVzqlFj39iRGIBV5XR0I9xcxDfCxBHFs3aIqAqE= hwtr@hwtr-prince ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCgmng5xL/auvI2F8ufFAfId2Ey55ONHjgnKKSEWLVWkPMutXT3BCnSglNAuEVRLX2zfzg3beQd80AHTow+qro5QWI/rYfeL1QPNEwoThbRFcvtWLTlgzBGA4ejjpIF9sCPNp0sXrrQRfxRP7w4b23BcRJQcsDoaEtKGKJZ2GQIoOafkYypwcunANb54EAouZTfHEPKDr26Gfw8usc2Sae32G/80QLBF2jGabyexJjNE3F6hdJTwq5iiqIVdSr4ue82zo3M8jBdtCMDGaOliI5RWSa9iuX9o2scCGDU69Gkw7ma+JHOP/e9Z8sUz03TkjPbEnGi3EC3YAHEoDzmwqTi07hppCuzacLB5NZ9UZ1g5PzBIZR8TJTONngT08EQyGrkNv2sUnn0dtBqve5tHR04NuXy65ym7Iwl2DDVbAL0NlM4gKWzOGZ2CnSLT0WmkG2sQKU37NmS2pBJ8RXJBatUFe4vQVzqlFj39iRGIBV5XR0I9xcxDfCxBHFs3aIqAqE= hwtr@hwtr-prince
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC/UzKwmFsAlLoCXvOq2lsC1sr1BRDW5uPkdcYUfQ7z4JowL/pscoTV9zjfJd1hPBvHLBvn7gs7gWt0wNnJfD1Oor26VreHjhi1PZE2kovrEzjmPoz+GqMPciV+HF9XNIRwDiHlUNFPt9qJjAJXJCFhzcmT9q0JQuPlNgJtQ6+By7RgPuJczpf17IbxpheLcXqtOFcTHyRT01KijIPhAtWRlmG5dahVuu50EfpmHRYZ8nCJJqkuJ6uRbFaPE6mYLnXLSzJUdyakYnzWbCd5phpoGAuFyQZnS503CFZUOFCnNEN8QfO2DXihp7lvrzzpI6PgcpvpotSo9kYFiEuB+DRlBQcVMWL0lUk2J1JHJH83y3CxwH0pUc7E1k6FAZE4pv4x0KEvbZSvmb8jAGWZkn4HvZCwXR5wGVi22s6RCdIHvR2PCpAy+ZSjpM+2FJIqDHpxY/vo3ktM9rpeCSwp14F/iiw6nanVq/KZBpCZ2paMcAU4WreCFZiPdGsdiixYlts= hungtr@bao ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC/UzKwmFsAlLoCXvOq2lsC1sr1BRDW5uPkdcYUfQ7z4JowL/pscoTV9zjfJd1hPBvHLBvn7gs7gWt0wNnJfD1Oor26VreHjhi1PZE2kovrEzjmPoz+GqMPciV+HF9XNIRwDiHlUNFPt9qJjAJXJCFhzcmT9q0JQuPlNgJtQ6+By7RgPuJczpf17IbxpheLcXqtOFcTHyRT01KijIPhAtWRlmG5dahVuu50EfpmHRYZ8nCJJqkuJ6uRbFaPE6mYLnXLSzJUdyakYnzWbCd5phpoGAuFyQZnS503CFZUOFCnNEN8QfO2DXihp7lvrzzpI6PgcpvpotSo9kYFiEuB+DRlBQcVMWL0lUk2J1JHJH83y3CxwH0pUc7E1k6FAZE4pv4x0KEvbZSvmb8jAGWZkn4HvZCwXR5wGVi22s6RCdIHvR2PCpAy+ZSjpM+2FJIqDHpxY/vo3ktM9rpeCSwp14F/iiw6nanVq/KZBpCZ2paMcAU4WreCFZiPdGsdiixYlts= hungtr@bao
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDAW4E8L/zGkcqixJo1102ddqeexoBMHIhXRXpWR3dTmJtbaaVbo4+rHRsjHPvHif9CRfi+BQ8CHG3zmBjH7DZPZIRCVtkms1EDe1k/G3fEnfgYc6gboJfoTdLkVjNOtdStTi03dCA/riQqUKc7/v16R5ZXIAmNCnmMHelObCSDPzYg8psZAUk1ZZY//pnhp9JRPsC2JxsshN7HCNIED9aFgrJkvUt+wUVGjVHzyQwyR6J7m1yyoivTwdmYdulG7OriLeeNq8vkoDmLGgLSC+zKehzJYOZsH3EKuxuZjQ3J9tK/NseQOhsQglRHE/OvphMwT/J96gl9dZR/LQXp4S6hwLccTzFfs8rLaTOIK6CEpqBUuBonot/1vJP5j5E73hfkHwZO7TQKwfXtpRCxCl5Nm3cB2Y3kz5mArDiwWioVsX4qd0XR0F9MFtuTVTn2f4K/Gwr9P3XMkLWXU1+1KbQiWIg+Zf5DpQgBW5HWryZzsMcjyMC2I2BJCl6Q+V8ofSM= nixos@Felia ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDAW4E8L/zGkcqixJo1102ddqeexoBMHIhXRXpWR3dTmJtbaaVbo4+rHRsjHPvHif9CRfi+BQ8CHG3zmBjH7DZPZIRCVtkms1EDe1k/G3fEnfgYc6gboJfoTdLkVjNOtdStTi03dCA/riQqUKc7/v16R5ZXIAmNCnmMHelObCSDPzYg8psZAUk1ZZY//pnhp9JRPsC2JxsshN7HCNIED9aFgrJkvUt+wUVGjVHzyQwyR6J7m1yyoivTwdmYdulG7OriLeeNq8vkoDmLGgLSC+zKehzJYOZsH3EKuxuZjQ3J9tK/NseQOhsQglRHE/OvphMwT/J96gl9dZR/LQXp4S6hwLccTzFfs8rLaTOIK6CEpqBUuBonot/1vJP5j5E73hfkHwZO7TQKwfXtpRCxCl5Nm3cB2Y3kz5mArDiwWioVsX4qd0XR0F9MFtuTVTn2f4K/Gwr9P3XMkLWXU1+1KbQiWIg+Zf5DpQgBW5HWryZzsMcjyMC2I2BJCl6Q+V8ofSM= nixos@Felia
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIJvOCZ4nyFiiKK7gkwzP4hXJ6NmtgbdUJdWgIzUL0GMA htran@Hungs-MacBook-Pro.local

View File

@ -62,6 +62,8 @@ Host bgp1
User htran User htran
Port 22 Port 22
StrictHostKeyChecking no StrictHostKeyChecking no
IdentityFile ~/.ssh/id_ed25519
IdentityFile ~/.ssh/id_rsa
HostKeyAlgorithms=+ssh-dss,ssh-rsa HostKeyAlgorithms=+ssh-dss,ssh-rsa
KexAlgorithms +diffie-hellman-group1-sha1,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1 KexAlgorithms +diffie-hellman-group1-sha1,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1
@ -70,8 +72,21 @@ Host bgp2
User htran User htran
Port 22 Port 22
StrictHostKeyChecking no StrictHostKeyChecking no
IdentityFile ~/.ssh/id_ed25519
IdentityFile ~/.ssh/id_rsa
HostKeyAlgorithms=+ssh-dss,ssh-rsa HostKeyAlgorithms=+ssh-dss,ssh-rsa
KexAlgorithms +diffie-hellman-group1-sha1,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1 KexAlgorithms +diffie-hellman-group1-sha1,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1
Host huaweil3
HostName 10.111.100.*
User htran
Port 22
StrictHostKeyChecking no
IdentityFile ~/.ssh/id_ed25519
IdentityFile ~/.ssh/id_rsa
HostKeyAlgorithms=+ssh-dss,ssh-rsa
KexAlgorithms +diffie-hellman-group1-sha1,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1
Host d1-30 Host d1-30
HostName 10.111.103.60 HostName 10.111.103.60
User htran User htran
@ -131,12 +146,28 @@ Host gl-egi
User git User git
Port 22 Port 22
IdentityFile ~/.ssh/id_ed25519 IdentityFile ~/.ssh/id_ed25519
IdentityFile ~/.ssh/id_rsa
Host 10.111.103.* Host 10.111.103.*
StrictHostKeyChecking no StrictHostKeyChecking no
UserKnownHostsFile /dev/null UserKnownHostsFile /dev/null
Host *
IdentityFile ~/.ssh/id_ed25519 IdentityFile ~/.ssh/id_ed25519
IdentityFile ~/.ssh/id_rsa IdentityFile ~/.ssh/id_rsa
Host *
SendEnv TERM
SetEnv TERM=xterm-256color
IdentityFile ~/.ssh/id_ed25519
IdentityFile ~/.ssh/id_rsa
Host *.egihosting.com
StrictHostKeyChecking no
IdentityFile ~/.ssh/id_ed25519
IdentityFile ~/.ssh/id_rsa
Host gh
HostName github.com
User git
Port 22
IdentityFile ~/.ssh/id_ed25519
IdentityFile ~/.ssh/id_rsa

View File

@ -1,57 +0,0 @@
{
config,
proj_root,
myLib,
...
}: let
inherit (myLib) fromYaml;
actualConfig = fromYaml (builtins.readFile "${proj_root.config.path}//alacritty/alacritty.yml");
cfg = config.base.alacritty;
in {
options.base.alacritty = {
font.family = myLib.mkOption {
type = myLib.types.singleLineStr;
default = actualConfig.font.normal.family;
description = ''
The font family for Alacritty
'';
example = "DroidSansMono NF";
};
font.size = myLib.mkOption {
type = myLib.types.number;
default = actualConfig.font.size;
description = ''
The default font size for Alacritty. This is probably measured in px.
'';
example = 7.0;
};
enable = myLib.mkOption {
type = myLib.types.bool;
default = true;
description = ''
Enables alacritty
'';
example = true;
};
_actualConfig = myLib.mkOption {
type = myLib.types.attrs;
visible = false;
default = actualConfig;
description = "underlying default config";
};
additionalConfigPath = myLib.mkOption {
type = myLib.types.nullOr myLib.types.path;
visible = false;
default = null;
description = "impurely write our alacritty.yml to this path";
};
};
config.programs.alacritty = {
enable = cfg.enable;
settings = myLib.recursiveUpdate actualConfig {
font.normal.family = cfg.font.family;
font.size = cfg.font.size;
};
};
}

View File

@ -1,54 +0,0 @@
{
lib,
pkgs,
config,
...
}: {
# This patch exists since Darwin's search bar requires solid apps and not
# symlinked
# TODO: QA
# - [x] works for base case
# - [x] works for repeated case
# - [ ] works after base case, then removed
# - [ ] works for repeated case, then removed
# Copy GUI apps to "~/Applications/Home Manager Apps"
# Based on this comment: https://github.com/nix-community/home-manager/issues/1341#issuecomment-778820334
home.activation.patch-spotlight =
if pkgs.stdenv.isDarwin
then let
apps = pkgs.buildEnv {
name = "home-manager-applications";
paths = config.home.packages;
pathsToLink = "/Applications";
};
in
lib.hm.dag.entryAfter ["linkGeneration"] ''
# Install MacOS applications to the user environment.
HM_APPS="$HOME/Applications/Home Manager Apps"
# Reset current state
if [ -e "$HM_APPS" ]; then
$DRY_RUN_CMD mv "$HM_APPS" "$HM_APPS.$(date +%Y%m%d%H%M%S)"
fi
$DRY_RUN_CMD mkdir -p "$HM_APPS"
# .app dirs need to be actual directories for Finder to detect them as Apps.
# In the env of Apps we build, the .apps are symlinks. We pass all of them as
# arguments to cp and make it dereference those using -H
$DRY_RUN_CMD cp --archive -H --dereference ${apps}/Applications/* "$HM_APPS"
$DRY_RUN_CMD chmod +w -R "$HM_APPS"
''
else "";
# We need this in case upstream home-manager changes the behavior of linking
# applications
home.activation.remove-patch-spotlight =
if pkgs.stdenv.isDarwin
then
lib.hm.dag.entryBefore ["checkLinkTargets"] ''
HM_APPS="$HOME/Applications/Home Manager Apps"
# Reset current state
if [ -e "$HM_APPS" ]; then
$DRY_RUN_CMD mv "$HM_APPS" "$HM_APPS.$(date +%Y%m%d%H%M%S)"
fi
''
else "";
}

View File

@ -1,13 +0,0 @@
{nix-index-database, ...} @ inputs: {
mkModuleArgs = import ./mkModuleArgs.nix;
modules = [
./alacritty.nix
./git.nix
./ssh.nix
./shells.nix
{
config.programs.home-manager.enable = true;
}
nix-index-database.hmModules.nix-index
];
}

View File

@ -1,80 +0,0 @@
{
config,
myLib,
...
}: let
cfg = config.base.git;
baseAliases = {
a = "add";
c = "commit";
ca = "commit --amend";
cm = "commit -m";
lol = "log --graph --decorate --pretty=oneline --abbrev-commit";
lola = "log --graph --decorate --pretty=oneline --abbrev-commit --all";
sts = "status";
co = "checkout";
b = "branch";
};
in {
options.base.git = {
aliases = myLib.mkOption {
type = myLib.types.attrs;
default = {};
example = baseAliases;
description = ''
Additional git aliases. This settings comes with base configuration.
Redeclaring the base config will override the values.
''; # TODO: Add baseAliases as string here (builtins.toString doesn't work)
};
name = myLib.mkOption {
type = myLib.types.str;
default = "Pegasust";
description = "Git username that appears on commits";
example = "Pegasust";
};
email = myLib.mkOption {
type = myLib.types.str;
default = "pegasucksgg@gmail.com";
example = "peagsucksgg@gmail.com";
description = "Git email that appears on commits";
};
ignores = myLib.mkOption {
type = myLib.types.listOf myLib.types.str;
default = [
".vscode" # vscode settings
".direnv" # .envrc cached outputs
".DS_Store" # MacOS users, amrite
];
description = ''
.gitignore patterns that are applied in every repository.
This is useful for IDE-specific settings.
'';
example = [".direnv" "node_modules"];
};
enable = myLib.mkOption {
type = myLib.types.bool;
default = true;
description = ''
Enables git
'';
example = false;
};
credentialCacheTimeoutSeconds = myLib.mkOption {
type = myLib.types.int;
default = 3000;
description = "Credential cache (in-memory store) for Git in seconds.";
example = 3000;
};
};
# TODO : anyway to override configuration?
config.programs.git = {
inherit (cfg) enable ignores;
userName = cfg.name;
userEmail = cfg.email;
aliases = baseAliases // cfg.aliases;
extraConfig = {
credential.helper = "cache --timeout=${builtins.toString cfg.credentialCacheTimeoutSeconds}";
};
lfs.enable = true;
};
}

View File

@ -1,49 +0,0 @@
{
pkgs,
config,
lib,
...
}: let
cfg = config.base.graphics;
cfgEnable = cfg.enable or (cfg.useNixGL.defaultPackage != null);
types = lib.types;
in {
imports = [./shells.nix];
options.base.graphics = {
enable = lib.mkEnableOption "graphics";
_enable = lib.mkOption {
type = types.bool;
description = "Whether the graphics is implicitly enabled (final)";
# internal = true;
default = false;
};
useNixGL = {
package = lib.mkPackageOption pkgs "nixGL package" {
default = [
"nixgl"
"auto"
"nixGLDefault"
];
};
defaultPackage = lib.mkOption {
type = types.nullOr (types.enum ["nixGLIntel" "nixGLNvidia" "nixGLNvidiaBumblebee"]);
description = "Which nixGL package to be aliased as `nixGL` on the shell";
default = null;
example = "nixGLIntel";
};
};
};
# NOTE: importing shells does not mean we're enabling everything, if we do mkDefault false
# but the dilemma is, if the user import BOTH graphics.nix and shells.nix
# they will also need to do `config.base.shells.enable`
# generally, we want the behavior: import means enable
config = lib.mkIf cfgEnable {
base.graphics._enable = lib.mkForce true;
base.shells = {
shellAliases = lib.mkIf (cfg.useNixGL.defaultPackage != null) {
nixGL = cfg.useNixGL.defaultPackage;
};
};
home.packages = [cfg.useNixGL.package];
};
}

View File

@ -1,70 +0,0 @@
{
config,
proj_root,
pkgs,
lib,
...
}: let
cfg = config.base.keepass;
trimNull = lib.filterAttrsRecursive (name: value: value != null);
in {
imports = [./graphics.nix];
options.base.keepass = {
enable = lib.mkEnableOption "keepass";
use_gui = lib.mkOption {
type = lib.types.bool;
description = "wheter to enable keepass GUI (the original one)";
default = false;
example = "true";
};
path = lib.mkOption {
type = lib.types.path;
description = "Path to kdbx file";
default = null;
example = "/media/homelab/f/PersistentHotStorage/keepass.kdbx";
};
keyfile_path = lib.mkOption {
type = lib.types.nullOr lib.types.path;
description = ''
Path to key file for the database
If null, then the field is unset
'';
default = null;
example = "/path/to/mykeyfile.key";
};
store_encrypted_password = lib.mkOption {
type = lib.types.bool;
description = "Whether to store encrypted password for 24 hrs before re-prompt";
default = true;
example = "false";
};
copy_timeout_secs = lib.mkOption {
type = lib.types.int;
description = "Timeout (seconds) before the password is expired from clipboard";
default = 12;
example = "60";
};
};
config = lib.mkIf cfg.enable {
home.packages =
[
pkgs.kpcli-py # kp but is in cli
]
++ (
if cfg.use_gui or config.base.graphics._enable
then [
pkgs.keepass # Personal secret management
]
else []
);
home.file.".kp/config.ini".text = lib.generators.toINI {} (trimNull {
default = {
KEEPASSDB = cfg.path;
KEEPASSDB_KEYFILE = cfg.keyfile_path;
STORE_ENCRYPTED_PASSWORD = cfg.store_encrypted_password;
KEEPASSDB_PASSWORD = null; # No good way yet to store the password
KEEPASSDB_TIMEOUT = cfg.copy_timeout_secs;
};
});
};
}

View File

@ -1,20 +0,0 @@
# Turns given inputs into the standardized shape of the inputs to configure
# custom base modules in this directory.
{
pkgs,
lib ? pkgs.lib,
...
} @ inputs: let
recursiveUpdate = lib.recursiveUpdate;
_lib = recursiveUpdate lib (import ../../lib {inherit pkgs lib;});
proj_root = builtins.toString ./../../..;
in
# TODO: Unpollute inputs
recursiveUpdate inputs {
proj_root = {
path = proj_root;
config.path = "${proj_root}/native_configs";
scripts.path = "${proj_root}/scripts";
};
myLib = _lib;
}

View File

@ -1,192 +0,0 @@
# TODO: vim-plug and Mason supports laziness. Probably worth it to explore incremental dependencies based on the project TODO: just install these things, then symlink to mason's bin directory
#
# One thing to consider, though, /nix/store of `nix-shell` or `nix-develop`
# might be different from `home-manager`'s (~/.nix_profile/bin/jq)
{
pkgs,
lib,
config,
proj_root,
...
}: let
# NOTE: Add packages to nvim_pkgs instead, so that it's available at userspace
# and is added to the path after wrapping.
# check: nix repl `homeConfigurations.hungtr.config.programs.neovim.finalPackage.buildCommand`
# see: :/--suffix.*PATH
# there should be mentions of additional packages
my_neovim = pkgs.neovim-unwrapped;
rust_pkgs =
pkgs.rust-bin.selectLatestNightlyWith
(
toolchain:
toolchain.default.override {
extensions = ["rust-src" "rust-analyzer" "rust-docs" "rustfmt" "clippy" "miri"];
}
);
nvim_pkgs =
[
# pkgs.gccStdenv
pkgs.tree-sitter
pkgs.fzf # file name fuzzy search
pkgs.ripgrep # content fuzzy search
pkgs.zk # Zettelkasten (limited support)
pkgs.fd # Required by a Telescope plugin (?)
pkgs.stdenv.cc.cc.lib
pkgs.rnix-lsp # doesn't work, Mason just installs it using cargo
pkgs.rust4cargo
pkgs.nickel
pkgs.nls
pkgs.go # doesn't work, Mason installs from runtime path
# Language-specific stuffs
pkgs.sumneko-lua-language-server
# pkgs.python3Packages.python-lsp-server
pkgs.nodePackages.pyright
pkgs.python3Packages.pylint
pkgs.python3Packages.flake8
# FIXME: installing ansible from here just doesn't work :/
# pkgs.ansible-lint
# pkgs.python38Packages.ansible
# pkgs.ansible-language-server
# TODO: the devShell should provide rust-analyzer so that
# cargo test builds binaries compatible with rust-analyzer
# pkgs.rust-analyzer
# rust_pkgs
# pkgs.evcxr # Rust REPL for Conjure!
]
++ lib.optionals (pkgs.stdenv.isDarwin) (
let
inherit (pkgs.darwin.apple_sdk.frameworks) System CoreFoundation;
in [
System
CoreFoundation
]
);
in {
options.base.neovim = {
enable = lib.mkOption {
default = true;
description = "enable personalized neovim as default editor";
type = lib.types.bool;
example = false;
f = let
adder = {
__functor = self: arg:
if builtins.isInt arg
then self // {x = self.x + arg;}
else self.x;
x = 0;
};
in {
what = adder 1 2 3 {};
};
};
};
config = lib.mkIf config.base.neovim.enable {
# home-manager
programs.neovim = {
enable = true;
package = my_neovim;
viAlias = true;
vimAlias = true;
withPython3 = true;
withNodeJs = true;
extraPackages = nvim_pkgs;
extraLuaConfig = builtins.readFile "${proj_root.config.path}//neovim/init.lua";
plugins = let
inherit
(pkgs.vimPlugins)
plenary-nvim
nvim-treesitter
nvim-treesitter-textobjects
nvim-treesitter-context
telescope-fzf-native-nvim
telescope-file-browser-nvim
telescope-nvim
nvim-lspconfig
gruvbox-community
neodev-nvim
cmp-nvim-lsp
cmp-path
cmp-buffer
cmp-cmdline
nvim-cmp
lspkind-nvim
nvim-autopairs
nvim-ts-autotag
guess-indent-nvim
harpoon
zk-nvim
luasnip
fidget-nvim
rust-tools-nvim
cmp_luasnip
gitsigns-nvim
indent-blankline-nvim
lualine-nvim
mason-lspconfig-nvim
mason-nvim
neogit
nlua-nvim
nvim-jqx
nvim-surround
nvim-web-devicons
playground
todo-comments-nvim
trouble-nvim
vim-dispatch
vim-dispatch-neovim
vim-fugitive
vim-jack-in
;
in [
plenary-nvim
nvim-treesitter.withAllGrammars
nvim-treesitter-textobjects
telescope-fzf-native-nvim
telescope-file-browser-nvim
telescope-nvim
nvim-lspconfig
gruvbox-community
neodev-nvim
cmp-nvim-lsp
cmp-path
cmp-buffer
cmp-cmdline
nvim-cmp
lspkind-nvim
nvim-autopairs
nvim-ts-autotag
guess-indent-nvim
harpoon
zk-nvim
luasnip
nvim-treesitter-context
fidget-nvim
rust-tools-nvim
cmp_luasnip
gitsigns-nvim
indent-blankline-nvim
lualine-nvim
mason-lspconfig-nvim
mason-nvim
neogit
nlua-nvim
nvim-jqx
nvim-surround
nvim-web-devicons
playground
todo-comments-nvim
trouble-nvim
vim-dispatch
vim-dispatch-neovim
vim-fugitive
vim-jack-in
];
};
# home.packages = nvim_pkgs;
};
}

View File

@ -1,58 +0,0 @@
# TODO: maybe throw if base.graphics is not enabled?
# Though, headless chromium might be possible
{
config,
pkgs,
lib,
...
}: let
cfg = config.base.private_chromium;
in {
options.base.private_chromium = {
enable = lib.mkOption {
type = lib.types.bool;
default = true;
example = false;
description = ''
Enable extremely lightweight chromium with vimium plugin
'';
};
};
config = lib.mkIf (cfg.enable) {
# home.packages = [pkgs.ungoogled-chromium];
programs.chromium = {
enable = true;
package = pkgs.ungoogled-chromium;
extensions = let
# TODO: how about a chrome extension registry?
mkChromiumExtForVersion = browserVersion: {
id,
sha256,
extVersion,
...
}: {
inherit id;
crxPath = builtins.fetchurl {
url =
"https://clients2.google.com/service/update2/crx"
+ "?response=redirect"
+ "&acceptformat=crx2,crx3"
+ "&prodversion=${browserVersion}"
+ "&x=id%3D${id}%26installsource%3Dondemand%26uc";
name = "${id}.crx";
inherit sha256;
};
version = extVersion;
};
mkChromiumExt = mkChromiumExtForVersion (lib.versions.major pkgs.ungoogled-chromium.version);
in [
# vimium
(mkChromiumExt {
id = "dbepggeogbaibhgnhhndojpepiihcmeb";
sha256 = "00qhbs41gx71q026xaflgwzzridfw1sx3i9yah45cyawv8q7ziic";
extVersion = "1.67.4";
})
];
};
};
}

View File

@ -1,12 +0,0 @@
# A module that takes care of a GUI-ful, productive desktop environment
inputs @ {pkgs, ...}: {
imports = [
# slack
({pkgs, ...}: {
home.packages = [
pkgs.slack
];
})
./private_chromium.nix
];
}

View File

@ -1,135 +0,0 @@
# Configurations for shell stuffs.
# Should probably be decoupled even more for each feature
{
config,
proj_root,
myLib,
pkgs,
...
}: let
cfg = config.base.shells;
in {
options.base.shells = {
enable = myLib.mkOption {
type = myLib.types.bool;
description = "Enable umbrella shell configuration";
default = true;
example = false;
};
# TODO: Support shell-specific init
shellInitExtra = myLib.mkOption {
type = myLib.types.str;
description = "Extra shell init. The syntax should be sh-compliant";
default = "";
example = ''
# X11 support for WSL
export DISPLAY=$(ip route list default | awk '{print $3}'):0
export LIBGL_ALWAYS_INDIRECT=1
'';
};
shellAliases = myLib.mkOption {
type = myLib.types.attrs;
description = "Shell command aliases";
default = {};
example = {
nixGL = "nixGLIntel";
};
};
};
config = myLib.mkIf cfg.enable {
# nix: Propagates the environment with packages and vars when enter (children of)
# a directory with shell.nix-compatible and .envrc
programs.direnv = {
enable = true;
nix-direnv.enable = true;
# nix-direnv.enableFlakes = true; # must remove. this will always be supported.
};
# z <path> as smarter cd
programs.zoxide = {
enable = true;
enableZshIntegration = true;
};
programs.tmux = {
enable = true;
# extraConfigBeforePlugin = builtins.readFile "${proj_root.config.path}/tmux/tmux.conf";
plugins = let inherit (pkgs.tmuxPlugins) cpu net-speed; in [cpu net-speed];
extraConfig = builtins.readFile "${proj_root.config.path}/tmux/tmux.conf";
};
xdg.configFile."tmux/tmux.conf".text = myLib.mkOrder 600 ''
set -g status-right '#{cpu_bg_color} CPU: #{cpu_icon} #{cpu_percentage} | %a %h-%d %H:%M '
'';
# Colored ls
programs.exa = {
enable = true;
enableAliases = true;
};
# Make the shell look beautiful
programs.starship = {
enable = true;
enableZshIntegration = true;
settings = let
native = builtins.fromTOML (builtins.readFile "${proj_root.config.path}/starship/starship.toml");
patch-nix = pkgs.lib.recursiveUpdate native {
# WARNING: home-manager fails on here for some reason. Likely not at the
# validation phase (type-checking), but at evaluation phaase (stringify)
# c.commands = [
# ["nix" "run" "nixpkgs#clang" "--" "--version"]
# ["nix" "run" "nixpkgs#gcc" "--" "--version"]
# ];
c.commands = "fuk";
};
in
patch-nix;
};
# Fuzzy finder. `fzf` for TUI, `fzf -f '<fuzzy query>'` for UNIX piping
programs.fzf.enable = true;
programs.bash = {
enable = true;
enableCompletion = true;
initExtra = cfg.shellInitExtra or "";
};
programs.zsh = {
enable = true;
enableCompletion = true;
enableAutosuggestions = true;
shellAliases =
{
nix-rebuild = "sudo nixos-rebuild switch";
hm-switch = "home-manager switch --flake";
}
// (cfg.shellAliases or {});
history = {
size = 10000;
path = "${config.xdg.dataHome}/zsh/history";
};
oh-my-zsh = {
enable = true;
plugins = [
"git" # git command aliases: https://github.com/ohmyzsh/ohmyzsh/tree/master/plugins/git#aliases
# "sudo" # double-escape to prepend sudo # UPDATE: just use vi-mode lol
"command-not-found" # suggests which package to install; does not support nixos (we have solution already)
"gitignore" # `gi list` -> `gi java >>.gitignore`
"ripgrep" # adds completion for `rg`
"rust" # compe for rustc/cargo
"poetry" # compe for poetry - Python's cargo
# "vi-mode" # edit promps with vi motions :)
];
};
sessionVariables = {
# Vim mode on the terminal
# VI_MODE_RESET_PROMPT_ON_MODE_CHANGE = true;
# VI_MODE_SET_CURSOR = true;
# ZVM_VI_ESCAPE_BINDKEY = "";
ZVM_READKEY_ENGINE = "$ZVM_READKEY_ENGINE_NEX";
ZVM_KEYTIMEOUT = 0.004; # 40ms, or subtly around 25 FPS. I'm a gamer :)
ZVM_ESCAPE_KEYTIMEOUT = 0.004; # 40ms, or subtly around 25 FPS. I'm a gamer :)
};
initExtra =
(cfg.shellInitExtra or "")
+ ''
source ${pkgs.zsh-vi-mode}/share/zsh-vi-mode/zsh-vi-mode.plugin.zsh
'';
};
};
}

View File

@ -1,22 +0,0 @@
{
config,
proj_root,
myLib,
...
}: let
cfg = config.base.ssh;
in {
options.base.ssh.enable = myLib.mkOption {
type = myLib.types.bool;
default = true;
example = false;
description = ''
Enables SSH
'';
};
config.programs.ssh = {
inherit (cfg) enable;
forwardAgent = true;
includes = ["${proj_root.config.path}/ssh/config"];
};
}

View File

@ -1,13 +0,0 @@
# We use top-level nix-flake, so default.nix is basically just a wrapper around ./flake.nix
(
import
(
let
lock = builtins.fromJSON (builtins.readFile ./flake.lock);
c_ = import ./../../c_.nix;
in
c_.fetchTree lock.nodes.flake-compat.locked
)
{src = ./.;}
)
.defaultNix

File diff suppressed because it is too large Load Diff

View File

@ -1,274 +0,0 @@
{
nixConfig = {
accept-flake-config = true;
experimental-features = "nix-command flakes";
extra-substituters = [
"https://nix-community.cachix.org"
"https://cache.nixos.org"
];
extra-trusted-public-keys = [
"nix-community.cachix.org-1:mB9FSh9qf2dCimDSUo8Zy7bkq5CX+/rkCWyvRCYg3Fs="
"cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY="
];
max-jobs = 12;
};
description = "simple home-manager config";
inputs = {
nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
nixpkgs-latest.url = "github:nixos/nixpkgs";
home-manager = {
url = "github:nix-community/home-manager";
# url = "github:pegasust/home-manager/starship-config-type";
follows = "nixpkgs";
};
flake-utils.url = "github:numtide/flake-utils";
nixgl.url = "path:./../../out-of-tree/nixGL";
rust-overlay.url = "github:oxalica/rust-overlay";
# Allows default.nix to call onto flake.nix. Useful for nix eval and automations
flake-compat = {
url = "path:../../out-of-tree/flake-compat";
flake = false;
};
nix-boost.url = "git+https://git.pegasust.com/pegasust/nix-boost.git";
kpcli-py = {
url = "github:rebkwok/kpcli";
flake = false;
};
neovim-nightly-overlay = {
url = "github:nix-community/neovim-nightly-overlay?rev=88a6c749a7d126c49f3374f9f28ca452ea9419b8";
};
nix-index-database = {
url = "github:mic92/nix-index-database";
inputs.nixpkgs.follows = "nixpkgs";
};
};
outputs = flake_inputs @ {
nixpkgs,
home-manager,
nixgl,
rust-overlay,
flake-utils,
kpcli-py,
neovim-nightly-overlay,
nix-boost,
nixpkgs-latest,
...
}: let
# config_fn:: system -> config
cross_platform = config_fn: {
packages =
builtins.foldl'
(prev: system:
prev
// {
"${system}" = config_fn system;
})
{}
flake-utils.lib.defaultSystems;
};
in
cross_platform (system: let
overlays = import ./overlays.nix (flake_inputs // {inherit system;});
# pkgs = nixpkgs.legacyPackages.${system}.appendOverlays overlays;
pkgs = import nixpkgs {
inherit system overlays;
config = {allowUnfree = true;};
};
# lib = (import ../lib { inherit pkgs; lib = pkgs.lib; });
base = import ./base flake_inputs;
inherit (base) mkModuleArgs;
nerd_font_module = {
config,
pkgs,
...
}: {
fonts.fontconfig.enable = true;
home.packages = [
# list of fonts are available at https://github.com/NixOS/nixpkgs/blob/nixos-unstable/pkgs/data/fonts/nerdfonts/shas.nix
(pkgs.nerdfonts.override {fonts = ["Hack"];})
];
base.alacritty.font.family = "Hack Nerd Font Mono";
};
in {
debug = {
inherit overlays pkgs base;
};
homeConfigurations = let
x11_wsl = ''
# x11 output for WSL
export DISPLAY=$(ip route list default | awk '{print $3}'):0
export LIBGL_ALWAYS_INDIRECT=1
'';
in {
"hungtr" = home-manager.lib.homeManagerConfiguration {
inherit pkgs;
modules =
base.modules
++ [
./home.nix
];
# optionally pass inarguments to module
# we migrate this from in-place modules to allow flexibility
# in this case, we can add "home" to input arglist of home.nix
extraSpecialArgs = mkModuleArgs {
inherit pkgs;
myHome = {
username = "hungtr";
homeDirectory = "/home/hungtr";
};
};
};
"hungtr@bao" = home-manager.lib.homeManagerConfiguration {
inherit pkgs;
modules =
base.modules
++ [
./home.nix
nerd_font_module
./base/productive_desktop.nix
{
# since home.nix forces us to use keepass, and base.keepass.path
# defaults to a bad value (on purpose), we should configure a
# it to be the proper path
base.keepass.path = "/perso/garden/keepass.kdbx";
base.graphics.useNixGL.defaultPackage = "nixGLNvidia";
base.graphics.useNixGL.enable = true;
}
];
# optionally pass inarguments to module
# we migrate this from in-place modules to allow flexibility
# in this case, we can add "home" to input arglist of home.nix
extraSpecialArgs = mkModuleArgs {
inherit pkgs;
myHome = {
username = "hungtr";
homeDirectory = "/home/hungtr";
};
};
};
# Personal darwin, effectively serves as the Darwin edge channel
"hungtran" = home-manager.lib.homeManagerConfiguration {
inherit pkgs;
modules =
base.modules
++ [
./home.nix
{
base.graphics.enable = false;
# don't want to deal with GL stuffs on mac yet :/
base.graphics.useNixGL.defaultPackage = null;
# NOTE: this actually does not exist
base.keepass.path = "/Users/hungtran/keepass.kdbx";
base.alacritty.font.size = 11.0;
}
nerd_font_module
./base/productive_desktop.nix
{
base.private_chromium.enable = false;
}
{
home.packages = [
pkgs.postman
];
}
];
extraSpecialArgs = mkModuleArgs {
inherit pkgs;
myHome = {
username = "hungtran";
homeDirectory = "/Users/hungtran";
};
};
};
# Work darwin
"htran" = home-manager.lib.homeManagerConfiguration {
inherit pkgs;
modules =
base.modules
++ [
./home.nix
./base/productive_desktop.nix
./base/darwin-spotlight.nix
{
base.private_chromium.enable = false;
}
nerd_font_module
{
base.graphics.enable = false;
# don't want to deal with GL stuffs on mac yet :/
base.graphics.useNixGL.defaultPackage = null;
base.alacritty.font.size = 11.0;
base.git.name = "Hung";
base.git.email = "htran@egihosting.com";
}
{
home.packages = [
pkgs.postman
];
}
{base.keepass.enable = pkgs.lib.mkForce false;}
];
extraSpecialArgs = mkModuleArgs {
inherit pkgs;
myHome = {
username = "htran";
homeDirectory = "/Users/htran";
};
};
};
"nixos@Felia" = home-manager.lib.homeManagerConfiguration {
inherit pkgs;
modules = [
./home.nix
{
base.shells = {
shellInitExtra =
''
''
+ x11_wsl;
};
}
];
# optionally pass inarguments to module
# we migrate this from in-place modules to allow flexibility
# in this case, we can add "home" to input arglist of home.nix
extraSpecialArgs = mkModuleArgs {
inherit pkgs;
myHome = {
username = "nixos";
homeDirectory = "/home/nixos";
};
};
};
# Personal laptop
hwtr = home-manager.lib.homeManagerConfiguration {
inherit pkgs;
modules =
base.modules
++ [
./home.nix
./base/graphics.nix
{
base.graphics.enable = true;
base.alacritty.font.family = "BitstreamVeraSansMono Nerd Font";
base.keepass.path = "/media/homelab/f/PersistentHotStorage/keepass.kdbx";
}
./base/productive_desktop.nix
];
extraSpecialArgs = mkModuleArgs {
inherit pkgs;
myHome = {
username = "hwtr";
homeDirectory = "/home/hwtr";
packages = [
pkgs.postman
];
};
};
};
};
});
}

View File

@ -1,76 +0,0 @@
# This is a nix module, with an additional wrapper from home-manager
# myHome, myLib is injected from extraSpecialArgs in flake.nix
# This file represents the base settings for each machine
# Additional configurations goes to profiles/<user>
# or inlined in flake.nix
{
config,
# Represents the realized final configuration
pkgs,
# This is by default just ``= import <nixpkgs>{}`
myHome,
myLib,
option,
# The options we're given, this might be useful for typesafety?
proj_root,
...
}: let
inherit (myLib) fromYaml;
in {
imports = [
./base/neovim.nix
./base/keepass.nix
];
home = {
username = myHome.username;
homeDirectory = myHome.homeDirectory;
stateVersion = myHome.stateVersion or "22.05";
};
home.packages = pkgs.lib.unique (
[
# pkgs.ncdu
pkgs.rclone # cloud file operations
pkgs.htop # system diagnostics in CLI
pkgs.ripgrep # content fuzzy search
pkgs.unzip # compression
pkgs.zip # compression
# cool utilities
pkgs.yq-go # Yaml adaptor for jq (only pretty print, little query)
# pkgs.xorg.xclock # TODO: only include if have gui # For testing GL installation
# pkgs.logseq # TODO: only include if have GL # Obsidian alt
pkgs.mosh # Parsec for SSH
# pkgs.nixops_unstable # nixops v2 # insecure for now
pkgs.lynx # Web browser at your local terminal
pkgs.zk
# pkgs.tailscale # VPC;; This should be installed in system-nix
pkgs.python310 # dev packages should be in project
# pkgs.python310.numpy
# pkgs.python310Packages.tensorflow
# pkgs.python310Packages.scikit-learn
]
++ (myHome.packages or [])
++ (
if pkgs.system == "x86_64-linux"
then [
pkgs.logseq
]
else []
)
);
## Configs ##
xdg.configFile."zk/config.toml".source = "${proj_root.config.path}//zk/config.toml";
## Programs ##
programs.jq = {
enable = true;
};
programs.nix-index = {
enable = true;
enableBashIntegration = true;
enableZshIntegration = true;
};
base.keepass.enable = true;
}

View File

@ -1,6 +0,0 @@
accept-flake-config = true
experimental-features = nix-command flakes
post-build-hook = /etc/nix/upload-to-cache.sh
trusted-users = root htran hungtran hwtr
max-jobs = 8
cores = 12

View File

@ -1,5 +0,0 @@
accept-flake-config = true
experimental-features = nix-command flakes
post-build-hook = /etc/nix/upload-to-cache.sh
trusted-users = root htran hungtran hwtr

View File

@ -1,4 +0,0 @@
accept-flake-config = true
experimental-features = nix-command flakes
post-build-hook = /etc/nix/upload-to-cache.sh
trusted-users = root htran hungtran hwtr

View File

@ -1,71 +0,0 @@
flake_input @ {
kpcli-py,
nixgl,
rust-overlay,
neovim-nightly-overlay,
system,
nix-boost,
nixpkgs-latest,
...
}: let
kpcli-py = final: prev: {
# use python3.9, which works because of cython somehow?
kpcli-py = final.poetry2nix.mkPoetryApplication {
projectDir = flake_input.kpcli-py;
overrides = final.poetry2nix.defaultPoetryOverrides.extend (self: super: {
# tableformatter requires setuptools
tableformatter = super.tableformatter.overridePythonAttrs (
old: {
buildInputs = (old.buildInputs or []) ++ [self.setuptools self.cython_3];
src = old.src;
}
);
kpcli = super.kpcli.overridePythonAttrs (old: {
buildInputs = (old.buildInputs or []) ++ [self.setuptools];
});
# ubersmith = super.ubersmith.overridePythonAttrs (old: {
# buildInputs = builtins.filter (x: ! builtins.elem x [ ]) ((old.buildInputs or [ ]) ++ [
# py-final.setuptools
# py-final.pip
# ]);
#
# src = final.fetchFromGitHub {
# owner = "jasonkeene";
# repo = "python-ubersmith";
# rev = "0c594e2eb41066d1fe7860e3a6f04b14c14f6e6a";
# sha256 = "sha256-Dystt7CBtjpLkgzCsAif8WkkYYeLyh7VMehAtwoDGuM=";
# };
# });
});
};
};
rust = final: prev: let
nightlyRustWithExts = exts:
final.rust-bin.selectLatestNightlyWith (
toolchain: (toolchain.minimal.override {
extensions = exts;
})
);
# https://rust-lang.github.io/rustup/concepts/profiles.html
rust-default-components = ["rust-docs" "rustfmt" "clippy"];
rust-dev-components = rust-default-components ++ ["rust-src" "rust-analyzer" "miri"];
in {
rust4devs = nightlyRustWithExts rust-dev-components;
rust4cargo = nightlyRustWithExts [];
rust4normi = nightlyRustWithExts rust-default-components;
};
vimPlugins = final: prev: {
inherit (nixpkgs-latest.legacyPackages.${system}) vimPlugins;
};
in [
nix-boost.overlays.default
nixgl.overlays.default
rust-overlay.overlays.default
neovim-nightly-overlay.overlay
rust
kpcli-py
vimPlugins
]

View File

@ -1,8 +0,0 @@
# main module exporter for different configuration profiles
{
pkgs,
libs,
...
} @ inputs: {
hwtr = import ./hwtr.nix;
}

View File

@ -1 +0,0 @@

View File

@ -1,12 +0,0 @@
{
pkgs,
lib ? pkgs.lib,
...
} @ flake_import: let
serde = import ./serde {inherit pkgs lib;};
recursiveUpdate = lib.recursiveUpdate;
in
recursiveUpdate (recursiveUpdate pkgs.lib lib) {
fromYaml = serde.fromYaml;
fromYamlPath = serde.fromYamlPath;
}

View File

@ -1,39 +0,0 @@
# Takes care of serializing and deserializing to some formats
# Blame: Pegasust<pegasucksgg@gmail.com>
# TODO: Add to* formats from pkgs.formats.*
{
pkgs,
lib,
} @ inputs: let
yamlToJsonDrv = yamlContent: outputPath:
pkgs.callPackage
({runCommand}:
# runCommand source: https://github.com/NixOS/nixpkgs/blob/master/pkgs/build-support/trivial-builders.nix#L33
runCommand outputPath
{
inherit yamlContent;
nativeBuildInputs = [pkgs.yq];
}
# run yq which outputs '.' (no filter) on file at yamlPath
# note that $out is passed onto the bash/sh script for execution
''
echo "$yamlContent" | yq >$out
'')
{};
in {
# Takes in a yaml string and produces a derivation with translated JSON at $outputPath
# similar to builtins.fromJSON, turns a YAML string to nix attrset
fromYaml = yamlContent: builtins.fromJSON (builtins.readFile (yamlToJsonDrv yamlContent "any_output.json"));
fromYamlPath = yamlPath:
builtins.fromJSON (
builtins.readFile (
yamlToJsonDrv
(
builtins.readFile yamlPath
)
"any-output.json"
)
);
fromTOML = builtins.fromTOML;
fromJSON = builtins.fromJSON;
}

View File

@ -1,14 +0,0 @@
# This module aims to be merge (not inject/override) with top-level pkgs to provide
# personalized/custom packages
{
pkgs,
lib,
naersk,
# rust packages
...
} @ pkgs_input: {
# dot-hwtr = import "./dot-hwtr" pkgs_input;
cargo-bacon = pkgs.rustPlatform.buildRustPackage rec {
pname = "bacon";
};
}

View File

@ -1,15 +0,0 @@
{
inputs = {
nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
rust-overlay.url = "github:oxalica/rust-overlay";
naersk.url = "gihub:nix-community/naersk";
};
outputs = {
nixpkgs,
rust-overlay,
naersk,
}: let
pkgs = import nixpkgs {overlays = [rust-overlay.overlays.default];};
lib = pkgs.lib;
in (import ./default.nix {inherit pkgs lib naersk;});
}

View File

@ -1,17 +0,0 @@
let
# user-specific (~/.ssh/id_ed25519.pub)
users = {
"hungtr@bao" = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIK+1+gps6phbZboIb9fH51VNPUCkhSSOAbkI3tq3Ou0Z";
};
# System-specific settings (/etc/ssh/ssh_hsot_ed25519_key.pub)
systems = {
"bao" = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIIBuAaAE7TiQmMH300VRj/pYCri1qPmHjd+y9aX2J0Fs";
};
all = users // systems;
# stands for calculus
c_ = builtins;
in {
"system/secrets/s3fs.age".publicKeys = c_.attrValues all;
"system/secrets/s3fs.digital-garden.age".publicKeys = c_.attrValues all;
"system/secrets/_nhitrl.age".publicKeys = c_.attrValues all;
}

View File

@ -1,71 +0,0 @@
{
lib,
pkgs,
config,
modulesPath,
specialArgs,
...
}: let
hostname = specialArgs.hostname;
enableSSH = specialArgs.enableSSH or true;
_networking = lib.recursiveUpdate {hostName = hostname;} (specialArgs._networking or {});
_boot = specialArgs._boot or {};
_services = specialArgs._services or {};
includeHardware = specialArgs.includeHardware or true;
proj_root = builtins.toString ./../..;
in
with lib; {
imports =
(
if includeHardware
then [
"${proj_root}/hosts/${hostname}/hardware-configuration.nix"
]
else []
)
++ [
"${modulesPath}/profiles/minimal.nix"
"${proj_root}/modules/tailscale.sys.nix"
"${proj_root}/modules/mosh.sys.nix"
];
boot = _boot;
# prune old builds
nix.settings.auto-optimise-store = true;
# Enable nix flakes
nix.package = pkgs.nixFlakes;
nix.extraOptions = ''
experimental-features = nix-command flakes
'';
users.users.hungtr = {
isNormalUser = true;
home = "/home/hungtr";
description = "pegasust/hungtr";
extraGroups = ["wheel" "networkmanager" "audio"];
};
users.users.root = {
# openssh runs in root, no? This is because port < 1024 requires root.
openssh.authorizedKeys.keys = lib.strings.splitString "\n" (builtins.readFile "${proj_root}/native_configs/ssh/authorized_keys");
};
# Some basic programs
programs.neovim = {
enable = true;
defaultEditor = true;
};
programs.git = {
enable = true;
# more information should be configured under user level
# See other config at @/home-nix
};
environment.systemPackages = [
pkgs.gnumake
pkgs.wget
pkgs.inetutils # network diag
pkgs.mtr # network diag
pkgs.sysstat # sys diag
];
}

View File

@ -1,47 +0,0 @@
{
"nodes": {
"agenix": {
"inputs": {
"nixpkgs": [
"nixpkgs"
]
},
"locked": {
"lastModified": 1665870395,
"narHash": "sha256-Tsbqb27LDNxOoPLh0gw2hIb6L/6Ow/6lIBvqcHzEKBI=",
"owner": "ryantm",
"repo": "agenix",
"rev": "a630400067c6d03c9b3e0455347dc8559db14288",
"type": "github"
},
"original": {
"owner": "ryantm",
"repo": "agenix",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1672525397,
"narHash": "sha256-WASDnyxHKWVrEe0dIzkpH+jzKlCKAk0husv0f/9pyxg=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "8ba56d7c0d7490680f2d51ba46a141eca7c46afa",
"type": "github"
},
"original": {
"id": "nixpkgs",
"ref": "nixos-unstable",
"type": "indirect"
}
},
"root": {
"inputs": {
"agenix": "agenix",
"nixpkgs": "nixpkgs"
}
}
},
"root": "root",
"version": 7
}

View File

@ -1,334 +0,0 @@
{
inputs = {
nixpkgs.url = "nixpkgs/nixos-unstable";
agenix = {
url = "github:ryantm/agenix";
inputs.nixpkgs.follows = "nixpkgs";
};
};
outputs = {
self,
nixpkgs,
agenix,
...
}: let
lib = nixpkgs.lib;
proj_root = ./../..;
# TODO: Change respectively to the system or make a nix shell to alias `nix run github:ryantm/agenix -- `
base_modules = [
agenix.nixosModule
{
age.secrets.s3fs = {
file = ../../secrets/s3fs.age;
# mode = "600"; # owner + group only
# owner = "hungtr";
# group = "users";
};
age.secrets."s3fs.digital-garden" = {
file = ../../secrets/s3fs.digital-garden.age;
};
age.secrets._nhitrl_cred = {
file = ../../secrets/_nhitrl.age;
};
environment.systemPackages = [agenix.defaultPackage.x86_64-linux];
}
];
in {
# Windows with NixOS WSL
nixosConfigurations.Felia = nixpkgs.lib.nixosSystem {
system = "x86_64-linux";
modules =
base_modules
++ [
./wsl-configuration.nix
{
system.stateVersion = "22.05";
}
];
specialArgs = {
# includeHardware = false;
hostname = "Felia";
_services.openssh = {
permitRootLogin = "no";
enable = true;
};
};
};
nixosConfigurations.lizzi = nixpkgs.lib.nixosSystem {
system = "x86_64-linux";
modules =
base_modules
++ [
./configuration.nix
{
system.stateVersion = "22.05";
mod.tailscale.enable = true;
}
];
specialArgs = {
hostname = "lizzi";
_networking = {
interfaces.eth1.ipv4.addresses = [
{
address = "71.0.0.1";
prefixLength = 24;
}
];
firewall = {
enable = true;
allowedTCPPorts = [80 443 22];
};
useDHCP = false;
# required so that we get IP address from linode
interfaces.eth0.useDHCP = true;
};
_boot.loader.grub.enable = true;
_boot.loader.grub.version = 2;
_services.openssh = {
permitRootLogin = "no";
enable = true;
};
_services.gitea = {
enable = true;
stateDir = "/gitea";
rootUrl = "https://git.pegasust.com";
settings = {
repository = {
"ENABLE_PUSH_CREATE_USER" = true;
"ENABLE_PUSH_CREATE_ORG" = true;
};
};
};
# Highly suspect that thanks to nginx, ipv6 is disabled?
_services.nginx = {
enable = true;
clientMaxBodySize = "100m"; # Allow big file transfers over git :^)
recommendedGzipSettings = true;
recommendedOptimisation = true;
recommendedProxySettings = true;
recommendedTlsSettings = true;
virtualHosts."git.pegasust.com" = {
# Gitea hostname
sslCertificate = "/var/lib/acme/git.pegasust.com/fullchain.pem";
sslCertificateKey = "/var/lib/acme/git.pegasust.com/key.pem";
forceSSL = true; # Runs on port 80 and 443
locations."/".proxyPass = "http://localhost:3000/"; # Proxy to Gitea
};
};
};
};
# Generic machine
nixosConfigurations.pixi = nixpkgs.lib.nixosSystem {
system = "x86_64-linux";
modules =
base_modules
++ [
./configuration.nix
{
system.stateVersion = "22.05";
}
];
specialArgs = {
hostname = "pixi";
_networking = {
# interfaces.eth1.ipv4.addresses = [{
# address = "71.0.0.1";
# prefixLength = 24;
# }];
firewall = {
enable = false;
allowedTCPPorts = [80 443 22];
};
useDHCP = false;
# interfaces.eth0.useDHCP = true;
};
_boot.loader.grub.enable = true;
_boot.loader.grub.version = 2;
_services.openssh = {
permitRootLogin = "no";
enable = true;
};
_services.gitea = {
enable = true;
stateDir = "/gitea";
rootUrl = "https://git.pegasust.com";
settings = {
repository = {
"ENABLE_PUSH_CREATE_USER" = true;
"ENABLE_PUSH_CREATE_ORG" = true;
};
};
};
_services.nginx = {
enable = true;
clientMaxBodySize = "100m"; # Allow big file transfers over git :^)
recommendedGzipSettings = true;
recommendedOptimisation = true;
recommendedProxySettings = true;
recommendedTlsSettings = true;
virtualHosts."git.pegasust.com" = {
# Gitea hostname
sslCertificate = "/var/lib/acme/git.pegasust.com/fullchain.pem";
sslCertificateKey = "/var/lib/acme/git.pegasust.com/key.pem";
forceSSL = true; # Runs on port 80 and 443
locations."/".proxyPass = "http://localhost:3000/"; # Proxy to Gitea
};
};
};
};
nixosConfigurations.nyx = nixpkgs.lib.nixosSystem {
system = "x86_64-linux";
modules =
base_modules
++ [
./configuration.nix
{
system.stateVersion = "22.05";
}
];
specialArgs = {
hostname = "nyx";
_networking = {
enableIPv6 = false;
interfaces.eth1.ipv4.addresses = [
{
address = "71.0.0.2";
prefixLength = 24;
}
];
firewall.enable = true;
useDHCP = false;
interfaces.eth0.useDHCP = true;
};
_boot.loader.grub.enable = true;
_boot.loader.grub.version = 2;
_services.openssh = {
permitRootLogin = "no";
enable = true;
};
};
};
nixosConfigurations.nixos = nixpkgs.lib.nixosSystem {
system = "x86_64-linux";
modules =
base_modules
++ [
./configuration.nix
{
system.stateVersion = "22.05";
}
];
specialArgs = {
hostname = "nixos";
};
};
nixosConfigurations.htran-dev = nixpkgs.lib.nixosSystem {
system = "x86_64-linux";
modules =
base_modules
++ [
./configuration.nix
{
system.stateVersion = "22.11";
mod.tailscale.enable = false;
networking.defaultGateway = {
address = "10.100.200.1";
# interface = "ens32";
};
networking.interfaces.ens32.ipv4.addresses = [
{
address = "10.100.200.230";
prefixLength = 24;
}
];
}
];
specialArgs = {
hostname = "htran-dev";
_networking = {
firewall.enable = true;
useDHCP = false;
interfaces.eth0.useDHCP = true;
};
_boot.loader.grub.enable = true;
_boot.loader.grub.version = 2;
_services.openssh = {
permitRootLogin = "no";
enable = true;
};
};
};
nixosConfigurations.bao = nixpkgs.lib.nixosSystem {
system = "x86_64-linux";
specialArgs.hostname = "bao";
modules =
base_modules
++ [
./configuration.nix
./../../modules/storage.perso.sys.nix
./../../modules/kde.sys.nix
# GPU, sound, networking stuffs
./../../modules/pulseaudio.sys.nix
./../../modules/opengl.sys.nix
./../../modules/nvgpu.sys.nix
({
config,
pkgs,
lib,
...
}: {
mod.tailscale.enable = true;
# Use UEFI
boot.loader.systemd-boot.enable = true;
networking.hostName = "bao"; # Define your hostname.
# Pick only one of the below networking options.
# networking.wireless.enable = true; # Enables wireless support via wpa_supplicant.
networking.networkmanager.enable = true; # Easiest to use and most distros use this by default.
time.timeZone = "America/Phoenix";
# Configure keymap in X11
services.xserver.layout = "us";
# services.xserver.xkbOptions = {
# "eurosign:e";
# "caps:escape" # map caps to escape.
# };
# Enable CUPS to print documents.
# services.printing.enable = true;
# Enable touchpad support (enabled default in most desktopManager).
# services.xserver.libinput.enable = true;
# Just an initial user to get this started lol
users.users.user = {
initialPassword = "pw123";
extraGroups = ["wheel" "networkmanager" "audio"];
isNormalUser = true;
};
# Some programs need SUID wrappers, can be configured further or are
# started in user sessions.
# programs.mtr.enable = true;
# programs.gnupg.agent = {
# enable = true;
# enableSSHSupport = true;
# };
# List services that you want to enable:
# Enable the OpenSSH daemon.
services.openssh.enable = true;
# This value determines the NixOS release from which the default
# settings for stateful data, like file locations and database versions
# on your system were taken. Its perfectly fine and recommended to leave
# this value at the release version of the first install of this system.
# Before changing this value read the documentation for this option
# (e.g. man configuration.nix or on https://nixos.org/nixos/options.html).
system.stateVersion = "22.11"; # Did you read the comment?
})
];
};
};
}

View File

@ -1,44 +0,0 @@
# Do not modify this file! It was generated by nixos-generate-config
# and may be overwritten by future invocations. Please make changes
# to /etc/nixos/configuration.nix instead.
{
config,
lib,
pkgs,
modulesPath,
...
}: {
imports = [
(modulesPath + "/profiles/qemu-guest.nix")
];
boot.initrd.availableKernelModules = ["virtio_pci" "virtio_scsi" "ahci" "sd_mod"];
boot.initrd.kernelModules = [];
boot.kernelParams = ["console=ttyS0,19200n8"];
boot.loader.grub.extraConfig = ''
serial --speed=19200 --unit=0 --word=8 --parity=no --stop=1
terminal_input serial;
terminal_output serial
'';
boot.loader.grub.forceInstall = true;
boot.loader.grub.device = "nodev";
boot.loader.timeout = 10;
boot.kernelModules = [];
boot.extraModulePackages = [];
fileSystems."/" = {
device = "/dev/sda";
fsType = "ext4";
};
swapDevices = [{device = "/dev/sdb";}];
# Enables DHCP on each ethernet and wireless interface. In case of scripted networking
# (the default) this is the recommended approach. When using systemd-networkd it's
# still possible to use this option, but it's recommended to use it in conjunction
# with explicit per-interface declarations with `networking.interfaces.<interface>.useDHCP`.
networking.useDHCP = lib.mkDefault true;
# networking.interfaces.enp0s5.useDHCP = lib.mkDefault true;
hardware.cpu.amd.updateMicrocode = lib.mkDefault config.hardware.enableRedistributableFirmware;
}

View File

@ -1,7 +0,0 @@
use_flake() {
watch_file flake.nix
watch_file flake.lock
eval "$(nix print-dev-env)"
}
use flake

View File

@ -1,26 +0,0 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: bug
assignees: ''
---
<!-- Please only open an issue, if you are experiencing a problem with NixOS-WSL, that looks like it has to be fixed in the code. If you aren't sure how to use the project or want help with using it, consider opening a discussion in the "Q&A"-Category instead -->
## Bug description
<!-- A clear and concise description of what the bug is. -->
## To Reproduce
Steps to reproduce the behavior:
**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->
## Logs
```
Include relevant console logs
```
<!-- If your issue is related to the installation process, please include the SHA256 checksum of the tarball you used to install NixOS-WSL -->

View File

@ -1,16 +0,0 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: enhancement
assignees: ''
---
<!-- Please only open an issue, if you want to suggest a concrete feature, including a way that it could be implemented. If you have more broad suggestions, consider opening a discussion in the "ideas" category instead. -->
## Problem
<!-- Describe the problem you are trying to solve -->
## Solution
<!-- Describe the solution you want to see integrated in the project -->

View File

@ -1,17 +0,0 @@
change-template: "* $TITLE (#$NUMBER) @$AUTHOR"
categories:
- title: '🚀 Features'
labels:
- enhancement
- title: "🪲 Bugfixes"
labels:
- bug
- title: "📖 Documentation"
labels:
- documentation
template: |
# Changelog
## 🛠️ General Changes
$CHANGES

View File

@ -1,78 +0,0 @@
name: 'Build NixOS WSL tarball'
on: [push, pull_request, release]
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
with:
# Nix Flakes doesn't work on shallow clones
fetch-depth: 0
- name: Install nix
uses: cachix/install-nix-action@v12
with:
install_url: https://github.com/numtide/nix-flakes-installer/releases/download/nix-2.4pre20201221_9fab14a/install
# Configure Nix to enable flakes
extra_nix_config: |
experimental-features = nix-command flakes
- name: Run checks
run: |
nix flake check
- name: Build tarball
run: |
nix build '.#nixosConfigurations.mysystem.config.system.build.tarball'
- name: Upload tarball
uses: actions/upload-artifact@v2
with:
name: rootfs
path: result/tarball/nixos-wsl-x86_64-linux.tar.gz
- name: Build installer
run: |
nix build '.#nixosConfigurations.mysystem.config.system.build.installer'
- name: Upload installer
uses: actions/upload-artifact@v2
with:
name: installer
path: result/tarball/nixos-wsl-installer.tar.gz
release:
if: startsWith(github.ref, 'refs/tags/')
needs: build
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
- uses: actions/download-artifact@v2
with:
name: rootfs
- uses: actions/download-artifact@v2
with:
name: installer
- name: Generate checksums
run: |
for x in *.tar.gz; do
sha256sum $x > ${x}.sha256
done
- name: Attach to release
uses: softprops/action-gh-release@v1
with:
files: |
nixos-wsl-x86_64-linux.tar.gz
nixos-wsl-x86_64-linux.tar.gz.sha256
nixos-wsl-installer.tar.gz
nixos-wsl-installer.tar.gz.sha256
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@ -1,19 +0,0 @@
name: Release Drafter
on:
push:
branches:
- main
pull_request:
types:
- opened
- reopened
- synchronize
-
jobs:
update_release_draft:
runs-on: ubuntu-latest
steps:
- uses: release-drafter/release-drafter@v5
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@ -1,50 +0,0 @@
name: 'Update flakes'
on:
workflow_dispatch:
schedule:
- cron: '0 2 * * 0'
jobs:
update-flakes:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
with:
# Nix Flakes doesn't work on shallow clones
fetch-depth: 0
- name: Install nix
uses: cachix/install-nix-action@v12
with:
install_url: https://github.com/numtide/nix-flakes-installer/releases/download/nix-2.4pre20201221_9fab14a/install
# Configure Nix to enable flakes
extra_nix_config: |
experimental-features = nix-command flakes
- name: Update flakes
run: nix flake update --recreate-lock-file
- name: Create Pull Request
id: cpr
uses: peter-evans/create-pull-request@v3
with:
commit-message: Update flakes
committer: GitHub <noreply@github.com>
author: ${{ github.actor }} <${{ github.actor }}@users.noreply.github.com>
signoff: false
branch: flake-updates
delete-branch: true
title: 'Update flakes'
body: |
Update report
- Updated with *today's* date
- Auto-generated by [create-pull-request][1]
[1]: https://github.com/peter-evans/create-pull-request
- name: Check outputs
run: |
echo "Pull Request Number - ${{ steps.cpr.outputs.pull-request-number }}"
echo "Pull Request URL - ${{ steps.cpr.outputs.pull-request-url }}"

View File

@ -1,2 +0,0 @@
result
result-*

View File

@ -1,202 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -1,112 +0,0 @@
<h1 align=center>
NixOS on WSL<br />
<a href="https://matrix.to/#/#wsl:nixos.org"><img src="https://img.shields.io/matrix/wsl:nixos.org?server_fqdn=nixos.ems.host&logo=matrix" alt="Matrix Chat" /></a>
<a href="https://github.com/NixOS/nixpkgs/tree/nixos-22.05"><img src="https://img.shields.io/badge/nixpkgs-22.05-brightgreen" alt="nixpkgs 22.05" /></a>
<a href="https://github.com/nix-community/NixOS-WSL/releases"><img alt="Downloads" src="https://img.shields.io/github/downloads/nix-community/NixOS-WSL/total"></a>
</h1>
A minimal root filesystem for running NixOS on WSL. It can be used with
[DistroLauncher](https://github.com/microsoft/WSL-DistroLauncher) as
`install.tar.gz` or as input to `wsl --import --version 2`.
## Quick start
First, [download the latest release\'s installer](https://github.com/nix-community/NixOS-WSL/releases/latest).
Then open up a Terminal, PowerShell or Command Prompt and run:
```sh
wsl --import NixOS .\NixOS\ nixos-wsl-installer.tar.gz --version 2
```
This sets up a new WSL distribution `NixOS` that is installed under
`.\NixOS`. `nixos-wsl-installer.tar.gz` is the path to the file you
downloaded earlier. You might need to change this path or change to the download directory first.
You can now run NixOS:
```sh
wsl -d NixOS
```
The installer will unpack the file system and subsequently start NixOS.
A few warnings about file systems and locales will pop up. You can
safely ignore them. After systemd has started, you should be greeted
with a bash prompt inside your fresh NixOS installation.
If you want to make NixOS your default distribution, you can do so with
```sh
wsl -s NixOS
```
## Building your own system tarball
This requires access to a system that already has Nix installed. Please refer to the [Nix installation guide](https://nixos.org/guides/install-nix.html) if that\'s not the case.
If you have a flakes-enabled Nix, you can use the following command to
build your own tarball instead of relying on a prebuilt one:
```cmd
nix build github:nix-community/NixOS-WSL#nixosConfigurations.mysystem.config.system.build.installer
```
Or, if you want to build with local changes, run inside your checkout:
```cmd
nix build .#nixosConfigurations.mysystem.config.system.build.installer
```
Without a flakes-enabled Nix, you can build a tarball using:
```cmd
nix-build -A nixosConfigurations.mysystem.config.system.build.installer
```
The resulting installer tarball can then be found under
`./result/tarball/nixos-wsl-installer.tar.gz`.
You can also build a rootfs tarball without wrapping it in the installer
by replacing `installer` with `tarball` in the above commands. The
rootfs tarball can then be found under
`./result/tarball/nixos-wsl-x86_64-linux.tar.gz`.
## Design
Getting NixOS to run under WSL requires some workarounds:
### systemd support
WSL comes with its own (non-substitutable) init system while NixOS uses
systemd. Simply starting systemd later on does not work out of the box,
because systemd as system instance refuses to start if it is not PID 1.
This unfortunate combination is resolved in two ways:
- the user\'s default shell is replaced by a wrapper script that acts
is init system and then drops to the actual shell
- systemd is started in its own PID namespace; therefore, it is PID 1.
The shell wrapper (see above) enters the systemd namespace before
dropping to the shell.
### Installer
Usually WSL distributions ship as a tarball of their root file system.
These tarballs however, can not contain any hard-links due to the way
they are unpacked by WSL, resulting in an \"Unspecified Error\". By
default some Nix-derivations will contain hard-links when they are
built. This results in system tarballs that can not be imported into
WSL. To circumvent this problem, the rootfs tarball is wrapped in that
of a minimal distribution (the installer), that is packaged without any
hard-links. When the installer system is started for the first time, it
overwrites itself with the contents of the rootfs tarball.
## License
Apache License, Version 2.0. See `LICENSE` or <http://www.apache.org/licenses/LICENSE-2.0.html> for details.
## Further links
- [DistroLauncher](https://github.com/microsoft/WSL-DistroLauncher)
- [A quick way into a systemd \"bottle\" for WSL](https://github.com/arkane-systems/genie)
- [NixOS in Windows Store for Windows Subsystem for Linux](https://github.com/NixOS/nixpkgs/issues/30391)
- [wsl2-hacks](https://github.com/shayne/wsl2-hacks)

View File

@ -1,14 +0,0 @@
(import
(
let
lock = builtins.fromJSON (builtins.readFile ./flake.lock);
in
fetchTarball {
url = "https://github.com/edolstra/flake-compat/archive/${lock.nodes.flake-compat.locked.rev}.tar.gz";
sha256 = lock.nodes.flake-compat.locked.narHash;
}
)
{
src = ./.;
})
.defaultNix

View File

@ -1,59 +0,0 @@
{
"nodes": {
"flake-compat": {
"flake": false,
"locked": {
"lastModified": 1650374568,
"narHash": "sha256-Z+s0J8/r907g149rllvwhb4pKi8Wam5ij0st8PwAh+E=",
"owner": "edolstra",
"repo": "flake-compat",
"rev": "b4a34015c698c7793d592d66adbab377907a2be8",
"type": "github"
},
"original": {
"owner": "edolstra",
"repo": "flake-compat",
"type": "github"
}
},
"flake-utils": {
"locked": {
"lastModified": 1659877975,
"narHash": "sha256-zllb8aq3YO3h8B/U0/J1WBgAL8EX5yWf5pMj3G0NAmc=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "c0e246b9b83f637f4681389ecabcb2681b4f3af0",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1660318005,
"narHash": "sha256-g9WCa9lVUmOV6dYRbEPjv/TLOR5hamjeCcKExVGS3OQ=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "5c211b47aeadcc178c5320afd4e74c7eed5c389f",
"type": "github"
},
"original": {
"id": "nixpkgs",
"ref": "nixos-22.05",
"type": "indirect"
}
},
"root": {
"inputs": {
"flake-compat": "flake-compat",
"flake-utils": "flake-utils",
"nixpkgs": "nixpkgs"
}
}
},
"root": "root",
"version": 7
}

View File

@ -1,59 +0,0 @@
{
description = "NixOS WSL";
inputs = {
nixpkgs.url = "nixpkgs/nixos-22.05";
flake-utils.url = "github:numtide/flake-utils";
flake-compat = {
url = "github:edolstra/flake-compat";
flake = false;
};
};
outputs = {
self,
nixpkgs,
flake-utils,
...
}:
{
nixosModules.wsl = {
imports = [
./modules/build-tarball.nix
./modules/docker-desktop.nix
./modules/docker-native.nix
./modules/installer.nix
./modules/interop.nix
./modules/wsl-distro.nix
];
};
nixosConfigurations.mysystem = nixpkgs.lib.nixosSystem {
system = "x86_64-linux";
modules = [
./configuration.nix
];
};
}
// flake-utils.lib.eachSystem
(with flake-utils.lib.system; ["x86_64-linux" "aarch64-linux"])
(
system: let
pkgs = import nixpkgs {inherit system;};
in {
checks.check-format =
pkgs.runCommand "check-format"
{
buildInputs = with pkgs; [nixpkgs-fmt];
} ''
nixpkgs-fmt --check ${./.}
mkdir $out # success
'';
devShell = pkgs.mkShell {
nativeBuildInputs = with pkgs; [nixpkgs-fmt];
};
}
);
}

View File

@ -1,104 +0,0 @@
{
config,
pkgs,
lib,
...
}:
with builtins;
with lib; let
pkgs2storeContents = l:
map
(x: {
object = x;
symlink = "none";
})
l;
nixpkgs = lib.cleanSource pkgs.path;
channelSources =
pkgs.runCommand "nixos-${config.system.nixos.version}"
{preferLocalBuild = true;}
''
mkdir -p $out
cp -prd ${nixpkgs.outPath} $out/nixos
chmod -R u+w $out/nixos
if [ ! -e $out/nixos/nixpkgs ]; then
ln -s . $out/nixos/nixpkgs
fi
echo -n ${toString config.system.nixos.revision} > $out/nixos/.git-revision
echo -n ${toString config.system.nixos.versionSuffix} > $out/nixos/.version-suffix
echo ${toString config.system.nixos.versionSuffix} | sed -e s/pre// > $out/nixos/svn-revision
'';
preparer = pkgs.writeShellScriptBin "wsl-prepare" ''
set -e
mkdir -m 0755 ./bin ./etc
mkdir -m 1777 ./tmp
# WSL requires a /bin/sh - only temporary, NixOS's activate will overwrite
ln -s ${config.users.users.root.shell} ./bin/sh
# WSL also requires a /bin/mount, otherwise the host fs isn't accessible
ln -s /nix/var/nix/profiles/system/sw/bin/mount ./bin/mount
# Set system profile
system=${config.system.build.toplevel}
./$system/sw/bin/nix-store --store `pwd` --load-db < ./nix-path-registration
rm ./nix-path-registration
./$system/sw/bin/nix-env --store `pwd` -p ./nix/var/nix/profiles/system --set $system
# Set channel
mkdir -p ./nix/var/nix/profiles/per-user/root
./$system/sw/bin/nix-env --store `pwd` -p ./nix/var/nix/profiles/per-user/root/channels --set ${channelSources}
mkdir -m 0700 -p ./root/.nix-defexpr
ln -s /nix/var/nix/profiles/per-user/root/channels ./root/.nix-defexpr/channels
# It's now a NixOS!
touch ./etc/NIXOS
# Write wsl.conf so that it is present when NixOS is started for the first time
cp ${config.environment.etc."wsl.conf".source} ./etc/wsl.conf
${lib.optionalString config.wsl.tarball.includeConfig ''
# Copy the system configuration
mkdir -p ./etc/nixos/nixos-wsl
cp -R ${lib.cleanSource ../.}/. ./etc/nixos/nixos-wsl
mv ./etc/nixos/nixos-wsl/configuration.nix ./etc/nixos/configuration.nix
# Patch the import path to avoid having a flake.nix in /etc/nixos
sed -i 's|import \./default\.nix|import \./nixos-wsl|' ./etc/nixos/configuration.nix
''}
'';
in {
options.wsl.tarball = {
includeConfig = mkOption {
type = types.bool;
default = true;
description = "Whether or not to copy the system configuration into the tarball";
};
};
config = mkIf config.wsl.enable {
# These options make no sense without the wsl-distro module anyway
system.build.tarball = pkgs.callPackage "${nixpkgs}/nixos/lib/make-system-tarball.nix" {
# No contents, structure will be added by prepare script
contents = [];
fileName = "nixos-wsl-${pkgs.hostPlatform.system}";
storeContents = pkgs2storeContents [
config.system.build.toplevel
channelSources
preparer
];
extraCommands = "${preparer}/bin/wsl-prepare";
# Use gzip
compressCommand = "gzip";
compressionExtension = ".gz";
};
};
}

View File

@ -1,42 +0,0 @@
{
config,
lib,
pkgs,
...
}:
with builtins;
with lib; {
imports = [
(mkRenamedOptionModule ["wsl" "docker"] ["wsl" "docker-desktop"])
];
options.wsl.docker-desktop = with types; {
enable = mkEnableOption "Docker Desktop integration";
};
config = let
cfg = config.wsl.docker-desktop;
in
mkIf (config.wsl.enable && cfg.enable) {
environment.systemPackages = with pkgs; [
docker
docker-compose
];
systemd.services.docker-desktop-proxy = {
description = "Docker Desktop proxy";
script = ''
${config.wsl.automountPath}/wsl/docker-desktop/docker-desktop-user-distro proxy --docker-desktop-root ${config.wsl.automountPath}/wsl/docker-desktop
'';
wantedBy = ["multi-user.target"];
serviceConfig = {
Restart = "on-failure";
RestartSec = "30s";
};
};
users.groups.docker.members = [
config.wsl.defaultUser
];
};
}

View File

@ -1,44 +0,0 @@
{
config,
lib,
pkgs,
...
}:
with builtins;
with lib; {
options.wsl.docker-native = with types; {
enable = mkEnableOption "Native Docker integration in NixOS.";
addToDockerGroup = mkOption {
type = bool;
default = config.security.sudo.wheelNeedsPassword;
description = ''
Wether to add the default user to the docker group.
This is not recommended, if you have a password, because it essentially permits unauthenticated root access.
'';
};
};
config = let
cfg = config.wsl.docker-native;
in
mkIf (config.wsl.enable && cfg.enable) {
nixpkgs.overlays = [
(self: super: {
docker = super.docker.override {iptables = pkgs.iptables-legacy;};
})
];
environment.systemPackages = with pkgs; [
docker
docker-compose
];
virtualisation.docker.enable = true;
users.groups.docker.members = lib.mkIf cfg.addToDockerGroup [
config.wsl.defaultUser
];
};
}

View File

@ -1,93 +0,0 @@
{
config,
lib,
pkgs,
...
}:
with builtins;
with lib; {
config = mkIf config.wsl.enable (
let
mkTarball = pkgs.callPackage "${lib.cleanSource pkgs.path}/nixos/lib/make-system-tarball.nix";
pkgs2storeContents = map (x: {
object = x;
symlink = "none";
});
rootfs = let tarball = config.system.build.tarball; in "${tarball}/tarball/${tarball.fileName}.tar${tarball.extension}";
installer = pkgs.writeScript "installer.sh" ''
#!${pkgs.busybox}/bin/sh
BASEPATH=$PATH
export PATH=$BASEPATH:${pkgs.busybox}/bin # Add busybox to path
set -e
cd /
echo "Unpacking root file system..."
${pkgs.pv}/bin/pv ${rootfs} | tar xz
echo "Activating nix configuration..."
/nix/var/nix/profiles/system/activate
PATH=$BASEPATH:/run/current-system/sw/bin # Use packages from target system
echo "Cleaning up installer files..."
nix-collect-garbage
rm /nix-path-registration
echo "Optimizing store..."
nix-store --optimize
# Don't package the shell here, it's contained in the rootfs
exec ${builtins.unsafeDiscardStringContext config.users.users.root.shell} "$@"
'';
# Set installer.sh as the root shell
passwd = pkgs.writeText "passwd" ''
root:x:0:0:System administrator:/root:${installer}
'';
in {
system.build.installer = mkTarball {
fileName = "nixos-wsl-installer";
compressCommand = "gzip";
compressionExtension = ".gz";
extraArgs = "--hard-dereference";
storeContents = with pkgs;
pkgs2storeContents [
installer
];
contents = [
{
source = config.environment.etc."wsl.conf".source;
target = "/etc/wsl.conf";
}
{
source = config.environment.etc."fstab".source;
target = "/etc/fstab";
}
{
source = passwd;
target = "/etc/passwd";
}
{
source = "${pkgs.busybox}/bin/busybox";
target = "/bin/sh";
}
{
source = "${pkgs.busybox}/bin/busybox";
target = "/bin/mount";
}
];
extraCommands = pkgs.writeShellScript "prepare" ''
export PATH=$PATH:${pkgs.coreutils}/bin
mkdir -p bin
ln -s /init bin/wslpath
'';
};
}
);
}

View File

@ -1,91 +0,0 @@
{
lib,
pkgs,
config,
...
}:
with builtins;
with lib; {
imports = [
(mkRenamedOptionModule ["wsl" "compatibility" "interopPreserveArgvZero"] ["wsl" "interop" "preserveArgvZero"])
];
options.wsl.interop = with types; {
register = mkOption {
type = bool;
default = false; # Use the existing registration by default
description = "Explicitly register the binfmt_misc handler for Windows executables";
};
includePath = mkOption {
type = bool;
default = true;
description = "Include Windows PATH in WSL PATH";
};
preserveArgvZero = mkOption {
type = nullOr bool;
default = null;
description = ''
Register binfmt interpreter for Windows executables with 'preserves argv[0]' flag.
Default (null): autodetect, at some performance cost.
To avoid the performance cost, set this to true for WSL Preview 0.58 and up,
or to false for any older versions, including pre-Microsoft Store and Windows 10.
'';
};
};
config = let
cfg = config.wsl.interop;
in
mkIf config.wsl.enable {
boot.binfmt.registrations = mkIf cfg.register {
WSLInterop = let
compat = cfg.preserveArgvZero;
# WSL Preview 0.58 and up registers the /init binfmt interp for Windows executable
# with the "preserve argv[0]" flag, so if you run `./foo.exe`, the interp gets invoked
# as `/init foo.exe ./foo.exe`.
# argv[0] --^ ^-- actual path
#
# Older versions expect to be called without the argv[0] bit, simply as `/init ./foo.exe`.
#
# We detect that by running `/init /known-not-existing-path.exe` and checking the exit code:
# the new style interp expects at least two arguments, so exits with exit code 1,
# presumably meaning "parsing error"; the old style interp attempts to actually run
# the executable, fails to find it, and exits with 255.
compatWrapper = pkgs.writeShellScript "nixos-wsl-binfmt-hack" ''
/init /nixos-wsl-does-not-exist.exe
[ $? -eq 255 ] && shift
exec /init "$@"
'';
# use the autodetect hack if unset, otherwise call /init directly
interpreter =
if compat == null
then compatWrapper
else "/init";
# enable for the wrapper and autodetect hack
preserveArgvZero =
if compat == false
then false
else true;
in {
magicOrExtension = "MZ";
fixBinary = true;
wrapInterpreterInShell = false;
inherit interpreter preserveArgvZero;
};
};
# Include Windows %PATH% in Linux $PATH.
environment.extraInit = mkIf cfg.includePath ''PATH="$PATH:$WSLPATH"'';
warnings = let
registrations = config.boot.binfmt.registrations;
in
optional (!(registrations ? WSLInterop) && (length (attrNames config.boot.binfmt.registrations)) != 0) "Having any binfmt registrations without re-registering WSLInterop (wsl.interop.register) will break running .exe files from WSL2";
};
}

View File

@ -1,142 +0,0 @@
{
lib,
pkgs,
config,
...
}:
with builtins;
with lib; {
options.wsl = with types; let
coercedToStr = coercedTo (oneOf [bool path int]) toString str;
in {
enable = mkEnableOption "support for running NixOS as a WSL distribution";
automountPath = mkOption {
type = str;
default = "/mnt";
description = "The path where windows drives are mounted (e.g. /mnt/c)";
};
automountOptions = mkOption {
type = str;
default = "metadata,uid=1000,gid=100";
description = "Options to use when mounting windows drives";
};
defaultUser = mkOption {
type = str;
default = "nixos";
description = "The name of the default user";
};
startMenuLaunchers = mkEnableOption "shortcuts for GUI applications in the windows start menu";
wslConf = mkOption {
type = attrsOf (attrsOf (oneOf [string int bool]));
description = "Entries that are added to /etc/wsl.conf";
};
};
config = let
cfg = config.wsl;
syschdemd = import ../syschdemd.nix {
inherit lib pkgs config;
inherit (cfg) automountPath defaultUser;
defaultUserHome = config.users.users.${cfg.defaultUser}.home;
};
in
mkIf cfg.enable {
wsl.wslConf = {
automount = {
enabled = true;
mountFsTab = true;
root = "${cfg.automountPath}/";
options = cfg.automountOptions;
};
network = {
generateResolvConf = mkDefault true;
generateHosts = mkDefault true;
};
};
# WSL is closer to a container than anything else
boot.isContainer = true;
environment.noXlibs = lib.mkForce false; # override xlibs not being installed (due to isContainer) to enable the use of GUI apps
hardware.opengl.enable = true; # Enable GPU acceleration
environment = {
etc = {
"wsl.conf".text = generators.toINI {} cfg.wslConf;
# DNS settings are managed by WSL
hosts.enable = !config.wsl.wslConf.network.generateHosts;
"resolv.conf".enable = !config.wsl.wslConf.network.generateResolvConf;
};
systemPackages = [
(pkgs.runCommand "wslpath" {} ''
mkdir -p $out/bin
ln -s /init $out/bin/wslpath
'')
];
};
networking.dhcpcd.enable = false;
users.users.${cfg.defaultUser} = {
isNormalUser = true;
uid = 1000;
extraGroups = ["wheel"]; # Allow the default user to use sudo
};
users.users.root = {
shell = "${syschdemd}/bin/syschdemd";
# Otherwise WSL fails to login as root with "initgroups failed 5"
extraGroups = ["root"];
};
security.sudo = {
extraConfig = ''
Defaults env_keep+=INSIDE_NAMESPACE
'';
wheelNeedsPassword = mkDefault false; # The default user will not have a password by default
};
system.activationScripts = {
copy-launchers = mkIf cfg.startMenuLaunchers (
stringAfter [] ''
for x in applications icons; do
echo "Copying /usr/share/$x"
mkdir -p /usr/share/$x
${pkgs.rsync}/bin/rsync -ar --delete $systemConfig/sw/share/$x/. /usr/share/$x
done
''
);
populateBin = stringAfter [] ''
echo "setting up /bin..."
ln -sf /init /bin/wslpath
ln -sf ${pkgs.bashInteractive}/bin/bash /bin/sh
ln -sf ${pkgs.util-linux}/bin/mount /bin/mount
'';
};
systemd = {
# Disable systemd units that don't make sense on WSL
services = {
"serial-getty@ttyS0".enable = false;
"serial-getty@hvc0".enable = false;
"getty@tty1".enable = false;
"autovt@".enable = false;
firewall.enable = false;
systemd-resolved.enable = false;
systemd-udevd.enable = false;
};
tmpfiles.rules = [
# Don't remove the X11 socket
"d /tmp/.X11-unix 1777 root root"
];
# Don't allow emergency mode, because we don't have a console.
enableEmergencyMode = false;
};
warnings = optional (config.systemd.services.systemd-resolved.enable && config.wsl.wslConf.network.generateResolvConf) "systemd-resolved is enabled, but resolv.conf is managed by WSL";
};
}

View File

@ -1,28 +0,0 @@
{
lib,
pkgs,
config,
automountPath,
defaultUser,
defaultUserHome ? "/home/${defaultUser}",
...
}:
pkgs.substituteAll {
name = "syschdemd";
src = ./syschdemd.sh;
dir = "bin";
isExecutable = true;
buildInputs = with pkgs; [daemonize];
inherit defaultUser defaultUserHome;
inherit (pkgs) daemonize;
inherit (config.security) wrapperDir;
fsPackagesPath = lib.makeBinPath config.system.fsPackages;
systemdWrapper = pkgs.writeShellScript "systemd-wrapper.sh" ''
mount -t binfmt_misc binfmt_misc /proc/sys/fs/binfmt_misc || true
mount --make-rshared ${automountPath}
exec systemd
'';
}

View File

@ -1,78 +0,0 @@
#! @shell@
set -e
sw="/nix/var/nix/profiles/system/sw/bin"
systemPath=$(${sw}/readlink -f /nix/var/nix/profiles/system)
function start_systemd {
echo "Starting systemd..." >&2
PATH=/run/current-system/systemd/lib/systemd:@fsPackagesPath@ \
LOCALE_ARCHIVE=/run/current-system/sw/lib/locale/locale-archive \
@daemonize@/bin/daemonize /run/current-system/sw/bin/unshare -fp --mount-proc @systemdWrapper@
# Wait until systemd has been started to prevent a race condition from occuring
while ! $sw/pgrep -xf systemd | $sw/tail -n1 >/run/systemd.pid; do
$sw/sleep 1s
done
# Wait for systemd to start services
status=1
while [[ $status -gt 0 ]]; do
$sw/sleep 1
status=0
$sw/nsenter -t $(</run/systemd.pid) -p -m -- \
$sw/systemctl is-system-running -q --wait 2>/dev/null ||
status=$?
done
}
# Needs root to work
if [[ $EUID -ne 0 ]]; then
echo "[ERROR] Requires root! :( Make sure the WSL default user is set to root" >&2
exit 1
fi
if [ ! -e "/run/current-system" ]; then
LANG="C.UTF-8" /nix/var/nix/profiles/system/activate
fi
if [ ! -e "/run/systemd.pid" ]; then
start_systemd
fi
userShell=$($sw/getent passwd @defaultUser@ | $sw/cut -d: -f7)
if [[ $# -gt 0 ]]; then
# wsl seems to prefix with "-c"
shift
cmd="$@"
else
cmd="$userShell"
fi
# Pass external environment but filter variables specific to root user.
exportCmd="$(export -p | $sw/grep -vE ' (HOME|LOGNAME|SHELL|USER)='); export WSLPATH=\"$PATH\"; export INSIDE_NAMESPACE=true"
if [[ -z "${INSIDE_NAMESPACE:-}" ]]; then
# Test whether systemd is still alive if it was started previously
if ! [ -d "/proc/$(</run/systemd.pid)" ]; then
# Clear systemd pid if the process is not alive anymore
$sw/rm /run/systemd.pid
start_systemd
fi
# If we are currently in /root, this is probably because the directory that WSL was started is inaccessible
# cd to the user's home to prevent a warning about permission being denied on /root
if [[ $PWD == "/root" ]]; then
cd @defaultUserHome@
fi
exec $sw/nsenter -t $(</run/systemd.pid) -p -m -- $sw/machinectl -q \
--uid=@defaultUser@ shell .host /bin/sh -c \
"cd \"$PWD\"; $exportCmd; source /etc/set-environment; exec $cmd"
else
exec $cmd
fi

View File

@ -1,81 +0,0 @@
# Do not modify this file! It was generated by nixos-generate-config
# and may be overwritten by future invocations. Please make changes
# to /etc/nixos/configuration.nix instead.
{
config,
lib,
pkgs,
modulesPath,
...
}: {
imports = [];
boot.initrd.availableKernelModules = [];
boot.initrd.kernelModules = [];
boot.kernelModules = [];
boot.extraModulePackages = [];
## NOTE: These filesystems are mounted by a wrapper script from nix-wsl
# fileSystems."/" =
# {
# device = "/dev/sdc";
# fsType = "ext4";
# };
#
# fileSystems."/mnt/wsl" =
# {
# device = "tmpfs";
# fsType = "tmpfs";
# };
#
# fileSystems."/mnt/wsl/docker-desktop/shared-sockets/guest-services" =
# {
# device = "none";
# fsType = "tmpfs";
# };
#
# fileSystems."/usr/lib/wsl/drivers" =
# {
# device = "drivers";
# fsType = "drvfs";
# };
#
# fileSystems."/usr/lib/wsl/lib" =
# {
# device = "lib";
# fsType = "drvfs";
# };
fileSystems."/mnt/c" = {
device = "C:";
fsType = "drvfs";
};
fileSystems."/mnt/d" = {
device = "D:";
fsType = "drvfs";
};
fileSystems."/mnt/f" = {
device = "F:";
fsType = "drvfs";
};
swapDevices = [];
# Enables DHCP on each ethernet and wireless interface. In case of scripted networking
# (the default) this is the recommended approach. When using systemd-networkd it's
# still possible to use this option, but it's recommended to use it in conjunction
# with explicit per-interface declarations with `networking.interfaces.<interface>.useDHCP`.
networking.useDHCP = lib.mkDefault true;
# networking.interfaces.bond0.useDHCP = lib.mkDefault true;
# networking.interfaces.bonding_masters.useDHCP = lib.mkDefault true;
# networking.interfaces.dummy0.useDHCP = lib.mkDefault true;
# networking.interfaces.eth0.useDHCP = lib.mkDefault true;
# networking.interfaces.sit0.useDHCP = lib.mkDefault true;
# networking.interfaces.tunl0.useDHCP = lib.mkDefault true;
nixpkgs.hostPlatform = lib.mkDefault "x86_64-linux";
hardware.cpu.intel.updateMicrocode = lib.mkDefault config.hardware.enableRedistributableFirmware;
}

View File

@ -1,3 +0,0 @@
# Machine-specific profile
- Currently only contains machine-specific details such as the `hardware-configuration.nix`

Some files were not shown because too many files have changed in this diff Show More