Skip to content

Commit

Permalink
Searching google and final version
Browse files Browse the repository at this point in the history
  • Loading branch information
Nick Tikhonov committed Aug 18, 2016
1 parent 039a1e1 commit aa9d0b5
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
34 changes: 31 additions & 3 deletions lib/sourcefetch.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 {

Expand All @@ -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()
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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.