branch_party_core 0.1.1

Core library for branch-party CLI tool
Documentation
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
use crate::{GitRepo, Config, Party, ConfigLoader, Error, Result};
use inquire::{MultiSelect, Select, Text, Confirm};
use tracing::{info, debug};

pub struct InteractiveSelector<'a> {
    git_repo: &'a GitRepo,
    config_loader: &'a ConfigLoader,
}

#[derive(Debug, Clone)]
pub struct BranchOption {
    pub name: String,
    pub branch_type: BranchType,
    pub description: String,
}

#[derive(Debug, Clone, PartialEq)]
pub enum BranchType {
    Local,
    Remote,
    Party,
}

#[derive(Debug, Clone)]
struct MergeOrderOption {
    key: &'static str,
    description: &'static str,
}

impl<'a> InteractiveSelector<'a> {
    pub fn new(git_repo: &'a GitRepo, config_loader: &'a ConfigLoader) -> Self {
        Self {
            git_repo,
            config_loader,
        }
    }

    /// Interactive branch selection for a party
    pub fn select_branches_for_party(&self, party_name: &str) -> Result<()> {
        info!("Starting interactive branch selection for party: {}", party_name);

        // Load current config
        let mut config = self.config_loader.load_config(None)?;
        
        // Get available branches
        let branch_options = self.get_available_branches(&config)?;
        
        if branch_options.is_empty() {
            println!("No branches available for selection.");
            return Ok(());
        }

        // Get current party configuration if it exists
        let current_members = config.parties.get(party_name)
            .map(|p| p.members.clone())
            .unwrap_or_default();

        // Pre-select current members
        let default_selection = self.get_default_selection(&branch_options, &current_members);

        println!("\n🎉 Branch Party - Interactive Branch Selection");
        println!("Party: {}", party_name);
        
        if !current_members.is_empty() {
            println!("Current members: {}", current_members.join(", "));
        }
        
        println!("\nSelect branches to include in the party:");
        println!("  • Local branches are shown as 'branch-name'");
        println!("  • Remote branches are shown as 'origin/branch-name'");
        println!("  • Other parties are shown as '@party-name'");

        // Multi-select branches
        let selected_options = MultiSelect::new("Branches:", branch_options)
            .with_default(&default_selection)
            .with_help_message("Use ↑↓ to navigate, Space to select/deselect, Enter to confirm")
            .prompt()?;

        if selected_options.is_empty() {
            println!("No branches selected. Party configuration unchanged.");
            return Ok(());
        }

        // Convert selected options to branch names
        let selected_branches: Vec<String> = selected_options
            .into_iter()
            .map(|opt| {
                match opt.branch_type {
                    BranchType::Party => format!("@{}", opt.name),
                    _ => opt.name,
                }
            })
            .collect();

        // Show selection summary
        println!("\n📋 Selection Summary:");
        for branch in &selected_branches {
            println!("{}", branch);
        }

        // Confirm the selection
        let confirm = Confirm::new("Save this configuration?")
            .with_default(true)
            .prompt()?;

        if !confirm {
            println!("Configuration not saved.");
            return Ok(());
        }

        // Update the configuration
        self.update_party_configuration(&mut config, party_name, selected_branches)?;

        println!("\n✅ Party '{}' configuration updated successfully!", party_name);
        Ok(())
    }

    /// Interactive party creation
    pub fn create_new_party(&self) -> Result<()> {
        info!("Starting interactive party creation");

        println!("\n🎉 Branch Party - Create New Party");

        // Get party name
        let party_name = Text::new("Enter party name:")
            .with_help_message("Use lowercase letters, numbers, and hyphens")
            .with_validator(|input: &str| {
                if input.trim().is_empty() {
                    Ok(inquire::validator::Validation::Invalid("Party name cannot be empty".into()))
                } else if !input.chars().all(|c| c.is_alphanumeric() || c == '-' || c == '_') {
                    Ok(inquire::validator::Validation::Invalid("Party name can only contain letters, numbers, hyphens, and underscores".into()))
                } else {
                    Ok(inquire::validator::Validation::Valid)
                }
            })
            .prompt()?;

        let party_name = party_name.trim().to_lowercase();

        // Check if party already exists
        let config = self.config_loader.load_config(None)?;
        if config.parties.contains_key(&party_name) {
            let overwrite = Confirm::new(&format!("Party '{}' already exists. Overwrite?", party_name))
                .with_default(false)
                .prompt()?;
            
            if !overwrite {
                println!("Party creation cancelled.");
                return Ok(());
            }
        }

        // Select branches for the new party
        self.select_branches_for_party(&party_name)?;

        Ok(())
    }

