forked from gemfileparser/gemfileparser
-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path__init__.py
More file actions
248 lines (203 loc) · 7.57 KB
/
Copy path__init__.py
File metadata and controls
248 lines (203 loc) · 7.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
#!/usr/bin/env python
#
# Copyright (c) Balasankar C <[email protected]> and others
# SPDX-License-Identifier: GPL-3.0-or-later OR MIT
"""
Python library to parse Ruby Gemfiles, gemspec and Cocoapods podspec files.
"""
import collections
import csv
import glob
import io
import os
import re
TRACE = False
def logger_debug(*args):
pass
if TRACE:
import logging
import sys
logger = logging.getLogger(__name__)
logging.basicConfig(stream=sys.stdout)
logger.setLevel(logging.DEBUG)
def logger_debug(*args):
return logger.debug(' '.join(isinstance(a, str) and a or repr(a) for a in args))
logger_debug = print
class Dependency(object):
"""
A class to hold information about a dependency gem.
"""
def __init__(self):
self.name = ""
self.requirement = []
self.autorequire = ""
self.source = ""
self.parent = []
self.group = ""
def to_dict(self):
return dict(
name=self.name,
requirement=self.requirement,
autorequire=self.autorequire,
source=self.source,
parent=self.parent,
group=self.group,
)
class GemfileParser(object):
"""
Create a GemfileParser object to perform operations.
"""
gemfile_regexes = collections.OrderedDict()
gemfile_regexes["source"] = re.compile(r"source:[ ]?(?P<source>[a-zA-Z:\/\.-]+)")
gemfile_regexes["git"] = re.compile(r"git:[ ]?(?P<git>[a-zA-Z:\/\.-]+)")
gemfile_regexes["platform"] = re.compile(r"platform:[ ]?(?P<platform>[a-zA-Z:\/\.-]+)")
gemfile_regexes["path"] = re.compile(r"path:[ ]?(?P<path>[a-zA-Z:\/\.-]+)")
gemfile_regexes["branch"] = re.compile(r"branch:[ ]?(?P<branch>[a-zA-Z:\/\.-]+)")
gemfile_regexes["autorequire"] = re.compile(r"require:[ ]?(?P<autorequire>[a-zA-Z:\/\.-]+)")
gemfile_regexes["group"] = re.compile(r"group:[ ]?(?P<group>[a-zA-Z:\/\.-]+)")
gemfile_regexes["name"] = re.compile(r"(?P<name>[a-zA-Z]+[\.0-9a-zA-Z _-]*)")
gemfile_regexes["requirement"] = re.compile(
r"(?P<requirement>([>|<|=|~>|\d]+[ ]*[0-9\.\w]+[ ,]*)+)"
)
group_block_regex = re.compile(r"group[ ]?:[ ]?(?P<groupblock>.*?) do")
gemspec_add_dvtdep_regex = re.compile(r".*add_development_dependency(?P<line>.*)")
gemspec_add_rundep_regex = re.compile(r".*add_runtime_dependency(?P<line>.*)")
gemspec_add_dep_regex = re.compile(r".*add_dependency(?P<line>.*)")
def __init__(self, filepath, appname=""):
self.filepath = filepath
self.current_group = "runtime"
self.appname = appname
self.dependencies = {
"development": [],
"runtime": [],
"dependency": [],
"test": [],
"production": [],
"metrics": [],
}
with open(filepath) as gf:
self.contents = gf.readlines()
self.gemspec = filepath.endswith((".gemspec", ".podspec"))
@staticmethod
def preprocess(line):
"""
Remove the comment portion and excess spaces.
"""
if "#" in line:
line = line[: line.index("#")]
line = line.strip()
return line
def parse_line(self, line):
"""
Parse a line and return a Dependency object.
"""
# csv requires a file-like object
linefile = io.StringIO(line)
for line in csv.reader(linefile, delimiter=","):
column_list = []
for column in line:
stripped_column = (
column.replace("'", "")
.replace('"', "")
.replace("%q<", "")
.replace("(", "")
.replace(")", "")
.replace("[", "")
.replace("]", "")
.replace(".freeze", "")
.strip()
)
column_list.append(stripped_column)
dep = Dependency()
dep.group = self.current_group
dep.parent.append(self.appname)
for column in column_list:
# Check for a match in each regex and assign to
# corresponding variables
for criteria, criteria_regex in GemfileParser.gemfile_regexes.items():
match = criteria_regex.match(column)
if match:
if criteria == "requirement":
dep.requirement.append(match.group(criteria))
else:
setattr(dep, criteria, match.group(criteria))
break
if dep.group in self.dependencies:
self.dependencies[dep.group].append(dep)
else:
self.dependencies[dep.group] = [dep]
def parse_gemfile(self):
"""
Parse a Gemfile and returns a mapping of categorized dependencies.
"""
for line in self.contents:
line = self.preprocess(line)
if line == "" or line.startswith("source"):
continue
elif line.startswith("group"):
match = self.group_block_regex.match(line)
if match:
self.current_group = match.group("groupblock")
elif line.startswith("end"):
self.current_group = "runtime"
elif line.startswith("gemspec"):
# Gemfile contains a call to gemspec
gemfiledir = os.path.dirname(self.filepath)
gemspec_list = glob.glob(os.path.join(gemfiledir, "*.gemspec"))
if not gemspec_list:
logger_debug(f"No gemspec files found: {gemspec_list}")
continue
if len(gemspec_list) > 1:
logger_debug("Multiple gemspec files found")
continue
gemspec_file = gemspec_list[0]
# FIXME: the path is not used
self.parse_gemspec(path=os.path.join(gemfiledir, gemspec_file))
elif line.startswith("gem "):
line = line[3:]
self.parse_line(line)
return self.dependencies
def parse_gemspec(self, path=None):
"""
Parse a .gemspec or .podspec and return a mapping of categorized
dependencies.
"""
for line in self.contents:
line = self.preprocess(line)
match = self.gemspec_add_dvtdep_regex.match(line)
if match:
self.current_group = "development"
else:
match = self.gemspec_add_rundep_regex.match(line)
if match:
self.current_group = "runtime"
else:
match = self.gemspec_add_dep_regex.match(line)
if match:
self.current_group = "dependency"
if match:
line = match.group("line")
self.parse_line(line)
return self.dependencies
def parse(self):
"""
Return a mapping of dependencies parsed from the Gemfile or gemspec.
"""
if self.gemspec:
return self.parse_gemspec()
else:
return self.parse_gemfile()
def command_line():
"""
A minimal command line entry point.
"""
import sys
if len(sys.argv) < 2:
print("Usage : parsegemfile <input file>")
sys.exit(0)
parsed = GemfileParser(sys.argv[1])
output = parsed.parse()
for key, value in list(output.items()):
print(key, ":")
for item in value:
print("\t", item)