95 lines
3 KiB
C#
95 lines
3 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Collections.ObjectModel;
|
|
using System.IO;
|
|
using System.Linq;
|
|
|
|
namespace JD.Core
|
|
{
|
|
public class CommandLineInterpreter
|
|
{
|
|
private readonly Dictionary<string, string> _namedArguments = new Dictionary<string,string>();
|
|
private readonly List<string> _unnamedArguments = new List<string>();
|
|
private ReadOnlyCollection<string> _unnamedArgumentsRO = null;
|
|
|
|
public CommandLineInterpreter()
|
|
{
|
|
}
|
|
|
|
public virtual void ReadCommandLine()
|
|
{
|
|
foreach (var argument in Environment.GetCommandLineArgs().Skip(1))
|
|
{
|
|
if (argument.StartsWith("/"))
|
|
{
|
|
var optionName = argument.TrimStart('/');
|
|
string optionValue = null;
|
|
if (argument.IndexOf(':') != -1)
|
|
{
|
|
optionValue = optionName.Substring(optionName.IndexOf(':') + 1);
|
|
optionName = optionName.Substring(0, optionName.IndexOf(':'));
|
|
}
|
|
|
|
_namedArguments.Add(optionName, optionValue);
|
|
}
|
|
else
|
|
{
|
|
_unnamedArguments.Add(argument);
|
|
}
|
|
}
|
|
}
|
|
|
|
public bool HasOption(string optionName)
|
|
{
|
|
return _namedArguments.ContainsKey(optionName);
|
|
}
|
|
|
|
public string this[string optionName] => _namedArguments[optionName];
|
|
|
|
public IEnumerable<KeyValuePair<string, string>> NamedArguments => _namedArguments;
|
|
|
|
public ReadOnlyCollection<string> UnnamedArguments
|
|
{
|
|
get
|
|
{
|
|
if(_unnamedArgumentsRO == null)
|
|
_unnamedArgumentsRO = new ReadOnlyCollection<string>(_unnamedArguments);
|
|
return _unnamedArgumentsRO;
|
|
}
|
|
}
|
|
|
|
public void FillArgument(string argument)
|
|
{
|
|
_unnamedArguments.Add(argument);
|
|
}
|
|
|
|
public void FillArgument(string argumentName, string argumentValue)
|
|
{
|
|
_namedArguments[argumentName] = argumentValue;
|
|
}
|
|
|
|
public string GetCommandLine()
|
|
{
|
|
var commandLine = "";
|
|
foreach(var keyValue in _namedArguments)
|
|
{
|
|
if (keyValue.Value == null)
|
|
commandLine += "/" + keyValue.Key + " ";
|
|
else if (File.Exists(keyValue.Value) || Directory.Exists(keyValue.Value))
|
|
commandLine += "/" + keyValue.Key + ":\"" + keyValue.Value + "\" ";
|
|
else
|
|
commandLine += "/" + keyValue.Key + ":" + keyValue.Value + " ";
|
|
}
|
|
|
|
foreach (var argument in _unnamedArguments)
|
|
{
|
|
if (File.Exists(argument) || Directory.Exists(argument))
|
|
commandLine += "\"" + argument + "\" ";
|
|
else
|
|
commandLine += argument + " ";
|
|
}
|
|
|
|
return commandLine;
|
|
}
|
|
}
|
|
}
|