dotconfig-hub 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ """AI Instructions Base - Central management for AI coding assistant instructions."""
2
+
3
+ __version__ = "0.1.0"
dotconfig_hub/cli.py ADDED
@@ -0,0 +1,391 @@
1
+ """Command-line interface for dotconfig-hub."""
2
+
3
+ import click
4
+ from pathlib import Path
5
+ from rich.console import Console
6
+ from rich.table import Table
7
+ from rich.prompt import Confirm, Prompt
8
+
9
+ from .config import Config
10
+ from .sync import FileSyncer
11
+ from .project_config import ProjectConfig
12
+
13
+
14
+ console = Console()
15
+
16
+
17
+ @click.group()
18
+ @click.version_option()
19
+ def main():
20
+ """dotconfig-hub - Central management for favorite dotfiles and configuration templates.
21
+
22
+ This tool helps you manage and distribute your favorite dotfiles and configuration
23
+ templates across development projects.
24
+ """
25
+ pass
26
+
27
+
28
+ @main.command()
29
+ @click.option('--templates-dir', '-t',
30
+ type=click.Path(exists=True, file_okay=False, path_type=Path),
31
+ help='Path to templates directory')
32
+ def setup(templates_dir: Path):
33
+ """Set up dotconfig-hub with templates directory.
34
+
35
+ This command configures the templates source directory for the current project.
36
+ The templates directory should contain a config.yaml file with environment sets.
37
+
38
+ Examples:
39
+ dotconfig-hub setup --templates-dir ~/dotconfig-templates
40
+ dotconfig-hub setup -t /path/to/templates
41
+ """
42
+ console.print("\n[bold blue]dotconfig-hub Setup[/bold blue]")
43
+
44
+ # Prompt for templates directory if not provided
45
+ if not templates_dir:
46
+ console.print("Please enter the path to your templates directory.")
47
+ console.print("[dim]Example: ~/dotconfig-templates[/dim]")
48
+
49
+ while True:
50
+ templates_input = Prompt.ask("Templates directory path")
51
+ if not templates_input.strip():
52
+ console.print("[red]Please enter a valid path[/red]")
53
+ continue
54
+
55
+ templates_dir = Path(templates_input.strip('"\'').strip()).expanduser().resolve()
56
+ if templates_dir.exists() and templates_dir.is_dir():
57
+ break
58
+ else:
59
+ console.print(f"[red]Directory not found: {templates_dir}[/red]")
60
+ if not Confirm.ask("Try again?", default=True):
61
+ console.print("[yellow]Setup cancelled[/yellow]")
62
+ return
63
+
64
+ # Validate templates directory
65
+ templates_dir = templates_dir.resolve()
66
+ config_file = templates_dir / "config.yaml"
67
+
68
+ if not config_file.exists():
69
+ console.print(f"[red]Error: config.yaml not found in {templates_dir}[/red]")
70
+ console.print("[yellow]The templates directory should contain a config.yaml file[/yellow]")
71
+ return
72
+
73
+ # Load and validate templates config
74
+ try:
75
+ import yaml
76
+ with open(config_file, 'r', encoding='utf-8') as f:
77
+ templates_config = yaml.safe_load(f)
78
+
79
+ if not templates_config or "environment_sets" not in templates_config:
80
+ console.print(f"[red]Error: Invalid config.yaml format[/red]")
81
+ console.print("[yellow]The config.yaml should contain 'environment_sets'[/yellow]")
82
+ return
83
+
84
+ env_sets = [key for key in templates_config["environment_sets"].keys()]
85
+ console.print(f"[green]Found {len(env_sets)} environment sets: {', '.join(env_sets)}[/green]")
86
+
87
+ except Exception as e:
88
+ console.print(f"[red]Error reading templates config: {e}[/red]")
89
+ return
90
+
91
+ # Initialize project config
92
+ project_config = ProjectConfig()
93
+
94
+ # Check if already configured
95
+ if project_config.exists():
96
+ current_source = project_config.get_templates_source()
97
+ if current_source and current_source != templates_dir:
98
+ if not Confirm.ask(f"Templates source is already set to {current_source}. Override?"):
99
+ console.print("[yellow]Setup cancelled[/yellow]")
100
+ return
101
+
102
+ # Save configuration
103
+ project_config.set_templates_source(templates_dir)
104
+ project_config.save_config()
105
+
106
+ console.print(f"[green]✓ Templates source configured: {templates_dir}[/green]")
107
+ console.print(f"[dim]Configuration saved to: {project_config.config_path}[/dim]")
108
+ console.print("\n[cyan]Next steps:[/cyan]")
109
+ console.print(" 1. Run 'dotconfig-hub init' to initialize your project")
110
+ console.print(" 2. Run 'dotconfig-hub list' to see available environment sets")
111
+
112
+
113
+ @main.command()
114
+ @click.option('--env-set', '-e', help='Environment set to initialize')
115
+ @click.option('--force', '-f', is_flag=True, help='Force initialization even if already configured')
116
+ def init(env_set: str, force: bool):
117
+ """Initialize current project with configuration templates.
118
+
119
+ This command sets up the current project to use specific environment sets
120
+ from the configured templates source.
121
+
122
+ Examples:
123
+ dotconfig-hub init --env-set my_project_init_template
124
+ dotconfig-hub init -e my_project_init_template
125
+ """
126
+ console.print("\n[bold blue]dotconfig-hub Project Initialization[/bold blue]")
127
+
128
+ # Load project config
129
+ project_config = ProjectConfig()
130
+
131
+ # Validate setup
132
+ issues = project_config.validate_setup()
133
+ if issues:
134
+ console.print("[red]Setup issues found:[/red]")
135
+ for issue in issues:
136
+ console.print(f" • {issue}")
137
+ console.print("\n[yellow]Run 'dotconfig-hub setup' first[/yellow]")
138
+ return
139
+
140
+ # Get available environment sets
141
+ templates_config_path = project_config.get_templates_config_path()
142
+ with open(templates_config_path, 'r', encoding='utf-8') as f:
143
+ import yaml
144
+ templates_config = yaml.safe_load(f)
145
+
146
+ available_sets = [key for key in templates_config["environment_sets"].keys()]
147
+
148
+ # Prompt for environment set if not provided
149
+ if not env_set:
150
+ console.print("Available environment sets:")
151
+ for i, set_name in enumerate(available_sets, 1):
152
+ set_config = templates_config["environment_sets"][set_name]
153
+ description = set_config.get("description", "No description")
154
+ console.print(f" {i}. [cyan]{set_name}[/cyan]: {description}")
155
+
156
+ while True:
157
+ choice = Prompt.ask(
158
+ "\nSelect environment set (number or name)",
159
+ choices=[str(i) for i in range(1, len(available_sets) + 1)] + available_sets,
160
+ show_choices=False
161
+ )
162
+
163
+ # Handle numeric choice
164
+ if choice.isdigit():
165
+ idx = int(choice) - 1
166
+ if 0 <= idx < len(available_sets):
167
+ env_set = available_sets[idx]
168
+ break
169
+ # Handle name choice
170
+ elif choice in available_sets:
171
+ env_set = choice
172
+ break
173
+
174
+ console.print("[red]Invalid choice[/red]")
175
+
176
+ # Validate environment set
177
+ if env_set not in available_sets:
178
+ console.print(f"[red]Unknown environment set: {env_set}[/red]")
179
+ console.print(f"[yellow]Available sets: {', '.join(available_sets)}[/yellow]")
180
+ return
181
+
182
+ # Check if already configured
183
+ current_sets = project_config.get_active_environment_sets()
184
+ if env_set in current_sets and not force:
185
+ console.print(f"[yellow]Environment set '{env_set}' is already active[/yellow]")
186
+ console.print("Use --force to reconfigure")
187
+ return
188
+
189
+ # Add environment set
190
+ project_config.add_environment_set(env_set)
191
+ project_config.save_config()
192
+
193
+ set_config = templates_config["environment_sets"][env_set]
194
+ tools = [key for key in set_config.get("tools", {}).keys()]
195
+
196
+ console.print(f"[green]✓ Environment set '{env_set}' activated[/green]")
197
+ console.print(f"[dim]Tools available: {', '.join(tools)}[/dim]")
198
+ console.print("\n[cyan]Next steps:[/cyan]")
199
+ console.print(" • Run 'dotconfig-hub sync' to synchronize files")
200
+ console.print(" • Run 'dotconfig-hub list' to see configured tools")
201
+
202
+
203
+ @main.command()
204
+ @click.option('--tool', '-t', help='Sync only specific tool')
205
+ @click.option('--env-set', '-e', help='Sync only specific environment set')
206
+ @click.option('--file', '-f', help='Sync only specific file by name (e.g., .gitignore)')
207
+ @click.option('--dry-run', '-n', is_flag=True, help='Show what would be synced without making changes')
208
+ @click.option('--auto-sync', type=click.Choice(['local', 'remote']),
209
+ help='Automatically sync in specified direction without prompting')
210
+ def sync(tool: str, env_set: str, file: str, dry_run: bool, auto_sync: str):
211
+ """Synchronize configuration files between templates and project.
212
+
213
+ This command syncs files from the configured templates to the current project
214
+ (or vice versa) based on the active environment sets.
215
+
216
+ Examples:
217
+ dotconfig-hub sync # Sync all active environment sets
218
+ dotconfig-hub sync --dry-run # Preview changes
219
+ dotconfig-hub sync --tool vscode # Sync only VS Code settings
220
+ dotconfig-hub sync --file .gitignore # Sync only .gitignore file
221
+ dotconfig-hub sync --auto-sync local # Auto-sync to local
222
+ """
223
+ console.print("\n[bold blue]dotconfig-hub Sync[/bold blue]")
224
+
225
+ # Load project config
226
+ project_config = ProjectConfig()
227
+
228
+ # Validate setup
229
+ issues = project_config.validate_setup()
230
+ if issues:
231
+ console.print("[red]Setup issues found:[/red]")
232
+ for issue in issues:
233
+ console.print(f" • {issue}")
234
+ console.print("\n[yellow]Run 'dotconfig-hub setup' and 'dotconfig-hub init' first[/yellow]")
235
+ return
236
+
237
+ # Load templates config
238
+ templates_config_path = project_config.get_templates_config_path()
239
+
240
+ # Initialize config with templates source
241
+ cfg = Config(config_path=templates_config_path)
242
+
243
+ # Set target directory
244
+ target_directory = Path.cwd()
245
+
246
+ # Initialize syncer
247
+ syncer = FileSyncer(cfg)
248
+
249
+ # Get active environment sets
250
+ active_env_sets = project_config.get_active_environment_sets()
251
+ if env_set:
252
+ if env_set not in active_env_sets:
253
+ console.print(f"[yellow]Environment set '{env_set}' is not active for this project[/yellow]")
254
+ if not Confirm.ask("Continue anyway?"):
255
+ return
256
+ active_env_sets = [env_set]
257
+
258
+ if not active_env_sets:
259
+ console.print("[yellow]No active environment sets. Run 'dotconfig-hub init' first[/yellow]")
260
+ return
261
+
262
+ # Perform sync
263
+ if dry_run:
264
+ console.print("[yellow]DRY RUN MODE - No files will be modified[/yellow]\n")
265
+
266
+ try:
267
+ all_results = {}
268
+
269
+ if file:
270
+ # Sync specific file
271
+ console.print(f"[bold]Syncing specific file: {file}[/bold]")
272
+ synced = syncer.sync_file(file, target_directory, auto_sync, dry_run, env_set)
273
+ all_results[f"file/{file}"] = synced
274
+ else:
275
+ # Sync by tool or all tools
276
+ for env_set_name in active_env_sets:
277
+ console.print(f"\n[bold magenta]Environment Set: {env_set_name}[/bold magenta]")
278
+
279
+ if tool:
280
+ # Sync specific tool
281
+ available_tools = cfg.get_tools(env_set_name)
282
+ if tool not in available_tools:
283
+ console.print(f"[red]Tool '{tool}' not found in environment set '{env_set_name}'[/red]")
284
+ console.print(f"[yellow]Available tools: {', '.join(available_tools)}[/yellow]")
285
+ continue
286
+
287
+ synced = syncer.sync_tool(tool, target_directory, auto_sync, dry_run, env_set_name)
288
+ all_results[f"{env_set_name}/{tool}"] = synced
289
+ else:
290
+ # Sync all tools in environment set
291
+ results = syncer.sync_all_tools(target_directory, auto_sync, dry_run, env_set_name)
292
+ all_results.update(results)
293
+
294
+ _display_results(all_results, dry_run)
295
+
296
+ except KeyboardInterrupt:
297
+ console.print("\n[yellow]Sync cancelled by user[/yellow]")
298
+ except Exception as e:
299
+ console.print(f"\n[red]Error during sync: {e}[/red]")
300
+ raise
301
+
302
+
303
+ @main.command()
304
+ def list():
305
+ """List available environment sets and tools.
306
+
307
+ Shows the currently configured templates and active environment sets
308
+ for this project.
309
+ """
310
+ console.print("\n[bold blue]dotconfig-hub Configuration[/bold blue]")
311
+
312
+ # Load project config
313
+ project_config = ProjectConfig()
314
+
315
+ # Check if configured
316
+ if not project_config.exists():
317
+ console.print("[yellow]Project not configured. Run 'dotconfig-hub setup' first.[/yellow]")
318
+ return
319
+
320
+ # Display templates source
321
+ templates_source = project_config.get_templates_source()
322
+ if templates_source:
323
+ console.print(f"[bold]Templates Source:[/bold] {templates_source}")
324
+ else:
325
+ console.print("[red]Templates source not configured[/red]")
326
+ return
327
+
328
+ # Validate setup
329
+ issues = project_config.validate_setup()
330
+ if issues:
331
+ console.print("\n[red]Setup issues:[/red]")
332
+ for issue in issues:
333
+ console.print(f" • {issue}")
334
+ return
335
+
336
+ # Load templates config
337
+ templates_config_path = project_config.get_templates_config_path()
338
+ with open(templates_config_path, 'r', encoding='utf-8') as f:
339
+ import yaml
340
+ templates_config = yaml.safe_load(f)
341
+
342
+ # Display available environment sets
343
+ console.print("\n[bold]Available Environment Sets:[/bold]")
344
+ active_sets = set(project_config.get_active_environment_sets())
345
+
346
+ for set_name, set_config in templates_config["environment_sets"].items():
347
+ status = "[green]●[/green]" if set_name in active_sets else "[dim]○[/dim]"
348
+ description = set_config.get("description", "No description")
349
+ console.print(f" {status} [cyan]{set_name}[/cyan]: {description}")
350
+
351
+ if set_name in active_sets:
352
+ tools = [key for key in set_config.get("tools", {}).keys()]
353
+ if tools:
354
+ console.print(f" [dim]Tools: {', '.join(tools)}[/dim]")
355
+
356
+ console.print(f"\n[dim]Legend: [green]●[/green] Active [dim]○[/dim] Available[/dim]")
357
+
358
+
359
+ def _display_results(results: dict, dry_run: bool):
360
+ """Display sync results in a table.
361
+
362
+ Args:
363
+ results: Dictionary mapping tool names to sync counts
364
+ dry_run: Whether this was a dry run
365
+ """
366
+ if not results:
367
+ console.print("\n[green]No files needed synchronization[/green]")
368
+ return
369
+
370
+ # Create results table
371
+ table = Table(title="\nSync Results" + (" (Dry Run)" if dry_run else ""))
372
+ table.add_column("Environment/Tool", style="cyan")
373
+ table.add_column("Files Synced", style="green")
374
+
375
+ total = 0
376
+ for tool, count in results.items():
377
+ table.add_row(tool, str(count))
378
+ total += count
379
+
380
+ if len(results) > 1:
381
+ table.add_row("[bold]Total[/bold]", f"[bold]{total}[/bold]")
382
+
383
+ console.print(table)
384
+
385
+ if dry_run:
386
+ console.print("\n[yellow]This was a dry run. No files were modified.[/yellow]")
387
+ console.print("[dim]Run without --dry-run to apply changes.[/dim]")
388
+
389
+
390
+ if __name__ == "__main__":
391
+ main()
@@ -0,0 +1,217 @@
1
+ """Configuration management for AI instructions sync tool."""
2
+
3
+ import os
4
+ from pathlib import Path
5
+ from typing import Dict, List, Any, Optional, Tuple
6
+ import yaml
7
+ import glob
8
+
9
+
10
+ class Config:
11
+ """Manages configuration for the AI instructions sync tool."""
12
+
13
+ def __init__(self, config_path: Optional[Path] = None):
14
+ """Initialize configuration.
15
+
16
+ Args:
17
+ config_path: Path to config.yaml file. If None, searches for it.
18
+ """
19
+ self.config_path = config_path or self._find_config_file()
20
+ self.config_data = self._load_config()
21
+ self.base_dir = self.config_path.parent if self.config_path else Path.cwd()
22
+ self._migrate_old_config()
23
+
24
+ def _find_config_file(self) -> Optional[Path]:
25
+ """Search for config.yaml in current and parent directories."""
26
+ current = Path.cwd()
27
+
28
+ # Search up to 5 levels up
29
+ for _ in range(5):
30
+ config_file = current / "config.yaml"
31
+ if config_file.exists():
32
+ return config_file
33
+
34
+ # Check if we've reached the root
35
+ if current.parent == current:
36
+ break
37
+ current = current.parent
38
+
39
+ return None
40
+
41
+ def _load_config(self) -> Dict[str, Any]:
42
+ """Load configuration from YAML file."""
43
+ if not self.config_path or not self.config_path.exists():
44
+ return {"environment_sets": {}}
45
+
46
+ with open(self.config_path, 'r', encoding='utf-8') as f:
47
+ return yaml.safe_load(f) or {"environment_sets": {}}
48
+
49
+ def _migrate_old_config(self):
50
+ """Migrate old config format to new environment sets format."""
51
+ if "tools" in self.config_data and "environment_sets" not in self.config_data:
52
+ # Migrate old format to new format
53
+ self.config_data["environment_sets"] = {
54
+ "default": {
55
+ "description": "Default environment set (migrated)",
56
+ "tools": self.config_data["tools"]
57
+ }
58
+ }
59
+ del self.config_data["tools"]
60
+
61
+ def get_environment_sets(self) -> List[str]:
62
+ """Get list of configured environment sets."""
63
+ return list(self.config_data.get("environment_sets", {}).keys())
64
+
65
+ def get_environment_set(self, set_name: str) -> Dict[str, Any]:
66
+ """Get configuration for a specific environment set."""
67
+ return self.config_data.get("environment_sets", {}).get(set_name, {})
68
+
69
+ def get_tools(self, env_set: Optional[str] = None) -> List[str]:
70
+ """Get list of configured tools.
71
+
72
+ Args:
73
+ env_set: Environment set name. If None, returns tools from all sets.
74
+
75
+ Returns:
76
+ List of tool names
77
+ """
78
+ if env_set:
79
+ env_config = self.get_environment_set(env_set)
80
+ return list(env_config.get("tools", {}).keys())
81
+ else:
82
+ # Return all tools from all environment sets
83
+ all_tools = []
84
+ for set_name in self.get_environment_sets():
85
+ env_config = self.get_environment_set(set_name)
86
+ all_tools.extend(env_config.get("tools", {}).keys())
87
+ return list(set(all_tools)) # Remove duplicates
88
+
89
+ def get_tool_config(self, tool_name: str, env_set: Optional[str] = None) -> Tuple[Dict[str, Any], str]:
90
+ """Get configuration for a specific tool.
91
+
92
+ Args:
93
+ tool_name: Name of the tool (e.g., 'claude', 'github_copilot')
94
+ env_set: Environment set name. If None, searches all sets.
95
+
96
+ Returns:
97
+ Tuple of (tool config dict, environment set name)
98
+ """
99
+ if env_set:
100
+ env_config = self.get_environment_set(env_set)
101
+ tool_config = env_config.get("tools", {}).get(tool_name, {})
102
+ if tool_config:
103
+ return tool_config, env_set
104
+ else:
105
+ # Search all environment sets for the tool
106
+ for set_name in self.get_environment_sets():
107
+ env_config = self.get_environment_set(set_name)
108
+ tool_config = env_config.get("tools", {}).get(tool_name, {})
109
+ if tool_config:
110
+ return tool_config, set_name
111
+
112
+ return {}, ""
113
+
114
+ def get_source_files(self, tool_name: str, env_set: Optional[str] = None) -> List[Path]:
115
+ """Get list of source files for a tool from the central repository.
116
+
117
+ Args:
118
+ tool_name: Name of the tool
119
+ env_set: Environment set name
120
+
121
+ Returns:
122
+ List of absolute paths to source files
123
+ """
124
+ tool_config, _ = self.get_tool_config(tool_name, env_set)
125
+ if not tool_config:
126
+ return []
127
+
128
+ project_dir = self.base_dir / tool_config.get("project_dir", "")
129
+ files = tool_config.get("files", [])
130
+
131
+ source_files = []
132
+ for file_pattern in files:
133
+ # Handle glob patterns
134
+ if '*' in file_pattern or '?' in file_pattern:
135
+ pattern_path = project_dir / file_pattern
136
+ matched_files = glob.glob(str(pattern_path), recursive=True)
137
+ source_files.extend(Path(f) for f in matched_files)
138
+ else:
139
+ file_path = project_dir / file_pattern
140
+ if file_path.exists():
141
+ source_files.append(file_path)
142
+
143
+ return source_files
144
+
145
+ def get_target_files(self, tool_name: str, target_dir: Path, env_set: Optional[str] = None) -> List[Path]:
146
+ """Get list of target files for a tool in the target directory.
147
+
148
+ Args:
149
+ tool_name: Name of the tool
150
+ target_dir: Target directory (project directory)
151
+ env_set: Environment set name
152
+
153
+ Returns:
154
+ List of absolute paths to target files
155
+ """
156
+ tool_config, _ = self.get_tool_config(tool_name, env_set)
157
+ if not tool_config:
158
+ return []
159
+
160
+ files = tool_config.get("files", [])
161
+
162
+ target_files = []
163
+ for file_pattern in files:
164
+ # Handle glob patterns
165
+ if '*' in file_pattern or '?' in file_pattern:
166
+ pattern_path = target_dir / file_pattern
167
+ matched_files = glob.glob(str(pattern_path), recursive=True)
168
+ target_files.extend(Path(f) for f in matched_files)
169
+ else:
170
+ file_path = target_dir / file_pattern
171
+ target_files.append(file_path) # Include even if doesn't exist
172
+
173
+ return target_files
174
+
175
+ def get_file_mapping(self, tool_name: str, target_dir: Path, env_set: Optional[str] = None) -> Dict[Path, Path]:
176
+ """Get mapping of source files to target files.
177
+
178
+ Args:
179
+ tool_name: Name of the tool
180
+ target_dir: Target directory
181
+ env_set: Environment set name
182
+
183
+ Returns:
184
+ Dictionary mapping source paths to target paths
185
+ """
186
+ tool_config, _ = self.get_tool_config(tool_name, env_set)
187
+ if not tool_config:
188
+ return {}
189
+
190
+ project_dir = self.base_dir / tool_config.get("project_dir", "")
191
+ files = tool_config.get("files", [])
192
+
193
+ mapping = {}
194
+ for file_pattern in files:
195
+ # For non-glob patterns, create direct mapping
196
+ if '*' not in file_pattern and '?' not in file_pattern:
197
+ source = project_dir / file_pattern
198
+ target = target_dir / file_pattern
199
+ if source.exists():
200
+ mapping[source] = target
201
+ else:
202
+ # For glob patterns, match files and create relative mappings
203
+ source_pattern = project_dir / file_pattern
204
+ source_files = glob.glob(str(source_pattern), recursive=True)
205
+
206
+ for source_file in source_files:
207
+ source_path = Path(source_file)
208
+ # Calculate relative path from project_dir
209
+ try:
210
+ relative_path = source_path.relative_to(project_dir)
211
+ target_path = target_dir / relative_path
212
+ mapping[source_path] = target_path
213
+ except ValueError:
214
+ # Skip if not relative to project_dir
215
+ continue
216
+
217
+ return mapping