Permalink
Browse files

Searching google and final version

  • Loading branch information...
NickTikhonov committed Aug 18, 2016
1 parent 039a1e1 commit aa9d0b5fc4811a70292869730e0f60ddf0bcf2aa
Showing with 32 additions and 3 deletions.
  1. +31 −3 lib/sourcefetch.js
  2. +1 −0 package.json
View
@@ -3,6 +3,9 @@
import { CompositeDisposable } from 'atom'
import request from 'request'
import cheerio from 'cheerio'
import google from 'google'
google.resultsPerPage = 1
export default {
@@ -25,21 +28,46 @@ export default {
let self = this
if (editor = atom.workspace.getActiveTextEditor()) {
let selection = editor.getSelectedText()
this.download(selection).then((html) => {
let query = editor.getSelectedText()
let language = editor.getGrammar().name
self.search(query, language).then((url) => {
atom.notifications.addSuccess('Found google results!')
return self.download(url)
}).then((html) => {
let answer = self.scrape(html)
if (answer === '') {
atom.notifications.addWarning('No answer found :(')
} else {
atom.notifications.addSuccess('Found snippet!')
editor.insertText(answer)
}
}).catch((error) => {
console.log(error)
atom.notifications.addWarning(error.reason)
})
}
},
search(query, language) {
return new Promise((resolve, reject) => {
let searchString = `${query} in ${language} site:stackoverflow.com`
google(searchString, (err, res) => {
if (err) {
reject({
reason: 'A search error has occured :('
})
} else if (res.links.length === 0) {
reject({
reason: 'No results found :('
})
} else {
resolve(res.links[0].href)
}
})
})
},
scrape(html) {
$ = cheerio.load(html)
return $('div.accepted-answer pre code').text()
View
@@ -14,6 +14,7 @@
},
"dependencies": {
"cheerio": "^0.20.0",
"google": "^2.0.0",
"request": "^2.73.0"
}
}

0 comments on commit aa9d0b5

Please sign in to comment.