    /// Get all available branches and parties
    fn get_available_branches(&self, config: &Config) -> Result<Vec<BranchOption>> {
        let mut options = Vec::new();

        // Get local branches
        match self.git_repo.list_local_branches() {
            Ok(local_branches) => {
                for branch in local_branches {
                    // Skip the current party branches to avoid confusion
                    if !branch.starts_with("party/") {
                        options.push(BranchOption {
                            name: branch.clone(),
                            branch_type: BranchType::Local,
                            description: format!("Local branch: {}", branch),
                        });
                    }
                }
            }
            Err(e) => {
                debug!("Could not list local branches: {}", e);
            }
        }

        // Get remote branches
        match self.git_repo.list_remote_branches() {
            Ok(remote_branches) => {
                for branch in remote_branches {
                    // Skip HEAD and party branches
                    if branch != "HEAD" && !branch.starts_with("party/") {
                        options.push(BranchOption {
                            name: format!("origin/{}", branch),
                            branch_type: BranchType::Remote,
                            description: format!("Remote branch: origin/{}", branch),
                        });
                    }
                }
            }
            Err(e) => {
                debug!("Could not list remote branches: {}", e);
            }
        }

        // Add existing parties (excluding the current one if updating)
        for (party_name, _party) in &config.parties {
            options.push(BranchOption {
                name: party_name.clone(),
                branch_type: BranchType::Party,
                description: format!("Party reference: @{}", party_name),
            });
        }

        // Sort options: local branches first, then remote, then parties
        options.sort_by(|a, b| {
            match (&a.branch_type, &b.branch_type) {
                (BranchType::Local, BranchType::Local) => a.name.cmp(&b.name),
                (BranchType::Remote, BranchType::Remote) => a.name.cmp(&b.name),
                (BranchType::Party, BranchType::Party) => a.name.cmp(&b.name),
                (BranchType::Local, _) => std::cmp::Ordering::Less,
                (BranchType::Remote, BranchType::Party) => std::cmp::Ordering::Less,
                (BranchType::Remote, BranchType::Local) => std::cmp::Ordering::Greater,
                (BranchType::Party, _) => std::cmp::Ordering::Greater,
            }
        });

        Ok(options)
    }

    /// Get default selection based on current party members
    fn get_default_selection(&self, options: &[BranchOption], current_members: &[String]) -> Vec<usize> {
        let mut default_indices = Vec::new();
        
        for (index, option) in options.iter().enumerate() {
            let member_name = match option.branch_type {
                BranchType::Party => format!("@{}", option.name),
                _ => option.name.clone(),
            };
            
            if current_members.contains(&member_name) {
                default_indices.push(index);
            }
        }
        
        default_indices
    }

    /// Update party configuration and save it
    fn update_party_configuration(&self, config: &mut Config, party_name: &str, branches: Vec<String>) -> Result<()> {
        // Create or update the party
        let party = Party {
            members: branches,
            merge_order: config.parties.get(party_name)
                .map(|p| p.merge_order.clone())
                .unwrap_or_default(),
            conflict_policy: config.parties.get(party_name)
                .map(|p| p.conflict_policy.clone())
                .unwrap_or_default(),
        };

        config.parties.insert(party_name.to_string(), party);

        // Save the updated configuration
        let config_path = self.config_loader.repo_config_path();
        let yaml = serde_yaml::to_string(config)?;
        
        // Add helpful comments
        let commented_yaml = self.add_comments_to_yaml(yaml);
        
        std::fs::write(config_path, commented_yaml)?;
        
        Ok(())
    }

    /// Add helpful comments to the YAML configuration
    fn add_comments_to_yaml(&self, yaml: String) -> String {
        let mut result = String::new();
        
        result.push_str("# Branch Party Configuration\n");
        result.push_str("# Updated via interactive selection\n");
        result.push_str("# See https://github.com/example/branch-party for documentation\n\n");
        
        for line in yaml.lines() {
            if line.trim_start().starts_with("base_branch:") {
                result.push_str("# Base branch to merge into (usually 'main' or 'develop')\n");
            } else if line.trim_start().starts_with("parties:") {
                result.push_str("# Party definitions\n");
                result.push_str("# Each party can contain branches or references to other parties (@party_name)\n");
            } else if line.trim_start().starts_with("members:") {
                result.push_str("    # Selected branches and party references\n");
            } else if line.trim_start().starts_with("merge_order:") {
                result.push_str("    # Options: listed, newest_first, oldest_first\n");
            } else if line.trim_start().starts_with("default:") && line.contains("manual") {
                result.push_str("      # Options: ours, theirs, union, manual\n");
            }
            
            result.push_str(line);
            result.push('\n');
        }
        
        result
    }

