Skip to content
This repository was archived by the owner on Jan 11, 2023. It is now read-only.

Commit 9adb6ca

Browse files
authored
Merge pull request #120 from sveltejs/gh-92
implement sapper upgrade
2 parents f6b26f1 + 2498065 commit 9adb6ca

File tree

2 files changed

+60
-2
lines changed

2 files changed

+60
-2
lines changed

src/cli/index.ts

+7-2
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import mri from 'mri';
22
import chalk from 'chalk';
33
import help from './help.md';
4-
import build from './build.js';
5-
import exporter from './export.js';
4+
import build from './build';
5+
import exporter from './export';
6+
import upgrade from './upgrade';
67
import { dest, entry, src } from '../config';
78
import * as pkg from '../../package.json';
89

@@ -46,4 +47,8 @@ if (cmd === 'build') {
4647
.catch(err => {
4748
console.error(err ? err.details || err.stack || err.message || err : 'Unknown error');
4849
});
50+
} else if (cmd === 'upgrade') {
51+
upgrade();
52+
} else {
53+
console.log(`unrecognized command ${cmd} — try \`sapper --help\` for more information`);
4954
}

src/cli/upgrade.ts

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import * as fs from 'fs';
2+
import chalk from 'chalk';
3+
4+
export default async function upgrade() {
5+
const upgraded = [
6+
await upgrade_sapper_main()
7+
].filter(Boolean);
8+
9+
if (upgraded.length === 0) {
10+
console.log(`No changes!`);
11+
}
12+
}
13+
14+
async function upgrade_sapper_main() {
15+
const _2xx = read('templates/2xx.html');
16+
const _4xx = read('templates/4xx.html');
17+
const _5xx = read('templates/5xx.html');
18+
19+
const pattern = /<script src='\%sapper\.main\%'><\/script>/;
20+
21+
let replaced = false;
22+
23+
['2xx', '4xx', '5xx'].forEach(code => {
24+
const file = `templates/${code}.html`
25+
const template = read(file);
26+
if (!template) return;
27+
28+
if (/\%sapper\.main\%/.test(template)) {
29+
if (!pattern.test(template)) {
30+
console.log(chalk.red(`Could not replace %sapper.main% in ${file}`));
31+
} else {
32+
write(file, template.replace(pattern, `%sapper.scripts%`));
33+
console.log(chalk.green(`Replaced %sapper.main% in ${file}`));
34+
replaced = true;
35+
}
36+
}
37+
});
38+
39+
return replaced;
40+
}
41+
42+
function read(file: string) {
43+
try {
44+
return fs.readFileSync(file, 'utf-8');
45+
} catch (err) {
46+
console.error(err);
47+
return null;
48+
}
49+
}
50+
51+
function write(file: string, data: string) {
52+
fs.writeFileSync(file, data);
53+
}

0 commit comments

Comments
 (0)