metripy 0.2.7__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of metripy might be problematic. Click here for more details.

Files changed (66) hide show
  1. metripy/Application/Analyzer.py +106 -0
  2. metripy/Application/Application.py +54 -0
  3. metripy/Application/Config/Config.py +13 -0
  4. metripy/Application/Config/File/ConfigFileReaderFactory.py +24 -0
  5. metripy/Application/Config/File/ConfigFileReaderInterface.py +14 -0
  6. metripy/Application/Config/File/JsonConfigFileReader.py +82 -0
  7. metripy/Application/Config/GitConfig.py +10 -0
  8. metripy/Application/Config/Parser.py +31 -0
  9. metripy/Application/Config/ProjectConfig.py +27 -0
  10. metripy/Application/Config/ReportConfig.py +10 -0
  11. metripy/Application/__init__.py +0 -0
  12. metripy/Component/Debug/Debugger.py +20 -0
  13. metripy/Component/File/Finder.py +37 -0
  14. metripy/Component/Output/CliOutput.py +49 -0
  15. metripy/Component/Output/ProgressBar.py +27 -0
  16. metripy/Dependency/Composer/Composer.py +30 -0
  17. metripy/Dependency/Composer/Packegist.py +55 -0
  18. metripy/Dependency/Dependency.py +30 -0
  19. metripy/Dependency/Npm/Npm.py +30 -0
  20. metripy/Dependency/Npm/NpmOrg.py +47 -0
  21. metripy/Dependency/Pip/Pip.py +69 -0
  22. metripy/Dependency/Pip/PyPi.py +49 -0
  23. metripy/Git/GitAnalyzer.py +86 -0
  24. metripy/LangAnalyzer/AbstractLangAnalyzer.py +65 -0
  25. metripy/LangAnalyzer/Generic/HalSteadAnalyzer.py +58 -0
  26. metripy/LangAnalyzer/Generic/__init__.py +0 -0
  27. metripy/LangAnalyzer/Php/PhpAnalyzer.py +193 -0
  28. metripy/LangAnalyzer/Php/PhpBasicAstParser.py +56 -0
  29. metripy/LangAnalyzer/Php/PhpBasicLocAnalyzer.py +174 -0
  30. metripy/LangAnalyzer/Php/PhpHalSteadAnalyzer.py +44 -0
  31. metripy/LangAnalyzer/Python/PythonAnalyzer.py +129 -0
  32. metripy/LangAnalyzer/Typescript/TypescriptAnalyzer.py +208 -0
  33. metripy/LangAnalyzer/Typescript/TypescriptAstParser.py +68 -0
  34. metripy/LangAnalyzer/Typescript/TypescriptBasicComplexityAnalyzer.py +114 -0
  35. metripy/LangAnalyzer/Typescript/TypescriptBasicLocAnalyzer.py +69 -0
  36. metripy/LangAnalyzer/Typescript/TypescriptHalSteadAnalyzer.py +55 -0
  37. metripy/LangAnalyzer/__init__.py +0 -0
  38. metripy/Metric/Code/AggregatedMetrics.py +42 -0
  39. metripy/Metric/Code/FileMetrics.py +33 -0
  40. metripy/Metric/Code/ModuleMetrics.py +32 -0
  41. metripy/Metric/Code/SegmentedMetrics.py +65 -0
  42. metripy/Metric/FileTree/FileTree.py +15 -0
  43. metripy/Metric/FileTree/FileTreeParser.py +42 -0
  44. metripy/Metric/Git/GitCodeHotspot.py +37 -0
  45. metripy/Metric/Git/GitContributor.py +37 -0
  46. metripy/Metric/Git/GitKnowledgeSilo.py +27 -0
  47. metripy/Metric/Git/GitMetrics.py +148 -0
  48. metripy/Metric/ProjectMetrics.py +55 -0
  49. metripy/Report/Csv/Reporter.py +12 -0
  50. metripy/Report/Html/Reporter.py +210 -0
  51. metripy/Report/Json/AbstractJsonReporter.py +11 -0
  52. metripy/Report/Json/GitJsonReporter.py +21 -0
  53. metripy/Report/Json/JsonReporter.py +12 -0
  54. metripy/Report/ReporterFactory.py +22 -0
  55. metripy/Report/ReporterInterface.py +17 -0
  56. metripy/Tree/ClassNode.py +32 -0
  57. metripy/Tree/FunctionNode.py +49 -0
  58. metripy/Tree/ModuleNode.py +42 -0
  59. metripy/__init__.py +0 -0
  60. metripy/metripy.py +15 -0
  61. metripy-0.2.7.dist-info/METADATA +113 -0
  62. metripy-0.2.7.dist-info/RECORD +66 -0
  63. metripy-0.2.7.dist-info/WHEEL +5 -0
  64. metripy-0.2.7.dist-info/entry_points.txt +2 -0
  65. metripy-0.2.7.dist-info/licenses/LICENSE +21 -0
  66. metripy-0.2.7.dist-info/top_level.txt +1 -0
