feat: use 'chatter +i' to make a file immutable on linux

This commit is contained in:
Ryan Yin
2023-06-17 22:00:32 +08:00
parent bfac95b71e
commit 1bfeeacf2f
2 changed files with 68 additions and 2 deletions

View File

@@ -0,0 +1,64 @@
{ config
, lib
, pkgs
, ...
}:
##############################################################################################
#
# Provide a option `home.immutable-file`, it works like `home.file` but make the generated file immutable.
#
# Copy from https://github.com/iosmanthus/nixos-config/blob/349917b/modules/immutable-file.nix
#
# this module use the `chattr +i` to make the file immutable, `i` indicates `immutable`,
# it's a i-node flags only works on Linux.
#
# TODO not used yet, need to test it.
#
##############################################################################################
with lib;
let
cfg = config.home.immutable-file;
immutableFileOpts = { ... }: {
options = {
src = mkOption {
type = types.path;
};
dst = mkOption {
type = types.path;
};
};
};
mkImmutableFile = pkgs.writeScript "make_immutable_file" ''
# $1: dst
# $2: src
if [ ! -d "$(dirname $1)" ]; then
mkdir -p $1
fi
if [ -f $1 ]; then
sudo chattr -i $1
fi
sudo cp $2 $1
sudo chattr +i $1
'';
in
{
options.home.immutable-file = mkOption {
type = with types; attrsOf (submodule immutableFileOpts);
default = { };
};
config = mkIf (cfg != { }) {
home.activation = mapAttrs'
(name: { src, dst }:
nameValuePair
"make-immutable-${name}"
(lib.hm.dag.entryAfter [ "writeBoundary" ] ''
${mkImmutableFile} ${dst} ${src}
''))
cfg;
};
}

View File

@@ -2,8 +2,10 @@
home.file.".config/fcitx5/profile".source = ./profile;
home.file.".config/fcitx5/profile-bak".source = ./profile; # used for backup
# fcitx5 每次切换输入法,就会修改 ~/.config/fcitx5/profile 文件,导致我用 hm 管理的配置被覆盖
# 解决方法是通过如下内置,每次 rebuild 前都先删除下 profile 文件
# every time fcitx5 switch input method, it will modify ~/.config/fcitx5/profile file,
# which will override my config managed by home-manager
# so we need to remove it before everytime we rebuild the config
home.activation.removeExistingFcitx5Profile = lib.hm.dag.entryBefore [ "checkLinkTargets" ] ''
rm -f "${config.xdg.configHome}/fcitx5/profile"
'';