Skip to main content

We can refactor this into a nice fish function

ID
55cd03f
date
2023-12-13 09:45:24+00:00
author
Alex Chan <alex@alexwlchan.net>
parent
16c4ea6
message
We can refactor this into a nice fish function
changed files
2 files, 18 additions, 6 deletions

Changed files

fish_functions/append_to_file_if_not_exists.fish (0) → fish_functions/append_to_file_if_not_exists.fish (495)

diff --git a/fish_functions/append_to_file_if_not_exists.fish b/fish_functions/append_to_file_if_not_exists.fish
new file mode 100644
index 0000000..dd30611
--- /dev/null
+++ b/fish_functions/append_to_file_if_not_exists.fish
@@ -0,0 +1,17 @@
+# Append a line to a file, but only if the line isn't already in the file.
+#
+# This is similar to:
+#
+#     echo "This is my new line" >> myfile.txt
+#
+# but it will only insert it once, and won't insert it repeatedly if you
+# call the function again.
+#
+function append_to_file_if_not_exists
+    set target_file $argv[1]
+    set line_to_append $argv[2]
+
+    if not grep --quiet --fixed-strings --line-regexp "$line_to_append" "$target_file"
+        echo $line_to_append >> $target_file
+    end
+end
\ No newline at end of file

fish_functions/venv.fish (1812) → fish_functions/venv.fish (1678)

diff --git a/fish_functions/venv.fish b/fish_functions/venv.fish
index 40e8a81..991d46f 100644
--- a/fish_functions/venv.fish
+++ b/fish_functions/venv.fish
@@ -10,12 +10,7 @@ function venv
     # Append .venv to the Git exclude file, but only if it's not
     # already there.
     if test -e .git
-        set exclude_file ".git/info/exclude"
-        set line_to_append ".venv"
-
-        if not grep -q -x $line_to_append $exclude_file
-            echo $line_to_append >> $exclude_file
-        end
+        append_to_file_if_not_exists ".git/info/exclude" ".venv"
     end
 
     source .venv/bin/activate.fish