Giter Site home page Giter Site logo

cosmiconfig's Issues

Look in user's home even if not in the path

Hi! I started the following question on stylelint/stylelint#2479 discussing about ensure that the user's home is checked for configuration files.

The scenario is the following:
I have a 128gb mounted on my card reader. That card is never removed and that's why I place almost all my projects there.

As it isn't mounted inside the user's home it will fail to find the configuration on the user's home.

This is a small suggestion to double check the system's path to be sure it is checked. I didn't made a PR because I'm short in time at this moment to look the best place to change the code. If you guys agree it's a good idea, you can assign it to me and I'll look for it.

Double-check API

As of this morning I think I've built in all the features I thought were needed. I'm wondering if anybody has feedback on this API before I cut 1.0.

@jeddy3, @MoOx, @TrySound, @ai --- any thoughts? or anybody else you know that might be interested in using this so should check it out?

Error: ENOENT: no such file or directory

cosmiconfig().load('/non-existent.css')

When we run this code. we will get a error.

Error: ENOENT: no such file or directory, stat '/non-existent.css'
    at Error (native)

Some gulp plugin will modify file extension.
Such as gulp-stylus, will rename *.styl to *.css.

gulp.src([ '*.styl', '!_*.styl' ])
  .pipe(stylus(options.stylus)) // => will rename `*.styl` to `*.css`.
  .pipe(postcss(processors))  // => postcss plugin that dependence `cosmiconfig` will throw a error.

See: masaakim/stylefmt#236

js config is treated as yaml

Context: prettier/prettier#2908 (comment)

For example, module.exports = { foo: true } is parsed as { "module.exports = { foo": "true }" } while passing with its filename (myConfig.js), cosmiconfig should infer format based on its filename if there is no format provided instead of always tryAllParsing, which always try yaml parsing first.

something like:

https://github.com/davidtheclark/cosmiconfig/blob/ad33e75766c194eaa9f28df1d9688b3ce5a8e462/src/loadDefinedFile.js#L22

const format = options.format ||
  /\.(js)$/.test(filepath)
    ? "js"
    : /\.(json)$/.test(filepath)
      ? "json"
      : /\.(yml|yaml)$/.test(filepath) ? "yaml" : undefined;

