@mrktg-common/project-generator 1.3.0 → 1.4.0

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.
package/README.md CHANGED
@@ -11,8 +11,10 @@
11
11
 
12
12
  1. Вопросы (`@clack/prompts`): имя проекта (или `.` — текущая папка), бренд из реестра,
13
13
  путь лендинга после префикса бренда, флюидная ли вёрстка (по умолчанию нет), ставить ли зависимости,
14
- делать ли `git init`. Любой ответ можно передать флагом (`--brand`, `--path`,
15
- `--fluid`/`--no-fluid`, `--install`/`--no-install`, `--git`/`--no-git`), тогда вопрос не задаётся.
14
+ делать ли `git init` и какую ссылку положить в `origin`. Любой ответ можно передать флагом
15
+ (`--brand`, `--path`, `--fluid`/`--no-fluid`, `--install`/`--no-install`, `--git`/`--no-git`,
16
+ `--remote <url>`), тогда вопрос не задаётся. Ссылка на репозиторий приводится к виду для `origin`:
17
+ https-адрес страницы репозитория переводится в ssh, https с `.git` и ssh остаются как есть.
16
18
  2. `buildVars`: из бренда и региона собирает словарь для шаблона — прод-урл
17
19
  `https://<хост бренда>/<префикс>/<путь>/`, `base` для Astro, фавиконка и язык бренда, урлы
18
20
  инфраструктуры региона (лоадер футера, clamp-scaling, лоадер аналитики), пакет и версия компонентов.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mrktg-common/project-generator",
3
- "version": "1.3.0",
3
+ "version": "1.4.0",
4
4
  "description": "Движок генератора лендингов: вопросы, шаблон Astro, подстановка. Бренды, регионы и региональные оверлеи приходят от региональных генераторов.",
5
5
  "type": "module",
6
6
  "files": [
package/src/args.js CHANGED
@@ -18,6 +18,7 @@ export const readArgs = (argv) => {
18
18
  'no-git': { type: 'boolean' },
19
19
  fluid: { type: 'boolean' },
20
20
  'no-fluid': { type: 'boolean' },
21
+ remote: { type: 'string' },
21
22
  help: { type: 'boolean', short: 'h' },
22
23
  },
23
24
  });
@@ -32,7 +33,9 @@ export const readArgs = (argv) => {
32
33
  landingPath: values.path,
33
34
  fluid: flag('fluid', 'no-fluid'),
34
35
  install: flag('install', 'no-install'),
35
- git: flag('git', 'no-git'),
36
+ // явный --remote означает, что репозиторий заводим: без git init origin некуда добавить
37
+ git: values.remote !== undefined && !values['no-git'] ? true : flag('git', 'no-git'),
38
+ gitRemote: values.remote,
36
39
  },
37
40
  };
38
41
  };
