Coverage for src/hatch_ci/version_hook.py: 0%

38 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-08-06 19:23 +0000

1from __future__ import annotations 

2 

3from typing import Any 

4 

5from hatchling.version.source.plugin.interface import VersionSourceInterface 

6 

7from .common import PLUGIN_NAME 

8 

9 

10class ValidationError(Exception): 

11 pass 

12 

13 

14class _NO: 

15 pass 

16 

17 

18def extract( 

19 config: dict[str, str], var: str, typ: Any = _NO, optional: Any = _NO 

20) -> Any: 

21 value = config.get(var, optional) 

22 if value is _NO: 

23 raise ValidationError(f"cannot find variable '{var}' for plugin 'ci'") 

24 try: 

25 new_value = typ(value) if typ is not _NO else value 

26 except Exception as exc: 

27 raise ValidationError(f"cannot convert to {typ=} the {value=}") from exc 

28 return new_value 

29 

30 

31def get_fixers(txt: str) -> dict[str, str]: 

32 if not isinstance(txt, list): 

33 raise ValidationError("fixers must be list of dicts") 

34 if not all(isinstance(t, list) for t in txt): 

35 raise ValidationError("fixers elements must be lists") 

36 if not all(len(t) == 2 for t in txt): 

37 raise ValidationError("all fixers list elements must be of length 2") 

38 return dict(txt) 

39 

40 

41class CIVersionSource(VersionSourceInterface): 

42 PLUGIN_NAME = PLUGIN_NAME 

43 

44 def get_version_data(self): 

45 from os import getenv 

46 from pathlib import Path 

47 

48 from hatch_ci import tools 

49 

50 paths = extract(self.config, "paths", typ=tools.list_of_paths) 

51 fixers = extract(self.config, "fixers", typ=get_fixers) 

52 version_file = Path(self.root) / extract(self.config, "version-file") 

53 

54 if not version_file.exists(): 

55 raise ValidationError( 

56 f"no 'version-file' key for plugin {self.PLUGIN_NAME}" 

57 ) 

58 gdata = tools.process( 

59 version_file, getenv("GITHUB_DUMP"), paths=paths, fixers=fixers 

60 ) 

61 return {"version": gdata["version"]}