@@ -0,0 +1,106 @@
1
+ from metripy.Application.Config.ProjectConfig import ProjectConfig
2
+ from metripy.Component.Debug.Debugger import Debugger
3
+ from metripy.Component.Output.CliOutput import CliOutput
4
+ from metripy.Component.Output.ProgressBar import ProgressBar
5
+ from metripy.Dependency.Composer.Composer import Composer
6
+ from metripy.Dependency.Dependency import Dependency
7
+ from metripy.Dependency.Npm.Npm import Npm
8
+ from metripy.Dependency.Pip.Pip import Pip
9
+ from metripy.Git.GitAnalyzer import GitAnalyzer
10
+ from metripy.LangAnalyzer.AbstractLangAnalyzer import AbstractLangAnalyzer
11
+ from metripy.LangAnalyzer.Php.PhpAnalyzer import PhpAnalyzer
12
+ from metripy.LangAnalyzer.Python.PythonAnalyzer import PythonAnalyzer
13
+ from metripy.LangAnalyzer.Typescript.TypescriptAnalyzer import \
14
+ TypescriptAnalyzer
15
+ from metripy.Metric.Code.FileMetrics import FileMetrics
16
+ from metripy.Metric.Git.GitMetrics import GitMetrics
17
+ from metripy.Metric.ProjectMetrics import ProjectMetrics
18
+
19
+
20
+ class Analyzer:
21
+ def __init__(self, config: ProjectConfig, output: CliOutput, debugger: Debugger):
22
+ self.config = config
23
+ self.output = output
24
+ self.debugger = debugger
25
+ self.runners: list[AbstractLangAnalyzer] = [
26
+ PythonAnalyzer(),
27
+ PhpAnalyzer(),
28
+ TypescriptAnalyzer(),
29
+ ]
30
+
31
+ def analyze_git(self) -> GitMetrics:
32
+ self.output.writeln("<info>Analyzing git history...</info>")
33
+ metrics = GitAnalyzer(self.config.git).analyze()
34
+ self.output.writeln("<success>Git history analyzed</success>")
35
+
36
+ return metrics
37
+
38
+ def analyze_code(self, files: list[str]) -> list[FileMetrics]:
39
+ file_metrics = []
40
+
41
+ # for multi language projects, register runner per language
42
+ runner_sizes = []
43
+ for runner in self.runners:
44
+ runner.set_files(files)
45
+ if not runner.is_needed():
46
+ continue
47
+ runner_sizes.append(len(runner.files))
48
+
49
+ self.debugger.debug(len(files))
50
+ self.output.writeln("<info>Analyzing code...</info>")
51
+ progress_bar = ProgressBar(self.output, sum(runner_sizes))
52
+ for runner in self.runners:
53
+ if not runner.is_needed():
54
+ continue
55
+ runner.before_run()
56
+ runner.run(progress_bar)
57
+ runner.after_run()
58
+
59
+ for metric in runner.get_metrics():
60
+ file_metrics.append(metric)
61
+
62
+ self.output.writeln("")
63
+ self.output.writeln("<success>Code analyzed</success>")
64
+
65
+ return file_metrics
66
+
67
+ def analyze_composer(self) -> list[Dependency]:
68
+ self.output.writeln("<info>Analyzing composer packages...</info>")
69
+ dependencies = Composer().get_composer_dependencies(self.config.base_path)
70
+ self.output.writeln("<success>Composer packages analyzed</success>")
71
+
72
+ return dependencies
73
+
74
+ def analyze_pip(self) -> list[Dependency]:
75
+ self.output.writeln("<info>Analyzing pip packages...</info>")
76
+ dependencies = Pip().get_dependencies(self.config.base_path)
77
+ self.output.writeln("<success>Pip packages analyzed</success>")
78
+
79
+ return dependencies
80
+
81
+ def analyze_npm(self) -> list[Dependency]:
82
+ self.output.writeln("<info>Analyzing npm packages...</info>")
83
+ dependencies = Npm().get_dependencies(self.config.base_path)
84
+ self.output.writeln("<success>Npm packages analyzed</success>")
85
+
86
+ return dependencies
87
+
88
+ def run(self, files: list[str]) -> ProjectMetrics:
89
+ git_stats = None
90
+ if self.config.git:
91
+ git_stats = self.analyze_git()
92
+
93
+ file_metrics = []
94
+ if True:
95
+ file_metrics = self.analyze_code(files)
96
+
97
+ # TODO: analyze dependencies: composer, pip, npm, etc etc
98
+ packages = None
99
+ if self.config.composer:
100
+ packages = self.analyze_composer()
101
+ elif self.config.pip:
102
+ packages = self.analyze_pip()
103
+ elif self.config.npm:
104
+ packages = self.analyze_npm()
105
+
106
+ return ProjectMetrics(file_metrics, git_stats, packages)
@@ -0,0 +1,54 @@
1
+ import json
2
+
3
+ from metripy.Application.Analyzer import Analyzer
4
+ from metripy.Application.Config.Parser import Parser
5
+ from metripy.Component.Debug.Debugger import Debugger
6
+ from metripy.Component.File.Finder import Finder
7
+ from metripy.Component.Output.CliOutput import CliOutput
8
+ from metripy.Report.ReporterFactory import ReporterFactory
9
+ from metripy.Report.ReporterInterface import ReporterInterface
10
+
11
+
12
+ class Application:
13
+ def run(self, argv) -> None:
14
+ output = CliOutput()
15
+
16
+ # issues and debug
17
+ debugger = Debugger(output).enable()
18
+
19
+ config = Parser().parse(argv)
20
+
21
+ finder = Finder()
22
+ files = finder.fetch(config.project_configs)
23
+
24
+ for project_config in config.project_configs:
25
+ debugger.debug(project_config.name)
26
+ project_files = files[project_config.name]
27
+ debugger.debug(f"Found {len(project_files)} files")
28
+ debugger.debug(json.dumps(project_files))
29
+
30
+ output.writeln(f"<info>Analying Project {project_config.name}...</info>")
31
+ project_metrics = Analyzer(project_config, output, debugger).run(
32
+ project_files
33
+ )
34
+ output.writeln(
35
+ f"<success>Done analying Project {project_config.name}</success>"
36
+ )
37
+
38
+ if not project_config.reports:
39
+ output.writeln(
40
+ f"<success>Skipping reports of {project_config.name}!</success>"
41
+ )
42
+ continue
43
+
44
+ output.writeln(
45
+ f"<info>Generating reports for {project_config.name}...</info>"
46
+ )
47
+ for report_config in project_config.reports:
48
+ reporter: ReporterInterface = ReporterFactory.create(
49
+ report_config, output
50
+ )
51
+ reporter.generate(project_metrics)
52
+ output.writeln(
53
+ f"<success>Reports generated for {project_config.name}</success>"
54
+ )
@@ -0,0 +1,13 @@
1
+ from metripy.Application.Config.ProjectConfig import ProjectConfig
2
+
3
+
4
+ class Config:
5
+ def __init__(self):
6
+ self.project_configs: list[ProjectConfig] = []
7
+
8
+ def to_dict(self) -> dict:
9
+ return {
10
+ "project_configs": [
11
+ project_config.to_dict() for project_config in self.project_configs
12
+ ],
13
+ }
@@ -0,0 +1,24 @@
1
+ import os
2
+ import pathlib
3
+
4
+ from metripy.Application.Config.File.ConfigFileReaderInterface import \
5
+ ConfigFileReaderInterface
6
+ from metripy.Application.Config.File.JsonConfigFileReader import \
7
+ JsonConfigFileReader
8
+
9
+
10
+ class ConfigFileReaderFactory:
11
+ @staticmethod
12
+ def createFromFileName(filename: str) -> ConfigFileReaderInterface:
13
+ if not os.path.isfile(filename):
14
+ raise FileNotFoundError(f"File {filename} does not exist")
15
+
16
+ extension = pathlib.Path(filename).suffix
17
+ if extension == ".json":
18
+ return JsonConfigFileReader(filename)
19
+ elif extension == ".yaml" or extension == ".yml":
20
+ raise NotImplementedError("YAML support is not implemented yet")
21
+ elif extension == ".xml":
22
+ raise NotImplementedError("XML support is not implemented yet")
23
+ else:
24
+ raise NotImplementedError(f"Unsupported file type: {extension}")
@@ -0,0 +1,14 @@
1
+ from abc import ABC, abstractmethod
2
+
3
+ from metripy.Application.Config.Config import Config
4
+
5
+
6
+ class ConfigFileReaderInterface(ABC):
7
+
8
+ @abstractmethod
9
+ def __init__(self, filename: str):
10
+ pass
11
+
12
+ @abstractmethod
13
+ def read(self, config: Config) -> None:
14
+ pass
@@ -0,0 +1,82 @@
1
+ import json
2
+ import os
3
+
4
+ from metripy.Application.Config.Config import Config
5
+ from metripy.Application.Config.File.ConfigFileReaderInterface import \
6
+ ConfigFileReaderInterface
7
+ from metripy.Application.Config.GitConfig import GitConfig
8
+ from metripy.Application.Config.ProjectConfig import ProjectConfig
9
+ from metripy.Application.Config.ReportConfig import ReportConfig
10
+
11
+
12
+ class JsonConfigFileReader(ConfigFileReaderInterface):
13
+ def __init__(self, filename: str):
14
+ self.filename = filename
15
+
16
+ def read(self, config: Config) -> None:
17
+ with open(self.filename, "r") as file:
18
+ json_data = json.load(file)
19
+
20
+ self.parse_json(json_data, config)
21
+
22
+ def resolve_path(self, path: str) -> str:
23
+ return os.path.join(os.path.dirname(self.filename), path)
24
+
25
+ def parse_json(self, json_data: dict, config: Config) -> None:
26
+
27
+ # configs
28
+ if configs := json_data.get("configs"):
29
+ for project_name, project_config in configs.items():
30
+ project_config = self.parse_config_json(project_name, project_config)
31
+ config.project_configs.append(project_config)
32
+
33
+ def parse_config_json(self, project_name: str, json_data: dict) -> ProjectConfig:
34
+ project_config = ProjectConfig(project_name)
35
+
36
+ # extensions
37
+ if base_path := json_data.get("base_path"):
38
+ project_config.base_path = base_path
39
+
40
+ # includes
41
+ if includes := json_data.get("includes"):
42
+ files = []
43
+ # with config file, includes are relative to the config file
44
+ for include in includes:
45
+ include = self.resolve_path(include)
46
+ files.append(include)
47
+
48
+ project_config.includes = files
49
+
50
+ # extensions
51
+ if extensions := json_data.get("extensions"):
52
+ project_config.extensions = extensions
53
+
54
+ # excludes
55
+ if excludes := json_data.get("excludes"):
56
+ project_config.excludes = excludes
57
+
58
+ # reports
59
+ if reports := json_data.get("reports"):
60
+ for report_type, path in reports.items():
61
+ path = self.resolve_path(path)
62
+ project_config.reports.append(ReportConfig(report_type, path))
63
+
64
+ # git
65
+ if git := json_data.get("git"):
66
+ project_config.git = GitConfig()
67
+ project_config.git.repo = project_config.base_path
68
+ project_config.git.branch = git.get("branch", project_config.git.branch)
69
+
70
+ # composer
71
+ if composer := json_data.get("composer"):
72
+ project_config.composer = composer
73
+
74
+ # pip
75
+ if pip := json_data.get("pip"):
76
+ project_config.pip = pip
77
+
78
+ # npm
79
+ if npm := json_data.get("npm"):
80
+ project_config.npm = npm
81
+
82
+ return project_config
@@ -0,0 +1,10 @@
1
+ class GitConfig:
2
+ def __init__(self):
3
+ self.repo = "./"
4
+ self.branch = "main"
5
+
6
+ def to_dict(self) -> dict:
7
+ return {
8
+ "repo": self.repo,
9
+ "branch": self.branch,
10
+ }
@@ -0,0 +1,31 @@
1
+ import re
2
+
3
+ from metripy.Application.Config.Config import Config
4
+ from metripy.Application.Config.File.ConfigFileReaderFactory import \
5
+ ConfigFileReaderFactory
6
+
7
+
8
+ class Parser:
9
+ def parse(self, argv: list[str]) -> Config:
10
+ config = Config()
11
+
12
+ if argv[0] == "codemetrics.py" or argv[0] == "codemetrics":
13
+ # TODO, fix when path ends with codemetrics.py
14
+ pass
15
+ argv.pop(0)
16
+
17
+ # check for a config file
18
+ for key, arg in enumerate(argv):
19
+ if matches := re.search(r"^--config=(.+)$", arg):
20
+ fileReader = ConfigFileReaderFactory.createFromFileName(
21
+ matches.group(1)
22
+ )
23
+ fileReader.read(config)
24
+ argv.pop(key)
25
+
26
+ # TODO: add the following
27
+ # arguments with options
28
+ # arguments without options
29
+ # last argument
30
+
31
+ return config
@@ -0,0 +1,27 @@
1
+ from metripy.Application.Config.GitConfig import GitConfig
2
+ from metripy.Application.Config.ReportConfig import ReportConfig
3
+
4
+
5
+ class ProjectConfig:
6
+ def __init__(self, name: str):
7
+ self.name: str = name
8
+ self.base_path: str = "./"
9
+ self.includes: list[str] = []
10
+ self.excludes: list[str] = []
11
+ self.extensions: list[str] = []
12
+ self.git: GitConfig | None = None
13
+ self.composer: bool = False
14
+ self.pip: bool = False
15
+ self.npm: bool = False
16
+ self.reports: list[ReportConfig] = []
17
+
18
+ def to_dict(self) -> dict:
19
+ return {
20
+ "name": self.name,
21
+ "base_path": self.base_path,
22
+ "includes": self.includes,
23
+ "excludes": self.excludes,
24
+ "extensions": self.extensions,
25
+ "git": self.git.to_dict() if self.git else None,
26
+ "reports": [report.to_dict() for report in self.reports],
27
+ }
@@ -0,0 +1,10 @@
1
+ class ReportConfig:
2
+ def __init__(self, report_type: str, path: str) -> None:
3
+ self.type = report_type
4
+ self.path = path
5
+
6
+ def to_dict(self) -> dict:
7
+ return {
8
+ "type": self.type,
9
+ "path": self.path,
10
+ }
File without changes
@@ -0,0 +1,20 @@
1
+ from typing import Self
2
+
3
+ from metripy.Component.Output.CliOutput import CliOutput
4
+
5
+
6
+ class Debugger:
7
+ def __init__(self, output: CliOutput):
8
+ self.enabled = False
9
+ self.output = output
10
+
11
+ def enable(self) -> Self:
12
+ self.enabled = True
13
+
14
+ return self
15
+
16
+ def debug(self, message: str):
17
+ if not self.enabled:
18
+ return
19
+
20
+ self.output.writeln(f"<debug>{message}</debug>")
@@ -0,0 +1,37 @@
1
+ import os
2
+
3
+ from metripy.Application.Config.ProjectConfig import ProjectConfig
4
+
5
+
6
+ class Finder:
7
+ def fetch(self, project_configs: list[ProjectConfig]) -> dict[str, list[str]]:
8
+ """returns a list of files per project project_name => [files,...]"""
9
+ project_files = {}
10
+ for project_config in project_configs:
11
+ files = []
12
+
13
+ paths = [
14
+ os.path.join(project_config.base_path, inc)
15
+ for inc in project_config.includes
16
+ ]
17
+ for path in paths:
18
+ if os.path.isdir(path):
19
+ self._search(
20
+ path, project_config.extensions, project_config.excludes, files
21
+ )
22
+ project_files[project_config.name] = files
23
+
24
+ return project_files
25
+
26
+ def _search(
27
+ self, path: str, extensions: list[str], excludes: list[str], results: list[str]
28
+ ):
29
+ if not os.path.isdir(path):
30
+ if path not in excludes and path.endswith(tuple(extensions)):
31
+ results.append(path)
32
+
33
+ for file in os.listdir(path):
34
+ if os.path.isdir(os.path.join(path, file)) and file not in excludes:
35
+ self._search(os.path.join(path, file), extensions, excludes, results)
36
+ elif file not in excludes and file.endswith(tuple(extensions)):
37
+ results.append(os.path.join(path, file))
@@ -0,0 +1,49 @@
1
+ import re
2
+ import sys
3
+ from typing import Self
4
+
5
+
6
+ class CliOutput:
7
+ def __init__(self):
8
+ self.quiet_mode = False
9
+
10
+ def set_quiet_mode(self, quiet_mode: bool):
11
+ self.quiet_mode = quiet_mode
12
+
13
+ def writeln(self, message: str) -> Self:
14
+ self.write(str(message), end="\n")
15
+
16
+ return self
17
+
18
+ def write(self, message: str, end="") -> Self:
19
+ if matches := re.search(r"<([a-z]+)>(.*?)</([a-z]+)>", message):
20
+ type = matches.group(1)
21
+ message = matches.group(2)
22
+ color = {
23
+ "error": "\033[31m",
24
+ "warning": "\033[33m",
25
+ "success": "\033[32m",
26
+ "info": "\033[34m",
27
+ "debug": "\033[95m",
28
+ }
29
+ message = color[type] + message + "\033[0m"
30
+
31
+ if not self.quiet_mode:
32
+ print(message, end=end)
33
+
34
+ return self
35
+
36
+ def err(self, message: str) -> Self:
37
+ sys.stderr.write(message)
38
+
39
+ return self
40
+
41
+ def clearln(self) -> Self:
42
+ if self.has_ansi():
43
+ self.write("\x0d")
44
+ self.write("\x1b[2K")
45
+
46
+ return self
47
+
48
+ def has_ansi(self) -> bool:
49
+ return sys.stdout.isatty()
@@ -0,0 +1,27 @@
1
+ from metripy.Component.Output.CliOutput import CliOutput
2
+
3
+
4
+ class ProgressBar:
5
+ def __init__(self, output: CliOutput, total: int):
6
+ self.output = output
7
+ self.total = total
8
+ self.current = 0
9
+
10
+ def start(self):
11
+ self.current = 0
12
+
13
+ def advance(self):
14
+ self.current += 1
15
+
16
+ if self.output.has_ansi():
17
+ percent = round(self.current / self.total * 100)
18
+ self.output.write("\x0d")
19
+ self.output.write("\x1b[2K")
20
+ self.output.write(f"... {percent}% ...")
21
+ else:
22
+ self.output.write(".")
23
+
24
+ def clear(self):
25
+ if self.output.has_ansi():
26
+ self.output.write("\x0d")
27
+ self.output.write("\x1b[2K")
@@ -0,0 +1,30 @@
1
+ import json
2
+ import os
3
+
4
+ from metripy.Dependency.Composer.Packegist import Packegist
5
+ from metripy.Dependency.Dependency import Dependency
6
+
7
+
8
+ class Composer:
9
+ def get_composer_dependencies(self, composer_json_path: str):
10
+ requirements = self.get_composer_json_requirements(composer_json_path)
11
+
12
+ packegist = Packegist()
13
+ packages = []
14
+ for dependency in requirements:
15
+ package = packegist.get_info(dependency)
16
+ packages.append(package)
17
+
18
+ return [item for item in packages if item is not None]
19
+
20
+ def get_composer_json_requirements(self, composer_json_path) -> list:
21
+ requirements = []
22
+ with open(os.path.join(composer_json_path, "composer.json"), "r") as file:
23
+ composer_json = json.load(file)
24
+ require = composer_json.get("require", None)
25
+ if require is None:
26
+ return []
27
+ for name, version in require.items():
28
+ requirements.append(Dependency(name, version))
29
+
30
+ return requirements
@@ -0,0 +1,55 @@
1
+ import re
2
+
3
+ import requests
4
+ from packaging import version
5
+
6
+ from metripy.Dependency.Dependency import Dependency
7
+
8
+
9
+ class Packegist:
10
+ def get_info(self, dependency: Dependency) -> Dependency | None:
11
+ if "/" not in dependency.name:
12
+ return None
13
+ [user, name] = dependency.name.split("/", 2)
14
+ uri = f"https://packagist.org/packages/{user}/{name}.json"
15
+
16
+ x = requests.get(uri)
17
+ d = x.json()
18
+
19
+ package_info = d.get("package", None)
20
+ if package_info is None:
21
+ print(f"package of {dependency.name} has no package info")
22
+ return dependency
23
+
24
+ dependency.type = package_info["type"]
25
+ dependency.description = package_info["description"]
26
+ dependency.repository = package_info["repository"]
27
+ dependency.github_stars = package_info["github_stars"]
28
+ dependency.downloads_total = package_info["downloads"]["total"]
29
+ dependency.downloads_monthly = package_info["downloads"]["monthly"]
30
+ dependency.downloads_daily = package_info["downloads"]["daily"]
31
+
32
+ latest = version.parse("0.0.0")
33
+ versions = package_info["versions"]
34
+ for ver_str, datas in versions.items():
35
+ # Strip leading 'v' if present
36
+ if ver_str.startswith("v"):
37
+ ver_str = ver_str[1:]
38
+
39
+ # Skip non-semver strings
40
+ if not re.match(r"^[\d.]+$", ver_str):
41
+ continue
42
+
43
+ current_version = version.parse(ver_str)
44
+ if current_version > latest:
45
+ latest = current_version
46
+ dependency.latest = ver_str
47
+ dependency.license = datas.get("license", [])
48
+ dependency.homepage = datas.get("homepage")
49
+ dependency.zip = datas.get("dist", {}).get("url")
50
+
51
+ if dependency.version == dependency.latest:
52
+ dependency.status = "latest"
53
+ else:
54
+ dependency.status = "outdated"
55
+ return dependency
@@ -0,0 +1,30 @@
1
+ class Dependency:
2
+ def __init__(self, name: str, version: str):
3
+ self.name = name
4
+ self.version = version
5
+ self.latest: str = ""
6
+ self.status: str = "unknown"
7
+ self.type: str = ""
8
+ self.description: str = ""
9
+ self.repository: str = ""
10
+ self.github_stars: int = 0
11
+ self.downloads_total: int = 0
12
+ self.downloads_monthly: int = 0
13
+ self.downloads_daily: int = 0
14
+ self.license: list[str] = []
15
+ self.homepage: str = ""
16
+ self.zip: str = ""
17
+
18
+ def to_dict(self) -> dict:
19
+ return {
20
+ "name": self.name,
21
+ "version": self.version,
22
+ "latest": self.latest,
23
+ "status": self.status,
24
+ "type": self.type,
25
+ "description": self.description,
26
+ "repository": self.repository,
27
+ "github_stars": self.github_stars,
28
+ "downloads_monthly": self.downloads_monthly,
29
+ "licenses": ",".join(self.license),
30
+ }
@@ -0,0 +1,30 @@
1
+ import json
2
+ import os
3
+
4
+ from metripy.Dependency.Dependency import Dependency
5
+ from metripy.Dependency.Npm.NpmOrg import NpmOrg
6
+
7
+
8
+ class Npm:
9
+ def get_dependencies(self, path: str) -> list[Dependency]:
10
+ requirements = self._get_requirements(path)
11
+
12
+ npm_org = NpmOrg()
13
+ packages = []
14
+ for dependency in requirements:
15
+ package = npm_org.get_info(dependency)
16
+ packages.append(package)
17
+
18
+ return [item for item in packages if item is not None]
19
+
20
+ def _get_requirements(self, path: str) -> list[Dependency]:
21
+ requirements = []
22
+ with open(os.path.join(path, "package.json"), "r") as file:
23
+ package_json = json.load(file)
24
+ dependencies = package_json.get("dependencies", None)
25
+ if dependencies is None:
26
+ return None
27
+ for name, version in dependencies.items():
28
+ requirements.append(Dependency(name, version))
29
+
30
+ return requirements