md-hopper 1.0.0-alpha → 1.0.0-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +20 -5
  2. package/cli/commands/generate/actions/link/package.json +6 -0
  3. package/cli/commands/generate/actions/rc/package.json +6 -0
  4. package/cli/commands/link/README.md/package.json +6 -0
  5. package/cli/commands/link/action/package.json +6 -0
  6. package/cli/commands/link/command/package.json +6 -0
  7. package/dist/_internal/types/command.d.ts +3 -5
  8. package/dist/_internal/types/configs/generate.d.ts +46 -0
  9. package/dist/_internal/types/configs/generate.js +131 -0
  10. package/dist/_internal/types/configs/help.d.ts +2 -0
  11. package/dist/_internal/types/configs/links.d.ts +19 -0
  12. package/dist/_internal/types/configs/links.js +1 -0
  13. package/dist/_internal/types/configs.d.ts +3 -0
  14. package/dist/_internal/types/md.d.ts +5 -2
  15. package/dist/_internal/types/md.js +2 -1
  16. package/dist/_internal/utils/chalk.d.ts +7 -0
  17. package/dist/_internal/utils/chalk.js +8 -0
  18. package/dist/_internal/utils/command.d.ts +13 -11
  19. package/dist/_internal/utils/command.js +10 -4
  20. package/dist/_internal/utils/configs.d.ts +2 -1
  21. package/dist/_internal/utils/configs.js +2 -1
  22. package/dist/_internal/utils/fs.d.ts +4 -0
  23. package/dist/_internal/utils/fs.js +17 -0
  24. package/dist/_internal/utils/link.d.ts +4 -0
  25. package/dist/_internal/utils/{settings.js → link.js} +15 -10
  26. package/dist/_internal/utils/log.d.ts +1 -0
  27. package/dist/_internal/utils/log.js +8 -5
  28. package/dist/_internal/utils/md/lexer.d.ts +1 -0
  29. package/dist/_internal/utils/md/lexer.js +5 -0
  30. package/dist/_internal/utils/md/line.d.ts +22 -0
  31. package/dist/_internal/utils/md/line.js +51 -0
  32. package/dist/_internal/utils/md.d.ts +10 -4
  33. package/dist/_internal/utils/md.js +40 -23
  34. package/dist/_internal/utils/minimatch.d.ts +2 -0
  35. package/dist/_internal/utils/minimatch.js +13 -0
  36. package/dist/_internal/utils/path.d.ts +5 -3
  37. package/dist/_internal/utils/path.js +10 -17
  38. package/dist/_internal/utils/process.js +4 -1
  39. package/dist/cli/commands/generate/action.d.ts +4 -2
  40. package/dist/cli/commands/generate/action.js +9 -84
  41. package/dist/cli/commands/generate/actions/link.d.ts +2 -0
  42. package/dist/cli/commands/generate/actions/link.js +121 -0
  43. package/dist/cli/commands/generate/actions/rc.d.ts +2 -0
  44. package/dist/cli/commands/generate/actions/rc.js +39 -0
  45. package/dist/cli/commands/generate/command.d.ts +7 -2
  46. package/dist/cli/commands/generate/command.js +84 -17
  47. package/dist/cli/commands/help/action.d.ts +2 -2
  48. package/dist/cli/commands/help/action.js +9 -9
  49. package/dist/cli/commands/help/command.d.ts +5 -2
  50. package/dist/cli/commands/help/command.js +5 -7
  51. package/dist/cli/commands/index.js +14 -4
  52. package/dist/cli/commands/link/action.d.ts +5 -0
  53. package/dist/cli/commands/link/action.js +112 -0
  54. package/dist/cli/commands/link/command.d.ts +5 -0
  55. package/dist/cli/commands/link/command.js +21 -0
  56. package/package.json +26 -14
  57. package/cli/commands/generate/README.md/package.json +0 -6
  58. package/dist/_internal/types/options.d.ts +0 -15
  59. package/dist/_internal/types/settings.d.ts +0 -8
  60. package/dist/_internal/utils/settings.d.ts +0 -5
  61. /package/dist/_internal/types/{settings.js → configs/help.js} +0 -0
  62. /package/dist/_internal/types/{options.js → configs.js} +0 -0
@@ -1,5 +1,11 @@
1
- import { Detail } from '../types/md.js';
2
- export declare const getParam: (text: string, key: string) => string;
3
- export declare const getParams: (text: string, key: string) => RegExpMatchArray | "";
4
- export declare const getTitle: (text: string) => string;
1
+ import { MdAttributes, Detail } from '../types/md.js';
2
+ export declare const getParam: (txt: string, key: string) => string;
3
+ export declare const getParamComment: (param: string, value: string) => string;
4
+ export declare const getKeyValues: (keyValues: Record<string, string | number | boolean>) => string;
5
+ type CommentParams = Record<string, string | number | boolean>;
6
+ export declare const getParamsComment: <T extends CommentParams = CommentParams>(keyValues: T) => string;
7
+ export declare const removeParam: (md: string, param: string) => string;
8
+ export declare const getTitle: (txt: string) => string;
5
9
  export declare const replace: (detail: Detail, details: Detail[]) => string;
