forked from KSP-CKAN/CKAN
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Prompt.cs
226 lines (205 loc) · 9.73 KB
/
Prompt.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
using System;
using System.Reflection;
using System.Linq;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using CommandLine;
using CommandLine.Text;
using log4net;
namespace CKAN.CmdLine
{
public class Prompt
{
public Prompt(GameInstanceManager mgr)
{
manager = mgr;
}
public int RunCommand(object raw_options)
{
CommonOptions opts = raw_options as CommonOptions;
bool headless = opts?.Headless ?? false;
// Print an intro if not in headless mode
if (!headless)
{
Console.WriteLine(Properties.Resources.PromptWelcome, exitCommand);
}
ReadLine.AutoCompletionHandler = GetSuggestions;
bool done = false;
while (!done)
{
// Prompt if not in headless mode
if (!headless)
{
Console.Write(
manager.CurrentInstance != null
? string.Format(Properties.Resources.PromptWithInstance,
Meta.GetVersion(), manager.CurrentInstance.game.ShortName, manager.CurrentInstance.Version(), manager.CurrentInstance.Name)
: string.Format(Properties.Resources.PromptWithoutInstance, Meta.GetVersion())
);
}
try
{
// Get input
string command = ReadLineWithCompletion(headless);
if (command == null || command == exitCommand)
{
done = true;
}
else if (command != "")
{
// Parse input as if it was a normal command line,
// but with a persistent GameInstanceManager object.
int cmdExitCode = MainClass.Execute(manager, opts,
ParseTextField(command));
// Clear the command if no exception was thrown
if (headless && cmdExitCode != Exit.OK)
{
// Pass failure codes to calling process in headless mode
// (in interactive mode the user can see the error and try again)
return cmdExitCode;
}
}
}
catch (NoGameInstanceKraken)
{
Console.WriteLine(Properties.Resources.CompletionNotAvailable);
}
}
return Exit.OK;
}
/// <summary>
/// Split string on spaces, unless they are between quotes.
/// Inspired by https://stackoverflow.com/a/14655145/2422988
/// </summary>
/// <param name="input">The string to parse</param>
/// <returns>Array split by strings, with quoted parts joined together</returns>
private static string[] ParseTextField(string input)
=> quotePattern.Matches(input)
.Cast<Match>()
.Select(m => m.Value)
.ToArray();
/// <summary>
/// Look for non-quotes surrounded by quotes, or non-space-or-quotes, or end preceded by space.
/// No attempt to allow escaped quotes within quotes.
/// Inspired by https://stackoverflow.com/a/14655145/2422988
/// </summary>
private static readonly Regex quotePattern = new Regex(
@"(?<="")[^""]*(?="")|[^ ""]+|(?<= )$", RegexOptions.Compiled);
private static string ReadLineWithCompletion(bool headless)
{
try
{
// ReadLine.Read can't read from pipes
return headless ? Console.ReadLine()
: ReadLine.Read("");
}
catch (InvalidOperationException)
{
// InvalidOperationException is thrown in a mintty on Windows
return Console.ReadLine();
}
}
private string[] GetSuggestions(string text, int index)
{
string[] pieces = ParseTextField(text);
TypeInfo ti = typeof(Actions).GetTypeInfo();
List<string> extras = new List<string> { exitCommand, "help" };
foreach (string piece in pieces.Take(pieces.Length - 1))
{
PropertyInfo pi = ti.DeclaredProperties
.FirstOrDefault(p => p?.GetCustomAttribute<VerbOptionAttribute>()?.LongName == piece);
if (pi == null)
{
// Couldn't find it, no suggestions
return null;
}
ti = pi.PropertyType.GetTypeInfo();
extras.Clear();
}
var lastPiece = pieces.LastOrDefault() ?? "";
return lastPiece.StartsWith("--") ? GetLongOptions(ti, lastPiece.Substring(2))
: lastPiece.StartsWith("-") ? GetShortOptions(ti, lastPiece.Substring(1))
: HasVerbs(ti) ? GetVerbs(ti, lastPiece, extras)
: WantsAvailIdentifiers(ti) ? GetAvailIdentifiers(lastPiece)
: WantsInstIdentifiers(ti) ? GetInstIdentifiers(lastPiece)
: WantsGameInstances(ti) ? GetGameInstances(lastPiece)
: null;
}
private static string[] GetLongOptions(TypeInfo ti, string prefix)
=> AllBaseTypes(ti.AsType())
.SelectMany(t => t.GetTypeInfo().DeclaredProperties)
.Select(p => p.GetCustomAttribute<OptionAttribute>()?.LongName
?? p.GetCustomAttribute<OptionArrayAttribute>()?.LongName
?? p.GetCustomAttribute<OptionListAttribute>()?.LongName)
.Where(o => o != null && o.StartsWith(prefix, StringComparison.InvariantCultureIgnoreCase))
.OrderBy(o => o)
.Select(o => $"--{o}")
.ToArray();
private static string[] GetShortOptions(TypeInfo ti, string prefix)
=> AllBaseTypes(ti.AsType())
.SelectMany(t => t.GetTypeInfo().DeclaredProperties)
.Select(p => p.GetCustomAttribute<OptionAttribute>()?.ShortName
?? p.GetCustomAttribute<OptionArrayAttribute>()?.ShortName
?? p.GetCustomAttribute<OptionListAttribute>()?.ShortName)
.Where(o => o != null && $"{o}".StartsWith(prefix, StringComparison.InvariantCultureIgnoreCase))
.OrderBy(o => o)
.Select(o => $"-{o}")
.ToArray();
private static IEnumerable<Type> AllBaseTypes(Type start)
{
for (Type t = start; t != null; t = t.BaseType)
{
yield return t;
}
}
private static bool HasVerbs(TypeInfo ti)
=> ti.DeclaredProperties
.Any(p => p.GetCustomAttribute<VerbOptionAttribute>() != null);
private static string[] GetVerbs(TypeInfo ti, string prefix, IEnumerable<string> extras)
=> ti.DeclaredProperties
.Select(p => p.GetCustomAttribute<VerbOptionAttribute>()?.LongName)
.Where(v => v != null)
.Concat(extras)
.Where(v => v.StartsWith(prefix, StringComparison.InvariantCultureIgnoreCase))
.OrderBy(v => v)
.ToArray();
private static bool WantsAvailIdentifiers(TypeInfo ti)
=> ti.DeclaredProperties
.Any(p => p.GetCustomAttribute<AvailableIdentifiersAttribute>() != null);
private string[] GetAvailIdentifiers(string prefix)
{
CKAN.GameInstance inst = MainClass.GetGameInstance(manager);
return RegistryManager.Instance(inst)
.registry
.CompatibleModules(inst.VersionCriteria())
.Where(m => !m.IsDLC)
.Select(m => m.identifier)
.Where(ident => ident.StartsWith(prefix,
StringComparison.InvariantCultureIgnoreCase))
.ToArray();
}
private static bool WantsInstIdentifiers(TypeInfo ti)
=> ti.DeclaredProperties
.Any(p => p.GetCustomAttribute<InstalledIdentifiersAttribute>() != null);
private string[] GetInstIdentifiers(string prefix)
{
CKAN.GameInstance inst = MainClass.GetGameInstance(manager);
var registry = RegistryManager.Instance(inst).registry;
return registry.Installed(false, false)
.Select(kvp => kvp.Key)
.Where(ident => ident.StartsWith(prefix, StringComparison.InvariantCultureIgnoreCase)
&& !registry.GetInstalledVersion(ident).IsDLC)
.ToArray();
}
private static bool WantsGameInstances(TypeInfo ti)
=> ti.DeclaredProperties
.Any(p => p.GetCustomAttribute<GameInstancesAttribute>() != null);
private string[] GetGameInstances(string prefix)
=> manager.Instances
.Select(kvp => kvp.Key)
.Where(ident => ident.StartsWith(prefix, StringComparison.InvariantCultureIgnoreCase))
.ToArray();
private readonly GameInstanceManager manager;
private const string exitCommand = "exit";
}
}