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
use core::prelude::*;

use alloc::rc::Rc;
use alloc::boxed::Box;

use collections::string::*;
use collections::Vec;
use collections::slice::SliceConcatExt;

use utils::*;


/// A command's hints to the autocompletition
#[derive(Clone)]
pub enum AutocompleteOption {
	/// Hint for the missing argument for the end user
	Hint { hint: String },
	/// The full line buffer of the suggested command
	FullCommand { line: String}
}

/// Terminal trait.
pub trait CliTerminal {
	/// Output a string with the newline characters at the end. The implementation
	/// adds the newline control characters.
	fn output_line(&mut self, line: &str);
}

/// A command that can be executed by the execution function.
pub trait CliCommand {
	/// Execute the command with the given line buffer
	fn execute(&mut self, cli: &mut CliTerminal, line: &str);
	/// Check if the line buffer is valid for this command
	fn is_match(&self, line: &str) -> bool;
	/// Give auto-complete hints
	fn autocomplete(&self, line_start: &str) -> Option<Vec<AutocompleteOption>>;
}

/// Execute the given line buffer with the set of commands.
pub fn cli_execute(line: &str, cmds: &mut [Box<CliCommand + 'static>], cli: &mut CliTerminal) {
	let mut line_start = line.trim();
	if line_start.len() == 0 { return; }

	for ref mut cmd in cmds.iter_mut() {
		if !cmd.is_match(line_start) {
			continue;
		}

		cmd.execute(cli, line_start);
		return;
	}

	if line_start.ends_with("?") {
		line_start = line_start.trim_right_matches("?").trim();
	} else {
		cli.output_line("Unrecognized command.");
	}	

	let fl = collect_options(line_start, cmds);

	if fl.len() > 0 {
		let mut hints = fl.iter().filter_map(|c| {
			match c {
				&AutocompleteOption::Hint {hint: ref hint} => { Some(hint.clone()) }
				_ => { None }
			}
		}).collect::<Vec<String>>();

		if hints.len() > 0 {
			// sort the lines

			hints.sort_by(|a, b| { a.cmp(&b) });

			cli.output_line(format!("Related commands: {}", hints.connect(", ")).as_str());
		}
	}
}

/// Result of the autocomplete request on a given set of commands
#[derive(Debug, Clone)]
pub enum AutocompleteResult {
	/// No suggestions available
	None,
	/// A single match has been found, the line buffer can be immediately expanded with the new command
	SingleMatch { line: AutocompleteLine },	
	/// Multiple matches, usually they can be presented to the end user in a column format.
	MultipleMatches { lines: Vec<AutocompleteLine> }
}

/// One autocomplete suggestion
#[derive(Debug, Clone)]
pub struct AutocompleteLine {
	/// The entire new suggested line buffer
	pub full_new_line: String,
	/// The additional suggested part of the buffer, can be sent to the terminal device
	pub additional_part: String
}

fn collect_options(line: &str, cmds: &mut [Box<CliCommand + 'static>]) -> Vec<AutocompleteOption> {
	let mut ret = Vec::new();
	for cmd in cmds.iter() {
		let options = cmd.autocomplete(line);
		if let Some(options) = options {
			for option in options.iter() {
				ret.push(option.clone());
			}
		}
	}
	ret
}

/// Collect autocomplete suggestions for this line buffer
pub fn cli_try_autocomplete(line: &str, cmds: &mut [Box<CliCommand + 'static>]) -> AutocompleteResult {
	// check if any command matches, ignore autocomplete in that case - for now

	for ref mut cmd in cmds.iter_mut() {
		if !cmd.is_match(line) {
			continue;
		}

		return AutocompleteResult::None;
	}


	let fl = collect_options(line, cmds);

	let mut matches = Vec::new();
	for opt in fl.iter() {
		match opt {
			&AutocompleteOption::FullCommand { line: ref line } => {
				matches.push(line.clone());
			}
			_ => {}
		}
	}

	match matches.len() {
		0 => AutocompleteResult::None,
		1 => {
			let ref m = matches[0];
			let c = m.chars().skip(line.len()).collect();
			let l = AutocompleteLine { full_new_line: m.clone(), additional_part: c };
			AutocompleteResult::SingleMatch { line: l }
		}
		_ => {			
			let mut lines = Vec::new();
			for m in matches.iter() {
				let c = m.chars().skip(line.len()).collect();
				let l = AutocompleteLine { full_new_line: m.clone(), additional_part: c };
				lines.push(l);
			}

			// sort the lines

			lines.sort_by(|a, b| { a.full_new_line.cmp(&b.full_new_line) });

			let lcp = {
				let mut strings = Vec::new();
				for m in lines.iter() {
					strings.push(m.full_new_line.as_str());
				}

				let lcp = longest_common_prefix(strings.as_slice());
				if let Some(lcp) = lcp {
					if lcp.len() == line.len() {
						None
					} else {
						Some(lcp)
					}
				} else {
					None
				}
			};



			if let Some(lcp) = lcp {
				//println!("lcp: {}", lcp);

				AutocompleteResult::SingleMatch { 
					line: AutocompleteLine {
						full_new_line: lcp.clone(),
						additional_part: lcp.chars().skip(line.len()).collect()
					}
				}
			} else {
				AutocompleteResult::MultipleMatches { lines: lines }
			}
		}
	}
}