From 73e605d9feec3985e35047e75eb49c3e2fcd9fd5 Mon Sep 17 00:00:00 2001
From: Roland Hopferwieser <develop@int0x80.at>
Date: Tue, 29 Aug 2017 17:10:00 +0200
Subject: [PATCH] Add function to write aliases

---
 doc/vcsh.1.ronn |  8 ++++++--
 vcsh            | 19 ++++++++++++++++++-
 2 files changed, 24 insertions(+), 3 deletions(-)

diff --git a/doc/vcsh.1.ronn b/doc/vcsh.1.ronn
index b517d7c..cc7edc2 100644
--- a/doc/vcsh.1.ronn
+++ b/doc/vcsh.1.ronn
@@ -5,7 +5,7 @@ vcsh(1) - Version Control System for $HOME - multiple Git repositories in $HOME
 
 `vcsh` [<options>] <command>
 
-`vcsh` alias [<alias-name>]
+`vcsh` alias [<alias>[=<command>]]
 
 `vcsh` clone [-b <branch>] <url> [<repo>]
 
@@ -85,7 +85,11 @@ an interactive user.
 ## COMMANDS
 
 * alias:
-  List defined aliases.
+  List all defined aliases.
+
+  `<alias>`: Print the right side of alias definition.
+
+  `<alias>=<command>`: Add an alias definition to <XDG_CONFIG_HOME/vcsh/aliases>.
 
 * clone:
   Clone an existing repository.
diff --git a/vcsh b/vcsh
index 6ad9fd6..86538d0 100755
--- a/vcsh
+++ b/vcsh
@@ -179,11 +179,28 @@ alias_get() {
 	fi
 }
 
+alias_write() {
+	[ -w "$XDG_CONFIG_HOME/vcsh/aliases" ] ||
+	[ ! -e "$XDG_CONFIG_HOME/vcsh/aliases" -a -w "$XDG_CONFIG_HOME/vcsh/" ] ||
+		fatal "File '$XDG_CONFIG_HOME/vcsh/aliases' not writeable"
+	[ "$2" == '=' ] || fatal 'Invalid alias format'
+	if [ -n "$(alias_get $1)" ]; then
+		local regex="s/^$1\s*=.*/$@/"
+		sed -i -re "$regex" "$XDG_CONFIG_HOME/vcsh/aliases"
+	else
+		echo "$@" >> "$XDG_CONFIG_HOME/vcsh/aliases"
+	fi
+}
+
 aliases() {
-	local a cmd
 	if [ -n "$1" ]; then
+		local alias=$(<<<"$@" sed -re 's/(\w+)\s*=\s*(\w.*)/\1 = \2/')
+		if [ -n "$alias" ]; then
+			alias_write $alias
+		fi
 		alias_get "$1"
 	else
+		local a cmd
 		while read a cmd; do
 			echo $a = $cmd
 		done <<< "$(alias_read)"
-- 
GitLab