Skip to content

Commit

Permalink
Merge pull request #53 from CentreForDigitalHumanities/feature/fronte…
Browse files Browse the repository at this point in the history
…nd-configuration

Feature/frontend configuration
  • Loading branch information
lukavdplas authored Apr 25, 2024
2 parents 4726e1f + 806342d commit fea44da
Show file tree
Hide file tree
Showing 26 changed files with 85 additions and 478 deletions.
121 changes: 0 additions & 121 deletions bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,10 @@

import os
import os.path as op
from distutils import dir_util
import glob
import json
import platform
import sys
import subprocess
import shlex
import shutil

SLUG = 'lettercraft'
WINDOWS = (platform.system() == 'Windows')
Expand Down Expand Up @@ -167,123 +163,6 @@ def make_create_db_command(psql_cmd):
psql_cmd + ' -f ' + op.join('backend', 'create_db.sql'),
)

def merge_json(target, source):
for key, value in source.items():
if value is None:
del target[key]
elif key in target and isinstance(target[key], dict) and \
isinstance(source[key], dict):
merge_json(target[key], source[key])
else:
target[key] = value
return target


def modify_angular_json():
with open('frontend/angular.json', 'r') as file:
data = json.load(file)
try:
project = 'lettercraft'.replace('_', '-')
data['projects'][project]['architect']['test']['options']['karmaConfig'] = 'karma.conf.js'
for lang in 'en:english'.split(','):
[code, lang_name] = lang.split(':')
production = merge_json({}, data['projects'][project]['architect']['build']['configurations']['production'])
production['outputPath'] = f'dist/{code}'
production['i18nFile'] = f'locale/messages.{code}.xlf'
production['i18nFormat'] = 'xlf'
production['i18nLocale'] = code
production['i18nMissingTranslation'] = 'error'
data['projects'][project]['architect']['build']['configurations'][f'production-{code}'] = production

serve = merge_json({}, data['projects'][project]['architect']['serve']['configurations']['production'])
serve['browserTarget'] += f'-{code}'
data['projects'][project]['architect']['serve']['configurations'][code] = serve

data['projects'][project]['architect']['build']['options']['outputPath'] = \
data['projects'][project]['architect']['build']['configurations']['production']['outputPath'] = 'dist'
except Exception as error:
print("Oh no! :( Maybe the format changed?")
print(json.dumps(data, indent=4))
raise error
with open('frontend/angular.json', 'w') as file:
json.dump(data, file, indent=4)


def activate_frontend():
framework = 'angular'
os.rename('package.angular.json', 'package.json')

if framework == 'backbone':
os.rename('frontend.backbone', 'frontend')
shutil.move(op.join('frontend', 'proxy.json'), 'proxy.json')
override_package_json()
elif framework == 'angular':
project_name = 'lettercraft'.replace('_', '-')
Command(
'Install dependencies',
['yarn', 'install', '--ignore-scripts']
)()
Command(
'Creating project',
['yarn', 'ng', 'new', project_name, '--prefix=lc',
'--skip-git=true',
'--skip-install=true',
'--package-manager=yarn',
'--style=scss',
'--routing=true']
)()
dir_util.copy_tree('frontend.angular', project_name)
os.rename(project_name, 'frontend')
shutil.move(op.join('frontend', 'proxy.conf.json'), 'proxy.conf.json')
override_package_json()
Command(
'Install frontend dependencies using Yarn',
['yarn'],
cwd="frontend"
)()
# Remove editorconfig
os.remove(os.path.join('frontend', '.editorconfig'))
modify_angular_json()
Command(
'ng add @angular/localize',
['yarn', 'ng', 'add', '@angular/localize', '--skip-confirmation'],
cwd="frontend"
)()
Command(
'Creating localizations',
['yarn', 'i18n'],
cwd="frontend"
)()
for lang in 'en:english'.split(','):
[code, lang_name] = lang.split(':')
shutil.copyfile('frontend/locale/messages.xlf', f'frontend/locale/messages.{code}.xlf')
if '4200' != '4200':
Command(
'Set frontend port',
['yarn', 'ng', 'config', "projects.lettercraft.architect.serve.options.port", '4200'],
cwd="frontend"
)()
else:
print('Unknown framework angular specified!')
# remove other frameworks
for path in glob.glob("frontend.*"):
shutil.rmtree(path)
for path in glob.glob("package.*.json"):
os.remove(path)