10
+ export declare const getLinkedMdDetail: (md: string) => MdAttributes;
11
+ export {};
@@ -1,35 +1,41 @@
1
1
  import { readFileSync } from 'fs';
2
- import { PROPERTIES, LINK_NAME_PREFIX, COMMENT_REG_EXP, PARAM_SEPARATOR, LINK_REG_EXP, MD_HOPPER_COMMENT_PREFIX, MD_HOPPER_COMMENT_PREFIX_REG_EXP, MD_HOPPER_PROPERTY_REG_EXP, MD_HOPPER_PARAMS_REG_EXP, BRAKE_LINE_REG_EXP, MD_HOPPER_CONTENT_REG_EXP, BEGIN_COMMENT, END_COMMENT, } from '../types/md.js';
2
+ import { PROPERTIES, LINK_NAME_PREFIX, COMMENT_REG_EXP, PARAM_SEPARATOR, LINK_REG_EXP, MD_HOPPER_COMMENT_PREFIX, MD_HOPPER_COMMENT_PREFIX_REG_EXP, MD_HOPPER_PROPERTY_REG_EXP, MD_HOPPER_PARAMS_REG_EXP, BRAKE_LINE_REG_EXP, MD_HOPPER_CONTENT_REG_EXP, BEGIN_COMMENT, END_COMMENT, getParamExp, } from '../types/md.js';
3
+ import { replaceLineToLink } from './md/line.js';
3
4
  import { getRelative } from './path.js';
4
5
  import { isBoolean } from './type-check.js';
