forked from EnerfisTeam/enectiva-web
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheck_for_missing_links.rb
241 lines (196 loc) · 5.72 KB
/
check_for_missing_links.rb
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
require 'net/http'
require 'set'
scheme = 'http'
host = 'energyanalytics.eu'
base_url = '/cs/o-enective'
locales_to_ignore = [:ru, :sk]
# Used to filter out paths which are not expected to be translated, must match anywhere in the path
snippets_to_skip = %w(/blog /password /login /media)
def parse_redirect(scheme, host, url, response)
location = response['location']
match = location.match "#{scheme}://#{host}(.+)"
if match
match[1]
else
location
end
end
def fetch_html(scheme, host, location, limit = 10)
# You should choose better exception.
raise ArgumentError, 'HTTP redirect too deep' if limit == 0
url = URI.parse("#{scheme}://#{host}#{location}")
req = Net::HTTP::Get.new(url.path)
response = Net::HTTP.start(url.host, url.port) { |http| http.request(req) }
case response
when Net::HTTPSuccess then response.body
when Net::HTTPRedirection then fetch_html(scheme, host, parse_redirect(scheme, host, url, response), limit - 1)
else
response.error!
end
end
def extract_urls(context, html, snippets_to_skip)
# Find all href attributes
urls = html.scan(/href=["'](.+?)["']/).flatten
# Filter out links to specific extension (assets)
urls = urls.find_all do |url|
if url.match /\..{2,3}$/
false
elsif url.match /^http/
false
elsif url.length == 3 # Only base locale
false
elsif url.match Regexp.new snippets_to_skip.join '|'
false
else
true
end
end.map do |url| # Prepend relative URLs by current context
if url[0] == '/'
url
else
"#{context}/#{url}"
end
end.map do |url| # Strip #link
match = url.match /(.+)#(.+)$/
if match
match[1]
else
url
end
end
Set.new urls
end
def extract_translations(url, html)
links = html.scan(/<a.+?(?:href=['"](.+?)['"])?.+?hreflang=['"](.+?)['"].+?(?:href=['"](.+?)['"])?.+?>/)
translations = {}
links.each do |link|
translations[link[1].to_sym] = link[0] || link[2]
end
if links
{
url: url,
locale: url.split('/')[1].to_sym,
translations: translations
}
else
nil
end
end
errors = []
urls_processed = Set.new
urls_to_process = Set.new [base_url]
localized_paths = {}
i = 1
until urls_to_process.empty?
# Get one URL
url = urls_to_process.take(1).first
urls_to_process.delete(url)
# Mark URL as processed
urls_processed << url
puts "Iteration #{i}, running #{url}, processed: #{urls_processed.size}, still left to process: #{urls_to_process.size}"
# Fetch HTML
begin
html = fetch_html scheme, host, url
rescue Net::HTTPServerException => e
errors << {
url: url,
exception: e
}
end
# Extract all links
links = extract_urls(url, html, snippets_to_skip)
# Add non-visited links to the list
urls_to_process.merge (links - urls_processed)
# Extract links to other translations of this page
translations = extract_translations url, html
if translations
localized_paths[url] = translations
end
i += 1
# break if i == 10
end
def identify_locales(paths, locales_to_ignore)
paths.map { |_, p| p[:locale] }.uniq - locales_to_ignore
end
# Count locales which were linked at least once
locales_encountered = identify_locales localized_paths, locales_to_ignore
locales_count = locales_encountered.count
puts "Found #{locales_count} locales: #{locales_encountered.join ', '}, ignored: #{locales_to_ignore.join ', '}"
# Segment localized_paths into interlinking groups
groups = []
until localized_paths.empty?
group = []
paths_in_group = Set.new [localized_paths.first[0]]
processed_in_group = Set.new []
until paths_in_group.empty?
path = paths_in_group.take(1).first
paths_in_group.delete(path)
processed_in_group << path
translation = localized_paths.delete path
next if translation.nil?
group << translation
paths_in_group.merge(Set.new(translation[:translations].values) - processed_in_group)
end
groups << group
end
def check_group_for_completeness(group, locales)
paths = group.map { |p| p[:url] }.sort
locales_in_group = group.map { |p| p[:locale] }
if locales_in_group != locales
(locales - locales_in_group).each do |missing_locale|
paths << "/#{missing_locale}/???"
end
end
links = {}
group.each { |p| links[p[:url]] = p[:translations].values }
links_present = []
paths.count.times do |i|
links_present[i] = Array.new(paths.count, nil)
end
paths.each_with_index do |row_path, i|
paths.each_with_index do |col_path, j|
links_present[i][j] = if row_path == col_path
nil
elsif not links.key? row_path
false
else
links[row_path].include? col_path
end
end
end
{
complete: !links_present.flatten.include?(false),
matrix: links_present,
paths: paths
}
end
def print_row(length, row)
format = "%-#{length}s"
x = row.map do |cell|
format % cell
end
puts x.join ' | '
end
def print_line(length, cols)
print_row length, cols.times.map { (length).times.map { '-' }.join '' }
end
def print_formatted_matrix(group)
length = group[:paths].map { |p| p.length }.max
puts ''
puts ''
print_row length, ['row -> col'] + group[:paths]
print_line length, group[:paths].count + 1
group[:paths].each_with_index do |path, i|
print_row length, [path] + group[:matrix][i]
end
end
puts "Found #{groups.count} groups, only incomplete will be printed"
groups.each do |group|
group = check_group_for_completeness group, locales_encountered
next if group[:complete]
print_formatted_matrix group
end
puts "Errors encountered:"
errors.each do |error|
puts "\t#{error[:url]}: #{error[:exception]}"
end