Skip to content
Merged
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
31 changes: 22 additions & 9 deletions Nodejs/Product/ProjectWizard/NodejsPackageParametersExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,23 +14,17 @@
//
//*********************************************************//

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using EnvDTE;
using Microsoft.VisualStudio.TemplateWizard;

namespace Microsoft.NodejsTools.ProjectWizard {
class NodejsPackageParametersExtension : IWizard {
public void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams) {
var projectName = replacementsDictionary["$projectname$"];

// Remove all leading url-invalid, underscore, and period characters from the string
var npmProjectNameTransform = Regex.Replace(projectName, "^[^a-zA-Z0-9-~]*", string.Empty);

// Replace all invalid characters with a dash
npmProjectNameTransform = Regex.Replace(npmProjectNameTransform, "[^a-zA-Z0-9-_~.]", "-");

replacementsDictionary.Add("$npmsafeprojectname$", npmProjectNameTransform);
replacementsDictionary.Add("$npmsafeprojectname$", NormalizeNpmPackageName(projectName));
}

public void ProjectFinishedGenerating(EnvDTE.Project project) {
Expand All @@ -51,6 +45,25 @@ public void BeforeOpeningFile(ProjectItem projectItem) {

public void RunFinished() {
return;
}

private const int NpmPackageNameMaxLength = 214;

/// <summary>
/// Normalize a project name to be a valid Npm package name: https://docs.npmjs.com/files/package.json#name
/// </summary>
/// <param name="projectName">Name of a VS project.</param>
private static string NormalizeNpmPackageName(string projectName) {
// Remove all leading url-invalid, underscore, and period characters
var npmProjectNameTransform = Regex.Replace(projectName, "^[^a-zA-Z0-9-~]*", string.Empty);

// Replace all invalid characters with a dash
npmProjectNameTransform = Regex.Replace(npmProjectNameTransform, "[^a-zA-Z0-9-_~.]", "-");

// Insert hyphens between camelcased sections.
npmProjectNameTransform = Regex.Replace(npmProjectNameTransform, "([a-z0-9])([A-Z])", "$1-$2").ToLowerInvariant();

return npmProjectNameTransform.Substring(0, Math.Min(npmProjectNameTransform.Length, NpmPackageNameMaxLength));
}
}
}