5
- export const getParam = (text, key) => {
6
+ export const getParam = (txt, key) => {
6
7
  const PREFIX = `${BEGIN_COMMENT}\\s*${MD_HOPPER_COMMENT_PREFIX}:\\s*${key}:`;
7
8
  const reg = new RegExp(`${PREFIX}(.*?)${END_COMMENT}`, 's');
8
- if (!reg.test(text)) {
9
+ if (!reg.test(txt)) {
9
10
  return '';
10
11
  }
11
- return reg.exec(text)[1];
12
+ return reg.exec(txt)[1];
12
13
  };
13
- export const getParams = (text, key) => {
14
- const PREFIX = `${BEGIN_COMMENT}\\s*${MD_HOPPER_COMMENT_PREFIX}:\\s*${key}:`;
15
- const reg = new RegExp(`${PREFIX}(.*?)${END_COMMENT}`, 'gs');
16
- if (!reg.test(text)) {
17
- return '';
18
- }
19
- return text.match(reg);
14
+ export const getParamComment = (param, value) => `${BEGIN_COMMENT} ${MD_HOPPER_COMMENT_PREFIX}${PARAM_SEPARATOR} ${param}${PARAM_SEPARATOR} ${value} ${END_COMMENT}`;
15
+ export const getKeyValues = (keyValues) => {
16
+ const arr = Object.entries(keyValues);
17
+ const txt = arr.map(([key, value]) => `${key}${PARAM_SEPARATOR} ${value}`).join('\n');
18
+ const prefixSuffix = arr.length >= 2 ? '\n' : '';
19
+ return `${prefixSuffix}${txt}${prefixSuffix}`;
20
+ };
21
+ export const getParamsComment = (keyValues) => `${BEGIN_COMMENT} ${MD_HOPPER_COMMENT_PREFIX}${PARAM_SEPARATOR} ${getKeyValues(keyValues)} ${END_COMMENT}`;
22
+ export const removeParam = (md, param) => {
23
+ return md.replace(getParamExp(param), '');
20
24
  };
21
- const getRemovedCommentOut = (text) => text.replace(COMMENT_REG_EXP, '');
22
- const getFirstLine = (text) => {
23
- const lines = text.split('\n').filter(line => line.trim().length);
25
+ const getRemovedComment = (txt) => txt.replace(COMMENT_REG_EXP, '');
26
+ const getFirstLine = (txt) => {
27
+ const lines = txt.split('\n').filter(line => line.trim().length);
24
28
  return lines.length ? lines[0].trim() : '';
25
29
  };
26
- export const getTitle = (text) => {
27
- const title = getParam(text, 'TITLE');
30
+ export const getTitle = (txt) => {
31
+ const title = getParam(txt, 'TITLE');
28
32
  if (title) {
29
33
  return title;
30
34
  }
31
- const md = getRemovedCommentOut(text);
32
- return getParam(text, 'TITLE') || md.replace(/\r?\n?#+(.*?)\r?\n.*/s, '$1').trim() || getFirstLine(md);
35
+ const md = getRemovedComment(txt);
36
+ const lines = md.split('\n').filter(line => /^#+\s*./.test(line));
37
+ const str = lines.length >= 1 ? lines[0].trim().replace(/^\s*#+\s*(.+)$/, '$1') : getFirstLine(md);
38
+ return str.replace(/[[\]():]/g, '');
33
39
  };
34
40
  const getLinkName = (id) => `${LINK_NAME_PREFIX}${id}`;
35
41
  const getLink = (id, title) => `[${title}][${getLinkName(id)}]`;
@@ -37,17 +43,16 @@ const getLinksByDetails = (details) => details.map(d => getLink(d.id, d.title));
37
43
  const getDefineLink = (id, url, title) => `[${getLinkName(id)}]: ${url}${title ? ` '${title}'` : ''}`;
38
44
  const replaceToLink = (txt, inline, detail) => {
39
45
  if (LINK_REG_EXP.test(txt)) {
40
- const url = txt.replace(LINK_REG_EXP, '$2');
46
+ const url = txt.replace(LINK_REG_EXP, '$3');
41
47
  if (url === getLinkName(detail.id)) {
42
48
  return txt;
43
49
  }
44
- return `[${txt.replace(LINK_REG_EXP, '$1')}][${getLinkName(detail.id)}]
45
- <!-- ${MD_HOPPER_COMMENT_PREFIX}${PARAM_SEPARATOR} ${PROPERTIES.BEFORE_GENERATE_LINK}${PARAM_SEPARATOR} -->
46
- <!-- ${txt} -->
50
+ return `${replaceLineToLink(txt.replace(LINK_REG_EXP, '$1$2'), getLinkName(detail.id))}
51
+ <!-- ${MD_HOPPER_COMMENT_PREFIX}${PARAM_SEPARATOR} ${PROPERTIES.BEFORE_GENERATE_LINK} (${new Date().toLocaleString()})${PARAM_SEPARATOR} ${txt} -->
47
52
  `;
48
53
  }
49
54
  if (inline) {
50
- return `[${txt}][${getLinkName(detail.id)}]`;
55
+ return replaceLineToLink(txt, getLinkName(detail.id));
51
56
  }
52
57
  else {
53
58
  return `[${detail.title}][${getLinkName(detail.id)}]
@@ -229,3 +234,15 @@ export const replace = (detail, details) => {
229
234
  }
230
235
  return sections.join(`${BEGIN_COMMENT} ${MD_HOPPER_COMMENT_PREFIX}${PARAM_SEPARATOR} `);
231
236
  };
237
+ export const getLinkedMdDetail = (md) => {
238
+ const id = getParam(md, 'ID').trim();
239
+ const LOCK = getParam(md, 'LOCK').trim();
240
+ const lock = LOCK ? JSON.parse(LOCK) : false;
241
+ const output = getParam(md, 'OUTPUT').trim();
242
+ return {
243
+ id,
244
+ lock,
245
+ title: (getTitle(md) || id).trim(),
246
+ output,
247
+ };
248
+ };
@@ -0,0 +1,2 @@
1
+ export declare const getExclude: (basePath: string, excludes: string[], skipHidden: boolean) => string[];
2
+ export declare const getInclude: (basePath: string, includes: string[]) => string[];
@@ -0,0 +1,13 @@
1
+ import { join } from 'path';
2
+ const replacePath = (str) => str.replace(/\/{2,}/, '/');
3
+ export const getExclude = (basePath, excludes, skipHidden) => {
4
+ return [
5
+ '**/node_modules/.*/*',
6
+ '**/node_modules/**/*',
7
+ ...(skipHidden ? ['**/.*/**/*', '**/.*'] : []),
8
+ ...excludes.map(path => replacePath(join(basePath, path))),
9
+ ];
10
+ };
11
+ export const getInclude = (basePath, includes) => {
12
+ return includes.map(path => replacePath(join(basePath, path)));
13
+ };
@@ -1,6 +1,8 @@
1
- export declare const getProjectRootPath: () => string;
2
- export declare const getFullPath: (...path: string[]) => string;
3
- export declare const getDir: (path: string) => string;
1
+ export declare const isDirectory: (path: string) => boolean;
2
+ export declare const getExecDir: () => string;
3
+ export declare const getParseDirPath: (path: string) => string;
4
+ export declare const getParentDirname: (path: string) => string | undefined;
5
+ export declare const getCommands: (path: string, start?: number, end?: number) => string[];
4
6
  export declare const DEPTH_TYPES: {
5
7
  ancestor: string;
6
8
  parent: string;
@@ -1,21 +1,14 @@
1
- import { existsSync } from 'fs';
2
- import { join, parse, relative } from 'path';
3
- import { SETTING_FILE_NAME } from './configs.js';
4
- export const getProjectRootPath = () => {
5
- let path = process.cwd();
6
- if (!existsSync(join(path, SETTING_FILE_NAME))) {
7
- for (const _ in process.cwd().split(/\//g)) {
8
- path = join(path, '..');
9
- if (existsSync(join(path, SETTING_FILE_NAME))) {
10
- break;
11
- }
12
- }
1
+ import { parse, relative } from 'path';
2
+ export const isDirectory = (path) => !parse(path).ext;
3
+ export const getExecDir = () => process.cwd();
4
+ export const getParseDirPath = (path) => parse(path).dir;
5
+ export const getParentDirname = (path) => path.split('/').pop();
6
+ export const getCommands = (path, start = 0, end = 1) => {
7
+ const dirname = getParentDirname(path);
8
+ if (!dirname) {
9
+ throw new Error('no command name');
13
10
  }
14
- return path;
15
- };
16
- export const getFullPath = (...path) => join(getProjectRootPath(), ...path);
17
- export const getDir = (path) => {
18
- return parse(path).dir;
11
+ return [dirname, dirname.substring(start, end)];
19
12
  };
20
13
  export const DEPTH_TYPES = {
21
14
  ancestor: 'ancestor',
@@ -1,8 +1,11 @@
1
+ import { join } from 'path';
1
2
  import { ENVS } from '../types/process.js';
2
- import pkg from '../../../package.json' assert { type: 'json' };
3
+ import { readJsonFileSync } from './fs.js';
3
4
  export * from '../types/process.js';
5
+ const __dirname = import.meta.dirname;
4
6
  export const args = process.argv.slice(2);
5
7
  export const init = () => {
8
+ const pkg = readJsonFileSync(join(__dirname, '../../..', 'package.json'));
6
9
  set(ENVS.PACKAGE_VERSION, pkg.version);
7
10
  set(ENVS.IS_DEBUG, bool(process.env.DEBUG) || args.includes('--debug'));
8
11
  };
@@ -1,3 +1,5 @@
1
1
  import { ActionArg } from '../../../_internal/types/command.js';
2
- import { BundleOptions } from '../../../_internal/types/options.js';
3
- export declare const action: (args: ActionArg<BundleOptions>) => Promise<void>;
2
+ import { CommandOptions, MdSettings } from '../../../_internal/types/configs/generate.js';
3
+ type Arg = ActionArg<CommandOptions, MdSettings>;
4
+ export declare const action: (args: Arg) => Promise<void>;
5
+ export {};
@@ -1,87 +1,12 @@
1
- import { readFileSync, writeFileSync } from 'fs';
2
- import { join } from 'path';
3
- import { getAllFiles } from '../../../_internal/utils/fs.js';
4
- import { getParam, getTitle, replace } from '../../../_internal/utils/md.js';
5
- import { getProjectRootPath } from '../../../_internal/utils/path.js';
6
- import { getDir, getDepthType, DEPTH_TYPES } from '../../../_internal/utils/path.js';
7
- const replacePath = (str) => str.replace(/\/{2,}/, '/');
8
- const splitComma = (str, alternative) => (str ? str.split(',') : null) || alternative;
9
- const mergeConfig = ({ options, settings }) => {
10
- return {
11
- 'skip-hidden': typeof options.skipHidden === 'undefined' ? settings['skip-hidden'] : JSON.parse(`${options.skipHidden}`),
12
- exclude: splitComma(options.exclude, settings.exclude),
13
- include: splitComma(options.include, settings.include),
14
- filenames: splitComma(options.filenames, settings.filenames),
15
- output: options.output || settings.output,
16
- };
17
- };
18
- const classify = (dataList) => {
19
- return dataList.reduce((mds, data) => {
20
- const classifyList = { children: [], grandchildren: [], parallels: [] };
21
- for (const { dir, path } of dataList) {
22
- if (data.path === path) {
23
- continue;
24
- }
25
- switch (getDepthType(dir, data.dir)) {
26
- case DEPTH_TYPES.parallel:
27
- classifyList.parallels.push(path);
28
- break;
29
- case DEPTH_TYPES.child:
30
- classifyList.children.push(path);
31
- break;
32
- case DEPTH_TYPES.grandchild:
33
- classifyList.grandchildren.push(path);
34
- break;
35
- }
36
- }
37
- mds.push({
38
- ...data,
39
- ...classifyList,
40
- });
41
- return mds;
42
- }, []);
43
- };
44
- const getPathDetails = (paths, config) => {
45
- const list = [];
46
- for (const path of paths) {
47
- const md = readFileSync(path, 'utf-8');
48
- const id = getParam(md, 'ID').trim();
49
- const LOCK = getParam(md, 'LOCK').trim();
50
- const lock = LOCK ? JSON.parse(LOCK) : false;
51
- const dir = getDir(path);
52
- const output = getParam(md, 'OUTPUT').trim() || config.output;
53
- list.push({
54
- id,
55
- lock,
56
- title: (getTitle(md) || id || path).trim(),
57
- path,
58
- dir,
59
- output,
60
- outputPath: join(dir, output),
61
- });
62
- }
63
- return classify(list);
64
- };
1
+ import { TYPES } from '../../../_internal/types/configs/generate.js';
2
+ import { exec as linkExec } from './actions/link.js';
3
+ import { exec as rcExec } from './actions/rc.js';
65
4
  export const action = async (args) => {
66
- const rootPath = getProjectRootPath();
67
- const config = mergeConfig(args);
68
- const skipHidden = config['skip-hidden'] ? ['**/.*/**/*', '**/.*'] : [];
69
- const exclude = [
70
- '**/node_modules/.*/*',
71
- '**/node_modules/**/*',
72
- ...skipHidden,
73
- ...config.exclude.map(path => replacePath(`${rootPath}/${path}`)),
74
- ];
75
- const include = config.include.map(path => replacePath(`${rootPath}/${path}`));
76
- const paths = getAllFiles(rootPath, [], { include, exclude }).filter(path => config.filenames.some(filename => path.endsWith(`/${filename}`)));
77
- const pathDetails = getPathDetails(paths, config);
78
- for (const pathDetail of pathDetails) {
79
- if (pathDetail.lock) {
80
- continue;
81
- }
82
- const content = replace(pathDetail, pathDetails);
83
- const output = pathDetail.output || config.output;
84
- const writePath = output ? join(pathDetail.dir, output) : pathDetail.path;
85
- writeFileSync(writePath, content, 'utf-8');
5
+ const { options, settings } = args;
6
+ switch (options.type) {
7
+ case TYPES.rc:
8
+ return rcExec(settings);
9
+ case TYPES.link:
10
+ return linkExec(settings);
86
11
  }
87
12
  };
@@ -0,0 +1,2 @@
1
+ import { MdSettings } from '../../../../_internal/types/configs/generate.js';
2
+ export declare const exec: (settings: MdSettings) => Promise<void>;
@@ -0,0 +1,121 @@
1
+ import { readFileSync, existsSync, writeFileSync } from 'fs';
2
+ import { parse, join } from 'path';
3
+ import inquirer from 'inquirer';
4
+ import { TablePlugin } from 'inquirer-plugins/table';
5
+ import { v4 as uuid } from 'uuid';
6
+ import { GENERATE_TYPES } from '../../../../_internal/types/configs/generate.js';
7
+ import { success, warn, hop, cyan, bold } from '../../../../_internal/utils/chalk.js';
8
+ import { getAllMdFiles } from '../../../../_internal/utils/fs.js';
9
+ import { getLinkedMdDetail, removeParam, getParamsComment } from '../../../../_internal/utils/md.js';
10
+ import { getExclude, getInclude } from '../../../../_internal/utils/minimatch.js';
11
+ import { isDirectory as isDirectoryPath, getExecDir } from '../../../../_internal/utils/path.js';
12
+ const PARAMS = ['id', 'title', 'output', 'lock'];
13
+ const getAnswers = (details) => {
14
+ inquirer.registerPrompt('table', TablePlugin);
15
+ const question = {
16
+ type: 'table',
17
+ name: 'links',
18
+ message: 'GENERATE LINKS PATH SETTINGS',
19
+ description: `Edit setting.`,
20
+ disableColumnIndexes: [0],
21
+ colors: {
22
+ selected: warn,
23
+ editable: success,
24
+ editing: hop,
25
+ },
26
+ columns: [
27
+ { name: cyan.bold('filepath'), value: 'path', type: 'input' },
28
+ { name: cyan.bold('id'), value: 'id', type: 'input' },
29
+ { name: cyan.bold('title'), value: 'title', type: 'input' },
30
+ { name: cyan.bold('output'), value: 'output', type: 'input' },
31
+ { name: cyan.bold('lock'), value: 'lock', type: 'confirm' },
32
+ ],
33
+ rows: details.map(({ path, id, title, output, lock }) => {
34
+ return [bold(path), id, title, output, lock];
35
+ }),
36
+ };
37
+ return inquirer.prompt([question]);
38
+ };
39
+ const getQuestionParam = (settings, path, md, prefixExp) => {
40
+ const detail = getLinkedMdDetail(md);
41
+ return {
42
+ ...detail,
43
+ id: settings.id || getGenerateId(detail.id, settings, path, prefixExp),
44
+ title: settings.title || detail.title,
45
+ output: settings.output || detail.output,
46
+ lock: settings.lock || detail.lock,
47
+ path,
48
+ };
49
+ };
50
+ const writeMd = (md, values) => {
51
+ const comments = [];
52
+ for (const params of PARAMS) {
53
+ const PARAM = params.toUpperCase();
54
+ md = removeParam(md, PARAM);
55
+ const value = values[params];
56
+ if (value) {
57
+ comments.push(getParamsComment({ [PARAM]: `${value}` }));
58
+ }
59
+ }
60
+ const content = `${comments.join('\n')}
61
+ ${md}`;
62
+ writeFileSync(values.path, content, 'utf-8');
63
+ };
64
+ const generateLink = async (settings, fullPath) => {
65
+ const isExists = existsSync(fullPath);
66
+ let md = '';
67
+ if (isExists) {
68
+ md = readFileSync(fullPath, 'utf-8');
69
+ }
70
+ const execDir = getExecDir();
71
+ const prefixExp = new RegExp(`${execDir}/(.+)$`);
72
+ const question = getQuestionParam(settings, fullPath, md, prefixExp);
73
+ const { links } = await getAnswers([question]);
74
+ for (const result of links.result) {
75
+ writeMd(md, result);
76
+ }
77
+ };
78
+ const getGenerateId = (id, settings, path, prefixExp) => {
79
+ if (id) {
80
+ return id;
81
+ }
82
+ switch (settings.idGen) {
83
+ case GENERATE_TYPES.path: {
84
+ const paths = path.replace(prefixExp, '$1').split('/');
85
+ const parsed = parse(`${paths.pop()}`);
86
+ return `${paths.join('-')}-${parsed.name.substring(0, 1).toLowerCase()}${parsed.ext.replace(/^\./, '')}`.replace(/^-+/, '');
87
+ }
88
+ case GENERATE_TYPES.random:
89
+ return uuid();
90
+ default:
91
+ return id;
92
+ }
93
+ };
94
+ const generateLinks = async (settings, fullPath) => {
95
+ const { depth } = settings;
96
+ const execDir = getExecDir();
97
+ const targetDir = join(execDir, settings.input);
98
+ const exclude = getExclude(targetDir, settings.exclude, settings.skipHidden);
99
+ const include = getInclude(targetDir, settings.include);
100
+ const paths = getAllMdFiles(settings.filenames, fullPath, { include, exclude, ...(depth >= 1 ? { depth } : {}) });
101
+ const prefixExp = new RegExp(`${execDir}/(.+)$`);
102
+ const questions = [];
103
+ for (const path of paths) {
104
+ const md = readFileSync(path, 'utf-8');
105
+ questions.push(getQuestionParam(settings, path, md, prefixExp));
106
+ }
107
+ const { links } = await getAnswers(questions);
108
+ console.log(links);
109
+ for (const result of links.result) {
110
+ writeMd(readFileSync(result.path, 'utf-8'), result);
111
+ }
112
+ };
113
+ export const exec = (settings) => {
114
+ const fullPath = join(getExecDir(), settings.input);
115
+ if (isDirectoryPath(settings.input)) {
116
+ return generateLinks(settings, fullPath);
117
+ }
118
+ else {
119
+ return generateLink(settings, fullPath);
120
+ }
121
+ };
@@ -0,0 +1,2 @@
1
+ import { MdSettings } from '../../../../_internal/types/configs/generate.js';
2
+ export declare const exec: (settings: MdSettings) => void;
@@ -0,0 +1,39 @@
1
+ import { readFileSync, existsSync, writeFileSync } from 'fs';
2
+ import { join } from 'path';
3
+ import { isArray } from 'my-gadgetry/type-check';
4
+ import { isDirectory as isDirectoryFile } from '../../../../_internal/utils/fs.js';
5
+ import { removeParam, getParamsComment, getKeyValues } from '../../../../_internal/utils/md.js';
6
+ import { getExecDir } from '../../../../_internal/utils/path.js';
7
+ const PARAMS = {
8
+ skipHidden: 'skip-hidden',
9
+ include: 'include',
10
+ exclude: 'exclude',
11
+ filenames: 'filenames',
12
+ output: 'output',
13
+ depth: 'depth',
14
+ };
15
+ export const exec = (settings) => {
16
+ const fullPath = join(getExecDir(), settings.input);
17
+ let md = '';
18
+ if (existsSync(fullPath)) {
19
+ if (isDirectoryFile(fullPath)) {
20
+ throw new Error(`this is dir. ${fullPath}`);
21
+ }
22
+ md = readFileSync(fullPath, 'utf-8');
23
+ }
24
+ md = removeParam(md, 'CONFIG');
25
+ const keyValues = Object.entries(PARAMS).reduce((acc, keyValue) => {
26
+ const [optKey, mdKey] = keyValue;
27
+ const value = settings[optKey];
28
+ const isArr = isArray(value);
29
+ if (!value || (isArr && !value.length)) {
30
+ return acc;
31
+ }
32
+ acc[mdKey] = isArr ? value.join(',') : `${value}`;
33
+ return acc;
34
+ }, {});
35
+ const params = getKeyValues(keyValues);
36
+ const content = `${getParamsComment({ CONFIG: params })}
37
+ ${md}`;
38
+ writeFileSync(fullPath, content, 'utf-8');
39
+ };
@@ -1,2 +1,7 @@
1
- import { Command as Program } from 'commander';
2
- export declare const init: (program: Program) => void;
1
+ import { ActionArg } from '../../../_internal/types/command.js';
2
+ import { CommandOptions, MdSettings } from '../../../_internal/types/configs/generate.js';
3
+ import { CommandClass } from '../../../_internal/utils/command.js';
4
+ export declare const COMMANDS: string[];
5
+ export declare const beforeAction: (args: ActionArg<CommandOptions, MdSettings>) => Promise<void>;
6
+ export declare const init: (commandClass: CommandClass<CommandOptions, MdSettings>) => void;
7
+ export declare const getSettings: (_options: CommandOptions) => {};
@@ -1,21 +1,88 @@
1
- import { CommandClass } from '../../../_internal/utils/command.js';
1
+ import inquirer from 'inquirer';
2
+ import { TYPES, GENERATE_TYPES, QUESTIONS } from '../../../_internal/types/configs/generate.js';
3
+ import { DEFAULT_MD_FILENAME } from '../../../_internal/utils/configs.js';
4
+ import { getCommands } from '../../../_internal/utils/path.js';
2
5
  import { action } from './action.js';
3
- const setAliases = (commandClass) => {
4
- commandClass
5
- .description('This command is used to exec target file.')
6
- .option('-sh --skip-hidden <boolean>', 'skip read hidden dir, default: true')
7
- .option('-incl, --include <strings>', 'include dirs, default: [] (all files)')
8
- .option('-excl, --exclude <strings>', 'ignore dirs, default: node_modules only')
9
- .option('-f, --filenames <strings>', 'filenames, default: README.md only')
10
- .option('-o, --output <filename>', 'output filename. default: README.md (replace)')
11
- .option('-i, --input <filename>', 'target root filename, default: README.md')
12
- .action(options => {
13
- return action(options);
14
- });
6
+ export const COMMANDS = getCommands(import.meta.dirname);
7
+ const DEFAULT_SETTINGS = {
8
+ include: [],
9
+ exclude: [],
10
+ filenames: [],
11
+ skipHidden: true,
12
+ input: '.',
13
+ output: DEFAULT_MD_FILENAME,
14
+ idGen: GENERATE_TYPES.path,
15
+ id: '',
16
+ title: '',
17
+ lock: false,
18
+ depth: 0,
15
19
  };
16
- const commands = ['generate', 'g'];
17
- export const init = (program) => {
18
- for (const command of commands) {
19
- setAliases(new CommandClass(program).command(command));
20
+ const mergeSetting = (options) => {
21
+ return {
22
+ include: options.include ? options.include.split(',') : DEFAULT_SETTINGS.include,
23
+ exclude: options.exclude ? options.exclude.split(',') : DEFAULT_SETTINGS.exclude,
24
+ filenames: options.filenames ? options.filenames.split(',') : DEFAULT_SETTINGS.filenames,
25
+ skipHidden: options.skipHidden || DEFAULT_SETTINGS.skipHidden,
26
+ input: options.input || DEFAULT_SETTINGS.input,
27
+ output: options.output || DEFAULT_SETTINGS.output,
28
+ idGen: options.idGen || DEFAULT_SETTINGS.idGen,
29
+ id: options.id || DEFAULT_SETTINGS.id,
30
+ title: options.title || DEFAULT_SETTINGS.title,
31
+ lock: options.lock || DEFAULT_SETTINGS.lock,
32
+ depth: options.depth || DEFAULT_SETTINGS.depth,
33
+ };
34
+ };
35
+ export const beforeAction = async (args) => {
36
+ let answers = {};
37
+ const { options: opts } = args;
38
+ const questions = [];
39
+ for (const question of QUESTIONS(opts)[opts.type]) {
40
+ const name = question.name || '';
41
+ if (name in opts) {
42
+ continue;
43
+ }
44
+ questions.push(question);
20
45
  }
46
+ answers = await inquirer.prompt(questions);
47
+ console.log(answers);
48
+ const options = {
49
+ ...opts,
50
+ ...answers,
51
+ };
52
+ return action({
53
+ options,
54
+ settings: mergeSetting(options),
55
+ });
56
+ };
57
+ export const init = (commandClass) => {
58
+ commandClass
59
+ .description('This command is generate template.')
60
+ .option('-t --type <string>', `template type default: ${TYPES.rc} (${Object.values(TYPES).join(', ')})`, (value) => {
61
+ const values = Object.values(TYPES);
62
+ if (!values.includes(value)) {
63
+ throw new Error(`Invalid type. Allowed values are: ${values.join(', ')}`);
64
+ }
65
+ return value;
66
+ }, TYPES.rc)
67
+ .option('-sh --skip-hidden', 'skip read hidden dir (default: true)')
68
+ .option('-incl, --include <strings>', 'include dirs (default: [] (all files))')
69
+ .option('-excl, --exclude <strings>', 'ignore dirs (default: node_modules only)')
70
+ .option('-f, --filenames <strings>', 'filenames (default: README.md only)')
71
+ .option('-o, --output <filename>', 'output filename (default: README.md (replace))')
72
+ .option('-i, --input <filename>', 'target root filename (default: README.md)')
73
+ .option('-ig, --id-gen <string>', `Choose generate type (default: ${GENERATE_TYPES.path})`, (value) => {
74
+ const values = Object.values(GENERATE_TYPES);
75
+ if (!values.includes(value)) {
76
+ throw new Error(`Invalid type. Allowed values are: ${values.join(', ')}`);
77
+ }
78
+ return value;
79
+ })
80
+ .option('-I, --id <string>', 'type id')
81
+ .option('-T, --title <string>', 'title name')
82
+ .option('-l --lock', 'is locked? if true not link this file. (default: false)')
83
+ .option('-D, --depth <filename>', 'depth level more than 0')
84
+ .action(beforeAction);
85
+ };
86
+ export const getSettings = (_options) => {
87
+ return {};
21
88
  };
@@ -1,3 +1,3 @@
1
1
  import { ActionArg } from '../../../_internal/types/command.js';
2
- import { HelpOptions } from '../../../_internal/types/options.js';
3
- export declare const action: (_: ActionArg<HelpOptions>) => Promise<void>;
2
+ import { CommandOptions, MdSettings } from '../../../_internal/types/configs/help.js';
3
+ export declare const action: (_: ActionArg<CommandOptions, MdSettings>) => Promise<void>;
@@ -1,23 +1,23 @@
1
1
  import { platform } from 'node:process';
2
- import { info } from '../../../_internal/utils/log.js';
2
+ import { info, hop } from '../../../_internal/utils/log.js';
3
3
  import { get, ENVS } from '../../../_internal/utils/process.js';
4
4
  const ASCII_ART = `
5
5
 
6
- _ _ __ _ _ _ ___ ___ _____
7
- | | | | | \\ | | | | / / / |/ | | _ \\
8
- | | | | | \\| | | |/ / / /| /| | | | | |
9
- | | | | | |\\ | | |\\ \\ / / |__/ | | | | | |
10
- | |___ | | | | \\ | | | \\ \\ / / | | | |_| |
11
- |_____| |_| |_| \\_| |_| \\_\\ /_/ |_| |_____/
6
+ ___ ___ _____ _ _ _____ _____ _____ _____ _____
7
+ / |/ | | _ \\ | | | | / _ \\ | _ \\ | _ \\ | ____| | _ \\
8
+ / /| /| | | | | | | |_| | | | | | | |_| | | |_| | | |__ | |_| |
9
+ / / |__/ | | | | | | | _ | | | | | | ___/ | ___/ | __| | _ /
10
+ / / | | | |_| | | | | | | |_| | | | | | | |___ | | \\ \\
11
+ /_/ |_| |_____/ |_| |_| \\_____/ |_| |_| |_____| |_| \\_\\
12
12
 
13
13
  `;
14
14
  const VERSIONS = `
15
- Link MD: ${get(ENVS.PACKAGE_VERSION)}
15
+ MD Hopper: ${get(ENVS.PACKAGE_VERSION)}
16
16
  Node: ${process.versions.node}
17
17
  OS: ${platform} ${process.arch}
18
18
  `;
19
19
  const show = () => {
20
- info(ASCII_ART);
20
+ hop(ASCII_ART);
21
21
  info(VERSIONS);
22
22
  };
23
23
  export const action = async (_) => {
@@ -1,2 +1,5 @@
1
- import { Command as Program } from 'commander';
2
- export declare const init: (program: Program) => void;
1
+ import { CommandOptions, MdSettings } from '../../../_internal/types/configs/help.js';
2
+ import { CommandClass } from '../../../_internal/utils/command.js';
3
+ export declare const COMMANDS: string[];
4
+ export declare const init: (commandClass: CommandClass<CommandOptions, MdSettings>) => void;
5
+ export declare const getSettings: (options: CommandOptions) => CommandOptions;