use typescript

This commit is contained in:
Bastian Ike
2020-07-16 11:07:42 +02:00
committed by Bastian
parent 442d964180
commit be0241674c
93 changed files with 9750 additions and 2190 deletions

View File

@@ -1,12 +0,0 @@
import { copy } from 'fs-extra';
import {
assetsPath,
distPath,
} from '../common/file';
copy(assetsPath(), distPath('assets'), (err) => {
if (err) {
return console.error(err);
}
console.log("copied assets");
});

View File

@@ -1,19 +0,0 @@
import { createRadar } from '../common/radar';
import { save } from '../common/file';
import { getPageNames } from '../common/config';
import { renderPage } from '../js/server';
(async () => {
try {
const radar = await createRadar();
getPageNames(radar).map(pageName => {
const pageHtml = renderPage(radar, pageName);
save(pageHtml, `${pageName}.html`);
});
console.log('Built radar');
} catch (e) {
console.error('error:', e);
}
})();

View File

@@ -1,13 +0,0 @@
import { emptyDir } from 'fs-extra';
import { distPath } from '../common/file';
var distDir = distPath();
emptyDir(distDir, (err) => {
if (!err) {
console.log('Cleaned dist dir', distDir);
} else {
console.error(err);
}
});

67
tasks/file.ts Normal file
View File

@@ -0,0 +1,67 @@
import { outputFile } from 'fs-extra';
import path from 'path';
import { walk } from 'walk';
export const relativePath = (...relativePath: string[]): string => (
path.resolve(__dirname, '..', ...relativePath)
);
export const radarPath = (...pathInSrc: string[]) => (
relativePath('radar', ...pathInSrc)
);
export const stylesPath = (...pathInSrc: string[]) => (
relativePath('styles', ...pathInSrc)
);
export const assetsPath = (...pathInSrc: string[]) => (
relativePath('assets', ...pathInSrc)
);
export const faviconPath = (...pathInSrc: string[]) => (
relativePath('assets/favicon.ico', ...pathInSrc)
);
export const jsPath = (...pathInSrc: string[]) => (
relativePath('js', ...pathInSrc)
);
export const distPath = (...pathInDist: string[]) => (
relativePath('dist', 'techradar', ...pathInDist)
);
export const getAllMarkdownFiles = (folder: string) => (
getAllFiles(folder, isMarkdownFile)
);
const getAllFiles = (folder: string, predicate: (s: string) => boolean): Promise<string[]> => (
new Promise((resolve, reject) => {
const walker = walk(folder, { followLinks: false });
const files: string[] = [];
walker.on("file", (root, fileStat, next) => {
if (predicate(fileStat.name)) {
files.push(path.resolve(root, fileStat.name));
}
next();
});
walker.on("errors", (root, nodeStatsArray, next) => {
nodeStatsArray.forEach(function (n) {
console.error("[ERROR] " + n.name)
if (n.error) {
console.error(n.error.message || (n.error.code + ": " + n.error.path));
}
});
next();
});
walker.on("end", () => {
resolve(files.sort());
});
})
);
const isMarkdownFile = (name: string) => name.match(/\.md$/) !== null;
export const save = (data: string | Buffer | DataView, fileName: string) => outputFile(distPath(fileName), data);

174
tasks/radar.ts Normal file
View File

