Skip to content

Commit

Permalink
Fix npm#1673 Support for regexps in search
Browse files Browse the repository at this point in the history
  • Loading branch information
isaacs committed Dec 3, 2011
1 parent beeb7fd commit 7d5fc66
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
3 changes: 3 additions & 0 deletions doc/cli/search.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ npm-search(1) -- Search for packages

Search the registry for packages matching the search terms.

If a term starts with `/` and ends with `/`, then it's interpreted as a
regular expression.

## CONFIGURATION

### description
Expand Down
27 changes: 21 additions & 6 deletions lib/search.js
Original file line number Diff line number Diff line change
Expand Up @@ -108,16 +108,22 @@ function getWords (data) {
function filterWords (data, args, notArgs) {
var words = data.words
for (var i = 0, l = args.length; i < l; i ++) {
if (words.indexOf(args[i]) === -1) {
return false
}
if (!match(words, args[i])) return false
}
for (var i = 0, l = notArgs.length; i < l; i ++) {
if (words.indexOf(notArgs[i]) !== -1) return false
if (match(words, notArgs[i])) return false
}
return true
}

function match (words, arg) {
if (arg.charAt(0) === "/" && arg.slice(-1) === "/") {
arg = new RegExp(arg.substr(1, arg.length - 2))
return words.match(arg)
}
return words.indexOf(arg) !== -1
}

function prettify (data, args) {
try {
var tty = require("tty")
Expand Down Expand Up @@ -201,8 +207,17 @@ function addColorMarker (str, arg, i) {
var m = i % cl + 1
, markStart = String.fromCharCode(m)
, markEnd = String.fromCharCode(0)
, pieces = str.toLowerCase().split(arg.toLowerCase())

if (arg.charAt(0) === "/" && arg.slice(-1) === "/") {
return str.replace( new RegExp(arg.substr(1, arg.length - 2), "gi")
, function (bit) { return markStart + bit + markEnd } )

}

// just a normal string, do the split/map thing
var pieces = str.toLowerCase().split(arg.toLowerCase())
, p = 0

return pieces.map(function (piece, i) {
piece = str.substr(p, piece.length)
var mark = markStart
Expand All @@ -211,8 +226,8 @@ function addColorMarker (str, arg, i) {
p += piece.length + arg.length
return piece + mark
}).join("")
return str.split(arg).join(mark)
}

function colorize (line) {
for (var i = 0; i < cl; i ++) {
var m = i + 1
Expand Down

0 comments on commit 7d5fc66

Please sign in to comment.