Coverage for src/prisma/cli/commands/generate.py: 88%

41 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2024-04-28 15:17 +0000

1import sys 

2import logging 

3from typing import Any, Dict, Tuple, Optional 

4from pathlib import Path 

5 

6import click 

7import pydantic 

8 

9from .. import prisma, options 

10from ..utils import EnumChoice, PathlibPath, warning 

11from ..._compat import PYDANTIC_V2 

12from ...generator.models import InterfaceChoices 

13 

14ARG_TO_CONFIG_KEY = { 

15 'partials': 'partial_type_generator', 

16 'type_depth': 'recursive_type_depth', 

17} 

18 

19log: logging.Logger = logging.getLogger(__name__) 

20 

21 

22# not sure why this type ignore is needed 

23@click.command('generate') # type: ignore 

24@options.schema 

25@options.watch 

26@click.option( 

27 '--interface', 

28 type=EnumChoice(InterfaceChoices), 

29 help='Method that the client will use to interface with Prisma', 

30) 

31@click.option( 

32 '--partials', 

33 type=PathlibPath(exists=True, readable=True), 

34 help='Partial type generator location', 

35) 

36@click.option( 

37 '-t', 

38 '--type-depth', 

39 type=int, 

40 help='Depth to generate pseudo-recursive types to; -1 signifies fully recursive types', 

41) 

42@click.option( 

43 '--generator', 

44 multiple=True, 

45 help='Specifies which generator to use. Can be specified multiple times. By default, all generators will be ran', 

46) 

47def cli(schema: Optional[Path], watch: bool, generator: Tuple[str], **kwargs: Any) -> None: 

48 """Generate prisma artifacts with modified config options""" 

49 # context https://github.com/microsoft/pyright/issues/6099 

50 if pydantic.VERSION.split('.') < ['1', '8']: # pyright: ignore 

51 warning( 

52 'Unsupported version of pydantic installed, this command may not work as intended\n' 

53 'Please update pydantic to 1.8 or greater.\n' 

54 ) 

55 

56 args = ['generate'] 

57 if schema is not None: 

58 args.append(f'--schema={schema}') 

59 

60 if watch: 60 ↛ 61line 60 didn't jump to line 61, because the condition on line 60 was never true

61 args.append('--watch') 

62 

63 if generator: 63 ↛ 64line 63 didn't jump to line 64, because the condition on line 63 was never true

64 for name in generator: 

65 args.append(f'--generator={name}') 

66 

67 env: Dict[str, str] = {} 

68 prefix = 'PRISMA_PY_CONFIG_' 

69 for key, value in kwargs.items(): 

70 if value is None: 

71 continue 

72 

73 env[prefix + ARG_TO_CONFIG_KEY.get(key, key).upper()] = serialize(key, value) 

74 

75 log.debug('Running generate with env: %s', env) 

76 sys.exit(prisma.run(args, env=env)) 

77 

78 

79def serialize(key: str, obj: Any) -> str: 

80 if not PYDANTIC_V2: 

81 if key == 'partials': 

82 # partials has to be JSON serializable 

83 return f'"{obj}"' 

84 return str(obj)