.gitignore added
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-prettier / node_modules / cosmiconfig / dist / loadDefinedFile.js
1 //      
2 'use strict';
3
4 const yaml = require('js-yaml');
5 const requireFromString = require('require-from-string');
6 const readFile = require('./readFile');
7 const parseJson = require('./parseJson');
8 const path = require('path');
9
10 module.exports = function loadDefinedFile(
11   filepath        ,
12   options   
13                    
14                                     
15    
16 )                                                     {
17   function parseContent(content         )                      {
18     if (!content) {
19       throw new Error(`Config file is empty! Filepath - "${filepath}".`);
20     }
21
22     let parsedConfig;
23
24     switch (options.format || inferFormat(filepath)) {
25       case 'json':
26         parsedConfig = parseJson(content, filepath);
27         break;
28       case 'yaml':
29         parsedConfig = yaml.safeLoad(content, {
30           filename: filepath,
31         });
32         break;
33       case 'js':
34         parsedConfig = requireFromString(content, filepath);
35         break;
36       default:
37         parsedConfig = tryAllParsing(content, filepath);
38     }
39
40     if (!parsedConfig) {
41       throw new Error(`Failed to parse "${filepath}" as JSON, JS, or YAML.`);
42     }
43
44     return {
45       config: parsedConfig,
46       filepath,
47     };
48   }
49
50   return !options.sync
51     ? readFile(filepath, { throwNotFound: true }).then(parseContent)
52     : parseContent(readFile.sync(filepath, { throwNotFound: true }));
53 };
54
55 function inferFormat(filepath        )          {
56   switch (path.extname(filepath)) {
57     case '.js':
58       return 'js';
59     case '.json':
60       return 'json';
61     // istanbul ignore next
62     case '.yml':
63     case '.yaml':
64       return 'yaml';
65     default:
66       return undefined;
67   }
68 }
69
70 function tryAllParsing(content        , filepath        )          {
71   return tryYaml(content, filepath, () => {
72     return tryRequire(content, filepath, () => {
73       return null;
74     });
75   });
76 }
77
78 function tryYaml(content        , filepath        , cb               ) {
79   try {
80     const result = yaml.safeLoad(content, {
81       filename: filepath,
82     });
83     if (typeof result === 'string') {
84       return cb();
85     }
86     return result;
87   } catch (e) {
88     return cb();
89   }
90 }
91
92 function tryRequire(content        , filepath        , cb               ) {
93   try {
94     return requireFromString(content, filepath);
95   } catch (e) {
96     return cb();
97   }
98 }