boostrap new proyect model

This commit is contained in:
srgooglo 2020-12-14 20:29:29 +01:00
parent b61b7e1893
commit ad4526fff4
26 changed files with 106852 additions and 10 deletions

2
.gitignore vendored
View File

@ -15,3 +15,5 @@
/src/.umi-test
/.env.local
/packages/*/node_modules
/packages/**/node_modules

View File

@ -1,3 +1,10 @@
{
"src": "/src"
"devRuntime": {
"headPackage": "ragestudio"
},
"runtime": {
"src": "/src",
"UUID": "C8mVSr-4nmPp2-pr5Vrz-CU4kg4",
"stage": "alpha"
}
}

1
.version Normal file
View File

@ -0,0 +1 @@
0.12.8

10
.vscode/launch.json vendored
View File

@ -1,5 +1,15 @@
{
"configurations": [
{
"name": "[Node] Run file",
"internalConsoleOptions": "openOnSessionStart",
"program": "${file}",
"request": "launch",
"skipFiles": [
"<node_internals>/**"
],
"type": "pwa-node"
},
{
"name": "Attach to Chrome",
"port": 9222,

31318
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

38
package.json Normal file
View File

@ -0,0 +1,38 @@
{
"version": "0.12.8",
"author": "RageStudio",
"license": "LGPL-2.1",
"types": "index.d.ts",
"private": true,
"workspaces": [
"packages"
],
"lint-staged": {
"*.{js,jsx,less,md,json}": [
"prettier --write"
],
"*.ts?(x)": [
"prettier --parser=typescript --write"
]
},
"scripts": {
"bootstrap": "node ./scripts/bootstrap.js",
"prettier": "prettier --write '**/*.{js,jsx,tsx,ts,less,md,json}'",
"release": "node ./scripts/release.js",
"start": "cd ./packages/comty && umi dev",
"debug": "cd ./packages/comty && node --inspect-brk ./node_modules/.bin/umi dev",
"build": "cd ./packages/comty && umi build",
"update:deps": "yarn upgrade-interactive --latest"
},
"devDependencies": {
"@babel/plugin-syntax-dynamic-import": "^7.8.3",
"@nodecorejs/dot-runtime": "^0.4.3",
"@nodecorejs/libs": "^0.4.4",
"@ragestudio/nodecore-utils": "^0.1.19",
"@types/node": "^12.12.59",
"concurrently": "^3.5.1",
"cross-env": "^6.0.0",
"jest": "^26.5.3",
"jsdoc": "^3.6.5"
}
}

View File

@ -0,0 +1 @@
# @undefined/comty-electron

View File

@ -0,0 +1,18 @@
{
"name": "@ragestudio/comty-electron",
"version": null,
"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"dist",
"src"
],
"repository": {
"type": "git",
"url": false
},
"license": "MIT",
"publishConfig": {
"access": "public"
}
}

1
packages/comty/README.md Normal file
View File

@ -0,0 +1 @@
# @undefined/comty

74905
packages/comty/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,19 +1,10 @@
{
"name": "comty",
"UUID": "C8mVSr-4nmPp2-pr5Vrz-CU4kg4",
"version": "0.12.8",
"stage": "alpha",
"description": "An prototype of a social network",
"author": "RageStudio",
"license": "LGPL-2.1",
"main": "main/index.js",
"types": "index.d.ts",
"scripts": {
"start": "umi dev",
"update:deps": "yarn upgrade-interactive --latest",
"debug": "node --inspect-brk ./node_modules/.bin/umi dev",
"build": "umi build"
},
"dependencies": {
"@icons-pack/react-simple-icons": "^3.8.0",
"@lingui/react": "^2.9.2",

99
scripts/bootstrap.js vendored Normal file
View File

@ -0,0 +1,99 @@
const { existsSync, writeFileSync, readdirSync } = require('fs');
const { join, resolve } = require('path');
const { getGit, getDevRuntimeEnvs } = require('@nodecorejs/dot-runtime')
const { yParser, execa } = require('@nodecorejs/libs');
const getPackages = require('./utils/getPackages');
(async () => {
const devRuntime = getDevRuntimeEnvs();
const args = yParser(process.argv);
const version = require('./versionManager').version;
const pkgs = getPackages();
pkgs.forEach((packageName) => {
const name = `@${devRuntime.headPackage}/${packageName}`;
const pkgPath = resolve(__dirname, `../packages/${packageName}`)
const pkgJSONPath = join(
__dirname,
'..',
'packages',
packageName,
'package.json',
);
const pkgJSONExists = existsSync(pkgJSONPath);
if (args.force || !pkgJSONExists) {
const json = {
name,
version: version,
main: 'dist/index.js',
types: 'dist/index.d.ts',
files: ['dist', 'src'],
repository: {
type: 'git',
url: getGit(),
},
license: 'MIT',
publishConfig: {
access: 'public',
},
};
if (pkgJSONExists) {
const pkg = require(pkgJSONPath);
[
'dependencies',
'devDependencies',
'peerDependencies',
'bin',
'files',
'authors',
'types',
'sideEffects',
'main',
'module',
].forEach((key) => {
if (pkg[key]) json[key] = pkg[key];
});
}
writeFileSync(pkgJSONPath, `${JSON.stringify(json, null, 2)}\n`);
}
if (packageName !== devRuntime.headPackage) {
const readmePath = join(
__dirname,
'..',
'packages',
packageName,
'README.md',
);
if (args.force || !existsSync(readmePath)) {
writeFileSync(readmePath, `# ${name}\n`);
}
}
try {
const changeDirectoryArgs = [`${pkgPath}`]
const installArgs = ['install']
console.log(`📦 Installing modules [${packageName}]`)
execa.sync('cd', changeDirectoryArgs)
execa.sync('npm', installArgs)
} catch (error) {
function errorTable(err) {
this.errno = err.errno
this.code = err.code
this.shortMessage = err.shortMessage
}
console.log(`❌ Cannot install node_modules from pkg '${packageName}'`)
console.table([new errorTable(error)])
}
});
})()
.then(() => console.log("done"));

0
scripts/build.js Normal file
View File

184
scripts/release.js Normal file
View File

@ -0,0 +1,184 @@
const { yParser, execa, chalk } = require('@nodecorejs/libs');
const { getDevRuntimeEnvs } = require('@nodecorejs/dot-runtime');
const { join } = require('path');
const { writeFileSync } = require('fs');
const newGithubReleaseUrl = require('new-github-release-url');
const open = require('open');
const exec = require('./utils/exec');
const getPackages = require('./utils/getPackages');
const isNextVersion = require('./utils/isNextVersion');
const { getChangelog } = require('./utils/changelog');
const { bumpVersion, parsedVersionToString } = require('./updateVersion')
const cwd = process.cwd();
const args = yParser(process.argv.slice(2));
const lernaCli = require.resolve('lerna/cli');
function printErrorAndExit(message) {
console.error(chalk.red(message));
process.exit(1);
}
function logStep(name) {
console.log(`${chalk.gray('>> Release:')} ${chalk.magenta.bold(name)}`);
}
async function release() {
// Check git status
if (!args.skipGitStatusCheck) {
const gitStatus = execa.sync('git', ['status', '--porcelain']).stdout;
if (gitStatus.length) {
printErrorAndExit(`Your git status is not clean. Aborting.`);
}
} else {
logStep(
'git status check is skipped, since --skip-git-status-check is supplied',
);
}
// get release notes
logStep('get release notes');
const releaseNotes = await getChangelog();
console.log(releaseNotes(''));
// Check npm registry
logStep('check npm registry');
const userRegistry = execa.sync(/^win/.test(process.platform) ? 'npm.cmd' : 'npm', ['config', 'get', 'registry']).stdout;
if (userRegistry.includes('https://registry.yarnpkg.com/')) {
printErrorAndExit(
`Release failed, please use ${chalk.blue('npm run release')}.`,
);
}
if (!userRegistry.includes('https://registry.npmjs.org/')) {
const registry = chalk.blue('https://registry.npmjs.org/');
printErrorAndExit(`Release failed, npm registry must be ${registry}.`);
}
let updated = null;
if (!args.publishOnly) {
// Get updated packages
logStep('check updated packages');
const updatedStdout = execa.sync(lernaCli, ['changed']).stdout;
updated = updatedStdout
.split('\n')
.map((pkg) => {
if (pkg === 'nodecore') return pkg;
else return pkg.split('/')[1];
})
.filter(Boolean);
if (!updated.length) {
printErrorAndExit('Release failed, no updated package is updated.');
}
// Clean
logStep('clean');
// Build
if (!args.skipBuild) {
logStep('build');
await exec('npm', ['run', 'build']);
require('./tsIngoreDefineConfig');
} else {
logStep('build is skipped, since args.skipBuild is supplied');
}
// Bump version
bumpVersion(["minor"])
const currVersion = require('../.version');
// Sync version to root package.json
logStep('sync version to root package.json');
const rootPkg = require('../package');
Object.keys(rootPkg.devDependencies).forEach((name) => {
if (
name.startsWith('@nodecorejs/') &&
!name.startsWith('@nodecorejs/p')
) {
rootPkg.devDependencies[name] = currVersion;
}
});
writeFileSync(
join(__dirname, '..', 'package.json'),
JSON.stringify(rootPkg, null, 2) + '\n',
'utf-8',
);
// Commit
const commitMessage = `release: v${currVersion}`;
logStep(`git commit with ${chalk.blue(commitMessage)}`);
await exec('git', ['commit', '--all', '--message', commitMessage]);
// Git Tag
logStep(`git tag v${currVersion}`);
await exec('git', ['tag', `v${currVersion}`]);
// Push
logStep(`git push`);
await exec('git', ['push', 'origin', 'master', '--tags']);
}
// Publish
// Umi must be the latest.
const runtimeEnvs = getDevRuntimeEnvs()
if (!runtimeEnvs.headPackage) {
return printErrorAndExit(`headPackage is missing on runtime`);
}
const pkgs = args.publishOnly ? getPackages() : updated;
logStep(`publish packages: ${chalk.blue(pkgs.join(', '))}`);
const currVersion = require('../lerna').version;
const isNext = isNextVersion(currVersion);
pkgs.sort((a) => {
return a === runtimeEnvs.headPackage ? 1 : -1;
})
.forEach((pkg, index) => {
const pkgPath = join(cwd, 'packages', pkg);
const { name, version } = require(join(pkgPath, 'package.json'));
if (version === currVersion) {
console.log(
`[${index + 1}/${pkgs.length}] Publish package ${name} ${isNext ? 'with next tag' : ''
}`,
);
const cliArgs = isNext ? ['publish', '--tag', 'next'] : ['publish'];
try {
const { stdout } = execa.sync('npm', cliArgs, {
cwd: pkgPath,
})
console.log(stdout);
} catch (error) {
console.log(`❌ Failed to publish > ${pkg} >`, err)
}
}
});
if (!runtimeEnvs.originGit) {
return printErrorAndExit(`originGit is missing on runtime`);
}
logStep('create github release');
const tag = `v${currVersion}`;
const changelog = releaseNotes(tag);
console.log(changelog);
const url = newGithubReleaseUrl({
repoUrl: runtimeEnvs.originGit,
tag,
body: changelog,
isPrerelease: isNext,
});
try {
await open(url);
} catch (error) {
console.log("Try opening url >", url)
}
logStep('done');
}
release().catch((err) => {
console.error(err);
process.exit(1);
});

View File

@ -0,0 +1,17 @@
const { join } = require('path');
const { readFileSync, writeFileSync } = require('fs');
const filePath = join(__dirname, '../packages/nodecore/dist/defineConfig.d.ts');
const content = readFileSync(filePath, 'utf-8');
const toReplace = `import { IConfigFromPlugins } from '@@/core/pluginConfig';`;
const tsIgnore = `// @ts-ignore`;
if (content.indexOf(toReplace) === -1) {
throw new Error('ts ignore add failed since target not found.');
}
writeFileSync(
filePath,
content.replace(toReplace, `${tsIgnore}\n${toReplace}`),
'utf-8',
);

1
scripts/utils/changelog.d.ts vendored Normal file
View File

@ -0,0 +1 @@
export function getChangelog(): Promise<(nextTag: any) => string>;

View File

@ -0,0 +1,29 @@
const { htmlEscape } = require('escape-goat');
const { getGit } = require('@nodecorejs/dot-runtime');
const git = require('./git');
exports.getChangelog = async () => {
const repoUrl = getGit();
if (!repoUrl) {
throw new Error(`Development git not found at runtime`);
}
const latest = await git.latestTagOrFirstCommit();
const log = await git.commitLogFromRevision(latest);
if (!log) {
throw new Error(`Get changelog failed, no new commits was found.`);
}
const commits = log.split('\n').map((commit) => {
const splitIndex = commit.lastIndexOf(' ');
return {
message: commit.slice(0, splitIndex),
id: commit.slice(splitIndex + 1),
};
});
return (nextTag) =>
commits
.map((commit) => `- ${htmlEscape(commit.message)} ${commit.id}`)
.join('\n') + `\n\n${repoUrl}/compare/${latest}...${nextTag}`;
};

2
scripts/utils/exec.d.ts vendored Normal file
View File

@ -0,0 +1,2 @@
declare function _exports(command: any, args: any, opts: any): Promise<any>;
export = _exports;

22
scripts/utils/exec.js Normal file
View File

@ -0,0 +1,22 @@
const { spawn } = require('child_process');
module.exports = function exec(command, args, opts) {
return new Promise((resolve, reject) => {
const child = spawn(
command,
args,
Object.assign({ stdio: 'inherit', env: process.env }, opts),
);
child.once('error', (err) => {
console.log(err);
reject(err);
});
child.once('close', (code) => {
if (code === 1) {
process.exit(1);
} else {
resolve();
}
});
});
};

2
scripts/utils/getPackages.d.ts vendored Normal file
View File

@ -0,0 +1,2 @@
declare function _exports(): string[];
export = _exports;

View File

@ -0,0 +1,9 @@
const { readdirSync } = require('fs');
const { join } = require('path');
const process = require('process')
module.exports = function getPackages() {
return readdirSync(join(process.cwd(), './packages')).filter(
(pkg) => pkg.charAt(0) !== '.',
);
};

3
scripts/utils/git.d.ts vendored Normal file
View File

@ -0,0 +1,3 @@
export function latestTag(): Promise<string>;
export function latestTagOrFirstCommit(): Promise<string>;
export function commitLogFromRevision(revision: any): Promise<string>;

37
scripts/utils/git.js Normal file
View File

@ -0,0 +1,37 @@
const { yParser, execa, chalk } = require('@nodecorejs/libs');
exports.latestTag = async () => {
const { stdout } = await execa('git', ['describe', '--abbrev=0', '--tags']);
return stdout;
};
const firstCommit = async () => {
const { stdout } = await execa('git', [
'rev-list',
'--max-parents=0',
'HEAD',
]);
return stdout;
};
exports.latestTagOrFirstCommit = async () => {
let latest;
try {
// In case a previous tag exists, we use it to compare the current repo status to.
latest = await exports.latestTag();
} catch (_) {
// Otherwise, we fallback to using the first commit for comparison.
latest = await firstCommit();
}
return latest;
};
exports.commitLogFromRevision = async (revision) => {
const { stdout } = await execa('git', [
'log',
'--format=%s %h',
`${revision}..HEAD`,
]);
return stdout;
};

2
scripts/utils/isNextVersion.d.ts vendored Normal file
View File

@ -0,0 +1,2 @@
declare function _exports(version: any): any;
export = _exports;

View File

@ -0,0 +1,7 @@
module.exports = function (version) {
return (
version.includes('-rc.') ||
version.includes('-beta.') ||
version.includes('-alpha.')
);
};

136
scripts/versionManager.js Normal file
View File

@ -0,0 +1,136 @@
const path = require("path")
const process = require('process')
const getPackages = require("./utils/getPackages")
const fs = require("fs")
const rootPackageJSON = require(path.resolve(process.cwd(), './package.json'))
const versionFile = path.resolve(process.cwd(), './.version')
let version = null
module.exports.version = version
let parsedVersion = {
major: 0,
minor: 0,
patch: 0
}
module.exports.parsedVersion = parsedVersion
try { //init from runtime
if (!fs.existsSync(versionFile)) {
console.log(`.version file not exist, creating...`)
fs.writeFileSync(versionFile, rootPackageJSON.version)
}
version = fs.readFileSync(versionFile, 'utf8')
const args = process.argv.slice(2);
const parsed = version.split('.')
parsedVersion.major = parsed[0] ? Number(parsed[0]) : 0
parsedVersion.minor = parsed[1] ? Number(parsed[1]) : 0
parsedVersion.patch = parsed[2] ? Number(parsed[2]) : 0
if (args[0]) {
switch (args[0]) {
case "update": {
console.log(`⚙ Updating version (${version}) to (${args[1]})`)
return updateVersion(args[1])
}
case "bump": {
return bumpVersion(args[1])
}
default: {
console.error("Invalid arguments!")
break;
}
}
}
} catch (error) {
console.error("Fatal error! >", error)
return false
}
function parsedVersionToString(version) {
return `${version.major}.${version.minor}.${version.patch}`
}
module.exports.parsedVersionToString = parsedVersionToString
function getVersion() {
return version
}
module.exports.getVersion = getVersion
function updateVersion(to) {
if (!to) {
return false
}
let updated
if (typeof (to) == "object") {
updated = parsedVersionToString(to)
} else {
const parsed = to.split('.')
parsedVersion.major = parsed[0] ? Number(parsed[0]) : 0
parsedVersion.minor = parsed[1] ? Number(parsed[1]) : 0
parsedVersion.patch = parsed[2] ? Number(parsed[2]) : 0
updated = parsedVersionToString(parsedVersion)
}
console.log(`✅ Version updated to > ${updated}`)
return fs.writeFileSync(versionFile, updated)
}
module.exports.updateVersion = updateVersion
function bumpVersion(params) {
const bumps = {
major: params.includes("major"),
minor: params.includes("minor"),
patch: params.includes("patch"),
}
if (bumps.major) {
parsedVersion.major = parsedVersion.major + 1
parsedVersion.minor = 0
parsedVersion.path = 0
}
if (bumps.minor) {
parsedVersion.minor = parsedVersion.minor + 1
parsedVersion.path = 0
}
if (bumps.patch) {
parsedVersion.patch = parsedVersion.patch + 1
}
function bumpTable(major, minor, patch) {
this.major = major ? parsedVersion.major : false;
this.minor = minor ? parsedVersion.minor : false;
this.patch = patch ? parsedVersion.patch : false;
}
console.table(new bumpTable(bumps.major, bumps.minor, bumps.patch));
return updateVersion(parsedVersion)
}
module.exports.bumpVersion = bumpVersion
function syncPackagesVersions() {
const pkgs = getPackages()
pkgs.forEach((pkg) => {
try {
const pkgFilePath = path.resolve(process.cwd(), `./packages/${pkg}/package.json`)
if (!fs.existsSync(pkgFilePath)) {
console.log(`[${pkg}] ❌ This package is not bootstraped! > package.json not found. > Run npm run bootstrap for init this package.`)
return false
}
const pkgFile = JSON.parse(fs.readFileSync(pkgFilePath, 'utf8'))
if (pkgFile.version !== version) {
console.log(`[${pkg}] ✅ New version synchronized`)
return fs.writeFileSync(pkgFilePath, version)
}
console.log(`[${pkg}] 💠 Version is synchronized, no changes have been made...`)
} catch (error) {
console.error(`[${pkg}] ❌ Error syncing ! > ${error}`)
}
})
}
module.exports.syncPackagesVersions = syncPackagesVersions