Class: SL::GitHubSearch

Inherits:
Object
  • Object
show all
Defined in:
lib/searchlink/searches/github.rb

Overview

GitHub search

Class Method Summary collapse

Class Method Details

.filter_gists(gists, search_terms) ⇒ Object



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
# File 'lib/searchlink/searches/github.rb', line 168

def filter_gists(gists, search_terms)
  return false if gists.is_a?(Hash)

  score = 0
  gists.map! do |g|
    {
      url: g["html_url"],
      description: g["description"],
      files: g["files"].map { |file, info| { filename: file, raw: info["raw_url"] } }
    }
  end
  matches = []
  gists.each do |g|
    if g.key?(:files)
      g[:files].each do |f|
        next unless f[:filename]

        score = f[:filename].matches_score(search_terms.gsub(/[^a-z0-9]/, " "))

        if score > 5
          url = "#{g[:url]}#file-#{f[:filename].gsub(/\./, '-')}"
          matches << { url: url, title: f[:filename], score: score }
        end
      end
    end

    score = g[:description].nil? ? 0 : g[:description].matches_score(search_terms.gsub(/[^a-z0-9]/, " "))
    matches << { url: g[:url], title: g[:files][0][:filename], score: score } if score > 5
  end

  return false if matches.empty?

  matches.max_by { |m| m[:score] }
end

.gist(terms, type, link_text) ⇒ Object



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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# File 'lib/searchlink/searches/github.rb', line 203

