Skip to content

Commit

Permalink
Simplified config, config is now either default config or in project.…
Browse files Browse the repository at this point in the history
… We can add support for config in home directory later if needed, but this unifies a lot of different but similar calls in the ConfigManager.
  • Loading branch information
thekevinbrown committed May 17, 2019
1 parent adb05d5 commit c19aad7
Show file tree
Hide file tree
Showing 9 changed files with 108 additions and 105 deletions.
33 changes: 21 additions & 12 deletions src/cli/lamington-build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,24 +10,33 @@ import { ConfigManager } from '../configManager';
*/
const run = async () => {
const contract = process.argv[2];
// Initialize configuration
await ConfigManager.initWithDefaults();
// Stop container if running
if (!ConfigManager.keepAlive && (await eosIsReady())) {
await stopContainer();

if (!(await ConfigManager.configExists())) {
console.log('Project has not yet been initialised.');
console.log('Please run lamington init before running this command.');

process.exit(1);
}
// This ensures we have our .gitignore inside the .lamington directory
await GitIgnoreManager.createIfMissing();
// Start the EOSIO container image

// Start the EOSIO container image if it's not running.
if (!(await eosIsReady())) {
await startEos();
}

// Build all smart contracts
await buildAll([contract]);

// And stop it if we don't have keepAlive set.
if (!ConfigManager.keepAlive) {
await stopContainer();
}
};

run().catch(error => {
stopContainer().then(() => {
throw error;
});
run().catch(async error => {
process.exitCode = 1;
console.log(error);

if (!ConfigManager.keepAlive && (await eosIsReady())) {
await stopContainer();
}
});
11 changes: 6 additions & 5 deletions src/cli/lamington-init.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import { ProjectManager } from './../project/projectManager';
import { ConfigManager } from './../configManager';
import * as colors from 'colors';

import { ProjectManager } from './../project/projectManager';
import { ConfigManager } from '../configManager';

/**
* Executes a contract build procedure
* @note Keep alive setup is incomplete
* @author Mitch Pierias <github.com/MitchPierias>
* @author Kevin Brown <github.com/thekevinbrown>
*/
const run = async () => {
await ProjectManager.initWithDefaults();

await ConfigManager.createConfigWhenMissing();

console.log(
colors.white(`
Expand All @@ -27,5 +27,6 @@ const run = async () => {
};

run().catch(error => {
throw error;
process.exitCode = 1;
console.log(error);
});
10 changes: 9 additions & 1 deletion src/cli/lamington-start.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,19 @@
import { startEos, eosIsReady, stopContainer } from './utils';
import { ConfigManager } from '../configManager';

/**
* Stops EOS docker container if it's running, then starts it.
* @note Keep alive setup is incomplete
* @author Kevin Brown <github.com/thekevinbrown>
*/
const run = async () => {
if (!(await ConfigManager.configExists())) {
console.log('Project has not yet been initialised.');
console.log('Please run lamington init before running this command.');

process.exit(1);
}

// Stop running instances for fresh test environment
if (await eosIsReady()) {
await stopContainer();
Expand All @@ -14,7 +22,7 @@ const run = async () => {
await startEos();
};

run().catch(async error => {
run().catch(error => {
process.exitCode = 1;
console.log(error);
});
33 changes: 22 additions & 11 deletions src/cli/lamington-stop.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,28 @@
import { stopContainer } from './utils';
import { stopContainer, eosIsReady } from './utils';
import { ConfigManager } from '../configManager';

/**
* Stops the current Lamington docker container
* @author Kevin Brown <github.com/thekevinbrown>
*/
stopContainer()
.then(() => console.log('Lamington container stopped.'))
.catch(error => {
console.log();
console.log('Could not stop container. Is it running?');
console.log();
console.log('Error from docker:');
console.error(error);
const run = async () => {
if (!(await ConfigManager.configExists())) {
console.log('Project has not yet been initialised.');
console.log('Please run lamington init before running this command.');

process.exit(2);
});
process.exit(1);
}

if (!(await eosIsReady())) {
console.log(`Can't stop the container as EOS is already not running.`);

process.exit(1);
}

await stopContainer();
};

run().catch(error => {
process.exitCode = 1;
console.log(error);
});
6 changes: 3 additions & 3 deletions src/cli/lamington-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@ import { ConfigManager } from '../configManager';
*/
const run = async () => {
// Initialize the configuration
await ConfigManager.initWithDefaults();
await ConfigManager.loadConfigFromDisk();

// Stop running instances for fresh test environment
if (await eosIsReady()) {
await stopContainer();
}
// Ensures we have our .gitignore inside the .lamington directory
await GitIgnoreManager.createIfMissing();

// Start an EOSIO instance if not running
if (!(await eosIsReady())) {
await startEos();
Expand Down
2 changes: 1 addition & 1 deletion src/cli/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ const versionFromUrl = (url: string) => {
* @returns Docker image name
*/
const dockerImageName = async () => {
await ConfigManager.initWithDefaults();
await ConfigManager.loadConfigFromDisk();

return `lamington:eos.${versionFromUrl(ConfigManager.eos)}-cdt.${versionFromUrl(
ConfigManager.cdt
Expand Down
110 changes: 40 additions & 70 deletions src/configManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@ const readFile = promisify(readFileCallback);

/** Root config directory path */
const CACHE_DIRECTORY = '.lamington';
/** Config file fullpath */
const CONFIG_FILE_PATH = path.join(CACHE_DIRECTORY, 'config.json');
/** Default encoding */
const ENCODING = 'utf8';
/** Configuration file name */
Expand All @@ -32,6 +30,16 @@ export interface LamingtonConfig {
debugTransactions?: boolean;
}

/**
* Default configuration values which are merged in as the base layer config. Users can override these values by specifying them in their .lamingtonrc
*/
const DEFAULT_CONFIG = {
debugTransactions: false,
keepAlive: false,
outDir: CACHE_DIRECTORY,
exclude: [],
};

/**
* Manages Lamington configuration setup and caching
*/
Expand All @@ -56,7 +64,7 @@ export class ConfigManager {
// Handle failed GitHub request
if (!result.data || !result.data.assets || !Array.isArray(result.data.assets)) {
console.error(result);
throw new Error('Unexpected response from GitHub API.');
throw new Error('Unexpected response from GitHub API. Please try again later.');
}
// Capture the GitHub url from response
const asset = result.data.assets.find((asset: any) =>
Expand All @@ -72,90 +80,52 @@ export class ConfigManager {
}

/**
* Fetches the latest EOS repository and freezes version changes
* in [[CONFIG_FILE_PATH]] to maintain a consistent development environment
* @author Kevin Brown <github.com/thekevinbrown>
* Creates a config file if it's not in the current working directory.
* @author Mitch Pierias <github.com/MitchPierias>
* @author Kevin Brown <github.com/thekevinbrown>
* @param atPath The path to check for the config file. Defaults to '.lamingtonrc'.
*/
public static async initWithDefaults() {
// Load existing configuration
const userConfig = {
outDir: CACHE_DIRECTORY,
keepAlive: false,
exclude: [],
...(await ConfigManager.readConfigFromProject()),
public static async createConfigIfMissing(atPath = CONFIGURATION_FILE_NAME) {
if (await ConfigManager.configExists()) return;

// Create the config directory
await mkdirp(CACHE_DIRECTORY);

// Fetch the latest repository configuration
const defaultConfig: LamingtonConfig = {
cdt: await ConfigManager.getAssetURL('EOSIO', 'eosio.cdt', 'amd64.deb'),
eos: await ConfigManager.getAssetURL('EOSIO', 'eos', 'ubuntu-18.04'),
};
// Check if configuration exists
if (!(await ConfigManager.configExists())) {
// Create the config directory
await mkdirp(CACHE_DIRECTORY);
// Fetch the latest repository configuration
const defaultConfig: LamingtonConfig = {
cdt: await ConfigManager.getAssetURL('EOSIO', 'eosio.cdt', 'amd64.deb'),
eos: await ConfigManager.getAssetURL('EOSIO', 'eos', 'ubuntu-18.04'),
};
// Freeze repository image
await writeFile(CONFIG_FILE_PATH, JSON.stringify(defaultConfig, null, 4), ENCODING);
}
// Load cached config
const existingConfig = JSON.parse(await readFile(CONFIG_FILE_PATH, ENCODING));
// Save cached configuration
await writeFile(
CONFIG_FILE_PATH,
JSON.stringify(
{
...existingConfig,
...userConfig,
},
null,
4
),
ENCODING
);
// Load existing configuration
await ConfigManager.loadConfigFromDisk();
}

public static async createConfigWhenMissing() {
const atPath = path.join(process.cwd(), '.lamingtonrc');
if (await ConfigManager.configExists(atPath)) return;
ConfigManager.initWithDefaults();
await writeFile(atPath, JSON.stringify(ConfigManager.config, null, 4), ENCODING);
await writeFile(atPath, JSON.stringify(defaultConfig, null, 4), ENCODING);
}

/**
* Checks the existence of the configuration
* file at the default [[CONFIG_FILE_PATH]] or
* file at the default [[CONFIGURATION_FILE_NAME]] or
* optional path
* @author Mitch Pierias <github.com/MitchPierias>
* @param atPath Optional file path for lookup
* @returns Config exists determiner
*/
public static async configExists(atPath: string = CONFIG_FILE_PATH) {
public static configExists(atPath: string = CONFIGURATION_FILE_NAME) {
// Should filter out any trailing filename and concatonate
// the default filename
return await exists(atPath);
return exists(atPath);
}

/**
* Loads the existing configuration file into [[ConfigManager.config]]
* Loads an existing configuration file into [[ConfigManager.config]]
* @author Kevin Brown <github.com/thekevinbrown>
* @param atPath Optional file path for lookup
*/
public static async loadConfigFromDisk() {
public static async loadConfigFromDisk(atPath = CONFIGURATION_FILE_NAME) {
// Read existing configuration and store
ConfigManager.config = JSON.parse(await readFile(CONFIG_FILE_PATH, ENCODING));
}

/**
* Reads the user defined config file if it exists
* @author Mitch Pierias <github.com/MitchPierias>
* @returns User defined configuration or object
* @hidden
*/
private static async readConfigFromProject() {
return (await exists(CONFIGURATION_FILE_NAME))
? JSON.parse(await readFile(CONFIGURATION_FILE_NAME, ENCODING))
: {};
ConfigManager.config = Object.assign(
{},
DEFAULT_CONFIG,
JSON.parse(await readFile(atPath, ENCODING))
);
}

/**
Expand All @@ -179,30 +149,30 @@ export class ConfigManager {
* @author Mitch Pierias <github.com/MitchPierias>
*/
static get keepAlive() {
return ConfigManager.config.keepAlive || false;
return ConfigManager.config.keepAlive || DEFAULT_CONFIG.keepAlive;
}

/**
* Returns the container keep alive setting or false
* @author Kevin Brown <github.com/thekevinbrown>
*/
static get debugTransactions() {
return ConfigManager.config.debugTransactions || false;
return ConfigManager.config.debugTransactions || DEFAULT_CONFIG.debugTransactions;
}

/**
* Returns the output build directory or [[CACHE_DIRECTORY]]
* @author Mitch Pierias <github.com/MitchPierias>
*/
static get outDir() {
return ConfigManager.config.outDir || CACHE_DIRECTORY;
return ConfigManager.config.outDir || DEFAULT_CONFIG.outDir;
}

/**
* Returns the array of excluded strings or patterns
* @author Mitch Pierias <github.com/MitchPierias>
*/
static get exclude() {
return ConfigManager.config.exclude || [];
return ConfigManager.config.exclude || DEFAULT_CONFIG.exclude;
}
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export * from './accounts';
export * from './contracts';
export * from './eosManager';
export * from './utils';

import * as cliUtils from './cli/utils';
Expand Down
7 changes: 5 additions & 2 deletions src/project/projectManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { promisify } from 'util';
import { ConfigManager, LamingtonConfig } from './../configManager';
import * as spinner from './../cli/logIndicator';
import { sleep } from '../utils';
import { GitIgnoreManager } from '../gitignoreManager';

const exists = promisify(existsCallback);
const mkdirp = promisify(mkdirpCallback);
Expand Down Expand Up @@ -57,8 +58,6 @@ export class ProjectManager {
await ProjectManager.configureScripts();

await ProjectManager.configureDependencies();
// Load Configuration
await ConfigManager.initWithDefaults();

await ProjectManager.createProjectStructure();

Expand All @@ -69,6 +68,10 @@ export class ProjectManager {
JSON.stringify(ProjectManager.pkg, null, 4),
ENCODING
);

await ConfigManager.createConfigIfMissing();

await GitIgnoreManager.createIfMissing();
}

/**
Expand Down

0 comments on commit c19aad7

Please sign in to comment.