private void Compile(ScriptPackage package, ProcessorSettings settings) { foreach (INamedType type in package.NamedTypes) { string metadataName = type.ConstructedFromType.FullName; if (type.Flags.IsInterface) // Interface { _extractedTypes.Add(metadataName, new ExtractedInterfaceType(type, settings.TypeNamespace, this)); } else if (type.Flags.IsEnum) { _extractedTypes.Add( metadataName, new ExtractedEnumType(type, settings.EnumNamespace, settings.DisplayNameFilter) ); } else // class { _extractedTypes.Add(metadataName, new ExtractedClassType(type, settings.TypeNamespace, this)); } } }
public void Preprocess(ScriptPackage scriptPackage, CSharpScriptClassDefinition classDefinition) { var usings = new List <string>(); var sourceCode = new StringBuilder(); foreach (var line in classDefinition.SourceCode.Split(new[] { Env.NewLine }, StringSplitOptions.None)) { if (line.Trim().StartsWith("using ", StringComparison.InvariantCulture)) { var trimmedLine = line.Trim(); var endIndex = trimmedLine.IndexOf(";", StringComparison.InvariantCulture); var use = trimmedLine.Substring("using ".Length, endIndex - "using ".Length); usings.Add(use); } else { sourceCode.AppendLine(line); } } classDefinition.SourceCode = sourceCode.ToString(); classDefinition.Usings.AddRange(usings); }
private IActionScriptObject CreateScriptObject(ScriptPackage scriptPackage) { try { var script = _scriptSpace.Build(scriptPackage); if (script != null) { return(script.CreateObject <IActionScriptObject>()); } Log.Error($"Script object '{scriptPackage.Name}' creation failed."); return(null); } catch (ScriptCompilationFailedException e) { Log.Error($"Script object '{scriptPackage.Name}' creation failed.", e); e.CompilationResultMessages.ForEach(x => Log.Error($"{x.MessageType}: {x.Message}")); return(null); } }
private async Task <bool> ExecuteCoreAsync( PackageIdentity packageIdentity, string fullScriptPath, string packageInstallPath, EnvDTEProject envDTEProject, NuGetProject nuGetProject, INuGetProjectContext nuGetProjectContext, bool throwOnFailure) { if (File.Exists(fullScriptPath)) { if (fullScriptPath.EndsWith(PowerShellScripts.Init, StringComparison.OrdinalIgnoreCase) && !TryMarkVisited(packageIdentity, PackageInitPS1State.FoundAndExecuted)) { return(true); } ScriptPackage package = null; if (envDTEProject != null) { NuGetFramework targetFramework; nuGetProject.TryGetMetadata(NuGetProjectMetadataKeys.TargetFramework, out targetFramework); // targetFramework can be null for unknown project types string shortFramework = targetFramework?.GetShortFolderName() ?? string.Empty; nuGetProjectContext.Log(MessageLevel.Debug, Strings.Debug_TargetFrameworkInfoPrefix, packageIdentity, envDTEProject.Name, shortFramework); } if (packageIdentity != null) { package = new ScriptPackage(packageIdentity.Id, packageIdentity.Version.ToString(), packageInstallPath); } string toolsPath = Path.GetDirectoryName(fullScriptPath); IPSNuGetProjectContext psNuGetProjectContext = nuGetProjectContext as IPSNuGetProjectContext; if (psNuGetProjectContext != null && psNuGetProjectContext.IsExecuting && psNuGetProjectContext.CurrentPSCmdlet != null) { var psVariable = psNuGetProjectContext.CurrentPSCmdlet.SessionState.PSVariable; // set temp variables to pass to the script psVariable.Set("__rootPath", packageInstallPath); psVariable.Set("__toolsPath", toolsPath); psVariable.Set("__package", package); psVariable.Set("__project", envDTEProject); psNuGetProjectContext.ExecutePSScript(fullScriptPath, throwOnFailure); } else { string logMessage = String.Format(CultureInfo.CurrentCulture, Resources.ExecutingScript, fullScriptPath); // logging to both the Output window and progress window. nuGetProjectContext.Log(MessageLevel.Info, logMessage); try { await ExecuteScriptCoreAsync( package, packageInstallPath, fullScriptPath, toolsPath, envDTEProject); } catch (Exception ex) { // throwFailure is set by Package Manager. if (throwOnFailure) { throw; } nuGetProjectContext.Log(MessageLevel.Warning, ex.Message); } } return(true); } else { if (fullScriptPath.EndsWith(PowerShellScripts.Init, StringComparison.OrdinalIgnoreCase)) { TryMarkVisited(packageIdentity, PackageInitPS1State.NotFound); } } return(false); }
public IScript Build(ScriptPackage scriptPackage) { return(_runtimeImplementation.Build(scriptPackage, _nameSpace)); }
private async Task ExecuteInitScriptsAsync() { // Fix for Bug 1426 Disallow ExecuteInitScripts from being executed concurrently by multiple threads. using (await _initScriptsLock.EnterAsync()) { if (!_solutionManager.IsSolutionOpen) { return; } Debug.Assert(_settings != null); if (_settings == null) { return; } // invoke init.ps1 files in the order of package dependency. // if A -> B, we invoke B's init.ps1 before A's. var sortedPackages = new List <PackageIdentity>(); var packagesFolderPackages = new HashSet <PackageIdentity>(PackageIdentity.Comparer); var globalPackages = new HashSet <PackageIdentity>(PackageIdentity.Comparer); var projects = _solutionManager.GetNuGetProjects().ToList(); var packageManager = new NuGetPackageManager( _sourceRepositoryProvider, _settings, _solutionManager, _deleteOnRestartManager); foreach (var project in projects) { // Skip project K projects. if (project is ProjectKNuGetProjectBase) { continue; } var buildIntegratedProject = project as BuildIntegratedNuGetProject; if (buildIntegratedProject != null) { var packages = BuildIntegratedProjectUtility.GetOrderedProjectDependencies(buildIntegratedProject); sortedPackages.AddRange(packages); globalPackages.UnionWith(packages); } else { var installedRefs = await project.GetInstalledPackagesAsync(CancellationToken.None); if (installedRefs != null && installedRefs.Any()) { // This will be an empty list if packages have not been restored var installedPackages = await packageManager.GetInstalledPackagesInDependencyOrder(project, CancellationToken.None); sortedPackages.AddRange(installedPackages); packagesFolderPackages.UnionWith(installedPackages); } } } // Get the path to the Packages folder. var packagesFolderPath = packageManager.PackagesFolderSourceRepository.PackageSource.Source; var packagePathResolver = new PackagePathResolver(packagesFolderPath); var globalFolderPath = SettingsUtility.GetGlobalPackagesFolder(_settings); var globalPathResolver = new VersionFolderPathResolver(globalFolderPath); var finishedPackages = new HashSet <PackageIdentity>(PackageIdentity.Comparer); foreach (var package in sortedPackages) { // Packages may occur under multiple projects, but we only need to run it once. if (!finishedPackages.Contains(package)) { finishedPackages.Add(package); try { string pathToPackage = null; // If the package exists in both the global and packages folder, use the packages folder copy. if (packagesFolderPackages.Contains(package)) { // Local package in the packages folder pathToPackage = packagePathResolver.GetInstalledPath(package); } else { // Global package pathToPackage = globalPathResolver.GetInstallPath(package.Id, package.Version); } if (!string.IsNullOrEmpty(pathToPackage)) { var toolsPath = Path.Combine(pathToPackage, "tools"); var scriptPath = Path.Combine(toolsPath, PowerShellScripts.Init); if (Directory.Exists(toolsPath)) { AddPathToEnvironment(toolsPath); if (File.Exists(scriptPath)) { if (_scriptExecutor.TryMarkVisited( package, PackageInitPS1State.FoundAndExecuted)) { var scriptPackage = new ScriptPackage( package.Id, package.Version.ToString(), pathToPackage); Runspace.ExecuteScript(pathToPackage, scriptPath, scriptPackage); } } else { _scriptExecutor.TryMarkVisited(package, PackageInitPS1State.NotFound); } } } } catch (Exception ex) { // if execution of Init scripts fails, do not let it crash our console ReportError(ex); ExceptionHelper.WriteToActivityLog(ex); } } } } }
public ScriptCompilationFailedException(ScriptPackage scriptPackage, IEnumerable <CompilationMessage> compilationResultMessages) : base("Script compilation failed") { ScriptPackage = scriptPackage; CompilationResultMessages = compilationResultMessages; }
private void PreprocessSourceCode(ScriptPackage scriptPackage, CSharpScriptClassDefinition classDefinition) { _sourcePreprocessors.ForEach(x => x.Preprocess(scriptPackage, classDefinition)); }
/// <summary> /// Generates the scripts /// </summary> /// <returns>The script generation result</returns> public IScriptGenerationResult GenerateScripts() { if (ConfigurationOptions == null || !ConfigurationOptions.Enabled) { return(new ScriptGenerationResult(false, $"Script generation is disabled in the configuration options.")); } if (string.IsNullOrEmpty(ConfigurationOptions.ServerObjectsResultFilepath)) { return(new ScriptGenerationResult(false, "ResultFilePath is not specified in the configuration options.")); } Uri projUri = new Uri(ProjectPath); Uri resultRelative; try { resultRelative = new Uri(ConfigurationOptions.ServerObjectsResultFilepath, UriKind.RelativeOrAbsolute); } catch (UriFormatException) { return(new ScriptGenerationResult(false, "ResultFilePath is not in a valid format.")); } Uri resultAbsolute = resultRelative.IsAbsoluteUri ? resultRelative : new Uri(projUri, resultRelative); FileInfo fi = new FileInfo(resultAbsolute.LocalPath); if (!fi.Directory.Exists) { return(new ScriptGenerationResult(false, $"The directory in ResultFilePath of the config file ({fi.Directory.FullName}) does not exist.")); } // At this point we are good ScriptPackage package = CreatePackage(); ProcessorSettings processorSettings = new ProcessorSettings() { TypeNamespace = ConfigurationOptions.ClassNamespace, EnumNamespace = ConfigurationOptions.EnumNamespace }; if (!string.IsNullOrEmpty(ConfigurationOptions.MvcActionAttributeName)) { processorSettings.MvcActionFilter = new IsOfTypeFilter(ConfigurationOptions.MvcActionAttributeName); } ExtractedTypeCollection typeCollection = new ExtractedTypeCollection(package, processorSettings); IScriptTemplate scriptGen = ScriptTemplateFactory.GetTemplate(ConfigurationOptions.TemplateType); // Write the object script text string scriptText = scriptGen.CreateTypeTemplate().GetText(typeCollection); File.WriteAllText(resultAbsolute.LocalPath, scriptText); // Write MVC controllers Uri ajaxModuleUri = string.IsNullOrEmpty(ConfigurationOptions.AjaxFunctionModulePath) ? null : new Uri(projUri, ConfigurationOptions.AjaxFunctionModulePath); ControllerContext context = new ControllerContext() { ServerObjectsResultFilepath = new Uri(resultAbsolute.LocalPath), AjaxFunctionName = ConfigurationOptions.AjaxFunctionName, WebMethodNamespace = ConfigurationOptions.WebMethodNamespace, ExtractedTypes = typeCollection, AjaxFunctionModulePath = ajaxModuleUri }; foreach (MvcControllerInfo controller in typeCollection.GetMvcControllers()) { string outputPath = GetControllerResultPath(controller); string controllerScript = scriptGen.CreateControllerTextTemplate().GetText(controller, context, new Uri(outputPath)); File.WriteAllText(outputPath, controllerScript); } return(new ScriptGenerationResult(true, null)); }
/// <summary> /// Creates a package /// </summary> /// <returns>The <see cref="ScriptPackage"/></returns> public ScriptPackage CreatePackage() { TypeVisitor visitor = new TypeVisitor(); return(ScriptPackage.BuildPackage(_typeIterator, visitor)); }
public TypeTable(ScriptPackage package, ProcessorSettings settings) { Compile(package, settings); }
public void Id_CtorArgument_IdIsSet() { var scriptPackage = new ScriptPackage("TestId", "TestScript", A.Fake <ISourceCode>()); Assert.Equal("TestId", scriptPackage.Id); }