@@ -0,0 +1,174 @@
import { readFile } from 'fs-extra';
import path from 'path';
import frontmatter from 'front-matter';
import marked from 'marked';
import hljs from 'highlight.js';
import { quadrants, rings } from '../src/config';
import { radarPath, getAllMarkdownFiles } from './file';
import { Item, Revision, ItemAttributes, Radar } from '../src/model';
type FMAttributes = ItemAttributes
marked.setOptions({
highlight: code => hljs.highlightAuto(code).value,
});
export const createRadar = async (): Promise<Radar> => {
const fileNames = await getAllMarkdownFiles(radarPath());
const revisions = await createRevisionsFromFiles(fileNames);
const allReleases = getAllReleases(revisions);
const items = createItems(revisions);
const flaggedItems = flagItem(items, allReleases);
return {
items: flaggedItems,
releases: allReleases,
};
};
const checkAttributes = (fileName: string, attributes: FMAttributes) => {
if (attributes.ring && !rings.includes(attributes.ring)) {
throw new Error(`Error: ${fileName} has an illegal value for 'ring' - must be one of ${rings}`);
}
if (attributes.quadrant && !quadrants.includes(attributes.quadrant)) {
throw new Error(`Error: ${fileName} has an illegal value for 'quadrant' - must be one of ${quadrants}`);
}
if (!attributes.quadrant || attributes.quadrant === '') {
// throw new Error(`Error: ${fileName} has no 'quadrant' set`);
}
if (!attributes.title || attributes.title === '') {
attributes.title = path.basename(fileName);
}
return attributes
};
const createRevisionsFromFiles = (fileNames: string[]) =>
Promise.all(
fileNames.map(fileName => {
return new Promise<Revision>((resolve, reject) => {
readFile(fileName, 'utf8', (err, data) => {
if (err) {
reject(err);
} else {
const fm = frontmatter<FMAttributes>(data);
// add target attribute to external links
// todo: check path
let html = marked(fm.body.replace(/\]\(\//g, '](/techradar/'));
html = html.replace(
/a href="http/g,
'a target="_blank" rel="noopener noreferrer" href="http',
);
resolve({
...itemInfoFromFilename(fileName),
...checkAttributes(fileName, fm.attributes),
fileName,
body: html,
} as Revision);
}
});
});
}),
);
const itemInfoFromFilename = (fileName: string) => {
const [release, nameWithSuffix] = fileName.split(path.sep).slice(-2);
return {
name: nameWithSuffix.substr(0, nameWithSuffix.length - 3),
release,
};
};
const getAllReleases = (revisions: Revision[]) =>
revisions
.reduce<string[]>((allReleases, { release }) => {
if (!allReleases.includes(release)) {
return [...allReleases, release];
}
return allReleases;
}, [])
.sort();
const createItems = (revisions: Revision[]) => {
const itemMap = revisions.reduce<{[name: string]: Item}>((items, revision) => {
return {
...items,
[revision.name]: addRevisionToItem(items[revision.name], revision),
};
}, {});
return Object.values(itemMap).sort((x, y) => (x.name > y.name ? 1 : -1));
};
const ignoreEmptyRevisionBody = (revision: Revision, item: Item) => {
if (!revision.body || revision.body.trim() === '') {
return item.body;
}
return revision.body;
};
const addRevisionToItem = (
item: Item = {
flag: 'default',
featured: true,
revisions: [],
name: '',
title: '',
ring: 'trial',
quadrant: '',
body: '',
info: '',
},
revision: Revision,
): Item => {
let newItem: Item = {
...item,
...revision,
body: ignoreEmptyRevisionBody(revision, item),
};
if (revisionCreatesNewHistoryEntry(revision)) {
newItem = {
...newItem,
revisions: [revision, ...newItem.revisions],
};
}
return newItem;
};
const revisionCreatesNewHistoryEntry = (revision: Revision) => {
return revision.body.trim() !== '' || typeof revision.ring !== 'undefined';
};
const flagItem = (items: Item[], allReleases: string[]) =>
items.map(
item => ({
...item,
flag: getItemFlag(item, allReleases),
} as Item),
[],
);
const isInLastRelease = (item: Item, allReleases: string[]) =>
item.revisions[0].release === allReleases[allReleases.length - 1];
const isNewItem = (item: Item, allReleases: string[]) =>
item.revisions.length === 1 && isInLastRelease(item, allReleases);
const hasItemChanged = (item: Item, allReleases: string[]) =>
item.revisions.length > 1 && isInLastRelease(item, allReleases);
const getItemFlag = (item: Item, allReleases: string[]): string => {
if (isNewItem(item, allReleases)) {
return 'new';
}
if (hasItemChanged(item, allReleases)) {
return 'changed';
}
return 'default';
};

25
tasks/radarjson.ts Normal file
View File

@@ -0,0 +1,25 @@
import { createRadar } from "./radar";
import { save } from "./file";
export const r = (async () => {
try {
console.log('start')
const radar = await createRadar();
// console.log(radar);
save(JSON.stringify(radar), 'radar.json')
// getPageNames(radar).map(pageName => {
// // const pageHtml = renderPage(radar, pageName);
// // save(pageHtml, `${pageName}.html`);
// save([pageName, radar], `${pageName}.html`)
// });
console.log('Built radar');
} catch (e) {
console.error('error:', e);
}
})();

View File

@@ -1,24 +0,0 @@
import pug from 'pug';
import moment from 'moment';
import { translate } from '../common/config';
import { relativePath } from '../common/file';
import {
groupByQuadrants,
groupByFirstLetter,
groupByRing,
} from './radar';
const templateFolder = 'templates';
export const vars = (vars) => ({
translate: translate,
formatRelease: (release) => moment(release, 'YYYY-MM-DD').format('MMM YYYY'),
groupByQuadrants,
groupByFirstLetter,
groupByRing,
...vars,
});
export const item = pug.compileFile(relativePath(templateFolder, 'item-page.pug'));
export const quadrant = pug.compileFile(relativePath(templateFolder, 'quadrant-page.pug'));

View File

@@ -1,41 +0,0 @@
import { watch } from 'fs';
import { exec } from 'child_process';
import liveServer from 'live-server';
import {
stylesPath,
assetsPath,
jsPath,
radarPath,
relativePath,
} from '../common/file';
const runBuild = name =>
exec(`yarn run build:${name}`, (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(stdout);
console.error(stderr);
});
const watchBuild = name => (eventType, fileName) => runBuild(name);
const options = {
recursive: true,
};
runBuild('all');
watch(stylesPath(), options, watchBuild('css'));
watch(jsPath(), options, watchBuild('js'));
watch(jsPath(), options, watchBuild('pages'));
watch(assetsPath(), options, watchBuild('assets'));
watch(radarPath(), options, watchBuild('pages'));
const params = {
root: relativePath('dist'),
logLevel: 0, // 0 = errors only, 1 = some, 2 = lots
};
liveServer.start(params);