1+ using System ;
2+ using System . Linq ;
3+ using CommandDotNet . Builders ;
4+ using CommandDotNet . Tokens ;
5+
6+ namespace CommandDotNet . Example
7+ {
8+ public class InteractiveSession
9+ {
10+ private readonly AppRunner _appRunner ;
11+ private readonly string _appName ;
12+ private readonly CommandContext _context ;
13+
14+ public InteractiveSession ( AppRunner appRunner , string appName , CommandContext context )
15+ {
16+ _appRunner = appRunner ;
17+ _appName = appName ;
18+ _context = context ;
19+ }
20+
21+ public void Start ( )
22+ {
23+ var console = _context . Console ;
24+ var cancellationToken = _context . CancellationToken ;
25+
26+ bool pressedCtrlC = false ;
27+ Console . CancelKeyPress += ( sender , args ) =>
28+ {
29+ pressedCtrlC = true ;
30+ } ;
31+
32+ PrintSessionInit ( ) ;
33+
34+ bool pendingNewLine = false ;
35+ void Write ( string ? value = null )
36+ {
37+ console ! . Write ( value ) ;
38+ pendingNewLine = true ;
39+ }
40+
41+ void WriteLine ( string ? value = null )
42+ {
43+ console ! . WriteLine ( value ) ;
44+ pendingNewLine = false ;
45+ }
46+
47+ void EnsureNewLine ( )
48+ {
49+ if ( pendingNewLine )
50+ {
51+ WriteLine ( ) ;
52+ }
53+ }
54+
55+ while ( ! cancellationToken . IsCancellationRequested )
56+ {
57+ EnsureNewLine ( ) ;
58+ Write ( ">>>" ) ;
59+ var input = console . In . ReadLine ( ) ;
60+ if ( input is null || pressedCtrlC )
61+ {
62+ pressedCtrlC = false ;
63+ WriteLine ( ) ;
64+ return ;
65+ }
66+
67+ var args = new CommandLineStringSplitter ( ) . Split ( input ) . ToArray ( ) ;
68+ if ( args . Length == 0 )
69+ {
70+ WriteLine ( ) ;
71+ continue ;
72+ }
73+ if ( args . Length == 1 )
74+ {
75+ var singleArg = args [ 0 ] ;
76+ switch ( singleArg )
77+ {
78+ case "exit" :
79+ case "quit" :
80+ return ;
81+ case "help" :
82+ PrintSessionHelp ( ) ;
83+ continue ;
84+ }
85+ if ( singleArg == Environment . NewLine )
86+ {
87+ WriteLine ( ) ;
88+ continue ;
89+ }
90+ }
91+ EnsureNewLine ( ) ;
92+ _appRunner . Run ( args ) ;
93+ }
94+ EnsureNewLine ( ) ;
95+ }
96+
97+ private void PrintSessionInit ( )
98+ {
99+ var appInfo = AppInfo . GetAppInfo ( _context ) ;
100+ var console = _context . Console ;
101+ console . WriteLine ( $ "{ _appName } { appInfo . Version } ") ;
102+ console . WriteLine ( "Type 'help' to see interactive options" ) ;
103+ console . WriteLine ( "Type '-h' or '--help' to options for commands" ) ;
104+ console . WriteLine ( "Type 'exit', 'quit' or 'Ctrl+C' to exit." ) ;
105+ }
106+
107+ private void PrintSessionHelp ( )
108+ {
109+ var console = _context . Console ;
110+ console . WriteLine ( "Type '-h' or '--help' to options for commands" ) ;
111+ console . WriteLine ( "Type 'exit', 'quit' or 'Ctrl+C' to exit." ) ;
112+ }
113+ }
114+ }
0 commit comments