@@ -48,5 +51,6 @@ ${registry.brands.map((brand) => ` ${brand.id}: https://${br
48
51
  --fluid / --no-fluid флюидная вёрстка (clamp-scaling); по умолчанию нет
49
52
  --install / --no-install
50
53
  --git / --no-git
54
+ --remote <url> ссылка на репозиторий для origin; https без .git кладётся как ssh
51
55
  -h, --help
52
56
  `;
package/src/cli.js CHANGED
@@ -5,6 +5,7 @@ import { buildHelp, readArgs } from './args.js';
5
5
  import { askQuestions } from './questions.js';
6
6
  import { buildVars } from './vars.js';
7
7
  import { scaffold } from './scaffold.js';
8
+ import { toRemoteUrl } from './git-remote.js';
8
9
 
9
10
  const run = (cmd, args, cwd) =>
10
11
  new Promise((resolve, reject) => {
@@ -44,9 +45,14 @@ export const runCli = async (config, argv = process.argv.slice(2)) => {
44
45
  await scaffold(config, targetDir, vars);
45
46
  spinner.stop(`Проект создан в ${path.relative(process.cwd(), targetDir) || 'текущей папке'}`);
46
47
 
48
+ const remote = toRemoteUrl(answers.gitRemote);
47
49
  if (answers.git) {
48
50
  await run('git', ['init', '-q'], targetDir);
49
51
  p.log.success('git init');
52
+ if (remote) {
53
+ await run('git', ['remote', 'add', 'origin', remote], targetDir);
54
+ p.log.success(`git remote add origin ${remote}`);
55
+ }
50
56
  }
51
57
  if (answers.install) {
52
58
  p.log.step('npm install');
@@ -59,6 +65,7 @@ export const runCli = async (config, argv = process.argv.slice(2)) => {
59
65
  `Прод: ${vars.PROD_URL}`,
60
66
  `Компоненты: ${vars.COMPONENTS_PACKAGE}@${vars.COMPONENTS_VERSION}`,
61
67
  `Футер: ${vars.FOOTER_LOADER_URL} (data-brand=${vars.BRAND_ID})`,
68
+ remote ? `Origin: ${remote}` : '',
62
69
  '',
63
70
  answers.projectName === '.' ? '' : `cd ${answers.projectName}`,
64
71
  answers.install ? '' : 'npm install',
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Приводит введённую ссылку на репозиторий к тому виду, в котором её стоит положить в origin.
3
+ *
4
+ * Ссылка вида git@host:group/repo.git или ssh://… остаётся ssh.
5
+ * https-ссылка с .git на конце остаётся https: раз её написали явно, значит так и хотят.
6
+ * https-ссылка без .git — это адрес страницы репозитория из браузера, для origin переводим её в ssh.
7
+ */
8
+ const SSH_RE = /^(?:ssh:\/\/)?[^@\s/]+@[^\s:/]+[:/]\S+$/;
9
+
10
+ export const toRemoteUrl = (value) => {
11
+ const input = (value ?? '').trim();
12
+ if (!input) return undefined;
13
+ if (SSH_RE.test(input)) return input;
14
+
15
+ const url = new URL(input);
16
+ const repoPath = url.pathname.replace(/^\/+/, '').replace(/\/+$/, '');
17
+ if (repoPath.endsWith('.git')) return input;
18
+ return `git@${url.host}:${repoPath}.git`;
19
+ };
20
+
21
+ /** Текст ошибки для непонятной ссылки, undefined — если всё в порядке. */
22
+ export const validateRemote = (value) => {
23
+ const input = (value ?? '').trim();
24
+ if (!input) return undefined;
25
+ if (SSH_RE.test(input)) return undefined;
26
+ let url;
27
+ try {
28
+ url = new URL(input);
29
+ } catch {
30
+ return 'Нужна ссылка вида https://host/group/repo или git@host:group/repo.git';
31
+ }
32
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') return 'Поддерживаются только https и ssh';
33
+ if (!url.pathname.replace(/\/+$/, '').replace(/^\/+/, '')) return 'В ссылке нет пути до репозитория';
34
+ return undefined;
35
+ };
package/src/questions.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import path from 'node:path';
2
2
  import * as p from '@clack/prompts';
3
3
  import { defaultLandingPrefix } from './landing-prefix.js';
4
+ import { validateRemote } from './git-remote.js';
4
5
 
5
6
  /**
6
7
  * Цепочка вопросов. Каждый вопрос — { id, ask(ctx) }: читает уже собранные ответы
@@ -80,12 +81,26 @@ export const buildQuestions = ({ registry, landingPrefix = defaultLandingPrefix
80
81
  id: 'git',
81
82
  ask: () => p.confirm({ message: 'Инициализировать git-репозиторий?', initialValue: true }),
82
83
  },
84
+ {
85
+ id: 'gitRemote',
86
+ // origin нужен только если репозиторий вообще заводим
87
+ when: (ctx) => ctx.git === true,
88
+ ask: () =>
89
+ p.text({
90
+ message: 'Ссылка на репозиторий для origin (пусто — без origin)',
91
+ placeholder: 'https://gitlab.example/group/repo',
92
+ defaultValue: '',
93
+ validate: validateRemote,
94
+ }),
95
+ validate: validateRemote,
96
+ },
83
97
  ];
84
98
 
85
99
  export const askQuestions = async (config, initial) => {
86
100
  const ctx = { ...initial };
87
101
 
88
102
  for (const question of buildQuestions(config)) {
103
+ if (question.when && !question.when(ctx)) continue;
89
104
  if (ctx[question.id] !== undefined) {
90
105
  const error = question.validate?.(ctx[question.id]);
91
106
  if (error) throw new Error(`--${question.id}: ${error}`);