Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 50 additions & 14 deletions lib/glob.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,34 +2,64 @@
constructor (glob) {
this.glob = glob

// If not a glob pattern then just match the string.
if (!this.glob.includes('*')) {
this.regexp = new RegExp(`.*${this.glob}.*`, 'u')
// For patterns without any wildcards, match them anywhere in the string
const hasWildcards = glob.includes('*') || glob.includes('?')

const hasNothingToEscape = escapeRegExp(glob) === glob

if (hasNothingToEscape) {
this.regexp = new RegExp(`\\b${glob}\\b`, 'u')
return
}
this.regexptText = this.globize(this.glob)
this.regexp = new RegExp(`^${this.regexptText}$`, 'u')
}

globize (glob) {
return glob
.replace(/\\/g, '\\\\') // escape backslashes
.replace(/\//g, '\\/') // escape forward slashes
.replace(/\./g, '\\.') // escape periods
.replace(/\?/g, '([^\\/])') // match any single character except /
.replace(/\*\*/g, '.+') // match any character except /, including /
.replace(/\*/g, '([^\\/]*)') // match any character except /
if (!hasWildcards) {
// Simple case: no wildcards, just do a simple substring match
this.regexp = new RegExp(escapeRegExp(glob), 'u')
return
}

// Handle wildcard patterns
let pattern

if (glob.includes('**')) {
// Handle ** which can match across directory boundaries
pattern = glob
.replace(/\*\*/g, '__GLOBSTAR__')
.replace(/\./g, '\\.')
.replace(/\//g, '\\/')
.replace(/\?/g, '.')
.replace(/\*/g, '[^\\/]*')
.replace(/__GLOBSTAR__/g, '.*')
} else {
// Handle patterns with * but not **
pattern = glob
.replace(/\./g, '\\.')
.replace(/\//g, '\\/')
.replace(/\?/g, '.')
.replace(/\*/g, '[^\\/]*')
}

// Handle character classes
pattern = pattern.replace(/\\\[([^\]]+)\\\]/g, '[$1]')

this.regexp = new RegExp(`^${pattern}$`, 'u')
}

toString () {
return this.glob
}

[Symbol.search] (s) {
console.log('regex patttern is ', this.regexp)
console.log('string to search is ', s)
console.log('string search result is ', s.search(this.regexp))
return s.search(this.regexp)
}

[Symbol.match] (s) {
console.log('regex patttern is ', this.regexp)
console.log('string to match is ', s)
console.log('string match result is ', s.match(this.regexp))
return s.match(this.regexp)
}

Expand All @@ -41,4 +71,10 @@
return s.replaceAll(this.regexp, replacement)
}
}

// Helper function to escape regular expression special chars
function escapeRegExp (string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}

module.exports = Glob