Coverage for analyzers/typescript.py: 86%

1"""TypeScript source file analyzer -- assembles all metrics."""

2

3 from __future__ import annotations

4

5 from pathlib import Path

6

7 from analyzers.shared import create_analyzer_file_fn, create_analyzer_source_fn

8 from parsers.typescript import parse, collect_functions, func_name

9 from metrics.lloc.typescript import count_lloc

10 from metrics.halstead.typescript import compute_halstead_ts

11 from metrics.npath.typescript import compute_npath_ts

12 from metrics.dtd.typescript import compute_dtd_ts

13 from metrics.cognitive.typescript import compute_cognitive_ts

14 from metrics.cyclomatic.typescript import compute_cyclomatic_ts

15 from metrics.duplication.config import TYPESCRIPT_CONFIG

16

17

18 def get_tsx_flag(filepath):

19 """Determine if file should be parsed as TSX."""

20 return Path(filepath).suffix.lower() == ".tsx"

21

22

23 def create_analyze_source_ts():

24 """Factory to create TypeScript-specific analyze_source function with tsx support."""

25

26 def analyze_source(code, tsx=False, **kwargs):

27 return create_analyzer_source_fn(

28 parse_fn=lambda c: parse(c, tsx=tsx),

29 collect_functions_fn=collect_functions,

30 func_name_fn=func_name,

31 compute_cognitive_fn=compute_cognitive_ts,

32 compute_halstead_fn=compute_halstead_ts,

33 compute_npath_fn=compute_npath_ts,

34 compute_dtd_fn=compute_dtd_ts,

35 compute_cyclomatic_fn=compute_cyclomatic_ts,

36 count_lloc_fn=count_lloc,

37 dup_config=TYPESCRIPT_CONFIG,

38 )(code, timing_manager=kwargs.get("timing_manager"))

39

40 return analyze_source

41

42

43 analyze_source = create_analyze_source_ts()

44

45

46 def analyze_file(filepath, timing_manager=None):

47 """Analyze a TypeScript file and return cognitive complexity scores."""

48 tsx = get_tsx_flag(filepath)

49 return create_analyzer_file_fn(analyze_source, tsx=tsx)(

50 filepath, timing_manager=timing_manager

51 )