From 19dbcc6b21f8fa7602252c0ac67cd0b3d23ef327 Mon Sep 17 00:00:00 2001 From: odelucca Date: Fri, 31 Jan 2020 21:34:47 -0300 Subject: [PATCH 1/2] :sparkles: Adds cache to returned op items To cache op list-items results I must first create a file everytime I get any return from the command itself. On this commit, I am creating the logic to save the return from op list-items into a given file for further usage. Now, I just need to add the logic to fetch from this file instead, if the file is new enought. --- scripts/main.sh | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/scripts/main.sh b/scripts/main.sh index 700ae7a..be6229a 100755 --- a/scripts/main.sh +++ b/scripts/main.sh @@ -84,6 +84,13 @@ get_op_items() { | jq "$JQ_FILTER" --raw-output } +cache_items() { + local items=$@ + local cache_file="/tmp/tmux-op-items" + + echo $items > $cache_file +} + get_op_item_password() { local -r ITEM_UUID="$1" @@ -153,6 +160,7 @@ main() { spinner_stop fi + cache_items $items selected_item_name="$(echo "$items" | awk -F ',' '{ print $1 }' | fzf --no-multi)" if [[ -n "$selected_item_name" ]]; then From a9d853b7ee8b4c85293f0146f7c521fe85b0f951 Mon Sep 17 00:00:00 2001 From: odelucca Date: Fri, 31 Jan 2020 22:24:31 -0300 Subject: [PATCH 2/2] :sparkles: Uses cache_file if available Now that I can cache the op list-items result, I need to use the cache instead of getting it online, if it exists. It is important to have a TTL on the cache file too. On this commit I'm going to add the logic to use the cache file (if applicable) and also create a rule to use it only when the cache is recent. Now, I've finished the feature and can start using it. --- scripts/main.sh | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/scripts/main.sh b/scripts/main.sh index be6229a..bdee3cb 100755 --- a/scripts/main.sh +++ b/scripts/main.sh @@ -46,7 +46,16 @@ op_get_session() { } get_op_items() { + local cache_file="/tmp/tmux-op-items" + + if [ -e $cache_file ]; then + echo "$(cat $cache_file)" + else + fetch_items + fi +} +fetch_items() { # The structure (we need) looks like the following: # [ # { @@ -85,10 +94,22 @@ get_op_items() { } cache_items() { - local items=$@ + local items=$1 local cache_file="/tmp/tmux-op-items" - echo $items > $cache_file + if ! [ -e $cache_file ]; then + echo "$items" > $cache_file + else + local last_update="$(stat -c %Y $cache_file)" + local now="$(date +%s)" + local seconds_since_last_update="$(($now-$last_update))" + + # Remove cache file if last cache was from 6h ago + if [[ $seconds_since_last_update < 21600 ]]; then + display_message "ok" + rm $cache_file + fi + fi } get_op_item_password() { @@ -160,7 +181,7 @@ main() { spinner_stop fi - cache_items $items + cache_items "$items" selected_item_name="$(echo "$items" | awk -F ',' '{ print $1 }' | fzf --no-multi)" if [[ -n "$selected_item_name" ]]; then