    /// Interactive merge order selection
    pub fn select_merge_order(&self, party_name: &str) -> Result<()> {
        println!("\n⚙️  Configure merge order for party '{}'", party_name);
        
        let options = vec![
            MergeOrderOption { key: "listed", description: "Keep branches in the order they are listed" },
            MergeOrderOption { key: "newest_first", description: "Merge branches with newest commits first" },
            MergeOrderOption { key: "oldest_first", description: "Merge branches with oldest commits first" },
        ];

        let selected = Select::new("Select merge order strategy:", options)
            .prompt()?;

        let mut config = self.config_loader.load_config(None)?;
        
        if let Some(party) = config.parties.get_mut(party_name) {
            party.merge_order = selected.key.parse().unwrap_or_default();
            
            // Save the configuration
            let config_path = self.config_loader.repo_config_path();
            let yaml = serde_yaml::to_string(&config)?;
            let commented_yaml = self.add_comments_to_yaml(yaml);
            std::fs::write(config_path, commented_yaml)?;
            
            println!("✅ Merge order updated to: {}", selected.key);
        } else {
            return Err(Error::party_not_found(party_name));
        }

        Ok(())
    }

    /// Interactive party selection - choose existing party to edit or create new
    pub fn interactive_party_selection(&self) -> Result<()> {
        match self.select_party_to_edit()? {
            Some(party_name) => {
                // Edit existing party
                self.select_branches_for_party(&party_name)?
            }
            None => {
                // Create new party
                self.create_new_party()?
            }
        }
        Ok(())
    }

    /// List parties and allow user to select one for editing
    pub fn select_party_to_edit(&self) -> Result<Option<String>> {
        let config = self.config_loader.load_config(None)?;
        
        if config.parties.is_empty() {
            println!("No parties configured. Use 'init --with-sample' to create sample parties.");
            return Ok(None);
        }

        let mut party_options: Vec<String> = config.parties.keys().cloned().collect();
        party_options.sort();

        // Add option to create new party
        party_options.insert(0, "➕ Create new party".to_string());

        let selected = Select::new("Select a party to configure:", party_options)
            .prompt()?;

        if selected == "➕ Create new party" {
            Ok(None) // Signal to create new party
        } else {
            Ok(Some(selected))
        }
    }
}

impl std::fmt::Display for BranchOption {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let icon = match self.branch_type {
            BranchType::Local => "🔧",
            BranchType::Remote => "🌐", 
            BranchType::Party => "🎉",
        };
        write!(f, "{} {}", icon, self.description)
    }
}

impl std::fmt::Display for MergeOrderOption {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.description)
    }
}

// Convert inquire errors to our error type
impl From<inquire::InquireError> for Error {
    fn from(err: inquire::InquireError) -> Self {
        match err {
            inquire::InquireError::OperationCanceled => Error::UserAborted,
            inquire::InquireError::OperationInterrupted => Error::UserAborted,
            _ => Error::config(format!("Interactive selection error: {}", err)),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    #[test]
    fn test_branch_option_display() {
        let local_option = BranchOption {
            name: "feature/test".to_string(),
            branch_type: BranchType::Local,
            description: "Local branch: feature/test".to_string(),
        };
        
        assert!(local_option.to_string().contains("🔧"));
        assert!(local_option.to_string().contains("Local branch: feature/test"));
        
        let party_option = BranchOption {
            name: "qa".to_string(),
            branch_type: BranchType::Party,
            description: "Party reference: @qa".to_string(),
        };
        
        assert!(party_option.to_string().contains("🎉"));
        assert!(party_option.to_string().contains("Party reference: @qa"));
    }

    #[test]
    fn test_default_selection() {
        let temp_dir = TempDir::new().unwrap();
        let _repo = git2::Repository::init(temp_dir.path()).unwrap();
        let git_repo = GitRepo::open(temp_dir.path()).unwrap();
        let config_loader = ConfigLoader::new(temp_dir.path().to_path_buf());
        let selector = InteractiveSelector::new(&git_repo, &config_loader);
        
        let options = vec![
            BranchOption {
                name: "main".to_string(),
                branch_type: BranchType::Local,
                description: "Local branch: main".to_string(),
            },
            BranchOption {
                name: "feature/a".to_string(),
                branch_type: BranchType::Local,
                description: "Local branch: feature/a".to_string(),
            },
        ];
        
        let current_members = vec!["main".to_string()];
        let selection = selector.get_default_selection(&options, &current_members);
        
        assert_eq!(selection, vec![0]);
    }
}