Skip to content

Add support for different templates #1218

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Nov 30, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions lib/commands/create-project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,14 @@ export class CreateProjectCommand implements ICommand {
constructor(private $projectService: IProjectService,
private $errors: IErrors,
private $logger: ILogger,
private $projectNameValidator: IProjectNameValidator) { }
private $projectNameValidator: IProjectNameValidator,
private $options: ICommonOptions) { }

public enableHooks = false;

execute(args: string[]): IFuture<void> {
return (() => {
this.$projectService.createProject(args[0]).wait();
this.$projectService.createProject(args[0], this.$options.template).wait();
}).future<void>()();
}

Expand Down
2 changes: 1 addition & 1 deletion lib/common
Submodule common updated 2 files
+1 −0 declarations.d.ts
+1 −0 options.ts
18 changes: 17 additions & 1 deletion lib/definitions/project.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@

interface IProjectService {
createProject(projectName: string): IFuture<void>;
createProject(projectName: string, selectedTemplate?: string): IFuture<void>;
}

interface IProjectData {
Expand All @@ -22,8 +22,24 @@ interface IProjectDataService {
removeDependency(dependencyName: string): IFuture<void>;
}

/**
* Describes working with templates.
*/
interface IProjectTemplatesService {
/**
* Defines the path where unpacked default template can be found.
*/
defaultTemplatePath: IFuture<string>;

/**
* Prepares template for project creation.
* In case templateName is not provided, use defaultTemplatePath.
* In case templateName is a special word, validated from us (for ex. typescript), resolve the real template name and add it to npm cache.
* In any other cases try to `npm install` the specified templateName to temp directory.
* @param {string} templateName The name of the template.
* @return {string} Path to the directory where extracted template can be found.
*/
prepareTemplate(templateName: string): IFuture<string>;
}

interface IPlatformProjectServiceBase {
Expand Down
3 changes: 2 additions & 1 deletion lib/npm-installation-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ export class NpmInstallationManager implements INpmInstallationManager {
private packageSpecificDirectories: IStringDictionary = {
"tns-android": constants.PROJECT_FRAMEWORK_FOLDER_NAME,
"tns-ios": constants.PROJECT_FRAMEWORK_FOLDER_NAME,
"tns-template-hello-world": constants.APP_RESOURCES_FOLDER_NAME
"tns-template-hello-world": constants.APP_RESOURCES_FOLDER_NAME,
"tns-template-hello-world-ts": constants.APP_RESOURCES_FOLDER_NAME
};

constructor(private $npm: INodePackageManager,
Expand Down
69 changes: 60 additions & 9 deletions lib/services/project-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import * as constants from "../constants";
import * as osenv from "osenv";
import * as path from "path";
import * as shell from "shelljs";
import * as shelljs from "shelljs";

export class ProjectService implements IProjectService {

Expand All @@ -18,7 +18,7 @@ export class ProjectService implements IProjectService {
private $projectTemplatesService: IProjectTemplatesService,
private $options: IOptions) { }

public createProject(projectName: string): IFuture<void> {
public createProject(projectName: string, selectedTemplate?: string): IFuture<void> {
return(() => {
if (!projectName) {
this.$errors.fail("You must specify <App name> when creating a new project.");
Expand Down Expand Up @@ -51,7 +51,6 @@ export class ProjectService implements IProjectService {

let appDirectory = path.join(projectDir, constants.APP_FOLDER_NAME);
let appPath: string = null;

if (customAppPath) {
this.$logger.trace("Using custom app from %s", customAppPath);

Expand All @@ -68,25 +67,77 @@ export class ProjectService implements IProjectService {
this.$logger.trace("Copying custom app into %s", appDirectory);
appPath = customAppPath;
} else {
// No custom app - use nativescript hello world application
this.$logger.trace("Using NativeScript hello world application");
let defaultTemplatePath = this.$projectTemplatesService.defaultTemplatePath.wait();
this.$logger.trace("Copying NativeScript hello world application into %s", appDirectory);
let defaultTemplatePath = this.$projectTemplatesService.prepareTemplate(selectedTemplate).wait();
this.$logger.trace(`Copying application from '${defaultTemplatePath}' into '${appDirectory}'.`);
appPath = defaultTemplatePath;
}

try {
this.createProjectCore(projectDir, appPath, projectId).wait();
//update dependencies and devDependencies of newly created project with data from template
this.mergeProjectAndTemplateProperties(projectDir, appPath).wait();
this.updateAppResourcesDir(appDirectory).wait();
// Delete app/package.json file, its just causing confusion.
// Also its dependencies and devDependencies are already merged in project's package.json.
this.$fs.deleteFile(path.join(projectDir, constants.APP_FOLDER_NAME, constants.PACKAGE_JSON_FILE_NAME)).wait();
this.$npm.install(projectDir, projectDir, { "ignore-scripts": this.$options.ignoreScripts }).wait();
} catch (err) {
this.$fs.deleteDirectory(projectDir).wait();
throw err;
}

this.$logger.out("Project %s was successfully created", projectName);

}).future<void>()();
}

private mergeProjectAndTemplateProperties(projectDir: string, templatePath: string): IFuture<void> {
return (() => {
let templatePackageJsonPath = path.join(templatePath, constants.PACKAGE_JSON_FILE_NAME);
if(this.$fs.exists(templatePackageJsonPath).wait()) {
let projectPackageJsonPath = path.join(projectDir, constants.PACKAGE_JSON_FILE_NAME);
let projectPackageJsonData = this.$fs.readJson(projectPackageJsonPath).wait();
this.$logger.trace("Initial project package.json data: ", projectPackageJsonData);
let templatePackageJsonData = this.$fs.readJson(templatePackageJsonPath).wait();
if(projectPackageJsonData.dependencies || templatePackageJsonData.dependencies) {
projectPackageJsonData.dependencies = this.mergeDependencies(projectPackageJsonData.dependencies, templatePackageJsonData.dependencies);
}

if(projectPackageJsonData.devDependencies || templatePackageJsonData.devDependencies) {
projectPackageJsonData.devDependencies = this.mergeDependencies(projectPackageJsonData.devDependencies, templatePackageJsonData.devDependencies);
}

this.$logger.trace("New project package.json data: ", projectPackageJsonData);
this.$fs.writeJson(projectPackageJsonPath, projectPackageJsonData).wait();
} else {
this.$logger.trace(`Template ${templatePath} does not have ${constants.PACKAGE_JSON_FILE_NAME} file.`);
}
}).future<void>()();
}

private updateAppResourcesDir(appDirectory: string): IFuture<void> {
return (() => {
let defaultAppResourcesDir = path.join(this.$projectTemplatesService.defaultTemplatePath.wait(), constants.APP_RESOURCES_FOLDER_NAME);
let targetAppResourcesDir = path.join(appDirectory, constants.APP_RESOURCES_FOLDER_NAME);
this.$logger.trace(`Updating AppResources values from ${defaultAppResourcesDir} to ${targetAppResourcesDir}`);
shelljs.cp("-R", path.join(defaultAppResourcesDir, "*"), targetAppResourcesDir);
}).future<void>()();
}

private mergeDependencies(projectDependencies: IStringDictionary, templateDependencies: IStringDictionary): IStringDictionary {
// Cast to any when logging as logger thinks it can print only string.
// Cannot use toString() because we want to print the whole objects, not [Object object]
this.$logger.trace("Merging dependencies, projectDependencies are: ", <any>projectDependencies, " templateDependencies are: ", <any>templateDependencies);
projectDependencies = projectDependencies || {};
_.extend(projectDependencies, templateDependencies || {});
let sortedDeps: IStringDictionary = {};
let dependenciesNames = _.keys(projectDependencies).sort();
_.each(dependenciesNames, (key: string) => {
sortedDeps[key] = projectDependencies[key];
});
this.$logger.trace("Sorted merged dependencies are: ", <any>sortedDeps);
return sortedDeps;
}

private createProjectCore(projectDir: string, appSourcePath: string, projectId: string): IFuture<void> {
return (() => {
this.$fs.ensureDirectoryExists(projectDir).wait();
Expand All @@ -97,7 +148,7 @@ export class ProjectService implements IProjectService {
if(this.$options.symlink) {
this.$fs.symlink(appSourcePath, appDestinationPath).wait();
} else {
shell.cp('-R', path.join(appSourcePath, "*"), appDestinationPath);
shelljs.cp('-R', path.join(appSourcePath, "*"), appDestinationPath);
}

this.createBasicProjectStructure(projectDir, projectId).wait();
Expand Down
94 changes: 91 additions & 3 deletions lib/services/project-templates-service.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,101 @@
///<reference path="../.d.ts"/>
"use strict";
import * as path from "path";
import * as temp from "temp";
import * as constants from "../constants";
import {EOL} from "os";
temp.track();

export class ProjectTemplatesService implements IProjectTemplatesService {
private static NPM_DEFAULT_TEMPLATE_NAME = "tns-template-hello-world";
private static RESERVED_TEMPLATE_NAMES: IStringDictionary = {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The current code is written to be case sensitive for template names. I think it is more user friendly to make it case insensitive but do not insist. Opinions?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In fact the default templates are case-insensitive:
https://github.com/NativeScript/nativescript-cli/pull/1218/files#diff-123e2a8a4e8daddf9ac8a60b8c79546dR29

In case the lowercased value is not one of the reserved template names, we'll call npm install with original value specified by user. We do not want to set toLowerCase() there as the specified value might be case sensitive URL.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great!

"default": "tns-template-hello-world",
"tsc": "tns-template-hello-world-ts",
"typescript": "tns-template-hello-world-ts"
};

public constructor(private $npmInstallationManager: INpmInstallationManager) { }
public constructor(private $errors: IErrors,
private $fs: IFileSystem,
private $logger: ILogger,
private $npm: INodePackageManager,
private $npmInstallationManager: INpmInstallationManager) { }

public get defaultTemplatePath(): IFuture<string> {
return this.$npmInstallationManager.install(ProjectTemplatesService.NPM_DEFAULT_TEMPLATE_NAME);
return this.prepareNativeScriptTemplate(ProjectTemplatesService.RESERVED_TEMPLATE_NAMES["default"]);
}

public prepareTemplate(originalTemplateName: string): IFuture<string> {
return ((): string => {
let realTemplatePath: string;
if(originalTemplateName) {
let templateName = originalTemplateName.toLowerCase();

// support <reserved_name>@<version> syntax
let [name, version] = templateName.split("@");
if(ProjectTemplatesService.RESERVED_TEMPLATE_NAMES[name]) {
realTemplatePath = this.prepareNativeScriptTemplate(ProjectTemplatesService.RESERVED_TEMPLATE_NAMES[name], version).wait();
} else {
let tempDir = temp.mkdirSync("nativescript-template-dir");
try {
// Use the original template name, specified by user as it may be case-sensitive.
this.$npm.install(originalTemplateName, tempDir, {production: true, silent: true}).wait();
} catch(err) {
this.$logger.trace(err);
this.$errors.failWithoutHelp(`Unable to use template ${originalTemplateName}. Make sure you've specified valid name, github URL or path to local dir.` +
`${EOL}Error is: ${err.message}.`);
}

realTemplatePath = this.getTemplatePathFromTempDir(tempDir).wait();
}
} else {
realTemplatePath = this.defaultTemplatePath.wait();
}

if(realTemplatePath) {
this.$fs.deleteDirectory(path.join(realTemplatePath, constants.NODE_MODULES_FOLDER_NAME)).wait();
return realTemplatePath;
}

this.$errors.failWithoutHelp("Unable to find the template in temp directory. " +
`Please open an issue at https://github.com/NativeScript/nativescript-cli/issues and send the output of the same command executed with --log trace.`);
}).future<string>()();
}

/**
* Install verified NativeScript template in the npm cache.
* The "special" here is that npmInstallationManager will check current CLI version and will instal best matching version of the template.
* For example in case CLI is version 10.12.8, npmInstallationManager will try to find latest 10.12.x version of the template.
* @param {string} templateName The name of the verified NativeScript template.
* @param {string} version The version of the template specified by user.
* @return {string} Path to the directory where the template is installed.
*/
private prepareNativeScriptTemplate(templateName: string, version?: string): IFuture<string> {
this.$logger.trace(`Using NativeScript verified template: ${templateName} with version ${version}.`);
return this.$npmInstallationManager.install(templateName, {version: version});
}

private getTemplatePathFromTempDir(tempDir: string): IFuture<string> {
return ((): string => {
let templatePath: string;
let tempDirContents = this.$fs.readDirectory(tempDir).wait();
this.$logger.trace(`TempDir contents: ${tempDirContents}.`);

// We do not know the name of the package that will be installed, so after installation to temp dir,
// there should be node_modules dir there and its only subdir should be our package.
// In case there's some other dir instead of node_modules, consider it as our package.
if(tempDirContents && tempDirContents.length === 1) {
let tempDirSubdir = _.first(tempDirContents);
if(tempDirSubdir === constants.NODE_MODULES_FOLDER_NAME) {
let templateDirName = _.first(this.$fs.readDirectory(path.join(tempDir, constants.NODE_MODULES_FOLDER_NAME)).wait());
if(templateDirName) {
templatePath = path.join(tempDir, tempDirSubdir, templateDirName);
}
} else {
templatePath = path.join(tempDir, tempDirSubdir);
}
}

return templatePath;
}).future<string>()();
}
}
$injector.register("projectTemplatesService", ProjectTemplatesService);
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
"mute-stream": "0.0.5",
"node-inspector": "https://github.com/NativeScript/node-inspector/tarball/v0.7.4.0",
"node-uuid": "1.4.3",
"npm": "2.6.1",
"npm": "2.14.12",
"open": "0.0.5",
"osenv": "0.1.3",
"plist": "1.1.0",
Expand Down
Loading