def override_package_json():
if os.path.isfile('frontend/package.overwrite.json'):
print('Overriding package.json')
with open('frontend/package.overwrite.json', 'r') as file:
overwrite = json.load(file)
with open('frontend/package.json', 'r') as file:
data = json.load(file)
with open('frontend/package.json', 'w') as file:
merge_json(data, overwrite)
json.dump(data, file, indent=4)
os.remove('frontend/package.overwrite.json')


install_pip_tools = Command(
'Install pip-tools',
Expand Down
31 changes: 1 addition & 30 deletions frontend/angular.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,26 +62,6 @@
"extractLicenses": false,
"sourceMap": true,
"namedChunks": true
},
"production-en": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kb",
"maximumError": "1mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "2kb",
"maximumError": "4kb"
}
],
"outputHashing": "all",
"outputPath": "dist/en",
"i18nFile": "locale/messages.en.xlf",
"i18nFormat": "xlf",
"i18nLocale": "en",
"i18nMissingTranslation": "error"
}
},
"defaultConfiguration": "production"
Expand All @@ -94,19 +74,10 @@
},
"development": {
"browserTarget": "lettercraft:build:development"
},
"en": {
"browserTarget": "lettercraft:build:production-en"
}
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "lettercraft:build"
}
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
Expand All @@ -130,4 +101,4 @@
}
}
}
}
}
60 changes: 5 additions & 55 deletions frontend/build/build-pre.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,64 +6,15 @@ const { exec } = require('child_process');

console.log(colors.cyan('\nRunning pre-build tasks'));

async function getHash() {
return new Promise((resolve, reject) => {
exec('git rev-parse HEAD', (error, stdout, stderr) => {
if (error) {
reject(`error: ${error.message}`);
return;
}
if (stderr) {
reject(`stderr: ${stderr}`);
return;
}

resolve(stdout.trim());
});
});
}

async function getRemoteUrl() {
return new Promise((resolve, reject) => {
exec('git config --get remote.origin.url', (error, stdout, stderr) => {
if (error) {
reject(`error: ${error.message}`);
return;
}
if (stderr) {
reject(`stderr: ${stderr}`);
return;
}

// format is either:
// [email protected]:UUDigitalHumanitieslab/lettercraft.git
// or https://github.com/UUDigitalHumanitieslab/lettercraft.git
// or https://USERNAME:[email protected]/UUDigitalHumanitieslab/lettercraft.git/

// remove https://
let sourceUrl = stdout.replace(/^https?:\/\//, '').trim();
// remove git@ or USERNAME:SECRET@
sourceUrl = sourceUrl.replace(/^[^@]+@/, '').trim();
// replace : with /
sourceUrl = sourceUrl.replace(':', '/');
// remove .git/
sourceUrl = sourceUrl.replace(/\.git\/?\n?$/, '');
resolve('https://' + sourceUrl);
});
});
}

Promise.all([getHash(), getRemoteUrl()]).then(([hash, remoteUrl]) => {
writeVersion(hash, remoteUrl);
}).catch((error) => {
try {
writeVersion();
} catch {
console.log(`${colors.red('Could not update version: ')} ${error}`);
});
}

function writeVersion(hash, remoteUrl) {
function writeVersion() {
const versionFilePath = path.join(__dirname + '/../src/environments/version.ts');
const src = `export const version = '${appVersion}';
export const buildTime = '${new Date()}';
export const sourceUrl = '${remoteUrl}/tree/${hash}';
`;

// ensure version module pulls value from package.json
Expand All @@ -74,6 +25,5 @@ export const sourceUrl = '${remoteUrl}/tree/${hash}';

console.log(colors.green(`Updating application version ${colors.yellow(appVersion)}`));
console.log(`${colors.green('Writing version module to ')}${colors.yellow(versionFilePath)}\n`);
console.log(src);
});
}
63 changes: 0 additions & 63 deletions frontend/locale/messages.en.xlf

This file was deleted.

63 changes: 0 additions & 63 deletions frontend/locale/messages.xlf

This file was deleted.

Loading

0 comments on commit fea44da

Please sign in to comment.