switch (format) {

I originally want to send a PR directly but failed since there are too many expect error tests failed I have no idea how to fix them.

Allow searching in `~/.config/`

The more people who use cosmiconfig, the more dot files will be littered in the home dir.

Lots of other modules place their config in ~/.config dir, mine looks like this:

Autodesk
Last.fm       
QCAD            
deluge          
git             
hub             
karabiner       
menus           
sinopia         
xbuild
NuGet           
configstore            
gtk-2.0        
inkscape    
robomongo      
stetic          
yarn

Would be cool...

Consider dropping require-from-string

It seems that require-from-string doesn't allow for modular configuration, i.e. it's impossible to split the configuration in multiple files and export them in index.js.

Is there a specific reason for using it? Perhaps a simple require(filepath) is better (and it also supports loading json files from node v0.5.x)?

Support for rc files with extensions

I read about the latest ESLint release (http://eslint.org/blog/2015/11/eslint-v1.10.0-released/) and thought that what they're doing with rc file extensions would be worth mimicking.

The idea is that rc files would not have to be extensionless: if user adds an extension to the file (e.g. .stylelintrc.yaml), then they'll get syntax highlighting in their editor and more exact error stacks if there are syntax errors.

A globally-installed ESLint cannot find a locally-installed plugin

E:\work\cosmiconfig (master) ([email protected])
ฮป eslint .

Oops! Something went wrong! :(

ESLint couldn't find the plugin "eslint-plugin-node". This can happen for a couple different reasons:

1. If ESLint is installed globally, then make sure eslint-plugin-node is also installed globally. A globally-installed ESLint cannot find a locally-installed plugin.

2. If ESLint is installed locally, then it's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

    npm i eslint-plugin-node@latest --save-dev

If you still can't figure out the problem, please stop by https://gitter.im/eslint/eslint to chat with the team.

I think it's a bug: A globally-installed ESLint cannot find a locally-installed plugin.

If we can solve this problem in cosmiconfig, it might be possible to recommend eslint to load the configuration file with cosmiconfig.

Document differences from rc

  • Stops at the first found, instead of finding all and merging them.
  • Looks for package.json prop.
  • Loads JSON, YAML, and CommonJS.
  • A little more configurable (different file name expectations).
  • Built-in extends support.
  • Not as built for extension -- not such a low-level module.

Any others?

JS config never gets garbage collected.

I discovered this issue while trying to catch a memory leak in our build tool. The way cosmiconfig loads '.js' config prevents it from ever getting garbage collected, even if userland code no longer needs. require-from-string package creates a new Module record which then permanently stored in memory. You can see it with this sample:

const cosmiconfig = require('cosmiconfig');

const loadRC = require.resolve('cosmiconfig/lib/loadRc.js');

function loadOnce() {
    const explorer = cosmiconfig('example');
    return explorer.load(__dirname)
        .then(() => console.log(require.cache[loadRC].children.length))
}

let count = 1000;
function loop() {
    if (count > 0) {
        count--;
        loadOnce().then(loop);
    }
}

loop();

Provided there is a non-empty example.config.js nearby, you should see that require.cache[loadRC].children.length grows by 1 after every load and never gets cleaned up.

Pass in initial configuration object directly

Some users (like stylelint) may want to be able to pass in configuration object directly and take advantage of this module's extends support.

Probably should rename the current options.config to options.configPath and then use options.config for this.

Yarn fails to install

Yarn is a new package manager that competes with npm.

It apparently validates engines (on npm install equivalent), which cosmiconfig has set to 4. Since I'm on node:6, the install fails.

> yarn
yarn install v0.15.0
[2/4] ๐Ÿšš  Fetching packages...
error [email protected]: The engine "node" is incompatible with this module. Expected version "4".
error Found incompatible module

I'm happy to submit a PR for this if it's desired

Remove const for Safari and node.js 0.12 support

I saw that there is const in this module code. PostCSS will use postcss-load-config, so it will have cosmiconf in dependencies.

And here we have few problems:

  • lack node.js 0.12 support. It is not a big deal, because it will be depreacted soon.
  • lack of Safari support. Some users use PostCSS in client-side. Of course, cosmiconfig will not be executed in browser. But Safari will not even load JS with const.

Of course, we could ask client-side users to use Babel. But because problems are only with const, I think it is too complicated :). var is not so trendy, but it works and it is easy :).

@davidtheclark what do you think about it?

Flow types

@sudo-suhas How do you feel about adding Flow types?

I was thinking about adding JSDoc-style comments to more of the functions, but that got me thinking that adding Flow types would both document functions and help with type safety. Type checking might be especially helpful now that we have a bunch of functions that sometimes return Promises, sometimes don't.

If you aren't opposed, I could do that at some point today so we can include it in the 3.0 release.

Check --config argument

If user specifies a --config argument via the command line, we'd like to use that path (as rc does). It should be an absolute path. I imagine it would just end up passing that argument's value to loadDefinedPath().

More options

Followup to discussion in #9:

  • js (default true): if false, don't look for modulename.config.js.
  • rc (default: true): if false, don't look for.modulenamerc`.
  • packageProp (default: true): if false, don't look for property modulename in package.json files.
  • argv (default: true): if false, don't look for --config arguments

Docs: "down the file tree" => "up the file tree"

File trees, like many others in computing (1), usually grow upside-down ๐Ÿ˜‰ The root is typically referred to as the "top", and descending "down" the tree means moving into subfolders... e.g., see the wording used in http://www.linfo.org/directory_tree.html, https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/3/html/Step_by_Step_Guide/s1-navigating-cd.html, and https://www.ibm.com/support/knowledgecenter/ssw_aix_61/com.ibm.aix.cmds1/cd.htm (2).

Since cosmiconfig searches parent folders rather than subfolders for config files ("the search continues in ./, ../, ../../, ../../../, etc."), the conventional wording would be that it walks "up the file tree" -- or even more idiomatically, "up the directory tree".

(1) Family trees sometime grow this way too (but only the descendancy kind).
(2) Did anyone else know that cd - toggles back and forth between two directories?!

Features of configuration loader

  • StyleLint
    • plugins path look up. returns path string.
    • extends load and merge
    • ignoreFiles support
  • ESLint
    • plugins / extends path look up or load, returns path string or object.
    • ignore support
  • Babel
    • presets / plugins path look up or load, returns path string or object.
    • extends load and merge
    • ignore support
  • stylefmt
    • same with StyleLint

I found 4 suitable to use cosmiconfig to replace its own loader project.

If they are using cosmiconfig to load the configuration file, you can solve the common existence of these projects bug. such as; con't work in editor plugin

@eslint
@babel

How to handle stylelint's plugins

This is a rough one.

In order for stylelint to fully take advantage of this module, stylelint needs to be able to interpret plugins values in extended configs relative to the file that references them. This means that if Config A extends Config B, and Config B includes plugins, we can't resolve the plugins relative to Config A once everything has been merged: we have to resolve Config B's plugins as they load.

This seems like a special case ... but we really do need to enable stylelint or other modules that want similar plugin syntax to do what they want.

I see two options:

  1. Build in special support for plugins, such that plugin resolution is done within cosmiconfig, and the resultant configuration object somehow exposes absolute paths to all plugins referenced.

  2. Expose configuration objects to transforms as they load, which I imagine would have to be done with some event-style API, e.g.

    .on('load', function(result) { 
      result.config = transformConfig(result.config);
    });

Any ideas welcome.

Right now I'm kind of leaning towards option 1, because I think this feature might only be required for plugins, so why build in more flexibility than necessary.

Version 2.2.0 and 2.2.2 break webpack build (Module build failed: TypeError: Invalid PostCSS Plugin found: [0])

Hello,

On previous week you have released version 2.2.0 which breaks our webpack build. Your revert in 2.2.1 fixed our problem but today I see that you publish version 2.2.2 which again breaks build.

Exception stack trace

[04:10:19]	Module build failed: TypeError: Invalid PostCSS Plugin found: [0]
[04:10:19]	/.../node_modules/postcss-load-plugins/lib/plugins.js:32:17
[04:10:19]       at Array.forEach (native)
[04:10:19]      (/.../node_modules/postcss-load-plugins/lib/plugins.js:21:15)
[04:10:19]      /.../node_modules/postcss-load-config/index.js:64:18

Versions of npm modules

[email protected]
[04:05:16]	[Step 1/2] โ”‚ โ”œโ”€โ”ฌ [email protected]
[04:05:16]	[Step 1/2] โ”‚ โ”‚ โ””โ”€โ”ฌ [email protected]
[04:05:16]	[Step 1/2] โ”‚ โ”‚ โ”œโ”€โ”ฌ [email protected]

https://github.com/michael-ciniawsky/postcss-load-config/blob/master/package.json

Thanks

Support .config/config folder lookup

๐Ÿ‘‹ @davidtheclark

@postcss-loader got a few requests to support setting a custom config path for postcss.config.js lookup and most of the folks especially wanted to store them in a separate .config/config folder somewhere in their project.

While thats totally fine and works for now, on the other hand it ignores/devalues the reason/benefit behind actually autoloading the config without the need for any additional 'setup' ๐Ÿ˜› . So maybe there is a compromise possible to enable additional search in .config/config folders while walking the file tree.

|โ€“ (.)config(<---)
|   |โ€“ postcss.config.js
|โ€“ client
|   |โ€“ (.)config (<---)
|   |   |โ€“ postcss.config.js 
|   |โ€“ styles
|        |โ€“ index.css (search starts here)
|        |โ€“ postcss.config.js (supported)
|โ€“ gulpfile.js
|โ€“ webpack.config.js

If you are basically ok with it, but don't have the time/interest to do it, coordinating me to the location in the source for getting started would be appreciated :)

cc @ai

Silently failing

I have the following code block:

const config = require('cosmiconfig');

const flatten = (key, source, rules) => {
    config('weblo')
        .load(null, `${process.cwd()}/package.json`)
        .then(result => {
            // Never hit
           console.log('hit');
        }).catch(err => {
            // Also never hit
            console.log(err);
        });

    // Hit straight away
    console.log( 'end');

};

module.exports = flatten;

If I pass anything invalid to load() it falls over, I have also tried passing nothing through, passing just process.cwd() through but ideally I do just want to read from the package.json hence trying to load the configPath as opposed to the searchPath. I have tried debugging but with silent output there is not too much I can do.

Sorry JS skills are a little limited so can't provide much more info.

Cheers.

Synchronous API

Hi, I'm the author of stylefmt. I use rc-loader to find stylelint configration file, so it cannot match .stylelint.config.js.

I tried to introduce cosmiconfig, but it has only an asynchronouse API to find files.
Do you have a plan to add synchronouse API?
If you have the plan, I can fix this bug easily :)