def gist(terms, type, link_text)
  terms.strip!
  case terms
  # If an id (and optional file) are given, expand it to include username an generate link
  when %r{^(?<id>[a-z0-9]{32}|[0-9]{6,10})(?:[#/](?<file>(?:file-)?.*?))?$}
    m = Regexp.last_match
    res = Curl::Html.new("https://gist.github.com/#{m['id']}", headers_only: true)
    url = res.headers["location"]
    title = SL::URL.title(url)

    url = "#{url}##{m['file']}" if m["file"]
  # If a user an id (an o) are given, convert to a link
  when %r{^(?<u>\w+)/(?<id>[a-z0-9]{32}|[0-9]{6,10})(?:[#/](?<file>(?:file-)?.*?))?$}
    m = Regexp.last_match
    url = "https://gist.github.com/#{m['u']}/#{m['id']}"
    title = SL::URL.title(url)

    url = "#{url}##{m['file']}" if m["file"]
  # if a full gist URL is given, simply clean it up
  when %r{(?<url>https://gist.github.com/(?:(?<user>\w+)/)?(?<id>[a-z0-9]{32}|[0-9]{6,10}))(?:[#/](?<file>(?:file-)?.*?))?$}
    m = Regexp.last_match
    url = m["url"]
    title = SL::URL.title(url)

    url = "#{url}##{m['file']}" if m["file"]
  # Otherwise do a search of gist.github.com for the keywords
  else
    if terms.split(/ +/).count > 1
      parts = terms.split(/ +/)
      gist = search_user_gists(parts[0], parts[1..].join(" "))

      if gist
        url = gist[:url]
        title = gist[:title]
      else
        url, title, link_text = SL.ddg("site:gist.github.com #{terms}", link_text)
      end
    else
      url, title, link_text = SL.ddg("site:gist.github.com #{terms}", link_text)
    end
  end

  # Assuming we retrieved a full gist URL
  if url && url =~ %r{https://gist.github.com/(?:(?<user>[^/]+)/)?(?<id>[a-z0-9]+?)(?:[#/](?<file>(?:file-)?.*?))?$}
    m = Regexp.last_match
    user = m["user"]
    id = m["id"]

    # If we're trying to create an embed, convert elements to a JS embed script
    if type =~ /e$/
      url = if m["file"]
              "https://gist.github.com/#{user}/#{id}.js?file=#{m['file'].fix_gist_file}"
            else
              "https://gist.github.com/#{user}/#{id}.js"
            end

      ["embed", %(<script src="#{url}"></script>), link_text]
    else
      [url, title, link_text]
    end
  else
    [false, title, link_text]
  end
end

.github(search_terms, link_text) ⇒ Object



91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# File 'lib/searchlink/searches/github.rb', line 91

def github(search_terms, link_text)
  terms = search_terms.split(%r{[ /]+})
  # SL.config['remove_seo'] = false

  url = case terms.count
        when 2
          "https://github.com/#{terms[0]}/#{terms[1]}"
        when 1
          "https://github.com/#{terms[0]}"
        else
          nurl, title, link_text = SL.ddg("site:github.com #{search_terms}", link_text)
          nurl
        end

  if SL::URL.valid_link?(url)
    title = SL::URL.title(url) if url && title.nil?

    [url, title, link_text]
  else
    SL.notify("Searching GitHub", "Repo not found, performing search")
    search_github(search_terms, link_text)
  end
end

.github_search_curl(endpoint, query) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/searchlink/searches/github.rb', line 47

def github_search_curl(endpoint, query)
  headers = {
    "Accept" => "application/vnd.github+json",
    "X-GitHub-Api-Version" => "2022-11-28"
  }
  headers["Authorization"] = "Bearer #{@auth_token}" if defined? @auth_token

  url = "https://api.github.com/search/#{endpoint}?q=#{query.url_encode}&per_page=1&page=1&order=desc"
  res = Curl::Json.new(url, headers: headers)

  if res.json.key?("total_count") && res.json["total_count"].positive?
    res.json["items"][0]
  else
    false
  end
end

.github_user(search_terms, link_text) ⇒ Object



115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/searchlink/searches/github.rb', line 115

def github_user(search_terms, link_text)
  if search_terms.split(/ /).count > 1
    query = %(#{search_terms} in:name)
    res = github_search_curl("users", query)
  else
    query = %(user:#{search_terms})
    res = github_search_curl("users", query)
    res ||= github_search_curl("users", search_terms)
  end

  if res
    url = res["html_url"]
    title = res["login"]

    [url, title, link_text]
  else
    [false, false, link_text]
  end
end

.search(search_type, search_terms, link_text) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/searchlink/searches/github.rb', line 27

def search(search_type, search_terms, link_text)
  @auth_token = Secrets::GH_AUTH_TOKEN if defined? Secrets::GH_AUTH_TOKEN
  @auth_token = SL.config["github_token"] if SL.config.key?("github_token") && !SL.config["github_token"].empty?

  case search_type
  when /^gist/
    url, title, link_text = gist(search_terms, search_type, link_text)
  when /^ghu$/
    url, title, link_text = github_user(search_terms, link_text)
  else
    url, title, link_text = github(search_terms, link_text)
  end

  return SL.ddg("site:github.com #{search_terms}", link_text) unless url

  link_text = title if link_text == "" || link_text == search_terms

  [url, title, link_text]
end

.search_github(search_terms, link_text) ⇒ Object



135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/searchlink/searches/github.rb', line 135

def search_github(search_terms, link_text)
  replacements = [
    [%r{(\S+)/(\S+)}, 'user:\1 \2'],
    [/\bu\w*:(\w+)/, 'user:\1'],
    [/\bl\w*:(\w+)/, 'language:\1'],
    [/\bin?:r\w*/, "in:readme"],
    [/\bin?:t\w*/, "in:topics"],
    [/\bin?:d\w*/, "in:description"],
    [/\bin?:(t(itle)?|n(ame)?)/, "in:name"],
    [/\br:/, "repo:"]
  ]

  replacements.each { |r| search_terms.gsub!(r[0], r[1]) }

  search_terms += " in:title" unless search_terms =~ /(in|user|repo):/

  res = github_search_curl("repositories", search_terms)

  return false unless res

  url = res["html_url"]
  title = res["description"] || res["full_name"]
  [url, title, link_text]
end

.search_user_gists(user, search_terms) ⇒ Object



160
161
162
163
164
165
166
# File 'lib/searchlink/searches/github.rb', line 160

def search_user_gists(user, search_terms)
  best_gist = user_gists(user, search_terms, 1)

  return false unless best_gist

  best_gist
end

.settingsObject



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/searchlink/searches/github.rb', line 7

def settings
  {
    trigger: "(?:giste?|ghu?)",
    searches: [
      ["gh", "GitHub User/Repo Link"],
      ["ghu", "GitHub User Search"],
      ["gist", "Gist Search"],
      ["giste", "Gist Embed"]
    ],
    config: [
      {
        key: "github_token",
        value: "github_patxxxxxxx",
        require: false,
        description: "GitHub Personal Access Token (optional)"
      }
    ]
  }
end

.user_gists(user, search_terms, page = 1) ⇒ Object



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
# File 'lib/searchlink/searches/github.rb', line 64

def user_gists(user, search_terms, page = 1)
  headers = {
    "Accept" => "application/vnd.github+json",
    "X-GitHub-Api-Version" => "2022-11-28"
  }
  headers["Authorization"] = "Bearer #{Secrets::GH_AUTH_TOKEN}" if defined? Secrets::GH_AUTH_TOKEN

  url = "https://api.github.com/users/#{user}/gists?per_page=100&page=#{page}"

  res = Curl::Json.new(url, headers: headers).json

  if res.is_a?(Hash) && res["status"].to_i == 401
    SL.notify("Error", "Bad GitHub credentials")
    return nil
  end

  best = nil
  best = filter_gists(res, search_terms) if res

  if !best && res.count == 100
    SL.notify("Paging", "Getting page #{page + 1} of #{user} gists")
    best = user_gists(user, search_terms, page + 1)
  end

  best
end