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

Allow filename to be a function #21

Closed
sholladay opened this issue Mar 17, 2018 · 1 comment · Fixed by #28
Closed

Allow filename to be a function #21

sholladay opened this issue Mar 17, 2018 · 1 comment · Fixed by #28

Comments

@sholladay
Copy link
Collaborator

Opening this so the result of our discussion in PR #18 is more discoverable.

Story

As a user searching for a file or directory, I want to limit the search to a specific area of the filesystem so that my app only considers files that are relevant to its operation and cannot accidentally find files above a certain project root that happen to be named similarly to the intended file.

As a user searching for a file or directory, I want to dynamically decide which filepaths match based on custom business logic beyond just the filename, so that I can do things like match a file only if it has a certain sibling file in the same directory.

Implementation

We will add a new call signature where the filename argument can be a function.

Below, we return the first data.json file that we encounter that is undocumented, meaning one that does not have a README.md file in the same directory. If that precise combination does not exist anywhere in the search path, then as per usual, we keep searching and eventually return null when we hit the root of the filesystem.

const undocumentedFile = await findUp((dir) => {
    return !path.existsSync(path.join(dir, 'README.md')) && path.existsSync(path.join(dir, 'data.json')) && 'data.json';
});

If the function returns a truthy string, it will be resolved against dir. This means the function can match the directory simply by returning dir, because dir is always an absolute path. Below, we return the first directory that contains a .gitignore file.

const dirWithIgnore = await findUp((dir) => {
    return path.existsSync(path.join(dir, '.gitignore')) && dir;
});
@sholladay
Copy link
Collaborator Author

There was also the idea of using an ES6 Symbol as a way to return the directory itself, because it would be more readable than returning true or '.'. But then I realized the user could just return dir if we resolve it rather than join it. That seems preferable to me.

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

Successfully merging a pull request may close this issue.

2 participants