winure/qdls/Program.cs

66 lines
1.8 KiB
C#

using Qdls;
// collect args and consume flags
List<string> arguments = args.ToList();
bool showHidden = Util.CheckFlag(arguments, "-a", "--all", "-A");
// default to "." if no target args
if(arguments.Count == 0)
arguments = ["."];
// run on targets
foreach(var arg in arguments) {
// don't try to list nonexistent entries or files
if(!Path.Exists(arg)) {
Console.WriteLine($"'{arg}': does not exist");
continue;
}
if(File.Exists(arg)) {
Console.WriteLine($"'{arg}': is file");
continue;
}
// fetch children
var children = Directory.GetFileSystemEntries(arg);
// exclude hidden files where applicable
if(!showHidden) { children = children.Where(f => !Util.IsHidden(f)).ToArray(); }
// state vars
var buffer = "";
var longest = Path.GetFileName(children.OrderByDescending(s => s.Length).First()).Length;
var columns = Console.WindowWidth / (longest + 2);
var multiline = columns < children.Count();
var position = 0;
// print names if more than one target
if(args.Length > 1)
Console.WriteLine($"{arg}:");
// iterate over children; build buffer and output when full
foreach(var child in children.OrderBy(f => (int)(Path.GetFileName(f)[0]))) {
var name = Path.GetFileName(child);
// format hidden files
if(Util.IsHidden(child))
buffer += Format.Hidden;
// format directories
if(Directory.Exists(child))
buffer += Format.Directory;
// if we pass max width, write buffer and clear
if( (++position > columns) && multiline ) {
position = 1;
Console.WriteLine(buffer.TrimEnd());
buffer = "";
}
if(multiline)
buffer += $"{name}{Format.Reset}".PadRight(longest + 6); // magic number 6 is +2 ignoring ansi reset sequence
else
buffer += $"{name}{Format.Reset} ";
}
// print last line
Console.WriteLine(buffer);
}