Created
March 22, 2023 23:01
-
-
Save itarato/2920eb41d856fe51431c8a8194710332 to your computer and use it in GitHub Desktop.
Redis watcher
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
=begin | |
WADIS is a Redis variable watcher. | |
Usage: | |
```shell | |
ruby wadis.rb <HOST> <PORT> --hkey=<key1>,<key2>... --vkey=<key1>,<key2>... | |
``` | |
=end | |
require("redis") | |
class ArgConf | |
attr_reader(:posArgs) | |
attr_reader(:namedArgs) | |
def initialize(posArgs: [], namedArgs: []) | |
@posArgs = posArgs | |
@namedArgs = namedArgs | |
end | |
end | |
class ArgParse | |
def self.parse(conf) | |
o = new(conf) | |
o.parse | |
o | |
end | |
def initialize(conf) | |
@conf = conf | |
@args = {} | |
end | |
def get(name) = @args[name] | |
def to_s | |
"<#{self.class.name} args: #{@args}>" | |
end | |
def parse | |
positional_idx = 0 | |
ARGV.each do |arg| | |
if arg.include?("=") | |
k, v = arg.split("=") | |
k = k.sub(/^-+/, "") | |
if !@conf.namedArgs.include?(k.to_sym) | |
raise(ArgumentError, "Unknown argument: '#{k}'. Allowed args: #{@conf.namedArgs}") | |
end | |
@args[k.to_sym] = v | |
else | |
positional_idx += 1 | |
if @conf.posArgs.size < positional_idx | |
raise(ArgumentError, "Positional arg overflow, max allowed: #{@conf.posArgs.size}") | |
end | |
@args[@conf.posArgs[positional_idx - 1]] = arg | |
end | |
end | |
if @conf.posArgs.size != positional_idx | |
$stderr.puts("Missing positional arguments: #{@conf.posArgs[positional_idx..]}") | |
exit(1) | |
end | |
end | |
end | |
class App | |
def initialize | |
@args = ArgParse.parse(ArgConf.new(posArgs: [:host, :port], namedArgs: [:hkey, :vkey])) | |
@redis = Redis.new(host: @args.get(:host), port: @args.get(:port).to_i) | |
end | |
def run | |
loop do | |
system("tput -x clear") | |
puts(Time.now) | |
@redis.info("keyspace").keys.each do |dbKey| | |
db_id = dbKey.delete_prefix("db").to_i | |
@redis.select(db_id) | |
(@args.get(:hkey)&.split(",") || []).each do |hkey| | |
@redis.keys("*#{hkey}*").each do |key| | |
vals = @redis.hgetall(key) | |
puts("\e[37m[db_#{db_id}] \e[93m#{key} \e[0m=> \e[95m#{vals}\e[0m") | |
end | |
end | |
(@args.get(:vkey)&.split(",") || []).each do |vkey| | |
@redis.keys("*#{vkey}*").each do |key| | |
val = @redis.get(key) | |
puts("\e[37m[db_#{db_id}] \e[93m#{key} \e[0m=> \e[95m#{val}\e[0m") | |
end | |
end | |
end | |
sleep(1) | |
end | |
end | |
end | |
App.new.run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment