Skip to content

Commit

Permalink
Merge pull request #61 from 0x78654C/v1.9.2-mkdirUpdate
Browse files Browse the repository at this point in the history
V1.9.2 mkdir update
  • Loading branch information
0x78654C authored Oct 7, 2024
2 parents dbe4033 + 36a5766 commit 98d4edd
Show file tree
Hide file tree
Showing 10 changed files with 282 additions and 42 deletions.
4 changes: 2 additions & 2 deletions Commands/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,5 @@
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.8.4.0")]
[assembly: AssemblyFileVersion("1.8.4.0")]
[assembly: AssemblyVersion("1.8.5.0")]
[assembly: AssemblyFileVersion("1.8.5.0")]
66 changes: 62 additions & 4 deletions Commands/TerminalCommands/ConsoleSystem/ListDirectories.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,16 @@ public class ListDirectories : ITerminalCommand
private static int s_countFilesText = 0;
private static int s_countDirectories = 0;
private static int s_countDirectoriesText = 0;
private static int s_countDirLen = 0;
private static int s_sm = 0;
private Stopwatch s_stopWatch;
private TimeSpan s_timeSpan;
private static List<string> s_listFiles = new List<string>();
private static List<string> s_listDirs = new List<string>();
private static List<string> s_listDuplicateFiles = new List<string>();
private static List<string> s_listSearched = new List<string>();
private static string s_virus;
private static string s_tree;
private static List<string> s_listParams = new List<string>() { "-h", "-d", "-s", "-c", "-cf", "-cd", "-hl", "-o", "-ct", "-la" };
private static string s_Header = "";
private readonly Func<IGrouping<string, FileInfo>, IEnumerable<Dupe>[]> DupesEnumerable = items => items.Select(t => new Dupe { FileName = t.FullName, Md5 = GetMD5CheckSum(t.FullName) })
Expand Down Expand Up @@ -63,6 +66,7 @@ public class ListDirectories : ITerminalCommand
-la : Displays last access date time of files and folders from current directory.
-hl : Highlights specific files/directories with by a specific text. Ex.: ls -hl <higlighted_text>
-o : Saves the output to a file. Ex.: ls -o <file_to_save>
-t : Display tree structure of directories. Use with param -o for store the output in a file: Ex.: ls -t -o <file_name>
Commands can be canceled with CTRL+X key combination.
Expand All @@ -84,7 +88,7 @@ public void Execute(string args)
// Set directory, to be used in other functions
s_currentDirectory =
File.ReadAllText(GlobalVariables.currentDirectory);

s_countDirLen = s_currentDirectory.Split('\\').Count() - 1;
string[] arg = args.Split(' ');
GlobalVariables.eventCancelKey = false;

Expand Down Expand Up @@ -268,6 +272,27 @@ public void Execute(string args)
return;
}

if (arg.ContainsParameter("-t"))
{
GlobalVariables.eventKeyFlagX = true;
var currDir = File.ReadAllText(GlobalVariables.currentDirectory);
DisplayTreeDirStructure(currDir);
if (arg.ContainsParameter("-o"))
{
var fileName = args.SplitByText("-o", 1).Trim();
FileSystem.SuccessWriteLine(FileSystem.SaveFileOutput(fileName, currDir, s_tree));
s_tree = "";
}
else
FileSystem.SuccessWriteLine(s_tree);
s_tree = "";
if (GlobalVariables.eventCancelKey)
FileSystem.SuccessWriteLine("Command stopped!");
ClearCounters();
return;
}


// Save ls output to a file
if (arg.ContainsParameter("-o"))
{
Expand Down Expand Up @@ -307,6 +332,39 @@ public void Execute(string args)
}
}

/// <summary>
/// Display structure dirs.
/// </summary>
/// <param name="currDir"></param>
private void DisplayTreeDirStructure(string currDir, string indent = "", bool isLast = true)
{
try
{
var directories = Directory.GetDirectories(currDir);
var dirInfo = new DirectoryInfo(currDir);
s_tree += indent + (isLast ? "└─ " : "├─ ") + dirInfo.Name + "\n";
indent += isLast ? " " : "│ ";
for (int i = 0; i < directories.Length; i++)
{
var directory = directories[i];
bool isLastDirectory = (i == directories.Length - 1);
DisplayTreeDirStructure(directory, indent, isLastDirectory);
}
}
catch
{
// Ignore if no access or any exceptions.
}
}

private string SeparatorIncrement(int count)
{
var sep = "";
for (int i = 0; i < count; i++)
sep += " ";
return sep;
}

