Coverage for gws-app/gws/plugin/qgis/cli.py: 0%

47 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-10-05 13:35 +0200

1"""Command-line commands for QGIS projects.""" 

2 

3import re 

4 

5import gws 

6import gws.lib.shape 

7import gws.lib.crs 

8import gws.lib.dynimport 

9import gws.lib.jsonx 

10 

11from . import project 

12 

13 

14class CapsParams(gws.CliParams): 

15 """Parameters for the caps command.""" 

16 

17 src: str 

18 """Project file path or Postgres address ``postgres:<dbUid>/<schema>/<projectName>``.""" 

19 out: str = '' 

20 """Output file name. If empty, the result is printed.""" 

21 

22 

23class CopyParams(gws.CliParams): 

24 """Parameters for the copy command.""" 

25 

26 src: str 

27 """Source project file path or Postgres address ``postgres:<dbUid>/<schema>/<projectName>``.""" 

28 dst: str 

29 """Destination project file path or Postgres address ``postgres:<dbUid>/<schema>/<projectName>``.""" 

30 

31 

32class Object(gws.Node): 

33 """CLI commands for QGIS projects.""" 

34 

35 @gws.ext.command.cli('qgisCopy') 

36 def do_copy(self, p: CopyParams): 

37 """Copy a QGIS project between files and databases.""" 

38 

39 root = gws.load_root() 

40 src_prj = project.from_store(root, _addr_to_store(p.src)) 

41 src_prj.to_store(root, _addr_to_store(p.dst)) 

42 

43 @gws.ext.command.cli('qgisCaps') 

44 def do_caps(self, p: CapsParams): 

45 """Print the parsed capabilities of a QGIS project as JSON.""" 

46 

47 root = gws.load_root() 

48 src_prj = project.from_store(root, _addr_to_store(p.src)) 

49 caps = src_prj.caps() 

50 

51 js = gws.lib.jsonx.to_pretty_string(caps, default=_caps_json) 

52 

53 if p.out: 

54 gws.u.write_file(p.out, js) 

55 gws.log.info(f'saved to {p.out!r}') 

56 else: 

57 print(js) 

58 

59 

60def _addr_to_store(addr): 

61 m = re.match(r'^postgres:(.*?)/(.*?)/(.+?)$', addr) 

62 if m: 

63 return project.Store(type=project.StoreType.postgres, dbUid=m.group(1), schema=m.group(2), projectName=m.group(3)) 

64 m = re.match(r'^(/.+)$', addr) 

65 if m: 

66 return project.Store( 

67 type=project.StoreType.file, 

68 path=m.group(1), 

69 ) 

70 raise ValueError('invalid path or postgres address') 

71 

72 

73def _caps_json(x): 

74 if isinstance(x, gws.Crs): 

75 return x.epsg 

76 if isinstance(x, gws.lib.shape.Shape): 

77 return x.to_geojson() 

78 try: 

79 return vars(x) 

80 except TypeError: 

81 return repr(x)