@mirta/cli 0.3.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/LICENSE ADDED
@@ -0,0 +1,24 @@
1
+ This is free and unencumbered software released into the public domain.
2
+
3
+ Anyone is free to copy, modify, publish, use, compile, sell, or
4
+ distribute this software, either in source code form or as a compiled
5
+ binary, for any purpose, commercial or non-commercial, and by any
6
+ means.
7
+
8
+ In jurisdictions that recognize copyright laws, the author or authors
9
+ of this software dedicate any and all copyright interest in the
10
+ software to the public domain. We make this dedication for the benefit
11
+ of the public at large and to the detriment of our heirs and
12
+ successors. We intend this dedication to be an overt act of
13
+ relinquishment in perpetuity of all present and future rights to this
14
+ software under copyright law.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19
+ IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22
+ OTHER DEALINGS IN THE SOFTWARE.
23
+
24
+ For more information, please refer to <https://unlicense.org>
package/README.md ADDED
@@ -0,0 +1,176 @@
1
+ # @mirta/cli
2
+
3
+ [![en](https://img.shields.io/badge/lang-en-olivedrab.svg?style=flat-square)](https://github.com/wb-mirta/core/blob/latest/packages/mirta-cli/README.md)
4
+ [![ru](https://img.shields.io/badge/lang-ru-dimgray.svg?style=flat-square)](https://github.com/wb-mirta/core/blob/latest/packages/mirta-cli/README.ru.md)
5
+ [![NPM Version](https://img.shields.io/npm/v/@mirta/globals?style=flat-square)](https://npmjs.com/package/@mirta/cli)
6
+ [![NPM Downloads](https://img.shields.io/npm/dm/@mirta/cli?style=flat-square&logo=npm)](https://npmjs.com/package/@mirta/cli)
7
+
8
+ Utility for efficient release management and automated package publishing in NPM, supports work in monorepositories.
9
+
10
+ ### Key Features
11
+
12
+ - Convenient system for updating project versions;
13
+ - Easy integration with existing CI/CD processes;
14
+ - Access to all necessary operations through intuitive commands;
15
+ - Support for customizing workflows specific to your infrastructure.
16
+
17
+ ## Installation and Initial Setup
18
+
19
+ Add `@mirta/cli` as a development dependency to your project using the following command:
20
+
21
+ ```sh
22
+ pnpm add -wD @mirta/cli
23
+ ```
24
+ You can configure additional parameters by adding a configuration file named `mirta.config.json` at the root of your main project. For example:
25
+
26
+ ```json
27
+ {
28
+ "scope": "myscope",
29
+ "scopeAsPackagePrefix": false
30
+ }
31
+ ```
32
+ ### Main Configuration Options
33
+
34
+ - `scope` sets the correspondence to an account or organization name in the NPM registry.
35
+ ```
36
+ - `scopeAsPackagePrefix` enables transformation of module paths by prefixing the specified `scope` before the package name. Default is `false`.
37
+
38
+ Example of `scopeAsPackagePrefix` for the package `@myscope/globals`:
39
+
40
+ - `false` - location `packages/globals`
41
+ - `true` - location `packages/myscope-globals`
42
+
43
+ Activating this option helps prevent collisions with third-party NPM packages without a `scope`.
44
+
45
+ If you are satisfied with the default behavior of the tool, creating a separate configuration file is not required. Simply specify the scope in the main `package.json` file like so:
46
+
47
+ ```json
48
+ {
49
+ "name": "@myscope/myproject"
50
+ }
51
+ ```
52
+
53
+ ### Special Mirta Framework Options
54
+
55
+ - `templates` contains a set of paths to templates used by the project generation wizard. Performs recursive search for `package.json` files within the listed locations.
56
+
57
+ Example Mirta configuration:
58
+
59
+ ```json
60
+ {
61
+ "scopeAsPackagePrefix": true,
62
+ "templates": [
63
+ "packages/create-mirta/public/templates"
64
+ ]
65
+ }
66
+ ```
67
+ ## Release Management
68
+
69
+ Performing the release procedure interactively:
70
+
71
+ ```sh
72
+ pnpm mirta release
73
+ ```
74
+ The command will prompt you to select an appropriate version. If the project is managed by Git, it will prepare a list of changes in the `CHANGELOG.md` file, check the CI status, and create a commit.
75
+
76
+ During operation with Git, the needed repository is automatically recognized, but two checks are performed:
77
+
78
+ 1. Local changes have been synchronized with the remote storage beforehand;
79
+ 2. The CI process named `Build` for the last commit has completed successfully.
80
+
81
+ To generate a change log file, add the [conventional-changelog-cli](https://www.npmjs.com/package/conventional-changelog-cli) package as a dev dependency in the root `package.json`. Additionally, include a `changelog` script in the `scripts` section:
82
+
83
+ ```json
84
+ {
85
+ "scripts": {
86
+ "changelog": "conventional-changelog -p angular -i CHANGELOG.md -s"
87
+ }
88
+ }
89
+ ```
90
+ The changelog entries are based on commits made within the version range. There are requirements for commit headers:
91
+
92
+ 1. Line length should not exceed 50 characters;
93
+ 2. Use prefixes such as `fix:`, `feat:`, `docs:`, `chore:`, etc.
94
+
95
+ For the full list of requirements, refer to the framework's [Commit Convention](https://github.com/wb-mirta/core/blob/latest/.github/commit-convention.md).
96
+
97
+ ### Semantic Versioning
98
+
99
+ A semantic version follows the format `major.minor.patch` (for example, `1.2.3`), where each segment represents different levels of changes:
100
+
101
+ - `major` increases when incompatible changes are introduced;
102
+ - `minor` increases when new functionality is added while maintaining backward compatibility;
103
+ - `patch` increases when bug fixes are applied, preserving backward compatibility.
104
+
105
+ Releasing with a specific version:
106
+
107
+ ```sh
108
+ pnpm mirta release 1.2.3
109
+ ```
110
+ Release specifying the incremented part:
111
+
112
+ ```sh
113
+ pnpm mirta release patch
114
+ # 0.0.1
115
+ ```
116
+ ```sh
117
+ pnpm mirta release minor
118
+ # 0.1.0
119
+ ```
120
+ ```sh
121
+ pnpm mirta release major
122
+ # 1.0.0
123
+ ```
124
+ Pre-release version specifying the type:
125
+
126
+ ```sh
127
+ pnpm mirta release prepatch --preid alpha
128
+ # 0.0.1-alpha.0
129
+ ```
130
+ ```sh
131
+ pnpm mirta release preminor --preid alpha
132
+ # 0.1.0-alpha.0
133
+ ```
134
+ ```sh
135
+ pnpm mirta release premajor --preid alpha
136
+ # 1.0.0-alpha.0
137
+ ```
138
+ Incrementing an already existing pre-release version is done via
139
+
140
+ ```sh
141
+ pnpm mirta release prerelease --preid alpha
142
+ # 0.0.1-alpha.1
143
+ ```
144
+ ## Automatic Publishing
145
+
146
+ Publish ready-made packages to the NPM repository:
147
+
148
+ ```sh
149
+ pnpm mirta publish
150
+ ```
151
+
152
+ This operation will initiate the build and publication process for the prepared packages.
153
+
154
+ If the process is triggered from a CI environment on GitHub, then every file inside the published package will be automatically enriched with [provenance information](https://docs.npmjs.com/generating-provenance-statements) - hash values and metadata that confirm its integrity and authenticity.
155
+
156
+ The primary goal of this feature is to enhance trust and security for published packages. When a package is published using this option, users can verify whether the content of the downloaded package matches the original source provided by the author.
157
+
158
+ ## Auxiliary options
159
+
160
+ ### `release` options
161
+
162
+ `--dry` runs the command in simulation mode ("dry run"), showing changes that would be made without actually applying them. Useful for previewing changes before application.
163
+
164
+ `--preid <custom-pre-release-id>` sets a custom prefix for the pre-release version, which is appended to the package version number (e.g., beta.1). This option allows creating pre-release versions such as alpha, beta, RC, etc., before the official stable release.
165
+
166
+ `--skipPrompts` skips interactive user queries. The command runs automatically using default values or predefined settings.
167
+
168
+ `--skipGit` ignores actions related to the Git version control system, such as committing changes, creating commit tags, or pushing updates to a remote repository. Might be useful if you wish to manage Git operations manually later.
169
+
170
+ ### `publish` options
171
+
172
+ `--dry` runs the command in simulation mode ("dry run"), showing changes that would be made without actually applying them. Useful for previewing changes before application.
173
+
174
+ `--skipBuild` excludes running the build process after updating package versions. Skips executing tasks defined in the build pipeline, allowing you to decide whether recompilation is necessary after changing version numbers.
175
+
176
+ `--skipGit` ignores actions related to the Git version control system, such as committing changes, creating commit tags, or pushing updates to a remote repository. Might be useful if you wish to manage Git operations manually later.
package/README.ru.md ADDED
@@ -0,0 +1,175 @@
1
+ # @mirta/cli
2
+
3
+ [![en](https://img.shields.io/badge/lang-en-dimgray.svg?style=flat-square)](https://github.com/wb-mirta/core/blob/latest/packages/mirta-cli/README.md)
4
+ [![ru](https://img.shields.io/badge/lang-ru-olivedrab.svg?style=flat-square)](https://github.com/wb-mirta/core/blob/latest/packages/mirta-cli/README.ru.md)
5
+ [![NPM Version](https://img.shields.io/npm/v/@mirta/globals?style=flat-square)](https://npmjs.com/package/@mirta/cli)
6
+ [![NPM Downloads](https://img.shields.io/npm/dm/@mirta/cli?style=flat-square&logo=npm)](https://npmjs.com/package/@mirta/cli)
7
+
8
+ Утилита для эффективного управления выпуском релизов и автоматизированной публикации пакетов в NPM, поддерживает работу в монорепозиториях.
9
+
10
+ ### Ключевые возможности
11
+
12
+ - Удобная система обновления версий проектов;
13
+ - Простая интеграция с существующими процессами CI/CD;
14
+ - Доступ ко всем необходимым операциям через интуитивные команды;
15
+ - Поддержка кастомизации рабочего потока под специфику вашей инфраструктуры.
16
+
17
+ ## Установка и начальная настройка
18
+
19
+ Подключите `@mirta/cli` в ваш проект как dev-зависимость следующей командой:
20
+
21
+ ```sh
22
+ pnpm add -wD @mirta/cli
23
+ ```
24
+ Можно настроить дополнительные параметры, добавив файл конфигурации `mirta.config.json` в корень главного проекта. Например:
25
+
26
+ ```json
27
+ {
28
+ "scope": "myscope",
29
+ "scopeAsPackagePrefix": false
30
+ }
31
+ ```
32
+ ### Основные опции конфигурации
33
+
34
+ - `scope` задаёт соответствие названию аккаунта или организации в реестре NPM
35
+
36
+ - `scopeAsPackagePrefix` включает преобразование путей к модулям, добавляя указанный `scope` перед названием пакета. По умолчанию - `false`.
37
+
38
+ Пример `scopeAsPackagePrefix` для пакета `@myscope/globals`:
39
+ - `true` - расположение `packages/myscope-globals`,
40
+ - `false` - расположение `packages/globals`.
41
+
42
+ Активация данной опции позволяет предотвратить коллизии со сторонними NPM-пакетами без `scope`.
43
+
44
+ Если вам подходит стандартное поведение инструмента, создание отдельного файла конфигурации не требуется. Достаточно указать scope в основном файле `package.json` следующим образом:
45
+
46
+ ```json
47
+ {
48
+ "name": "@myscope/myproject"
49
+ }
50
+ ```
51
+
52
+ ### Специальные опции фреймворка Мирта
53
+
54
+ - `templates` содержит набор путей к шаблонам мастера генерации проектов. Выполняет рекурсивный поиск файлов `package.json` в перечисленных расположениях.
55
+
56
+ Пример конфигурации Мирты:
57
+
58
+ ```json
59
+ {
60
+ "scopeAsPackagePrefix": true,
61
+ "templates": [
62
+ "packages/create-mirta/public/templates"
63
+ ]
64
+ }
65
+ ```
66
+
67
+ ## Управление релизами
68
+
69
+ Выполнение процедуры выпуска релиза в интерактивном режиме:
70
+
71
+ ```sh
72
+ pnpm mirta release
73
+ ```
74
+ Команда предложит выбрать подходящую версию, а если проект управляется Git, то подготовит список изменений в файле `CHANGELOG.md`, проверит CI-статус и создаст коммит.
75
+
76
+ Во время работы с Git нужный репозиторий распознаётся автоматически, однако выполняются две проверки:
77
+ 1. Локальные изменения заранее синхронизированы с удалённым хранилищем;
78
+ 2. Процесс CI под названием `Build` для последнего коммита успешно завершён.
79
+
80
+ Для генерации файла со списком изменений в dev-зависимости корневого `package.json` нужно добавить пакет [conventional-changelog-cli](https://www.npmjs.com/package/conventional-changelog-cli), а в секции `scripts` должна присутствовать команда `changelog`:
81
+ ```json
82
+ {
83
+ "scripts": {
84
+ "changelog": "conventional-changelog -p angular -i CHANGELOG.md -s"
85
+ }
86
+ }
87
+ ```
88
+
89
+ Список изменений в автоматически генерируемом Changelog основывается на выполненных в пределах версии коммитах. При этом есть требования к заголовкам:
90
+
91
+ 1. Общая длина строки не должна превышать 50 символов;
92
+ 2. Использовать префиксы вида `fix:`, `feat:`, `docs:`, `chore:` и т.п.
93
+
94
+ Полный список требований смотреть в соглашении [Commit Convention](https://github.com/wb-mirta/core/blob/latest/.github/commit-convention.md) фреймворка.
95
+
96
+ ### Семантическое версионирование
97
+
98
+ Семантическая версия имеет вид `major.minor.patch` (например, `1.2.3`), где каждый сегмент обозначает разные уровни изменений:
99
+
100
+ - `major` увеличивается, когда вносятся несовместимые изменения;
101
+ - `minor` увеличивается, когда добавляется новая функциональность, сохраняющая обратную совместимость;
102
+ - `patch` увеличивается при исправлениях багов, сохраняя обратную совместимость.
103
+
104
+ Релиз с указанием конкретной версии:
105
+
106
+ ```sh
107
+ pnpm mirta release 1.2.3
108
+ ```
109
+ Релиз с указанием инкрементируемой части:
110
+
111
+ ```sh
112
+ pnpm mirta release patch
113
+ # 0.0.1
114
+ ```
115
+ ```sh
116
+ pnpm mirta release minor
117
+ # 0.1.0
118
+ ```
119
+ ```sh
120
+ pnpm mirta release major
121
+ # 1.0.0
122
+ ```
123
+ Релиз предварительной версии с указанием типа:
124
+
125
+ ```sh
126
+ pnpm mirta release prepatch --preid alpha
127
+ # 0.0.1-alpha.0
128
+ ```
129
+ ```sh
130
+ pnpm mirta release preminor --preid alpha
131
+ # 0.1.0-alpha.0
132
+ ```
133
+ ```sh
134
+ pnpm mirta release premajor --preid alpha
135
+ # 1.0.0-alpha.0
136
+ ```
137
+ Инкремент уже существующей предварительной версии осуществляется через
138
+
139
+ ```sh
140
+ pnpm mirta release prerelease --preid alpha
141
+ # 0.0.1-alpha.1
142
+ ```
143
+
144
+ ## Автоматическая публикация
145
+
146
+ Публикуйте готовые пакеты в репозиторий NPM:
147
+
148
+ ```sh
149
+ pnpm mirta publish
150
+ ```
151
+ Операция запустит процедуру сборки и публикации готовых пакетов.
152
+
153
+ Если процесс запущен через CI на GitHub, то к публикуемому пакету автоматически добавляется [информация о происхождении](https://docs.npmjs.com/generating-provenance-statements) каждого файла внутри пакета - хэш и метаданные, подтверждающие целостность и подлинность.
154
+
155
+ Основная цель опции заключается в повышении уровня доверия и безопасности публикуемых пакетов. Если пакет опубликован с использованием этой опции, пользователи смогут проверить, соответствует ли содержимое загруженного пакета оригинальному источнику, указанному автором.
156
+
157
+ ## Вспомогательные опции
158
+
159
+ ### Опции `release`
160
+
161
+ `--dry` запускает команду в режиме симуляции ("dry run"), показывая изменения, которые будут произведены, но фактически ничего не меняя. Полезно для предварительного просмотра изменений перед применением.
162
+
163
+ `--preid <custom-pre-release-id>` устанавливает кастомный префикс для предварительной версии, который добавляется к номеру версии пакета (например, beta.1). Эта опция позволяет создавать предварительные версии типа альфа, бета, RC и др. перед официальным стабильным выпуском.
164
+
165
+ `--skipPrompts` пропускает интерактивные запросы пользователя. Команда выполняется автоматически, используя значения по умолчанию или заданные настройки.
166
+
167
+ `--skipGit` игнорирует действия, связанные с системой контроля версий Git, такие как фиксация изменений, создание меток коммитов или отправка изменений на удалённый репозиторий. Может пригодиться, если вы хотите самостоятельно управлять операциями с Git позже.
168
+
169
+ ### Опции `publish`
170
+
171
+ `--dry` запускает команду в режиме симуляции ("dry run"), показывая изменения, которые будут произведены, но фактически ничего не меняя. Полезно для предварительного просмотра изменений перед применением.
172
+
173
+ `--skipBuild` исключает запуск процесса сборки после обновления версий пакетов. Пропускает выполнение заданий, указанных в конвейере сборки, позволяя вам самим решать, необходима ли повторная компиляция после изменения номеров версий.
174
+
175
+ `--skipGit` игнорирует действия, связанные с системой контроля версий Git, такие как фиксация изменений, создание меток коммитов или отправка изменений на удалённый репозиторий. Может пригодиться, если вы хотите самостоятельно управлять операциями с Git позже.
package/bin/mirta.mjs ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+
3
+ import '../dist/index.mjs'
@@ -0,0 +1,135 @@
1
+ import p from 'prompts';
2
+ import { r as runCommandAsync } from './shell.mjs';
3
+
4
+ class PromptCanceledError extends Error {
5
+ constructor() {
6
+ super();
7
+ // Убедимся, что экземпляр имеет правильный прототип
8
+ Object.setPrototypeOf(this, PromptCanceledError.prototype);
9
+ this.name = 'PromptCanceledError';
10
+ Error.captureStackTrace(this, PromptCanceledError);
11
+ }
12
+ }
13
+ /**
14
+ * @param {import('prompts').PromptObject<string> | Array<import('prompts').PromptObject<string>>} questions
15
+ * @param {import('prompts').Options} options
16
+ */
17
+ async function prompts(questions, options) {
18
+ const po = {
19
+ onCancel: () => {
20
+ throw new PromptCanceledError();
21
+ },
22
+ };
23
+ return await p(questions, po);
24
+ }
25
+
26
+ const baseUrl = 'https://api.github.com/repos';
27
+ /** Класс ошибки уровня Git. */
28
+ class GitError extends Error {
29
+ constructor(message) {
30
+ super(message);
31
+ // Убедимся, что экземпляр имеет правильный прототип
32
+ Object.setPrototypeOf(this, GitError.prototype);
33
+ this.name = 'GitError';
34
+ this.message = message;
35
+ Error.captureStackTrace(this, GitError);
36
+ }
37
+ }
38
+ /** Класс ошибки уровня взаимодействия GitHub. */
39
+ class GithubError extends Error {
40
+ constructor(message) {
41
+ super(message);
42
+ // Убедимся, что экземпляр имеет правильный прототип
43
+ Object.setPrototypeOf(this, GithubError.prototype);
44
+ this.name = 'GithubError';
45
+ this.message = message;
46
+ Error.captureStackTrace(this, GithubError);
47
+ }
48
+ }
49
+ /** Класс ошибки уровня GitHub Workflow. */
50
+ class WorkflowStatusError extends Error {
51
+ constructor(message) {
52
+ super(message);
53
+ // Убедимся, что экземпляр имеет правильный прототип
54
+ Object.setPrototypeOf(this, WorkflowStatusError.prototype);
55
+ this.name = 'WorkflowStatusError';
56
+ this.message = message;
57
+ Error.captureStackTrace(this, WorkflowStatusError);
58
+ }
59
+ }
60
+ /** Определяет, находится ли текущее решение в рабочем дереве Git. */
61
+ async function checkIsInWorkTreeAsync() {
62
+ try {
63
+ const { stdout } = await runCommandAsync('git', ['rev-parse', '--is-inside-work-tree'], { stdio: 'pipe' });
64
+ return stdout === 'true';
65
+ }
66
+ catch {
67
+ return false;
68
+ }
69
+ }
70
+ const getConnectionType = (url) => {
71
+ if (url.startsWith('git@'))
72
+ return 'ssh';
73
+ if (url.startsWith('https://'))
74
+ return 'https';
75
+ };
76
+ /** Возвращает имя репозитория и тип подключения. */
77
+ async function getRepositoryDetails() {
78
+ const { stdout, stderr } = await runCommandAsync('git', ['config', 'remote.origin.url'], { stdio: 'pipe' });
79
+ if (stderr)
80
+ throw new GitError(stderr);
81
+ // Match the URLs like:
82
+ // git@github.com:wb-mirta/core.git
83
+ // https://github.com/wb-mirta/core.git
84
+ //
85
+ const regex = /^(?:git@|https:\/\/)(?:[^/:]+)[/:]?(.*?).git$/i;
86
+ const match = regex
87
+ .exec(stdout);
88
+ if (!match?.[1])
89
+ throw new GitError(`Unable to detect remote origin url`);
90
+ return {
91
+ name: match[1],
92
+ connectionType: getConnectionType(stdout),
93
+ };
94
+ }
95
+ /** Возвращает SHA текущего HEAD. */
96
+ async function getShaAsync() {
97
+ return (await runCommandAsync('git', ['rev-parse', 'HEAD'])).stdout;
98
+ }
99
+ /** Возвращает имя текущей ветки. */
100
+ async function getBranchAsync() {
101
+ return (await runCommandAsync('git', ['rev-parse', '--abbrev-ref', 'HEAD'])).stdout;
102
+ }
103
+ /** Проверяет, синхронизирован ли текущий HEAD с удаленным. */
104
+ async function ensureIsSyncedWithRemoteAsync(repository) {
105
+ let isSynced = false;
106
+ try {
107
+ const branch = await getBranchAsync();
108
+ const remote = await fetch(`${baseUrl}/${repository}/commits/${branch}?per_page=1`);
109
+ const data = await remote.json();
110
+ isSynced = data.sha === await getShaAsync();
111
+ }
112
+ catch {
113
+ throw new GithubError('Failed to check whether local HEAD is up-to-date with remote');
114
+ }
115
+ if (!isSynced)
116
+ throw new GithubError('Local HEAD is not up-to-date with remote');
117
+ }
118
+ /** Проверяет успешность CI-построения последнего коммита. */
119
+ async function ensureWorkflowResultAsync(repository, name) {
120
+ let isBuildPassed = false;
121
+ try {
122
+ const sha = await getShaAsync();
123
+ const result = await fetch(`${baseUrl}/${repository}/actions/runs?head_sha=${sha}&status=completed&exclude_pull_requests=true`);
124
+ const data = await result.json();
125
+ isBuildPassed = data.workflow_runs.some(({ name: workflowName, conclusion }) => workflowName.toLowerCase() === name.toLowerCase()
126
+ && conclusion === 'success');
127
+ }
128
+ catch {
129
+ throw new GithubError('Unable to get CI status for the current commit');
130
+ }
131
+ if (!isBuildPassed)
132
+ throw new WorkflowStatusError('CI build of the latest commit has not passed yet');
133
+ }
134
+
135
+ export { GitError as G, PromptCanceledError as P, WorkflowStatusError as W, GithubError as a, ensureWorkflowResultAsync as b, checkIsInWorkTreeAsync as c, ensureIsSyncedWithRemoteAsync as e, getRepositoryDetails as g, prompts as p };
package/dist/index.mjs ADDED
@@ -0,0 +1,46 @@
1
+ import { g as getLocalized, S as ShellError, u as useLogger } from './shell.mjs';
2
+ import { G as GitError, a as GithubError, W as WorkflowStatusError, P as PromptCanceledError } from './github.mjs';
3
+ import 'node:child_process';
4
+ import 'node:url';
5
+ import 'node:fs';
6
+ import 'node:path';
7
+ import 'lodash.merge';
8
+ import 'chalk';
9
+ import 'prompts';
10
+
11
+ const messages = await getLocalized();
12
+ const logger = useLogger(messages);
13
+ async function run() {
14
+ const command = process.argv[2];
15
+ if (command === 'release') {
16
+ await import('./release.mjs');
17
+ }
18
+ else if (command === 'publish') {
19
+ await import('./publish.mjs');
20
+ }
21
+ }
22
+ function prettify(message, name) {
23
+ if (name && message.startsWith(name))
24
+ return message.slice(name.length);
25
+ return message;
26
+ }
27
+ run().catch((e) => {
28
+ if (e instanceof GitError || e instanceof GithubError || e instanceof WorkflowStatusError || e instanceof ShellError) {
29
+ logger.error(prettify(e.message, e.name));
30
+ }
31
+ else if (e instanceof PromptCanceledError) {
32
+ logger.cancel(messages.errors.operationCanceled);
33
+ }
34
+ else if (e instanceof Error && 'code' in e) {
35
+ // if (e.code === 'ERR_PARSE_ARGS_UNKNOWN_OPTION')
36
+ // if (e.code === 'ENOENT')
37
+ logger.error(prettify(e.message, e.name));
38
+ }
39
+ else if (e instanceof Error) {
40
+ logger.error(prettify(e.message, e.name));
41
+ }
42
+ else if (typeof e === 'string') {
43
+ logger.error(e);
44
+ }
45
+ process.exit();
46
+ });
@@ -0,0 +1,21 @@
1
+ {
2
+ "validation": {
3
+ "required": "Must be provided"
4
+ },
5
+ "status": {
6
+ "info": "Info",
7
+ "note": "Note",
8
+ "success": "Success",
9
+ "warn": "Warn",
10
+ "error": "Error",
11
+ "canceled": "Canceled"
12
+ },
13
+ "accent": {
14
+ "recommended": "(recommended)",
15
+ "ifConfigured": "(if configured)"
16
+ },
17
+ "errors": {
18
+ "operationCanceled": "Operation canceled",
19
+ "rootIsNotRelative": "Location is out of working directory"
20
+ }
21
+ }
@@ -0,0 +1,21 @@
1
+ {
2
+ "validation": {
3
+ "required": "Требуется указать значение"
4
+ },
5
+ "status": {
6
+ "info": "Инфо",
7
+ "note": "Примечание",
8
+ "success": "Успешно",
9
+ "warn": "Внимание",
10
+ "error": "Ошибка",
11
+ "canceled": "Отменено"
12
+ },
13
+ "accent": {
14
+ "recommended": "(рекомендуется)",
15
+ "ifConfigured": "(если настроен)"
16
+ },
17
+ "errors": {
18
+ "operationCanceled": "Операция прервана",
19
+ "rootIsNotRelative": "Расположение находится вне рабочей директории"
20
+ }
21
+ }