Coverage for geoparser/cli/install.py: 100%

37 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-20 18:08 +0000

1from importlib.resources import files 

2from pathlib import Path 

3 

4import typer 

5 

6from geoparser.gazetteer.artifact import artifact_path, list_artifacts 

7from geoparser.gazetteer.build import GazetteerBuilder 

8from geoparser.gazetteer.build.builder import uninstall 

9 

10 

11def _get_builtin_gazetteers() -> dict[str, Path]: 

12 """ 

13 Discover all built-in gazetteer configurations. 

14 

15 Returns: 

16 Dictionary mapping gazetteer names to their config file paths. 

17 """ 

18 configs_dir = files("geoparser.gazetteer") / "configs" 

19 

20 # Get all yaml files in the configs directory 

21 gazetteers = {} 

22 for config_file in configs_dir.iterdir(): 

23 if config_file.name.endswith(".yaml"): 

24 gazetteer_name = config_file.name[:-5] # Remove .yaml extension 

25 gazetteers[gazetteer_name] = Path(str(config_file)) 

26 

27 return gazetteers 

28 

29 

30def install_cli(config: str): 

31 """ 

32 Install a gazetteer from a configuration file. 

33 

34 Args: 

35 config: Either a gazetteer name (e.g., 'geonames', 'swissnames3d') or 

36 a path to a custom YAML configuration file. 

37 """ 

38 # Check if config is a built-in gazetteer name 

39 config_path = Path(config) 

40 

41 if not config_path.exists(): 

42 # Get available built-in gazetteers 

43 builtin_gazetteers = _get_builtin_gazetteers() 

44 

45 if config in builtin_gazetteers: 

46 config_path = builtin_gazetteers[config] 

47 else: 

48 available = "\n".join( 

49 f" - {name}" for name in sorted(builtin_gazetteers.keys()) 

50 ) 

51 raise FileNotFoundError( 

52 f"Gazetteer config not found: {config}\n" 

53 f"Available built-in gazetteer configs:\n{available}" 

54 ) 

55 

56 builder = GazetteerBuilder() 

57 builder.build(config_path) 

58 

59 

60def list_cli(): 

61 """ 

62 List installed gazetteers. 

63 """ 

64 names = list_artifacts() 

65 if not names: 

66 typer.echo("No gazetteers installed.") 

67 return 

68 for name in names: 

69 size = artifact_path(name).stat().st_size 

70 typer.echo(f"{name} ({size / 1024 / 1024:.1f} MB)") 

71 

72 

73def uninstall_cli(name: str): 

74 """ 

75 Remove an installed gazetteer. 

76 

77 Args: 

78 name: Name of the gazetteer to remove. 

79 """ 

80 if uninstall(name): 

81 typer.echo(f"Removed gazetteer '{name}'.") 

82 else: 

83 typer.secho( 

84 f"Gazetteer '{name}' is not installed.", fg=typer.colors.YELLOW, err=True 

85 ) 

86 raise typer.Exit(code=1)