Skip to content

Commit

Permalink
do not mkdir if prerequisite failed
Browse files Browse the repository at this point in the history
  • Loading branch information
e2tox committed Oct 19, 2016
1 parent 25de36e commit b07f784
Show file tree
Hide file tree
Showing 13 changed files with 104 additions and 104 deletions.
127 changes: 69 additions & 58 deletions src/lib/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,56 +4,63 @@ import { Directory } from './utils/directory';
import { ObjectEntries } from './utils/utils';

export function LoadSettings(root: Directory, confDir: string, autoCreateDir: boolean) {

const loader = new Loader();

console.log();

/**
* Ensure NODE_ENV is present
*/
const env = loader.checkEnvironment();
const conf = root.resolve(confDir);
const settings = {};

const settings = {
LOG_DIR: 'logs'
};

/**
* Load default settings
*/
loader.applyEnvironmentSettings(conf, settings, 'settings.yaml');
loader.applyFileSettings(conf, settings, 'settings.yaml');

/**
* Validate NODE_ENV and path default settings with environment settings
*/
loader.applyEnvironmentSettings(conf, settings, env + '.yaml');

loader.applyFileSettings(conf, settings, env + '.yaml');

/**
* Apply missing settings from environment
*/
loader.applyEnvironmentSettings(conf, settings);

/**
* Load local environment settings
*/
loader.applyEnvironmentSettings(conf, settings, env + '.local.yaml');
loader.applyFileSettings(conf, settings, env + '.local.yaml');

/**
* Load app version
*/
loader.loadPackageVersion(root, settings);

/**
* This is the last chance to get mandatory configurations from environment variables.
*/
loader.resolveAbsolutePath(root, settings, autoCreateDir);

/**
* Add system level settings
*/
loader.setSystemVariable(root, settings, env);

console.log();

// freeze the settings
return Object.freeze(settings);
}

