ggen_core/utils/
user_level.rs1use serde::{Deserialize, Serialize};
39use std::collections::HashMap;
40use std::fs;
41use std::path::PathBuf;
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
61pub enum UserLevel {
62 Newcomer,
64 Intermediate,
66 Advanced,
68 Expert,
70}
71
72impl UserLevel {
73 pub fn from_usage_count(count: usize) -> Self {
74 match count {
75 0..=5 => UserLevel::Newcomer,
76 6..=20 => UserLevel::Intermediate,
77 21..=50 => UserLevel::Advanced,
78 _ => UserLevel::Expert,
79 }
80 }
81
82 pub fn as_str(&self) -> &'static str {
83 match self {
84 UserLevel::Newcomer => "newcomer",
85 UserLevel::Intermediate => "intermediate",
86 UserLevel::Advanced => "advanced",
87 UserLevel::Expert => "expert",
88 }
89 }
90
91 pub fn get_help_focus(&self) -> &'static str {
93 match self {
94 UserLevel::Newcomer => "Getting Started",
95 UserLevel::Intermediate => "Common Workflows",
96 UserLevel::Advanced => "Advanced Features",
97 UserLevel::Expert => "Power User Tips",
98 }
99 }
100}
101
102#[derive(Debug, Clone, Serialize, Deserialize)]
104pub struct UserActivity {
105 pub total_commands: usize,
106 pub command_counts: HashMap<String, usize>,
107 pub level: UserLevel,
108 pub last_command: Option<String>,
109}
110
111impl Default for UserActivity {
112 fn default() -> Self {
113 Self {
114 total_commands: 0,
115 command_counts: HashMap::new(),
116 level: UserLevel::Newcomer,
117 last_command: None,
118 }
119 }
120}
121
122impl UserActivity {
123 pub fn load() -> Result<Self, Box<dyn std::error::Error>> {
125 let path = Self::config_path()?;
126 if !path.exists() {
127 return Ok(Self::default());
128 }
129
130 let contents = fs::read_to_string(&path)?;
131 let activity: UserActivity = toml::from_str(&contents)?;
132 Ok(activity)
133 }
134
135 pub fn save(&self) -> Result<(), Box<dyn std::error::Error>> {
137 let path = Self::config_path()?;
138 if let Some(parent) = path.parent() {
139 fs::create_dir_all(parent)?;
140 }
141
142 let contents = toml::to_string_pretty(self)?;
143 fs::write(&path, contents)?;
144 Ok(())
145 }
146
147 pub fn record_command(&mut self, command: &str) {
149 self.total_commands += 1;
150 *self.command_counts.entry(command.to_string()).or_insert(0) += 1;
151 self.level = UserLevel::from_usage_count(self.total_commands);
152 self.last_command = Some(command.to_string());
153 }
154
155 pub fn get_level(&self) -> UserLevel {
157 self.level
158 }
159
160 pub fn get_top_commands(&self, limit: usize) -> Vec<(String, usize)> {
162 let mut commands: Vec<_> = self
163 .command_counts
164 .iter()
165 .map(|(k, v)| (k.clone(), *v))
166 .collect();
167 commands.sort_by_key(|b| std::cmp::Reverse(b.1));
168 commands.into_iter().take(limit).collect()
169 }
170
171 pub fn has_used_command(&self, command: &str) -> bool {
173 self.command_counts.contains_key(command)
174 }
175
176 fn config_path() -> Result<PathBuf, Box<dyn std::error::Error>> {
178 let home = dirs::home_dir().ok_or("Could not determine home directory")?;
179 Ok(home.join(".ggen").join("user_activity.toml"))
180 }
181}
182
183pub struct ProgressiveHelp;
185
186impl ProgressiveHelp {
187 pub fn get_command_help(command: &str, level: UserLevel) -> String {
189 match (command, level) {
190 ("gen", UserLevel::Newcomer) => "Generate code from a template.\n\n\
192 Quickstart: ggen gen templates/example.tmpl\n\n\
193 This will read the template and generate the output file.\n\
194 Templates use YAML frontmatter and Tera syntax.\n\n\
195 💡 Tip: Try 'ggen list' to see available templates first!"
196 .to_string(),
197 ("gen", UserLevel::Intermediate) => "Generate code from templates with variables.\n\n\
198 Usage: ggen gen <template> [--vars key=value]\n\n\
199 Examples:\n\
200 • ggen gen rust-module.tmpl --vars name=auth\n\
201 • ggen gen service.tmpl --vars name=user service=api\n\n\
202 Variables are passed to the template engine for substitution."
203 .to_string(),
204 ("gen", UserLevel::Advanced | UserLevel::Expert) => {
205 "Advanced template generation with RDF graphs and SPARQL.\n\n\
206 Usage: ggen gen <template> [--vars] [--graph] [--inject]\n\n\
207 Features:\n\
208 • Use --graph to load RDF knowledge graphs\n\
209 • SPARQL queries in templates for semantic data\n\
210 • Injection modes for idempotent updates\n\
211 • Deterministic generation with fixed seeds\n\n\
212 See: https://seanchatmangpt.github.io/ggen/advanced-templates"
213 .to_string()
214 }
215
216 ("doctor", UserLevel::Newcomer) => "Check if your environment is ready for ggen.\n\n\
218 This command verifies:\n\
219 • Rust and Cargo are installed\n\
220 • Git is available\n\
221 • Optional tools like Ollama and Docker\n\n\
222 Run 'ggen doctor' whenever you encounter setup issues!"
223 .to_string(),
224 ("doctor", _) => "Environment health check and diagnostics.\n\n\
225 Usage: ggen doctor [-v|--verbose]\n\n\
226 Checks for required and optional dependencies.\n\
227 Use --verbose for detailed fix instructions."
228 .to_string(),
229
230 _ => format!(
232 "Help for '{}' command\n\nRun 'ggen {} --help' for details.",
233 command, command
234 ),
235 }
236 }
237
238 pub fn get_contextual_tips(activity: &UserActivity) -> Vec<String> {
240 let mut tips = Vec::new();
241 let level = activity.get_level();
242
243 match level {
244 UserLevel::Newcomer => {
245 tips.push("💡 Try 'ggen quickstart demo' for a quick tutorial".to_string());
246 tips.push("📚 Run 'ggen --help' to see all available commands".to_string());
247 tips.push("🔍 Use 'ggen search <query>' to find templates".to_string());
248 }
249 UserLevel::Intermediate => {
250 if !activity.has_used_command("ai") {
251 tips.push("🤖 Try AI-powered generation with 'ggen ai generate'".to_string());
252 }
253 if !activity.has_used_command("market") {
254 tips.push("📦 Explore the marketplace with 'ggen market search'".to_string());
255 }
256 }
257 UserLevel::Advanced => {
258 tips.push("⚡ Tip: Use aliases for common workflows".to_string());
259 tips.push("🔧 Check out lifecycle commands for project automation".to_string());
260 }
261 UserLevel::Expert => {
262 tips.push("🚀 You're a power user! Consider contributing templates".to_string());
263 }
264 }
265
266 tips
267 }
268
269 pub fn suggest_next_command(last_command: Option<&str>, level: UserLevel) -> Option<String> {
271 match (last_command, level) {
272 (Some("doctor"), UserLevel::Newcomer) => Some("Try: ggen quickstart demo".to_string()),
273 (Some("list"), _) => Some("Try: ggen gen <template-name>".to_string()),
274 (Some("search"), _) => Some("Try: ggen add <package-name>".to_string()),
275 (Some("gen"), UserLevel::Newcomer) => {
276 Some("Next: ggen ai project \"your idea\"".to_string())
277 }
278 _ => None,
279 }
280 }
281}
282
283#[cfg(test)]
284mod tests {
285 use super::*;
286
287 #[test]
288 fn test_user_level_from_count() {
289 assert_eq!(UserLevel::from_usage_count(0), UserLevel::Newcomer);
290 assert_eq!(UserLevel::from_usage_count(5), UserLevel::Newcomer);
291 assert_eq!(UserLevel::from_usage_count(10), UserLevel::Intermediate);
292 assert_eq!(UserLevel::from_usage_count(25), UserLevel::Advanced);
293 assert_eq!(UserLevel::from_usage_count(100), UserLevel::Expert);
294 }
295
296 #[test]
297 fn test_user_activity_default() {
298 let activity = UserActivity::default();
299 assert_eq!(activity.total_commands, 0);
300 assert_eq!(activity.level, UserLevel::Newcomer);
301 }
302
303 #[test]
304 fn test_record_command() {
305 let mut activity = UserActivity::default();
306 activity.record_command("gen");
307 assert_eq!(activity.total_commands, 1);
308 assert_eq!(*activity.command_counts.get("gen").unwrap(), 1);
309 }
310
311 #[test]
312 fn test_level_progression() {
313 let mut activity = UserActivity::default();
314
315 assert_eq!(activity.get_level(), UserLevel::Newcomer);
317
318 for _ in 0..10 {
320 activity.record_command("test");
321 }
322 assert_eq!(activity.get_level(), UserLevel::Intermediate);
323
324 for _ in 0..15 {
326 activity.record_command("test");
327 }
328 assert_eq!(activity.get_level(), UserLevel::Advanced);
329
330 for _ in 0..30 {
332 activity.record_command("test");
333 }
334 assert_eq!(activity.get_level(), UserLevel::Expert);
335 }
336
337 #[test]
338 fn test_top_commands() {
339 let mut activity = UserActivity::default();
340 activity.record_command("gen");
341 activity.record_command("gen");
342 activity.record_command("list");
343 activity.record_command("gen");
344
345 let top = activity.get_top_commands(2);
346 assert_eq!(top[0].0, "gen");
347 assert_eq!(top[0].1, 3);
348 }
349}