using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
namespace RedisManager.Utils
{
///
/// Provides utility methods for Redis operations, including instance retrieval, connection, array conversion, and table printing.
///
public static class RedisUtils
{
///
/// Retrieves an InstanceConfig by name from the provided configuration. Exits if not found.
///
/// The configuration containing Redis instances.
/// The name of the instance to retrieve.
/// The matching InstanceConfig.
public static InstanceConfig GetInstance(Config config, string name)
{
var instance = config.Instances.Find(i => i.Name == name);
if (instance == null)
{
Console.WriteLine(Output.Red($"Instance '{name}' not found."));
Environment.Exit(1);
}
return instance;
}
///
/// Connects to a Redis instance using the provided configuration.
///
/// The instance configuration to connect with.
/// A connected ConnectionMultiplexer.
public static ConnectionMultiplexer ConnectRedis(InstanceConfig instance)
{
var options = new ConfigurationOptions
{
EndPoints = { $"{instance.Host}:{instance.Port}" },
Password = instance.Password
};
return ConnectionMultiplexer.Connect(options);
}
///
/// Converts an enumerable of strings to a RedisValue array.
///
/// The string values to convert.
/// An array of RedisValue.
public static RedisValue[] ArrayFrom(IEnumerable values)
{
var list = new List();
foreach (var v in values)
list.Add(v);
return list.ToArray();
}
///
/// Converts an enumerable of strings to a RedisKey array.
///
/// The string values to convert.
/// An array of RedisKey.
public static RedisKey[] ArrayFromKeys(IEnumerable values)
{
var list = new List();
foreach (var v in values)
list.Add(v);
return list.ToArray();
}
///
/// Prints a formatted table to the console with headers and rows.
///
/// The column headers.
/// The table rows.
public static void PrintTable(string[] headers, List rows)
{
if (rows.Count == 0)
{
Console.WriteLine(Output.Yellow("No data"));
return;
}
// Calculate column widths
var widths = new int[headers.Length];
for (int i = 0; i < headers.Length; i++)
{
widths[i] = headers[i].Length;
foreach (var row in rows)
{
if (i < row.Length && row[i] != null)
widths[i] = Math.Max(widths[i], row[i].Length);
}
}
// Print header
Console.WriteLine(Output.Blue(string.Join(" | ", headers.Select((h, i) => h.PadRight(widths[i])))));
Console.WriteLine(Output.Blue(new string('-', widths.Sum() + (headers.Length - 1) * 3)));
// Print rows
foreach (var row in rows)
{
var formattedRow = new string[headers.Length];
for (int i = 0; i < headers.Length; i++)
{
formattedRow[i] = i < row.Length && row[i] != null ? row[i].PadRight(widths[i]) : "".PadRight(widths[i]);
}
Console.WriteLine(Output.Green(string.Join(" | ", formattedRow)));
}
}
}
}