export class Loader {

checkEnvironment() {
if (!process.env['NODE_ENV']) {
console.error('\x1b[33m', 'NODE_ENV is not defined! Using default production environment', '\x1b[0m');
Expand All @@ -64,47 +71,69 @@ export class Loader {
}
return process.env['NODE_ENV'];
}
applyEnvironmentSettings(root: Directory, settings: any, filename: string): boolean {

applyFileSettings(root: Directory, settings: any, filename: string): boolean {

let localSettingsFile;
let environmentSettings;

try {
localSettingsFile = root.file(filename);
}
catch (err) {
console.log(`WARN: Application settings file '${err.file}' is not found, ignoring...`);
return false;
}

try {
environmentSettings = parseYAML(localSettingsFile);
}
catch (err) {
console.error(`ERROR: Error parsing '${localSettingsFile.path}', reason: '${err.message}', exiting...`);
throw err;
}

if (typeof environmentSettings !== 'object') {
const err = new Error(`'${localSettingsFile.path}' is not validate settings file`);
console.error(err.message);
throw err;
}

const keys = [];
for (let [key, value] of ObjectEntries(environmentSettings)) {
settings[key] = environmentSettings[key];
settings[key] = value;
keys.push(key);
}
console.log(`INFO: Applied ${keys.length} key(s) from '${localSettingsFile.path}'`);
return true;
}


applyEnvironmentSettings(root: Directory, settings: any) {

let fulfilled = true;

for (let [key, value] of ObjectEntries(settings)) {
if (process.env[key] != null) {
console.log('Applying ' + key + ' from environment value `' + process.env[key] + '`');
settings[key] = process.env[key];
} else if (value == null) {
fulfilled = false;
console.error('ERROR: Missing environment variable: ' + key);
}
}

if (!fulfilled) {
const err = new Error('ERROR: Prerequisite environment variable is missing, exiting...');
console.error(err.message);
throw err;
}

}

loadPackageVersion(root: Directory, settings: any) {

let packageFile;

try {
packageFile = root.file('package.json');
try {
Expand All @@ -118,38 +147,26 @@ export class Loader {
catch (err) {
console.log(`WARN: Package file '${err.file}' is not found, ignoring...`);
}

}

resolveAbsolutePath(root: Directory, settings: any, autoCreateDir: boolean) {

let fulfilled = true;


const postfix = '_DIR';

if (autoCreateDir) {
console.log('WARN: Auto create directory is ON, all missing directory in the configuration will be created automatically.');
console.log('WARN: Auto create directory is ON, all missing directory in the configuration ' +
'will be created automatically.');
}

for (let [key, value] of ObjectEntries(settings)) {
/**
* Set undefined settings from environment
*/
if (process.env[key] != null) {
console.log('Applying ' + key + ' from environment value `' + process.env[key] + '`');
settings[key] = process.env[key];
} else if (settings[key] == null) {
fulfilled = false;
console.error('ERROR: Missing environment variable: ' + key);
}

/**
* Convert all relative path to absolute path
*/
if (key.indexOf(postfix, key.length - postfix.length) !== -1) {
const value = settings[key].split(':');
const pathname = value[0];
const permission = value[1] === 'rw' ? 'rw' : 'ro';
const dirs = value.split(':');
const pathname = dirs[0];
const permission = dirs[1] === 'rw' ? 'rw' : 'ro';
const absolutePathname = path.resolve(root.path, pathname);
// create dir if not exists
if (autoCreateDir && Directory.mkdir(absolutePathname)) {
Expand All @@ -164,19 +181,13 @@ export class Loader {
}
}
}

if (!fulfilled) {
const err = new Error('ERROR: Prerequisite environment variable is missing, exiting....');
console.error(err.message);
throw err;
}


}

setSystemVariable(root: Directory, settings: any, env: string) {
// set home dir to root
settings['HOME_DIR'] = root.path;
settings['ENV'] = env;
}

}
3 changes: 1 addition & 2 deletions src/lib/utils/directory.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import * as fs from 'fs'
import * as path from 'path'
import { agent } from 'agentframework';

export class Directory {

Expand All @@ -19,7 +18,7 @@ export class Directory {
return Directory.resolve(process.cwd(), directory, fs.constants.R_OK | fs.constants.W_OK);
}

public static mkdir(dir: string, mode?: number):boolean {
public static mkdir(dir: string, mode?: number): boolean {
const currentPaths: Array<string> = dir.split(path.sep);
let n = 1;
let created = false;
Expand Down
6 changes: 4 additions & 2 deletions src/lib/utils/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ export function IsUndefined(x: any): boolean {
}

export function* ObjectEntries(obj) {
for (let key of Object.keys(obj)) {
yield [key, obj[key]];
if (obj) {
for (let key of Object.keys(obj)) {
yield [key, obj[key]];
}
}
}
1 change: 0 additions & 1 deletion test/minimal-customized/conf/settings.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,4 @@ PORT:

# dirs
DATA_DIR: '/data' # absolute path
LOG_DIR: '/logs' # relative path to server.js

6 changes: 3 additions & 3 deletions test/minimal/onestack.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@ describe('OneStack - Minimal Tests', () => {
});

describe('#init', () => {

it('should init to __dirname', () => {
expect(()=>{
expect(() => {
app.init()
}).toThrowError(`Directory '${process.cwd()}/conf' is not exist`);
});

it('should init to __dirname', () => {
app.init({ root: testRoot })
});
Expand Down
2 changes: 1 addition & 1 deletion test/missing-directory/conf/settings.yaml
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
---
DATA_DIR: 'data'

2 changes: 1 addition & 1 deletion test/missing-directory/missing-directory.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ describe('TEST: missing-directory', () => {
const kernel = new Kernel();
expect(() => {
kernel.init({ root: testRoot, autoCreateDir: false });
}).toThrowError(`Directory '${testRoot}/data' is not exist`)
}).toThrowError(`Directory '${testRoot}/logs' is not exist`)
});

});
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,19 @@ import * as path from 'path'
import { Kernel } from '../../src/lib/kernel'

describe('TEST: missing-environment-settings', () => {

let testRoot: string;

beforeAll(() => {
// resolve from process.cwd()
testRoot = path.resolve(__dirname);
});

it('should able to init()', () => {
const kernel = new Kernel();
expect(()=> {
expect(() => {
kernel.init({ root: testRoot });
}).toThrowError(`ERROR: Prerequisite environment variable is missing, exiting....`);
}).toThrowError(`ERROR: Prerequisite environment variable is missing, exiting...`);
});

});
8 changes: 4 additions & 4 deletions test/missing-package-json/missing-package-json.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@ import * as path from 'path'
import { Kernel } from '../../src/lib/kernel'

describe('TEST: missing-package-json', () => {

let testRoot: string;

beforeAll(() => {
// resolve from process.cwd()
testRoot = path.resolve(__dirname);
});

it('should able to init()', () => {
const kernel = new Kernel();
kernel.init({ root: testRoot });
});

});
8 changes: 4 additions & 4 deletions test/missing-settings-file/missing-settings-file.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,19 @@ import * as path from 'path'
import { Kernel } from '../../src/lib/kernel'

describe('TEST: missing-settings-file', () => {

let testRoot: string;

beforeAll(() => {
// resolve from process.cwd()
testRoot = path.resolve(__dirname);
});

it('should able to init()', () => {
const kernel = new Kernel();
expect(() => {
kernel.init({ root: testRoot });
}).toThrowError(`Directory '${testRoot}/conf' is not exist`);
});

});
8 changes: 4 additions & 4 deletions test/missing-settings/missing-settings.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@ import * as path from 'path'
import { Kernel } from '../../src/lib/kernel'

describe('TEST: missing-settings', () => {

let testRoot: string;

beforeAll(() => {
// resolve from process.cwd()
testRoot = path.resolve(__dirname);
});

it('should able to init()', () => {
const kernel = new Kernel();
kernel.init({ root: testRoot });
});

});

0 comments on commit b07f784

Please sign in to comment.