/// <summary>
/// Get duplicates files based on MD5 checksuma and file size.
/// A big thanks for @mkbmain for help.
Expand Down Expand Up @@ -452,7 +510,7 @@ private static void SaveLSOutput(string path)
dirList += string.Join(Environment.NewLine, s_listDirs);
string fileList = Environment.NewLine + "-------Files-------" + Environment.NewLine;
fileList += string.Join(Environment.NewLine, s_listFiles);
string finalList =s_Header + dirList + fileList;
string finalList = s_Header + dirList + fileList;
FileSystem.SuccessWriteLine(FileSystem.SaveFileOutput(path, s_currentDirectory, finalList));
s_listDirs.Clear();
s_listFiles.Clear();
Expand Down Expand Up @@ -539,7 +597,7 @@ private static void DisplayCurrentDirectoryFiles(bool displaySizes, string highl
else
{
var isPipe = GlobalVariables.isPipeCommand && GlobalVariables.pipeCmdCount > 0;
if (isCreationTime)
if (isCreationTime)
SetHeader(TypeHeader.CreationTime);
else if (isLastAccessTime)
SetHeader(TypeHeader.LastAccess);
Expand Down Expand Up @@ -810,7 +868,7 @@ Attributes Owner {typeHead}{spacesSize}Size{spacesFile}Di
";
if (isSaveToFile)
{
s_Header = header+"\n";
s_Header = header + "\n";
}
else
Console.WriteLine(header);
Expand Down
26 changes: 22 additions & 4 deletions Commands/TerminalCommands/DirFiles/Delete.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ public class Delete : ITerminalCommand
-a : Deletes all files and directories in the current directory.
-af : Deletes all files in the current directory.
-ad : Deletes all directories in the current directory.
Example1: del <dir_path>
Example2: del <dir_path1;dir_path2;dir_path3>
";

public void Execute(string args)
Expand Down Expand Up @@ -50,11 +53,26 @@ public void Execute(string args)
else
{
args = args.Replace("del ", "");
if (GlobalVariables.isPipeCommand && GlobalVariables.pipeCmdCount == 0 || GlobalVariables.pipeCmdCount < GlobalVariables.pipeCmdCountTemp)
args = FileSystem.SanitizePath(GlobalVariables.pipeCmdOutput.Trim(), _currentLocation);


// Multi dir delete
if (args.Contains(";"))
{
var dirs = args.Split(';');
foreach (var dir in dirs)
{
var sanitizedPath = FileSystem.SanitizePath(dir, _currentLocation);
DeleteFile(sanitizedPath);
}
}
else
args = FileSystem.SanitizePath(args, _currentLocation);
DeleteFile(args);
{
if (GlobalVariables.isPipeCommand && GlobalVariables.pipeCmdCount == 0 || GlobalVariables.pipeCmdCount < GlobalVariables.pipeCmdCountTemp)
args = FileSystem.SanitizePath(GlobalVariables.pipeCmdOutput.Trim(), _currentLocation);
else
args = FileSystem.SanitizePath(args, _currentLocation);
DeleteFile(args);
}
}
}

Expand Down
44 changes: 18 additions & 26 deletions Commands/TerminalCommands/DirFiles/MakeDirectory.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Core;
using Core.DirFiles;
using System;
using System.IO;
using System.Runtime.Versioning;
Expand All @@ -9,43 +10,34 @@ namespace Commands.TerminalCommands.DirFiles
public class MakeDirectory : ITerminalCommand
{
public string Name => "mkdir";
private string s_helpMessage = @"Usage of mkdir command:
mkdir dir_name : Create one directory.
mkdir dir_name1;dir_name2;dir_name3 : Create multiple directories.
mkdir new;new2{snew1,snew3{dnew1,dnew3}};new3{rnew1{tne1,tne2},rnew2} : Create directories with nested subdirectories.
Root directories are splitted with ';'
Sub directoriers must be between '{' '}' and splited by ','
";

public void Execute(string arg)
{
try
{
int argLength = arg.Length - 6;

string input = arg.Substring(6, argLength);
string newlocation = File.ReadAllText(GlobalVariables.currentDirectory); ; // Get the new location
string locinput = newlocation + input; // New location+input
if (input.Contains(":") && input.Contains(@"\"))
{
try
{
Directory.CreateDirectory(input);
FileSystem.SuccessWriteLine($"Directory {input} is created!");
}
catch (Exception)
{
FileSystem.ErrorWriteLine("Something went wrong. Check path maybe!");
}
}
else
if (input == "-h")
{
try
{
Directory.CreateDirectory(locinput);
FileSystem.SuccessWriteLine($"Directory {locinput} is created!");
}
catch (Exception)
{
FileSystem.ErrorWriteLine("Something went wrong. Check path maybe!");
}
Console.WriteLine(s_helpMessage);
return;
}
string currentDir = File.ReadAllText(GlobalVariables.currentDirectory); // Get the new location
var makeDirectory = new DirectoryMake( currentDir);
makeDirectory.Create(input);
}
catch
catch (Exception)
{
FileSystem.ErrorWriteLine("You must type the directory name!");
FileSystem.ErrorWriteLine("Something went wrong. Check path maybe!");
}
}
}
Expand Down
25 changes: 23 additions & 2 deletions Commands/TerminalCommands/DirFiles/MakeFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,35 @@ namespace Commands.TerminalCommands.DirFiles
public class MakeFile : ITerminalCommand
{
public string Name => "mkfile";
private string s_helpMessage = @"Usage of mkfile command:
mkfile <file_name> : Create one file.
mkfile <file_name1;file_name2;file_name3> : Create multiple files.
";
public void Execute(string arg)
{
string currentDirectory = File.ReadAllText(GlobalVariables.currentDirectory); ;
string file;
try
{
int argLenght = arg.Length - 7;
file = FileSystem.SanitizePath(arg.Substring(7, argLenght), currentDirectory);
var param = arg.Substring(7, argLenght);
if (param == "-h")
{
Console.WriteLine(s_helpMessage);
return;
}

if (param.Contains(";"))
{
var files = param.Split(';');
foreach (var fileIn in files)
{
var sanitizedPath = FileSystem.SanitizePath(fileIn, currentDirectory);
File.Create(sanitizedPath);
FileSystem.SuccessWriteLine($"File {fileIn} was created!");
}
return;
}
var file = FileSystem.SanitizePath(param, currentDirectory);
File.Create(file);
FileSystem.SuccessWriteLine($"File {file} was created!");
}
Expand Down
114 changes: 114 additions & 0 deletions Core/DirFiles/DirectoryMake.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Versioning;
using System.Text;

namespace Core.DirFiles
{
[SupportedOSPlatform("Windows")]
public class DirectoryMake
{
/// <summary>
/// Current Diretory location.
/// </summary>
private string CurrentDir { get; set; }
public DirectoryMake(string currentDirectory) {

CurrentDir = currentDirectory;
}

/// <summary>
/// Create directory/directories and subdirectories.
/// Example: command dir1;dir2{sdir1,sdir2};dir3
/// </summary>
public void Create(string pathDir)
{
var listDirs = new List<string>();
CreateDirectories(pathDir, CurrentDir, listDirs, "");
FileSystem.SuccessWriteLine("The following directories are created:");
foreach (var dir in listDirs)
FileSystem.SuccessWriteLine(dir);
}

/// <summary>
/// Create structure directoris based on pattern
/// </summary>
/// <param name="pathDir"></param>
/// <param name="currentPath"></param>
/// <param name="listDirs"></param>
/// <param name="indent"></param>
/// <exception cref="InvalidOperationException"></exception>
private void CreateDirectories(string pathDir, string currentPath, List<string> listDirs, string indent)
{
int index = 0;
while (index < pathDir.Length)
{
// Skip whitespace
while (index < pathDir.Length && char.IsWhiteSpace(pathDir[index])) index++;

if (index >= pathDir.Length) break; // End of string

// Get directory name
string dirName = ExtractDirectoryName(pathDir, ref index);
if (!string.IsNullOrEmpty(dirName))
{
// Create the directory
string newDirPath = Path.Combine(currentPath, dirName);
Directory.CreateDirectory(newDirPath);
listDirs.Add($"{indent}{newDirPath}"); // Add the directory path to the list
}

// Check for nested directories
if (index < pathDir.Length && pathDir[index] == '{')
{
int endBraceIndex = FindMatchingBrace(pathDir, index);
if (endBraceIndex < 0) throw new InvalidOperationException("Unmatched braces in path.");

// Extract nested directories and recursively create them
string nestedDirs = pathDir.Substring(index + 1, endBraceIndex - index - 1);
CreateDirectories(nestedDirs, Path.Combine(currentPath, dirName), listDirs, $"{indent} |-- ");
index = endBraceIndex + 1; // Move past the closing brace
}

// Move past any delimiter (either ';' or ',')
while (index < pathDir.Length && (pathDir[index] == ';' || pathDir[index] == ',')) index++;
}
}

/// <summary>
/// Get directory name if
/// </summary>
/// <param name="pathDir"></param>
/// <param name="index"></param>
/// <returns></returns>
private string ExtractDirectoryName(string pathDir, ref int index)
{
int start = index;
while (index < pathDir.Length && pathDir[index] != ';' && pathDir[index] != ',' && pathDir[index] != '{')
{
index++;
}
return pathDir.Substring(start, index - start).Trim();
}

/// <summary>
/// Find matching brace for subdirs.
/// </summary>
/// <param name="pathDir"></param>
/// <param name="startIndex"></param>
/// <returns></returns>
private int FindMatchingBrace(string pathDir, int startIndex)
{
int braceCount = 1; // Start with one brace
for (int i = startIndex + 1; i < pathDir.Length; i++)
{
if (pathDir[i] == '{') braceCount++;
if (pathDir[i] == '}') braceCount--;

if (braceCount == 0) return i; // Found the matching brace
}
return -1; // No matching brace found
}
}
}
Loading

0 comments on commit 98d4edd

Please sign in to comment.