Thanks.

Support `config` key in package.json

I know we currently support the module name directly in package.json. But I think it would make things more organized if we also supported by default inside of a config property. Like this:

{
  "name""soursock",
  "version": "1.0.0",
  "config": {
    "soursock": {}
  }
}

Should `ENOENT` be suppressed when looking up a non-existent location?

Ref: postcss/postcss-cli#122

cosmiconfig will throw an error when trying to resolve config from a postcss-cli input coming in from stdin. This is because the filepath is set to whatever the process.cwd() is plus stdin (e.g. /path/to/project/stdin).

I noticed that the current isDirectory function in https://github.com/davidtheclark/cosmiconfig/blob/de81cf6f4bd8f18f4c36255b8a9f13733e3cc7f7/lib/createExplorer.js#L100 doesn't make any exception for ENOENT type errors, however the utility is-directory from npm does. Do you see any problems with migrating to is-directory instead?

Using external files with --config option - does it work?

I'm confused about how this is meant to work.

I am setting a path to an external config file with a --config command line argument e.g.

--config=/etc/path/to/config/file.conf

I can see this is initially working, in that it is setting a property within cosmiconfig's options variable in index.js to the correct value:

options.configPath = path.resolve(parsedCliArgs[options.argv]);

But, how are you mean to actually load that file? Because when you call the load() method, there's no need to specify searchPath (because the location is fixed), and you can't specify configPath (because only cosmiconfig knows what it got from the command line argument). And you have to specify one or the other, or load() just resolves with null.

I have been through the code and I can't see anywhere that actually uses the .configPath property. So even if I do something like

conf.load(process.cwd())

It's presumably just going to behave in the standard way, and ignore the --config setting.

I must be missing something obvious!

On a probably unrelated note, putting --config aside for the moment. Why can't you just call load() with no arguments and have it default to process.cwd()?

Duplicate keys throw an error with an unhelpful message

I am working on stylelint webpack plugin and I think it would be appropriate for stylelint itself to inform users that they have duplicate keys in their .stylelintrc. I have been trying to get a PR going but I haven't had success running the tests on master yet.

Raising the issue here because I don't think that it's difficult to fix but I'm kinda blocked right now.

Allow extends

An option allowExtends could enable extending.

The model I have in mind is https://github.com/stylelint/stylelint/blob/master/src/postcssPlugin.js#L69. Hopefully we can avoid using require() directly, though, because it is synchronous. Open to other implementation ideas, of course, if they are comparably simple.

Whatever the implementation, key requirements are:

  • extend configurations of JSON or YAML format.
  • extends accepts a single string or an array of strings.
  • extends lookups can be absolute or relative paths, or a node_module name.
  • merging of extends occurs in the order of the array, so the last item takes priority over the first item (merges on top of it).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.