deploy-vir 0.0.0 → 0.0.2

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-CC0 ADDED
@@ -0,0 +1,121 @@
1
+ CC0 1.0 Universal
2
+
3
+ Creative Commons Legal Code
4
+
5
+ CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
6
+ LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
7
+ ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
8
+ INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
9
+ REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
10
+ PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
11
+ THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
12
+ HEREUNDER.
13
+
14
+ Statement of Purpose
15
+
16
+ The laws of most jurisdictions throughout the world automatically confer
17
+ exclusive Copyright and Related Rights (defined below) upon the creator
18
+ and subsequent owner(s) (each and all, an "owner") of an original work of
19
+ authorship and/or a database (each, a "Work").
20
+
21
+ Certain owners wish to permanently relinquish those rights to a Work for
22
+ the purpose of contributing to a commons of creative, cultural and
23
+ scientific works ("Commons") that the public can reliably and without fear
24
+ of later claims of infringement build upon, modify, incorporate in other
25
+ works, reuse and redistribute as freely as possible in any form whatsoever
26
+ and for any purposes, including without limitation commercial purposes.
27
+ These owners may contribute to the Commons to promote the ideal of a free
28
+ culture and the further production of creative, cultural and scientific
29
+ works, or to gain reputation or greater distribution for their Work in
30
+ part through the use and efforts of others.
31
+
32
+ For these and/or other purposes and motivations, and without any
33
+ expectation of additional consideration or compensation, the person
34
+ associating CC0 with a Work (the "Affirmer"), to the extent that he or she
35
+ is an owner of Copyright and Related Rights in the Work, voluntarily
36
+ elects to apply CC0 to the Work and publicly distribute the Work under its
37
+ terms, with knowledge of his or her Copyright and Related Rights in the
38
+ Work and the meaning and intended legal effect of CC0 on those rights.
39
+
40
+ 1. Copyright and Related Rights. A Work made available under CC0 may be
41
+ protected by copyright and related or neighboring rights ("Copyright and
42
+ Related Rights"). Copyright and Related Rights include, but are not
43
+ limited to, the following:
44
+
45
+ i. the right to reproduce, adapt, distribute, perform, display,
46
+ communicate, and translate a Work;
47
+ ii. moral rights retained by the original author(s) and/or performer(s);
48
+ iii. publicity and privacy rights pertaining to a person's image or
49
+ likeness depicted in a Work;
50
+ iv. rights protecting against unfair competition in regards to a Work,
51
+ subject to the limitations in paragraph 4(a), below;
52
+ v. rights protecting the extraction, dissemination, use and reuse of data
53
+ in a Work;
54
+ vi. database rights (such as those arising under Directive 96/9/EC of the
55
+ European Parliament and of the Council of 11 March 1996 on the legal
56
+ protection of databases, and under any national implementation
57
+ thereof, including any amended or successor version of such
58
+ directive); and
59
+ vii. other similar, equivalent or corresponding rights throughout the
60
+ world based on applicable law or treaty, and any national
61
+ implementations thereof.
62
+
63
+ 2. Waiver. To the greatest extent permitted by, but not in contravention
64
+ of, applicable law, Affirmer hereby overtly, fully, permanently,
65
+ irrevocably and unconditionally waives, abandons, and surrenders all of
66
+ Affirmer's Copyright and Related Rights and associated claims and causes
67
+ of action, whether now known or unknown (including existing as well as
68
+ future claims and causes of action), in the Work (i) in all territories
69
+ worldwide, (ii) for the maximum duration provided by applicable law or
70
+ treaty (including future time extensions), (iii) in any current or future
71
+ medium and for any number of copies, and (iv) for any purpose whatsoever,
72
+ including without limitation commercial, advertising or promotional
73
+ purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
74
+ member of the public at large and to the detriment of Affirmer's heirs and
75
+ successors, fully intending that such Waiver shall not be subject to
76
+ revocation, rescission, cancellation, termination, or any other legal or
77
+ equitable action to disrupt the quiet enjoyment of the Work by the public
78
+ as contemplated by Affirmer's express Statement of Purpose.
79
+
80
+ 3. Public License Fallback. Should any part of the Waiver for any reason
81
+ be judged legally invalid or ineffective under applicable law, then the
82
+ Waiver shall be preserved to the maximum extent permitted taking into
83
+ account Affirmer's express Statement of Purpose. In addition, to the
84
+ extent the Waiver is so judged Affirmer hereby grants to each affected
85
+ person a royalty-free, non transferable, non sublicensable, non exclusive,
86
+ irrevocable and unconditional license to exercise Affirmer's Copyright and
87
+ Related Rights in the Work (i) in all territories worldwide, (ii) for the
88
+ maximum duration provided by applicable law or treaty (including future
89
+ time extensions), (iii) in any current or future medium and for any number
90
+ of copies, and (iv) for any purpose whatsoever, including without
91
+ limitation commercial, advertising or promotional purposes (the
92
+ "License"). The License shall be deemed effective as of the date CC0 was
93
+ applied by Affirmer to the Work. Should any part of the License for any
94
+ reason be judged legally invalid or ineffective under applicable law, such
95
+ partial invalidity or ineffectiveness shall not invalidate the remainder
96
+ of the License, and in such case Affirmer hereby affirms that he or she
97
+ will not (i) exercise any of his or her remaining Copyright and Related
98
+ Rights in the Work or (ii) assert any associated claims and causes of
99
+ action with respect to the Work, in either case contrary to Affirmer's
100
+ express Statement of Purpose.
101
+
102
+ 4. Limitations and Disclaimers.
103
+
104
+ a. No trademark or patent rights held by Affirmer are waived, abandoned,
105
+ surrendered, licensed or otherwise affected by this document.
106
+ b. Affirmer offers the Work as-is and makes no representations or
107
+ warranties of any kind concerning the Work, express, implied,
108
+ statutory or otherwise, including without limitation warranties of
109
+ title, merchantability, fitness for a particular purpose, non
110
+ infringement, or the absence of latent or other defects, accuracy, or
111
+ the present or absence of errors, whether or not discoverable, all to
112
+ the greatest extent permissible under applicable law.
113
+ c. Affirmer disclaims responsibility for clearing rights of other persons
114
+ that may apply to the Work or any use thereof, including without
115
+ limitation any person's Copyright and Related Rights in the Work.
116
+ Further, Affirmer disclaims responsibility for obtaining any necessary
117
+ consents, permissions or other rights required for any use of the
118
+ Work.
119
+ d. Affirmer understands and acknowledges that Creative Commons is not a
120
+ party to this document and has no duty or obligation with respect to
121
+ this CC0 or use of the Work.
package/LICENSE-MIT ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 electrovir
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,56 @@
1
+ # deploy-vir
2
+
3
+ Deploy from branch to branch via git.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ npm i -D deploy-vir
9
+ ```
10
+
11
+ ## Setup
12
+
13
+ Add a TypeScript or JavaScript config file somewhere in your repo. Its default export should be your config:
14
+
15
+ <!-- example-link: src/readme-examples/config.example.ts -->
16
+
17
+ ```TypeScript
18
+ import {defineDeployVirConfig, NotificationTarget} from 'deploy-vir';
19
+
20
+ export default defineDeployVirConfig({
21
+ repos: [
22
+ {
23
+ /** This does not need to match the actual repo name. */
24
+ name: 'whatever',
25
+ girUrl: 'git@github.com:electrovir/deploy-vir.git',
26
+ deploys: [
27
+ {
28
+ deployName: 'staging',
29
+ fromBranch: 'dev',
30
+ toBranch: 'staging',
31
+ },
32
+ {
33
+ deployName: 'prod',
34
+ fromBranch: 'staging',
35
+ toBranch: 'prod',
36
+ },
37
+ ],
38
+ },
39
+ ],
40
+ notifications: [
41
+ {
42
+ target: NotificationTarget.Slack,
43
+ webhookUrl: 'https://hooks.slack.com/services/X/X/X',
44
+ channelName: '#deploys',
45
+ },
46
+ ],
47
+ });
48
+ ```
49
+
50
+ ## Running
51
+
52
+ Then just run the CLI:
53
+
54
+ ```sh
55
+ npx deploy-vir <path-to-config> <repo-name-to-deploy> <deploy-name-to-deploy>
56
+ ```
package/bin.js ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+
3
+ import {runCliScript} from '@augment-vir/node/dist/index.js';
4
+ import {join} from 'node:path';
5
+
6
+ const cliPath = join(import.meta.dirname, 'src', 'cli.script.ts');
7
+
8
+ await runCliScript(cliPath, import.meta.filename, 'deploy-vir');
@@ -0,0 +1,25 @@
1
+ import { type DeployVirConfig } from '../config.js';
2
+ /**
3
+ * Run the deploy-vir CLI.
4
+ *
5
+ * @category Internal
6
+ */
7
+ export declare function runDeployVirCli(args: ReadonlyArray<string>, cwd?: string): Promise<void>;
8
+ /**
9
+ * Args for {@link runDeployVir}.
10
+ *
11
+ * @category Internal
12
+ */
13
+ export type DeployVirArgs = {
14
+ /** This must match a repo name in your config. */
15
+ repoName: string;
16
+ /** This much match a deploy name in your config. */
17
+ deployName: string;
18
+ cwd: string;
19
+ };
20
+ /**
21
+ * Run a deploy.
22
+ *
23
+ * @category Main
24
+ */
25
+ export declare function runDeployVir(args: Readonly<DeployVirArgs>, config: Readonly<DeployVirConfig>): Promise<void>;
@@ -0,0 +1,48 @@
1
+ import { assertWrap } from '@augment-vir/assert';
2
+ import { extractErrorMessage, log } from '@augment-vir/common';
3
+ import simpleGit from 'simple-git';
4
+ import { getGitRemoteName, pushDeploy } from '../git.js';
5
+ import { KnownError } from '../known.error.js';
6
+ import { sendNotifications } from '../notifications/send-notifications.js';
7
+ /**
8
+ * Run the deploy-vir CLI.
9
+ *
10
+ * @category Internal
11
+ */
12
+ export async function runDeployVirCli(args, cwd = process.cwd()) {
13
+ const configPath = assertWrap.isTruthy(args[0], 'Missing config path.');
14
+ const repoName = assertWrap.isTruthy(args[1], 'Missing repo name.');
15
+ const deployName = assertWrap.isTruthy(args[2], 'Missing deploy name.');
16
+ const config = (await import(configPath)).default;
17
+ await runDeployVir({ cwd, deployName, repoName }, config);
18
+ }
19
+ /**
20
+ * Run a deploy.
21
+ *
22
+ * @category Main
23
+ */
24
+ export async function runDeployVir(args, config) {
25
+ try {
26
+ const git = simpleGit(args.cwd);
27
+ const repoConfig = assertWrap.isDefined(config.repos.find((repo) => repo.name === args.repoName, `Failed to find a repo config by name '${args.repoName}'`));
28
+ const branchConfig = assertWrap.isDefined(repoConfig.deploys.find((deploy) => deploy.deployName === args.deployName, `Failed to find a deploy named '${args.deployName}' in repo '${args.repoName}'.`));
29
+ const remoteName = await getGitRemoteName(git, repoConfig);
30
+ const deployCommits = await pushDeploy(git, branchConfig, remoteName);
31
+ if (config.notifications?.length) {
32
+ await sendNotifications(config.notifications, {
33
+ branchConfig,
34
+ deployCommits,
35
+ repoConfig,
36
+ });
37
+ }
38
+ }
39
+ catch (error) {
40
+ if (error instanceof KnownError) {
41
+ /** If its a known error, don't log the whole stack trace. */
42
+ log.error(extractErrorMessage(error));
43
+ }
44
+ else {
45
+ log.error(error);
46
+ }
47
+ }
48
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ import { runDeployVirCli } from './cli.js';
2
+ await runDeployVirCli(process.argv, process.cwd());
@@ -0,0 +1,101 @@
1
+ /**
2
+ * The full deploy-vir config object.
3
+ *
4
+ * @category Config
5
+ */
6
+ export type DeployVirConfig = {
7
+ repos: DeployVirRepoConfig[];
8
+ notifications?: NotificationConfig[] | undefined;
9
+ };
10
+ /**
11
+ * All available targets for sending notifications to.
12
+ *
13
+ * @category Internal
14
+ */
15
+ export declare enum NotificationTarget {
16
+ Slack = "slack"
17
+ }
18
+ /**
19
+ * Notification config for Slack.
20
+ *
21
+ * @category Internal
22
+ */
23
+ export type SlackNotificationConfig = {
24
+ target: NotificationTarget;
25
+ /**
26
+ * Find or create this by going to:
27
+ *
28
+ * Apps and workflows > Custom Integrations > Incoming WebHooks
29
+ */
30
+ webhookUrl: string;
31
+ /**
32
+ * An emoji string for the Webhook's message. If not provided, the Webhook integration's avatar
33
+ * that you set will be used.
34
+ */
35
+ avatarEmoji?: string | undefined;
36
+ /**
37
+ * A username for the Webhook's message. If not provided, the Webhook integration's avatar that
38
+ * you set will be used.
39
+ */
40
+ username?: string | undefined;
41
+ /** A channel for the Webhook's message. If not provided, the Webhook integration */
42
+ channelName: string | undefined;
43
+ /**
44
+ * By default the notification will list out all commits that are getting deployed. This will
45
+ * turn that off.
46
+ */
47
+ hideAllCommits?: boolean | undefined;
48
+ };
49
+ /**
50
+ * Config for a notification when a deploy runs.
51
+ *
52
+ * @category Config
53
+ */
54
+ export type NotificationConfig = SlackNotificationConfig;
55
+ /**
56
+ * A repo config for deploying.
57
+ *
58
+ * @category Config
59
+ */
60
+ export type DeployVirRepoConfig = {
61
+ /**
62
+ * Does not need to match the actual repo name in GitHub, it can just be whatever name you want
63
+ * to call it for deploy-vir.
64
+ */
65
+ name: string;
66
+ /**
67
+ * A git URL to the repo.
68
+ *
69
+ * @example
70
+ *
71
+ * - 'git@github.com:electrovir/deploy-vir.git'
72
+ * - 'https://github.com/electrovir/deploy-vir.git'
73
+ */
74
+ girUrl: string;
75
+ /**
76
+ * A url to the base commit path for links. The commit hash will be appended to this for links
77
+ * in notifications. If this is omitted, there simply won't be any links.
78
+ *
79
+ * @example
80
+ *
81
+ * - 'https://github.com/electrovir/deploy-vir/commit'
82
+ */
83
+ commitBaseUrl?: string | undefined;
84
+ deploys: DeployVirBranchConfig[];
85
+ };
86
+ /**
87
+ * A deploy configuration.
88
+ *
89
+ * @category Config
90
+ */
91
+ export type DeployVirBranchConfig = {
92
+ deployName: string;
93
+ fromBranch: string;
94
+ toBranch: string;
95
+ };
96
+ /**
97
+ * Define a type safe deploy-vir config.
98
+ *
99
+ * @category Internal
100
+ */
101
+ export declare function defineDeployVirConfig(config: Readonly<DeployVirConfig>): Readonly<DeployVirConfig>;
package/dist/config.js ADDED
@@ -0,0 +1,17 @@
1
+ /**
2
+ * All available targets for sending notifications to.
3
+ *
4
+ * @category Internal
5
+ */
6
+ export var NotificationTarget;
7
+ (function (NotificationTarget) {
8
+ NotificationTarget["Slack"] = "slack";
9
+ })(NotificationTarget || (NotificationTarget = {}));
10
+ /**
11
+ * Define a type safe deploy-vir config.
12
+ *
13
+ * @category Internal
14
+ */
15
+ export function defineDeployVirConfig(config) {
16
+ return config;
17
+ }
package/dist/git.d.ts ADDED
@@ -0,0 +1,29 @@
1
+ import { type DefaultLogFields, type ListLogLine, type SimpleGit } from 'simple-git';
2
+ import { type DeployVirBranchConfig, type DeployVirRepoConfig } from './config.js';
3
+ /**
4
+ * Find the git remote's name, or create a new one.
5
+ *
6
+ * @category Internal
7
+ */
8
+ export declare function getGitRemoteName(git: Readonly<SimpleGit>, repoConfig: Readonly<Pick<DeployVirRepoConfig, 'name' | 'girUrl'>>): Promise<string>;
9
+ /**
10
+ * A git commit.
11
+ *
12
+ * @category Internal
13
+ */
14
+ export type Commit = DefaultLogFields & ListLogLine;
15
+ /**
16
+ * All commits involved in a deploy.
17
+ *
18
+ * @category Internal
19
+ */
20
+ export type DeployCommits = {
21
+ deployedCommits: ReadonlyArray<Readonly<Commit>>;
22
+ overwrittenCommits: ReadonlyArray<Readonly<Commit>>;
23
+ };
24
+ /**
25
+ * Push the deploy via git.
26
+ *
27
+ * @category Internal
28
+ */
29
+ export declare function pushDeploy(git: Readonly<SimpleGit>, { deployName, fromBranch, toBranch }: Readonly<DeployVirBranchConfig>, remoteName: string): Promise<DeployCommits>;
package/dist/git.js ADDED
@@ -0,0 +1,80 @@
1
+ import { assert, check } from '@augment-vir/assert';
2
+ import { extractErrorMessage, log, logColors } from '@augment-vir/common';
3
+ import { askQuestion } from '@augment-vir/node';
4
+ import { KnownError } from './known.error.js';
5
+ /**
6
+ * Find the git remote's name, or create a new one.
7
+ *
8
+ * @category Internal
9
+ */
10
+ export async function getGitRemoteName(git, repoConfig) {
11
+ assert.isTruthy(repoConfig.name, 'Repo config name cannot be empty.');
12
+ assert.isTruthy(repoConfig.girUrl, 'Repo git URL cannot be empty.');
13
+ const remotes = await git.getRemotes(true);
14
+ const remoteMatchByUrl = remotes.find((remote) => remote.refs.fetch === repoConfig.girUrl || remote.refs.push === repoConfig.girUrl);
15
+ if (remoteMatchByUrl) {
16
+ return remoteMatchByUrl.name;
17
+ }
18
+ const remoteMatchByNameCount = remotes.reduce((count, remote) => count + (remote.name === repoConfig.name ? 1 : 0), 0);
19
+ const newRemoteName = [
20
+ repoConfig.name,
21
+ remoteMatchByNameCount,
22
+ ]
23
+ .filter(check.isTruthy)
24
+ .join('-');
25
+ await git.addRemote(newRemoteName, repoConfig.girUrl);
26
+ return newRemoteName;
27
+ }
28
+ /**
29
+ * Push the deploy via git.
30
+ *
31
+ * @category Internal
32
+ */
33
+ export async function pushDeploy(git, { deployName, fromBranch, toBranch }, remoteName) {
34
+ assert.isTruthy(fromBranch, `Deploy '${deployName}' fromBranch cannot be empty.`);
35
+ assert.isTruthy(toBranch, `Deploy '${deployName}' toBranch cannot be empty.`);
36
+ assert.isTruthy(remoteName, 'Remote name cannot be empty.');
37
+ await git.fetch(remoteName, fromBranch);
38
+ const pushString = `${remoteName}/${fromBranch}:${toBranch}`;
39
+ /** Get commits that are on {@link toBranch} but not on {@link fromBranch}. */
40
+ const commitsAhead = (await git.log({
41
+ from: `${remoteName}/${toBranch}`,
42
+ to: `${remoteName}/${fromBranch}`,
43
+ })).all;
44
+ if (!commitsAhead.length) {
45
+ throw new KnownError('No commit diff: nothing to deploy!');
46
+ }
47
+ try {
48
+ await git.push(remoteName, pushString);
49
+ return {
50
+ deployedCommits: commitsAhead,
51
+ overwrittenCommits: [],
52
+ };
53
+ }
54
+ catch (error) {
55
+ log.error(`Push failed: ${extractErrorMessage(error)}`);
56
+ /** Get commits that are on {@link toBranch} but not on {@link fromBranch}. */
57
+ const commitsBehind = await git.log({
58
+ from: `${remoteName}/${fromBranch}`,
59
+ to: `${remoteName}/${toBranch}`,
60
+ });
61
+ if (commitsBehind.total > 0) {
62
+ log.info(`\nThe following ${commitsBehind.total} commit${commitsBehind.total === 1 ? '' : 's'} are on ${logColors.bold}${toBranch}${logColors.reset} but not on ${logColors.bold}${fromBranch}${logColors.reset}:`);
63
+ commitsBehind.all.forEach((commit, index) => {
64
+ log.faint(` ${index + 1}. ${commit.hash.slice(0, 7)} (${commit.author_name}) - ${commit.message}`);
65
+ });
66
+ }
67
+ const shouldForcePush = await askQuestion(`\nDo you want to force push ${logColors.bold}${fromBranch}${logColors.reset} to ${logColors.bold}${toBranch}${logColors.reset}?\n\n${logColors.warning}This will overwrite the commits listed above.${logColors.reset} (y/N): `);
68
+ if (shouldForcePush.toLowerCase() === 'y' || shouldForcePush.toLowerCase() === 'yes') {
69
+ await git.push(remoteName, pushString, ['--force']);
70
+ log.warning(`Force pushed ${logColors.bold}${fromBranch}${logColors.reset} to ${logColors.bold}${toBranch}${logColors.reset}.`);
71
+ }
72
+ else {
73
+ throw new KnownError(`Deploy aborted.`);
74
+ }
75
+ return {
76
+ deployedCommits: commitsAhead,
77
+ overwrittenCommits: commitsBehind.all,
78
+ };
79
+ }
80
+ }
@@ -0,0 +1,7 @@
1
+ export * from './cli/cli.js';
2
+ export * from './config.js';
3
+ export * from './git.js';
4
+ export * from './known.error.js';
5
+ export * from './notifications/notification-params.js';
6
+ export * from './notifications/send-notifications.js';
7
+ export * from './notifications/slack.js';
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ export * from './cli/cli.js';
2
+ export * from './config.js';
3
+ export * from './git.js';
4
+ export * from './known.error.js';
5
+ export * from './notifications/notification-params.js';
6
+ export * from './notifications/send-notifications.js';
7
+ export * from './notifications/slack.js';
@@ -0,0 +1,8 @@
1
+ /**
2
+ * A known error that won't get its full stack trace logged.
3
+ *
4
+ * @category Internal
5
+ */
6
+ export declare class KnownError extends Error {
7
+ readonly name = "KnownError";
8
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * A known error that won't get its full stack trace logged.
3
+ *
4
+ * @category Internal
5
+ */
6
+ export class KnownError extends Error {
7
+ name = 'KnownError';
8
+ }
@@ -0,0 +1,15 @@
1
+ import { type DeployVirBranchConfig, type DeployVirRepoConfig, type NotificationConfig, type NotificationTarget } from '../config.js';
2
+ import { type DeployCommits } from '../git.js';
3
+ /**
4
+ * Params for sending a notification.
5
+ *
6
+ * @category Internal
7
+ */
8
+ export type NotificationParams<Target extends NotificationTarget = NotificationTarget> = {
9
+ deployCommits: Readonly<DeployCommits>;
10
+ branchConfig: Readonly<DeployVirBranchConfig>;
11
+ repoConfig: Readonly<Pick<DeployVirRepoConfig, 'commitBaseUrl'>>;
12
+ notification: Readonly<Extract<NotificationConfig, {
13
+ target: Target;
14
+ }>>;
15
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,8 @@
1
+ import { type NotificationConfig } from '../config.js';
2
+ import { type NotificationParams } from './notification-params.js';
3
+ /**
4
+ * Send all configured notifications.
5
+ *
6
+ * @category Internal
7
+ */
8
+ export declare function sendNotifications(notifications: ReadonlyArray<Readonly<NotificationConfig>>, { branchConfig, deployCommits, repoConfig }: Readonly<Omit<NotificationParams, 'notification'>>): Promise<void>;
@@ -0,0 +1,24 @@
1
+ import { NotificationTarget } from '../config.js';
2
+ import { KnownError } from '../known.error.js';
3
+ import { sendNotificationToSlack } from './slack.js';
4
+ /**
5
+ * Send all configured notifications.
6
+ *
7
+ * @category Internal
8
+ */
9
+ export async function sendNotifications(notifications, { branchConfig, deployCommits, repoConfig }) {
10
+ await Promise.all(notifications.map(async (notification) => {
11
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
12
+ if (notification.target === NotificationTarget.Slack) {
13
+ await sendNotificationToSlack({
14
+ deployCommits,
15
+ branchConfig,
16
+ repoConfig,
17
+ notification,
18
+ });
19
+ }
20
+ else {
21
+ throw new KnownError(`Unexpected notification target: '${String(notification.target)}'`);
22
+ }
23
+ }));
24
+ }
@@ -0,0 +1,8 @@
1
+ import { type NotificationParams } from './notification-params.js';
2
+ export { type ChatPostMessageArguments } from '@slack/web-api';
3
+ /**
4
+ * Send a notification to Slack.
5
+ *
6
+ * @category Internal
7
+ */
8
+ export declare function sendNotificationToSlack({ branchConfig, deployCommits: { deployedCommits, overwrittenCommits }, notification, repoConfig, }: Readonly<NotificationParams>): Promise<void>;
@@ -0,0 +1,95 @@
1
+ import { addPrefix } from '@augment-vir/common';
2
+ import { joinUrlPaths } from 'url-vir';
3
+ function truncateString(value, truncateAt = 100) {
4
+ if (value.length > truncateAt) {
5
+ return `${value.slice(0, Math.max(0, truncateAt))}...`;
6
+ }
7
+ else {
8
+ return value;
9
+ }
10
+ }
11
+ function formatCommit(baseCommitUrl, commit) {
12
+ const commitLine = `${commit.hash.slice(0, 7)} (${commit.author_name}) - ${truncateString(commit.message)}`;
13
+ if (baseCommitUrl) {
14
+ return `<${joinUrlPaths(baseCommitUrl, commit.hash)}|${commitLine}>`;
15
+ }
16
+ else {
17
+ return commitLine;
18
+ }
19
+ }
20
+ /**
21
+ * Send a notification to Slack.
22
+ *
23
+ * @category Internal
24
+ */
25
+ export async function sendNotificationToSlack({ branchConfig, deployCommits: { deployedCommits, overwrittenCommits }, notification, repoConfig, }) {
26
+ const deployedCommitBullets = deployedCommits.map((commit) => formatCommit(repoConfig.commitBaseUrl, commit));
27
+ const overwrittenCommitBullets = overwrittenCommits.map((commit) => formatCommit(repoConfig.commitBaseUrl, commit));
28
+ const deployedCommitBulletsText = deployedCommitBullets
29
+ .map((bullet) => `• ${bullet}`)
30
+ .join('\n');
31
+ const overwrittenCommitBulletsText = overwrittenCommitBullets.length
32
+ ? overwrittenCommitBullets.map((bullet) => `• ${bullet}`).join('\n')
33
+ : undefined;
34
+ const blocks = [
35
+ {
36
+ type: 'section',
37
+ text: {
38
+ type: 'mrkdwn',
39
+ text: `*${branchConfig.deployName}* Deployed`,
40
+ },
41
+ },
42
+ {
43
+ type: 'section',
44
+ text: {
45
+ type: 'mrkdwn',
46
+ text: `\n*Deployed Commits*\n${deployedCommitBulletsText}`,
47
+ },
48
+ },
49
+ ...(overwrittenCommitBulletsText
50
+ ? [
51
+ {
52
+ type: 'section',
53
+ text: {
54
+ type: 'mrkdwn',
55
+ text: `\n*Overwritten Commits*\n${overwrittenCommitBulletsText}`,
56
+ },
57
+ },
58
+ ]
59
+ : []),
60
+ ];
61
+ await sendSlackMessage(notification, {
62
+ attachments: [],
63
+ channel: addPrefix({ value: notification.channelName, prefix: '#' }),
64
+ blocks,
65
+ });
66
+ }
67
+ async function sendSlackMessage(slackConfig, body) {
68
+ try {
69
+ const response = await fetch(slackConfig.webhookUrl, {
70
+ method: 'POST',
71
+ headers: {
72
+ 'Content-Type': 'application/json',
73
+ },
74
+ body: JSON.stringify({
75
+ ...body,
76
+ ...(slackConfig.avatarEmoji
77
+ ? {
78
+ icon_emoji: slackConfig.avatarEmoji,
79
+ }
80
+ : {}),
81
+ ...(slackConfig.username
82
+ ? {
83
+ username: slackConfig.username,
84
+ }
85
+ : {}),
86
+ }),
87
+ });
88
+ if (!response.ok) {
89
+ throw new Error(`Failed to send Slack webhook: ${response.status}`);
90
+ }
91
+ }
92
+ catch (error) {
93
+ console.error('Error sending Slack message:', error);
94
+ }
95
+ }
package/package.json CHANGED
@@ -1,13 +1,90 @@
1
1
  {
2
- "name": "deploy-vir",
3
- "version": "0.0.0",
4
- "description": "",
5
- "main": "index.js",
6
- "scripts": {
7
- "test": "echo \"Error: no test specified\" && exit 1"
8
- },
9
- "keywords": [],
10
- "author": "",
11
- "license": "MIT",
12
- "type": "commonjs"
2
+ "name": "deploy-vir",
3
+ "version": "0.0.2",
4
+ "description": "Deploy a branch to another branch with notifications.",
5
+ "keywords": [
6
+ "deploy",
7
+ "devops",
8
+ "pipeline"
9
+ ],
10
+ "homepage": "https://github.com/electrovir/deploy-vir",
11
+ "bugs": {
12
+ "url": "https://github.com/electrovir/deploy-vir/issues"
13
+ },
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/electrovir/deploy-vir.git"
17
+ },
18
+ "license": "(MIT or CC0 1.0)",
19
+ "author": {
20
+ "name": "electrovir",
21
+ "url": "https://github.com/electrovir"
22
+ },
23
+ "sideEffects": false,
24
+ "type": "module",
25
+ "main": "dist/index.js",
26
+ "module": "dist/index.js",
27
+ "types": "dist/index.d.ts",
28
+ "bin": "bin.js",
29
+ "scripts": {
30
+ "compile": "virmator compile",
31
+ "docs": "virmator docs",
32
+ "format": "virmator format",
33
+ "lint": "virmator lint fix",
34
+ "publish": "virmator publish npm run test:all",
35
+ "test:all": "npm run compile && concurrently --colors --kill-others-on-fail -c auto --names spelling,format,docs,deps,lint \"npm run test:spelling\" \"npm run test:format\" \"npm run test:docs\" \"npm run test:deps\" \"npm run test:lint\"",
36
+ "test:deps": "virmator deps check",
37
+ "test:docs": "virmator docs check",
38
+ "test:format": "virmator format check",
39
+ "test:lint": "virmator lint",
40
+ "test:spelling": "virmator spellcheck",
41
+ "test:update": "npm run test update"
42
+ },
43
+ "dependencies": {
44
+ "@augment-vir/assert": "^31.28.0",
45
+ "@augment-vir/common": "^31.28.0",
46
+ "@augment-vir/node": "^31.28.0",
47
+ "@slack/web-api": "^7.9.3",
48
+ "simple-git": "^3.28.0",
49
+ "tsx": "^4.20.3",
50
+ "url-vir": "^2.1.3"
51
+ },
52
+ "devDependencies": {
53
+ "@eslint/eslintrc": "^3.3.1",
54
+ "@eslint/js": "^9.32.0",
55
+ "@stylistic/eslint-plugin": "^5.2.2",
56
+ "@stylistic/eslint-plugin-ts": "^4.4.1",
57
+ "@types/node": "^24.1.0",
58
+ "@typescript-eslint/eslint-plugin": "^8.38.0",
59
+ "cspell": "^9.2.0",
60
+ "dependency-cruiser": "^17.0.0",
61
+ "esbuild": "^0.25.8",
62
+ "eslint": "^9.32.0",
63
+ "eslint-config-prettier": "^10.1.8",
64
+ "eslint-plugin-jsdoc": "^52.0.1",
65
+ "eslint-plugin-monorepo-cop": "^1.0.2",
66
+ "eslint-plugin-playwright": "^2.2.1",
67
+ "eslint-plugin-prettier": "^5.5.3",
68
+ "eslint-plugin-require-extensions": "^0.1.3",
69
+ "eslint-plugin-sonarjs": "^3.0.4",
70
+ "eslint-plugin-unicorn": "^57.0.0",
71
+ "istanbul-smart-text-reporter": "^1.1.5",
72
+ "markdown-code-example-inserter": "^3.0.3",
73
+ "npm-check-updates": "^18.0.2",
74
+ "prettier": "^3.3.3",
75
+ "prettier-plugin-interpolated-html-tags": "^2.0.1",
76
+ "prettier-plugin-jsdoc": "^1.3.3",
77
+ "prettier-plugin-multiline-arrays": "^4.0.3",
78
+ "prettier-plugin-organize-imports": "^4.2.0",
79
+ "prettier-plugin-packagejson": "^2.5.19",
80
+ "prettier-plugin-sort-json": "^4.1.1",
81
+ "prettier-plugin-toml": "^2.0.6",
82
+ "typedoc": "^0.28.8",
83
+ "typescript": "^5.8.3",
84
+ "typescript-eslint": "^8.38.0",
85
+ "virmator": "^13.15.6"
86
+ },
87
+ "engines": {
88
+ "node": ">=22"
89
+ }
13
90
  }