Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a way to generate a glob from a file name #227

Open
andreaskundig opened this issue Jan 10, 2022 · 1 comment
Open

Add a way to generate a glob from a file name #227

andreaskundig opened this issue Jan 10, 2022 · 1 comment

Comments

@andreaskundig
Copy link

I need to generate a valid glob that uniquely matches a filename.

For a file called ba[ra].foo the glob needs to escape the brackets like this: bar\[ra\].foo, in order to avoid matching files called baa.foo or bar.foo. There are enough other characters and expressions that need escaping that the task does not seem trivial.

Maybe the solution to this is as simple as a regex that you could add to the documentation.

@andreaskundig
Copy link
Author

andreaskundig commented Jan 11, 2022

Here's my solution, with some tests, but I don't know if this catches everything

export function convertPathToGlob(filePath) {
  if (!filePath) {
    throw new Error(`cannot create glob for file path "${filePath}"`)
  }
  return filePath.replace(/([[\]{}*!()])/g, '\\$1')
}

test('convertPathToGlob', () => {
  const testConversion = (path, glob, shouldNotMatch) => {
    expect(convertPathToGlob(path)).toBe(glob)
    expect(micromatch.isMatch(path, glob)).toBe(true)
    expect(micromatch.isMatch(path, convertPathToGlob(path))).toBe(true)
    expect(micromatch.isMatch(shouldNotMatch, glob)).toBe(false)
    expect(micromatch.isMatch(shouldNotMatch, path)).toBe(true)
  }
  testConversion('ba[r].foo', 'ba\\[r\\].foo', 'bar.foo')
  testConversion('ba[r-t].foo', 'ba\\[r-t\\].foo', 'bas.foo')
  testConversion('ba*.foo', 'ba\\*.foo', 'bar.foo')
  testConversion('!baa.foo', '\\!baa.foo', 'bar.foo')
  testConversion('*.!(a)', '\\*.\\!\\(a\\)', 'a.b')
  testConversion('foo/{a,b,c}/bar', 'foo/\\{a,b,c\\}/bar', 'foo/a/bar')
  testConversion('ba?(a).foo', 'ba?\\(a\\).foo', 'baa.foo')
  testConversion('ba*(a).foo', 'ba\\*\\(a\\).foo', 'baa.foo')
  testConversion('ba@(a).foo', 'ba@\\(a\\).foo', 'baa.foo')
  testConversion('ba+(a).foo', 'ba+\\(a\\).foo', 'baa.foo')
  testConversion('ba[[:alpha:]]', 'ba\\[\\[:alpha:\\]\\]', 'baa')
  testConversion(
    '{f,b}*/{1..3}/{b,q}*',
    '\\{f,b\\}\\*/\\{1..3\\}/\\{b,q\\}\\*',
    'foo/2/qux'
  )
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant