Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix deploy task #159

Merged
merged 5 commits into from
Apr 8, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,15 @@

- **break**: make `src/build.task.ts`, `src/deploy.task.ts`,
and `src/start.task.ts` work with SvelteKit
([#157](https://github.com/feltcoop/gro/pull/157))
([#157](https://github.com/feltcoop/gro/pull/157),
[#159](https://github.com/feltcoop/gro/pull/159))
- add flag `gro deploy --clean` to reset deployment state
- add flag `--branch` to both tasks, default to `main`
- default to the `deploy` branch instead of `gh-pages`
- **break**: rename `toEnvString` and `toEnvNumber` from `stringFromEnv` and `numberFromEnv`
([#158](https://github.com/feltcoop/gro/pull/158))
- add helper `readDir` to `src/fs/node.ts`
[#159](https://github.com/feltcoop/gro/pull/159)

## 0.14.0

Expand Down
2 changes: 2 additions & 0 deletions src/build.task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ import {clean} from './fs/clean.js';
import {move} from './fs/node.js';
import {printBuildConfigLabel} from './config/buildConfig.js';

// outputs build artifacts to dist/ using SvelteKit or Gro config

export interface TaskArgs {
mapInputOptions?: MapInputOptions;
mapOutputOptions?: MapOutputOptions;
Expand Down
76 changes: 46 additions & 30 deletions src/deploy.task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,36 @@ import {join, basename} from 'path';

import type {Task} from './task/task.js';
import {spawnProcess} from './utils/process.js';
import {copy} from './fs/node.js';
import {paths} from './paths.js';
import {copy, move, remove, readDir} from './fs/node.js';
import {GIT_PATH, paths} from './paths.js';
import {printError, printPath} from './utils/print.js';
import {magenta, green, rainbow, red} from './utils/terminal.js';
import {GIT_DEPLOY_BRANCH} from './config/defaultBuildConfig.js';

// TODO support other kinds of deployments
// TODO add a flag to delete the existing deployment branch to avoid bloat (and maybe run `git gc --auto`)

// terminal command to clean up while live testing:
// gro deploy --clean && gro clean -b && gb -D deploy && git push origin :deploy

export interface TaskArgs {
branch?: string; // optional branch to deploy from; defaults to 'main'
dry?: boolean;
clean?: boolean; // clean the git worktree and Gro cache
}

// TODO customize
const distDir = paths.dist;
const distDirName = basename(distDir);
const deploymentBranch = 'deploy';
const initialFile = 'package.json'; // this is a single file that's copied into the new branch to bootstrap it
const DIST_DIR = paths.dist;
const DIST_DIR_NAME = basename(DIST_DIR);
const WORKTREE_DIR_NAME = 'worktree';
const WORKTREE_DIR = `${paths.root}${WORKTREE_DIR_NAME}`;
const DEPLOY_BRANCH = 'deploy';
const INITIAL_FILE = 'package.json'; // this is a single file that's copied into the new branch to bootstrap it
const TEMP_PREFIX = '__TEMP__';

export const task: Task<TaskArgs> = {
description: 'deploy to static hosting',
dev: false,
run: async ({invokeTask, args, log}): Promise<void> => {
const {branch, dry, clean} = args;

Expand All @@ -50,12 +56,12 @@ export const task: Task<TaskArgs> = {
// If the `deploymentBranch` already exists, this is a no-op.
log.info(magenta('↓↓↓↓↓↓↓'), green('ignore any errors in here'), magenta('↓↓↓↓↓↓↓'));
await spawnProcess(
`git checkout --orphan ${deploymentBranch} && ` +
`git checkout --orphan ${DEPLOY_BRANCH} && ` +
// TODO there's definitely a better way to do this
`cp ${initialFile} ${TEMP_PREFIX}${initialFile} && ` +
`cp ${INITIAL_FILE} ${TEMP_PREFIX}${INITIAL_FILE} && ` +
`git rm -rf . && ` +
`mv ${TEMP_PREFIX}${initialFile} ${initialFile} && ` +
`git add ${initialFile} && ` +
`mv ${TEMP_PREFIX}${INITIAL_FILE} ${INITIAL_FILE} && ` +
`git add ${INITIAL_FILE} && ` +
`git commit -m "setup" && git checkout ${sourceBranch}`,
[],
// this uses `shell: true` because the above is unwieldy with standard command construction
Expand All @@ -74,55 +80,65 @@ export const task: Task<TaskArgs> = {
return;
}

// Set up the deployment worktree in the dist directory.
await spawnProcess('git', ['worktree', 'add', distDirName, deploymentBranch]);

try {
// Run the build.
await invokeTask('build');

// Update the initial file.
await copy(initialFile, join(distDir, initialFile));
await copy(INITIAL_FILE, join(DIST_DIR, INITIAL_FILE));
} catch (err) {
log.error(red('build failed'), 'but', green('no changes were made to git'), printError(err));
if (dry) {
log.info(red('dry deploy failed:'), 'files are available in', printPath(distDirName));
} else {
await cleanGitWorktree(true);
log.info(red('dry deploy failed:'), 'files are available in', printPath(DIST_DIR_NAME));
}
throw Error(`Deploy safely canceled due to build failure. See the error above.`);
}

// At this point, `dist/` is ready to be committed and deployed!
if (dry) {
log.info(green('dry deploy complete:'), 'files are available in', printPath(distDirName));
log.info(green('dry deploy complete:'), 'files are available in', printPath(DIST_DIR_NAME));
return;
}

try {
// TODO wait is this `cwd` correct or vestiges of the old code?
const gitArgs = {cwd: distDir};
await spawnProcess('git', ['add', '.'], gitArgs);
// Set up the deployment worktree in the dist directory.
await spawnProcess('git', ['worktree', 'add', WORKTREE_DIR_NAME, DEPLOY_BRANCH]);
// Populate the worktree dir with the new files.
// We're doing this rather than copying the directory
// because we need to preserve the existing worktree directory, or git breaks.
// TODO there is be a better way but what is it
await Promise.all(
(await readDir(WORKTREE_DIR)).map((path) =>
path === GIT_PATH ? null : remove(`${WORKTREE_DIR}/${path}`),
),
);
await Promise.all(
(await readDir(DIST_DIR)).map((path) =>
move(`${DIST_DIR}${path}`, `${WORKTREE_DIR}/${path}`),
),
);
// commit the changes
const gitArgs = {cwd: WORKTREE_DIR};
await spawnProcess('git', ['add', '.', '-f'], gitArgs);
await spawnProcess('git', ['commit', '-m', 'deployment'], gitArgs);
await spawnProcess('git', ['push', 'origin', deploymentBranch], gitArgs);
await spawnProcess('git', ['push', 'origin', DEPLOY_BRANCH], gitArgs);
} catch (err) {
log.error(red('updating git failed:'), printError(err));
await cleanGitWorktree();
throw Error(`Deploy failed in a bad state: built but not pushed. See the error above.`);
}

// Clean up the worktree so it doesn't interfere with development.
// TODO maybe add a flag to preserve these files instead of overloading `dry`?
// or maybe just create a separate `deploy` dir to avoid problems?
// Clean up and efficiently reconstruct dist/ for users
await remove(`${WORKTREE_DIR}/${GIT_PATH}`);
await move(WORKTREE_DIR, DIST_DIR, {overwrite: true});
await cleanGitWorktree();

log.info(rainbow('deployed'));
log.info(rainbow('deployed')); // TODO log a different message if "Everything up-to-date"
},
};

// TODO like above, these cause some misleading logging
const cleanGitWorktree = async (force = false): Promise<void> => {
const removeCommand = ['worktree', 'remove', distDirName];
if (force) removeCommand.push('--force');
await spawnProcess('git', removeCommand);
const cleanGitWorktree = async (): Promise<void> => {
await spawnProcess('git', ['worktree', 'remove', WORKTREE_DIR_NAME, '--force']);
await spawnProcess('git', ['worktree', 'prune']);
};
1 change: 1 addition & 0 deletions src/fs/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ export type Stats = fsExtra.Stats;
export const readFile = fsExtra.readFile;
export const readJson = fsExtra.readJson;
export const outputFile = fsExtra.outputFile;
export const readDir = fsExtra.readdir;
export const emptyDir = fsExtra.emptyDir;
export const ensureDir = fsExtra.ensureDir;
export const copy = fsExtra.copy;
Expand Down
1 change: 1 addition & 0 deletions src/paths.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export const NODE_MODULES_PATH = 'node_modules';
export const SVELTE_KIT_DEV_PATH = '.svelte';
export const SVELTE_KIT_BUILD_PATH = 'build';
export const SVELTE_KIT_DIST_PATH = 'sveltekit'; // dist/sveltekit/<your_svelte_build>
export const GIT_PATH = '.git';

export const CONFIG_SOURCE_BASE_PATH = 'gro.config.ts';
export const CONFIG_BUILD_BASE_PATH = 'gro.config.js';
Expand Down