public void TestIsDirectoryOnly() { Assert.False(new UFile("/a/b/c.txt").IsDirectoryOnly); var dirPath = new UDirectory("/a/b/c"); Assert.True(dirPath.IsDirectoryOnly); Assert.AreEqual("/a/b/c", dirPath.GetDirectory()); var filePath = new UFile("/test.txt"); Assert.AreEqual("/", filePath.GetDirectory()); Assert.AreEqual("test.txt", filePath.GetFileNameWithExtension()); }
public static BuildStep FromRequest(AssetCompilerContext context, Package package, UDirectory urlRoot, EffectCompileRequest effectCompileRequest) { var compilerParameters = new CompilerParameters(effectCompileRequest.UsedParameters); compilerParameters.EffectParameters.Platform = context.GetGraphicsPlatform(package); compilerParameters.EffectParameters.Profile = context.GetGameSettingsAsset().GetOrCreate <RenderingSettings>(context.Platform).DefaultGraphicsProfile; compilerParameters.EffectParameters.ApplyCompilationMode(context.GetCompilationMode()); return(new CommandBuildStep(new EffectCompileCommand(context, urlRoot, effectCompileRequest.EffectName, compilerParameters, package))); }
private static async void Startup(UFile initialSessionPath) { try { InitializeLanguageSettings(); var serviceProvider = InitializeServiceProvider(); try { PackageSessionPublicHelper.FindAndSetMSBuildVersion(); } catch (Exception e) { var message = "Could not find a compatible version of MSBuild.\r\n\r\n" + "Check that you have a valid installation with the required workloads, or go to [www.visualstudio.com/downloads](https://www.visualstudio.com/downloads) to install a new one.\r\n\r\n" + e; await serviceProvider.Get <IEditorDialogService>().MessageBox(message, Core.Presentation.Services.MessageBoxButton.OK, Core.Presentation.Services.MessageBoxImage.Error); app.Shutdown(); return; } // We use a MRU that contains the older version projects to display in the editor var mru = new MostRecentlyUsedFileCollection(InternalSettings.LoadProfileCopy, InternalSettings.MostRecentlyUsedSessions, InternalSettings.WriteFile); mru.LoadFromSettings(); var editor = new GameStudioViewModel(serviceProvider, mru); AssetsPlugin.RegisterPlugin(typeof(XenkoDefaultAssetsPlugin)); AssetsPlugin.RegisterPlugin(typeof(XenkoEditorPlugin)); // Attempt to load the startup session, if available if (!UPath.IsNullOrEmpty(initialSessionPath)) { var sessionLoaded = await editor.OpenInitialSession(initialSessionPath); if (sessionLoaded == true) { var mainWindow = new GameStudioWindow(editor); Application.Current.MainWindow = mainWindow; WindowManager.ShowMainWindow(mainWindow); return; } } // No session successfully loaded, open the new/open project window bool?completed; // The user might cancel after chosing a template to instantiate, in this case we'll reopen the window var startupWindow = new ProjectSelectionWindow { WindowStartupLocation = WindowStartupLocation.CenterScreen, ShowInTaskbar = true, }; var viewModel = new NewOrOpenSessionTemplateCollectionViewModel(serviceProvider, startupWindow); startupWindow.Templates = viewModel; startupWindow.ShowDialog(); // The user selected a template to instantiate if (startupWindow.NewSessionParameters != null) { // Clean existing entry in the MRU data var directory = startupWindow.NewSessionParameters.OutputDirectory; var name = startupWindow.NewSessionParameters.OutputName; var mruData = new MRUAdditionalDataCollection(InternalSettings.LoadProfileCopy, GameStudioInternalSettings.MostRecentlyUsedSessionsData, InternalSettings.WriteFile); mruData.RemoveFile(UFile.Combine(UDirectory.Combine(directory, name), new UFile(name + SessionViewModel.SolutionExtension))); completed = await editor.NewSession(startupWindow.NewSessionParameters); } // The user selected a path to open else if (startupWindow.ExistingSessionPath != null) { completed = await editor.OpenSession(startupWindow.ExistingSessionPath); } // The user cancelled from the new/open project window, so exit the application else { completed = true; } if (completed != true) { var windowsClosed = new List <Task>(); foreach (var window in Application.Current.Windows.Cast <Window>().Where(x => x.IsLoaded)) { var tcs = new TaskCompletionSource <int>(); window.Unloaded += (s, e) => tcs.SetResult(0); windowsClosed.Add(tcs.Task); } await Task.WhenAll(windowsClosed); // When a project has been partially loaded, it might already have initialized some plugin that could conflict with // the next attempt to start something. Better start the application again. var commandLine = string.Join(" ", Environment.GetCommandLineArgs().Skip(1).Select(x => $"\"{x}\"")); var process = new Process { StartInfo = new ProcessStartInfo(typeof(Program).Assembly.Location, commandLine) }; process.Start(); app.Shutdown(); return; } if (editor.Session != null) { // If a session was correctly loaded, show the main window var mainWindow = new GameStudioWindow(editor); Application.Current.MainWindow = mainWindow; WindowManager.ShowMainWindow(mainWindow); } else { // Otherwise, exit. app.Shutdown(); } } catch (Exception) { app.Shutdown(); } }
public AssetFolder Find(UDirectory folder) { return(folders.FirstOrDefault(sourceFolder => sourceFolder.Path == folder)); }
public void TestMakeRelative() { UPath assetPath2 = null; UPath newAssetPath2 = null; var dir1 = new UDirectory("/a/b/c"); var assetDir2 = new UDirectory("/a/b/c"); newAssetPath2 = dir1.MakeRelative(assetDir2); Assert.Equal(".", newAssetPath2.FullPath); var assetDir3 = new UDirectory("/a/b"); newAssetPath2 = dir1.MakeRelative(assetDir3); Assert.Equal("c", newAssetPath2.FullPath); var assetDir4 = new UDirectory("/a/b/c/d"); newAssetPath2 = dir1.MakeRelative(assetDir4); Assert.Equal("..", newAssetPath2.FullPath); // Test direct relative assetPath2 = new UFile("/a/b/c/test.txt"); newAssetPath2 = assetPath2.MakeRelative(dir1); Assert.Equal("test.txt", newAssetPath2.FullPath); // Test direct relative + subdir assetPath2 = new UFile("/a/b/c/test/test.txt"); newAssetPath2 = assetPath2.MakeRelative(dir1); Assert.Equal("test/test.txt", newAssetPath2.FullPath); // Test relative 1 assetPath2 = new UFile("/a/b/test.txt"); newAssetPath2 = assetPath2.MakeRelative(dir1); Assert.Equal("../test.txt", newAssetPath2.FullPath); // Test relative 2 assetPath2 = new UFile("/a/test.txt"); newAssetPath2 = assetPath2.MakeRelative(dir1); Assert.Equal("../../test.txt", newAssetPath2.FullPath); // Test relative 3 assetPath2 = new UFile("/test.txt"); newAssetPath2 = assetPath2.MakeRelative(dir1); Assert.Equal("../../../test.txt", newAssetPath2.FullPath); // Test already relative assetPath2 = new UFile("../test.txt"); newAssetPath2 = assetPath2.MakeRelative(dir1); Assert.Equal("../test.txt", newAssetPath2.FullPath); // Test only root path in common assetPath2 = new UFile("/e/f/g/test.txt"); newAssetPath2 = assetPath2.MakeRelative(dir1); Assert.Equal("../../../e/f/g/test.txt", newAssetPath2.FullPath); // Test only root path in common with single file assetPath2 = new UFile("/test.txt"); newAssetPath2 = assetPath2.MakeRelative(dir1); Assert.Equal("../../../test.txt", newAssetPath2.FullPath); }
public static void Build(ILogger log, Package package, string outputDirectory = null) { if (package == null) { throw new ArgumentNullException(nameof(package)); } var meta = new ManifestMetadata(); PackageStore.ToNugetManifest(package.Meta, meta); // Sanity check: Xenko version should be same between NuGet package and Xenko package var nugetVersion = new PackageVersion(XenkoVersion.NuGetVersion).Version; var packageVersion = package.Meta.Version.Version; if (nugetVersion != packageVersion) { log.Error($"Package has mismatching version: NuGet package version is {nugetVersion} and Xenko Package version is {packageVersion}"); return; } if (nugetVersion.Revision <= 0) { // If 0, we have special cases with NuGet dropping it in install path, could be dangerous and lead to bugs if not properly tested. log.Error($"Package has revision {nugetVersion} but 4th digit needs to be at least 1."); return; } // Override version with NuGet version (4th number is different in Xenko package) meta.Version = XenkoVersion.NuGetVersion; var builder = new NugetPackageBuilder(); builder.Populate(meta); var currentAssemblyLocation = Assembly.GetExecutingAssembly().Location; var mainPlatformDirectory = Path.GetFileName(Path.GetDirectoryName(currentAssemblyLocation)); // TODO this is not working // We are excluding everything that is in a folder that starts with a dot (ie. .shadow, .vs) var files = new List <ManifestFile>() { NewFile(@"Bin\**\*.exe", "Bin", @"Bin\**\.*\**\*.exe;Bin\**\Tools\**.exe"), NewFile(@"Bin\**\*.so", "Bin", @"Bin\**\.*\**\*.so;Bin\Windows\lib\**\*.so"), NewFile(@"Bin\**\*.ssdeps", "Bin", @"Bin\**\.*\**\*.ssdeps"), NewFile(@"Bin\**\*.a", "Bin", @"Bin\**\.*\**\*.a"), NewFile(@"Bin\**\*.md", "Bin", @"Bin\**\.*\**\*.md"), NewFile(@"Bin\**\*.html", "Bin", @"Bin\**\.*\**\*.html"), NewFile(@"Bin\**\*.config", "Bin", @"Bin\**\.*\**\*.config"), NewFile(@"Bin\**\*.dll", "Bin", @"Bin\**\.*\**\*.dll;Bin\Windows\lib\**\*.dll"), NewFile(@"Bin\**\*.xml", "Bin", @"Bin\**\.*\**\*.xml"), NewFile(@"Bin\**\*.usrdoc", "Bin", @"Bin\**\.*\**\*.usrdoc"), NewFile(@"Bin\**\*.winmd", "Bin", @"Bin\**\.*\**\*.winmd"), NewFile(@"Bin\**\*.sh", "Bin", @"Bin\**\.*\**\*.sh"), NewFile(@"Bin\**\*.json", "Bin", @"Bin\**\.*\**\*.json"), NewFile(@"deps\AssemblyProcessor\*.exe", @"deps/AssemblyProcessor"), NewFile(@"deps\AssemblyProcessor\*.dll", @"deps/AssemblyProcessor"), NewFile(@"deps\CoreFX\**\*.*", @"deps\CoreFX"), NewFile($@"Bin\{mainPlatformDirectory}\ios-tcprelay\*.py", $@"Bin\{mainPlatformDirectory}\ios-tcprelay"), NewFile(@"Targets\*.targets", "Targets"), NewFile($@"Bin\{mainPlatformDirectory}\SiliconStudio.*.pdb", $@"Bin\{mainPlatformDirectory}", @"Bin\**\SiliconStudio.Xenko.Importer*.pdb;Bin\**\SiliconStudio.Xenko.Assimp.Translation.pdb"), }; // Handle Assets var rootDir = package.RootDirectory; var newPackage = new Package { Meta = package.Meta }; foreach (var profile in package.Profiles) { var target = "Assets/" + profile.Name; foreach (var assetFolder in profile.AssetFolders) { // TODO: handle exclude in asset folders //files.Add(NewFile(source, target, @"**\*.cs;**\*.hlsl;**\*.csproj;**\*.csproj.user;**\obj\**")); files.Add(NewFile(assetFolder.Path.MakeRelative(rootDir) + "/**/*.xksl", target)); files.Add(NewFile(assetFolder.Path.MakeRelative(rootDir) + "/**/*.xkfx", target)); files.Add(NewFile(assetFolder.Path.MakeRelative(rootDir) + "/**/*.xkfnt", target)); files.Add(NewFile(assetFolder.Path.MakeRelative(rootDir) + "/**/*.xksheet", target)); files.Add(NewFile(assetFolder.Path.MakeRelative(rootDir) + "/**/*.xkuilib", target)); files.Add(NewFile(assetFolder.Path.MakeRelative(rootDir) + "/**/*.xkgfxcomp", target)); files.Add(NewFile(assetFolder.Path.MakeRelative(rootDir) + "/**/*.xktex", target)); var resourceFolder = UPath.Combine(assetFolder.Path, new UDirectory("../../Resources")); if (Directory.Exists(resourceFolder.ToWindowsPath())) { files.Add(NewFile(resourceFolder.MakeRelative(rootDir) + "/**/*.*", "Resources")); } } var targetProfile = new PackageProfile(profile.Name); targetProfile.AssetFolders.Add(new AssetFolder(target)); newPackage.Profiles.Add(targetProfile); } //Handle RootAssets foreach (var rootAsset in package.RootAssets) { newPackage.RootAssets.Add(rootAsset); } // Handle templates var targetFolder = new TemplateFolder("Templates"); foreach (var templateFolder in package.TemplateFolders) { var source = templateFolder.Path.MakeRelative(rootDir) + "/**"; UDirectory target = targetFolder.Path; if (templateFolder.Group != null) { target = UPath.Combine(target, templateFolder.Group); } var excludeFiles = templateFolder.Exclude; files.Add(NewFile(source, target, excludeFiles)); // Add template files foreach (var templateFile in templateFolder.Files) { var newTemplateFile = templateFile.MakeRelative(templateFolder.Path); if (templateFolder.Group != null) { newTemplateFile = UPath.Combine(templateFolder.Group, newTemplateFile); } newTemplateFile = UPath.Combine(targetFolder.Path, newTemplateFile); targetFolder.Files.Add(newTemplateFile); } } // Add files builder.PopulateFiles(package.RootDirectory, files); files.Clear(); var dataFiles = builder.Files.ToList(); builder.ClearFiles(); // Create temp package for archive newPackage.TemplateFolders.Add(targetFolder); var newPackageFileName = "temp" + Guid.NewGuid() + ".xkpkg"; newPackage.FullPath = package.RootDirectory + "/" + newPackageFileName; var result = new LoggerResult(); newPackage.Save(result); if (result.HasErrors) { throw new InvalidOperationException(result.ToText()); // TODO throw error } // Add the package file files.Add(NewFile(newPackageFileName, package.Meta.Name + Package.PackageFileExtension)); // Add entry point to decompress LZMA files.Add(NewFile(@"tools\**\*.exe", "tools")); files.Add(NewFile(@"tools\**\*.dll", "tools")); // Add an empty .xz file so that it gets added to [Content_Types].xml // This file will be removed later files.Add(NewFile(@"tools\data_empty.xz", string.Empty)); // Repopulate with .xkpkg file builder.PopulateFiles(package.RootDirectory, files); outputDirectory = outputDirectory ?? Environment.CurrentDirectory; // Save the nupkg var outputPath = GetOutputPath(builder, outputDirectory); bool isExistingPackage = File.Exists(outputPath); if (isExistingPackage) { File.Delete(outputPath); } try { using (Stream stream = File.Create(outputPath)) { builder.Save(stream); stream.Position = 0; // Add LZMA file as update so that it is stored without compression using (var archive = new ZipArchive(stream, ZipArchiveMode.Update, true)) { // Delete data_empty.xz var dataEntry = archive.GetEntry("data_empty.xz"); dataEntry.Delete(); // Create data.xz (no compression since .xz is already compressed) dataEntry = archive.CreateEntry("data.xz", CompressionLevel.NoCompression); using (var dataStream = dataEntry.Open()) { // Generate LZMA using (var indexedArchive = new IndexedArchive()) { foreach (var file in dataFiles) { indexedArchive.AddFile(Path.Combine(package.RootDirectory, file.SourcePath), file.Path); } indexedArchive.Save(dataStream, new ConsoleProgressReport()); } } } } } catch { if (!isExistingPackage && File.Exists(outputPath)) { File.Delete(outputPath); } throw; } File.Delete(newPackage.FullPath); }
/// <summary> /// Sync <paramref name="sourceDir"/> with <paramref name="destDir"/> /// </summary> /// <param name="connectInfo">Credentials to access host where synchronization takes place.</param> /// <param name="sourceDir">Source directory on the local host.</param> /// <param name="destDir">Destination directory on the remote host</param> /// <param name="logger">Logging facility</param> /// <returns><c>true</c> if successful; otherwise, <c>false</c>.</returns> private static bool SyncTo(ConnectionInfo connectInfo, UDirectory sourceDir, UDirectory destDir, LoggerResult logger) { // Copy files over using (var sftp = new SftpClient(connectInfo)) { try { sftp.Connect(); if (!sftp.IsConnected) { return(false); } } catch { logger.Error("Cannot connect"); return(false); } // Perform recursive copy of all the folders under `sourceDir`. This is required // as the sftp client only synchronize directories at their level only, no // subdirectory. var dirs = new Queue <DirectoryInfo>(); dirs.Enqueue(new DirectoryInfo(sourceDir)); var parentPath = sourceDir; while (dirs.Count != 0) { var currentDir = dirs.Dequeue(); var currentPath = new UDirectory(currentDir.FullName); foreach (var subdir in currentDir.EnumerateDirectories()) { dirs.Enqueue(subdir); } // Get the destination path by adding to `Location` the relative path of `sourceDir` to `currentDir`. var destination = UPath.Combine(destDir, currentPath.MakeRelative(parentPath)); logger.Info("Synchronizing " + currentPath + " with " + destination.FullPath); // Try to create a remote directory. If it throws an exception, we will assume // for now that the directory already exists. See https://github.com/sshnet/SSH.NET/issues/25 try { sftp.CreateDirectory(destination.FullPath); logger.Info("Creating remote directory " + destination.FullPath); } catch (SshException) { // Do nothing, as this is when the directory already exists } // Synchronize files. foreach (var file in sftp.SynchronizeDirectories(currentPath.FullPath, destination.FullPath, "*")) { logger.Info("Updating " + file.Name); // Some of our files needs executable rights, however we do not know in advance which one // need it. For now all files will be rwxr.xr.x (0755 in octal but written in decimal for readability). sftp.ChangePermissions(destination.FullPath + "/" + file.Name, 755); } } return(true); } }
public MaterialDescription Run(MaterialDescription material, UDirectory materialPath, PixelFormat outputFormat = PixelFormat.ETC1) { if (material == null) { throw new ArgumentNullException("material"); } var assetManager = new AssetManager(); var modifiedMaterial = material.Clone(); var textureVisitor = new MaterialTextureVisitor(modifiedMaterial); var nodeReplacer = new MaterialNodeReplacer(modifiedMaterial); var textureNodes = textureVisitor.GetAllModelTextureValues(); foreach (var textureNode in textureNodes) { var itemAsset = assetSession.FindAsset(textureNode.TextureReference.Id); if (itemAsset == null) { throw new InvalidOperationException("The referenced texture is not included in the project session."); } var textureAsset = (TextureAsset)itemAsset.Asset; if (textureAsset.Format != TextureFormat.Compressed || textureAsset.Alpha == AlphaFormat.None) { continue; // the texture has no alpha so there is no need to divide the texture into two sub-textures } var originalLocation = textureNode.TextureReference.Location; using (var image = assetManager.Load <Image>(originalLocation)) { CreateAndSaveSeparateTextures(image, originalLocation, textureAsset.GenerateMipmaps, outputFormat); assetManager.Unload(image); // matching unload to the previous asset manager load call } // make new tree var colorNode = new MaterialTextureNode(GenerateColorTextureURL(originalLocation), textureNode.TexcoordIndex, Vector2.One, Vector2.Zero); var alphaNode = new MaterialTextureNode(GenerateAlphaTextureURL(originalLocation), textureNode.TexcoordIndex, Vector2.One, Vector2.Zero); var substituteAlphaNode = new MaterialShaderClassNode { MixinReference = new AssetReference <EffectShaderAsset>(Guid.Empty, "ComputeColorSubstituteAlphaWithColor") }; substituteAlphaNode.CompositionNodes.Add("color1", colorNode); substituteAlphaNode.CompositionNodes.Add("color2", alphaNode); // set the parameters of the children so that they match the original texture var children = new[] { colorNode, alphaNode }; foreach (var childTexture in children) { childTexture.Sampler.AddressModeU = textureNode.Sampler.AddressModeU; childTexture.Sampler.AddressModeV = textureNode.Sampler.AddressModeV; childTexture.Sampler.Filtering = textureNode.Sampler.Filtering; childTexture.Offset = textureNode.Offset; childTexture.Sampler.SamplerParameterKey = textureNode.Sampler.SamplerParameterKey; childTexture.Scale = textureNode.Scale; childTexture.TexcoordIndex = textureNode.TexcoordIndex; } // copy the parameter key on the color and let the one of the alpha null so that it is set automatically to available value later colorNode.Key = textureNode.Key; alphaNode.Key = null; // update all the material references to the new node nodeReplacer.Replace(textureNode, substituteAlphaNode); } return(modifiedMaterial); }
public static void Build(ILogger log, Package package, string outputDirectory = null) { if (package == null) { throw new ArgumentNullException(nameof(package)); } var meta = new ManifestMetadata(); PackageStore.ToNugetManifest(package.Meta, meta); // Sanity check: Xenko version should be same between NuGet package and Xenko package var nugetVersion = new PackageVersion(XenkoVersion.NuGetVersion).Version; var packageVersion = package.Meta.Version.Version; if (nugetVersion != packageVersion) { log.Error($"Package has mismatching version: NuGet package version is {nugetVersion} and Xenko Package version is {packageVersion}"); return; } if (nugetVersion.Revision <= 0) { // If 0, we have special cases with NuGet dropping it in install path, could be dangerous and lead to bugs if not properly tested. log.Error($"Package has revision {nugetVersion} but 4th digit needs to be at least 1."); return; } // Override version with NuGet version (4th number is different in Xenko package) meta.Version = XenkoVersion.NuGetVersion; var builder = new NugetPackageBuilder(); builder.Populate(meta); var currentAssemblyLocation = Assembly.GetExecutingAssembly().Location; var mainPlatformDirectory = Path.GetFileName(Path.GetDirectoryName(currentAssemblyLocation)); // TODO this is not working // We are excluding everything that is in a folder that starts with a dot (ie. .shadow, .vs) var files = new List <ManifestFile>() { NewFile(@"Bin\**\*.exe", "Bin", @"Bin\**\.*\**\*.exe;Bin\**\Tools\**.exe"), NewFile(@"Bin\**\*.so", "Bin", @"Bin\**\.*\**\*.so;Bin\Windows\lib\**\*.so"), NewFile(@"Bin\**\*.ssdeps", "Bin", @"Bin\**\.*\**\*.ssdeps"), NewFile(@"Bin\**\*.a", "Bin", @"Bin\**\.*\**\*.a"), NewFile(@"Bin\**\*.md", "Bin", @"Bin\**\.*\**\*.md"), NewFile(@"Bin\**\*.html", "Bin", @"Bin\**\.*\**\*.html"), NewFile(@"Bin\**\*.config", "Bin", @"Bin\**\.*\**\*.config"), NewFile(@"Bin\**\*.dll", "Bin", @"Bin\**\.*\**\*.dll;Bin\Windows\lib\**\*.dll"), NewFile(@"Bin\**\*.xml", "Bin", @"Bin\**\.*\**\*.xml"), NewFile(@"Bin\**\*.usrdoc", "Bin", @"Bin\**\.*\**\*.usrdoc"), NewFile(@"Bin\**\*.winmd", "Bin", @"Bin\**\.*\**\*.winmd"), NewFile(@"Bin\**\*.sh", "Bin", @"Bin\**\.*\**\*.sh"), NewFile(@"Bin\**\*.json", "Bin", @"Bin\**\.*\**\*.json"), NewFile(@"deps\AssemblyProcessor\*.exe", @"deps/AssemblyProcessor"), NewFile(@"deps\AssemblyProcessor\*.dll", @"deps/AssemblyProcessor"), NewFile($@"Bin\{mainPlatformDirectory}\ios-tcprelay\*.py", $@"Bin\{mainPlatformDirectory}\ios-tcprelay"), NewFile(@"Targets\*.targets", "Targets"), NewFile(@"Targets\*.props", "Targets"), NewFile($@"Bin\{mainPlatformDirectory}\Xenko.Core.*.pdb", $@"Bin\{mainPlatformDirectory}", @"Bin\**\Xenko.Importer*.pdb;Bin\**\Xenko.Assimp.Translation.pdb"), NewFile(@"build\Xenko.targets", @"build"), NewFile(@"build\Xenko.props", @"build"), NewFile(@"tools\**\*.exe", "tools"), NewFile(@"tools\**\*.dll", "tools"), NewFile(@"LICENSE.md", @""), NewFile(@"THIRD PARTY.md", @""), NewFile(@"BACKERS.md", @""), }; // Handle Assets var rootDir = package.RootDirectory; var newPackage = new Package { Meta = AssetCloner.Clone(package.Meta) }; newPackage.Meta.Version = new PackageVersion(meta.Version); foreach (var profile in package.Profiles) { var target = "Assets/" + profile.Name; foreach (var assetFolder in profile.AssetFolders) { files.Add(NewFile(assetFolder.Path.MakeRelative(rootDir) + "/**/*.xk*", target)); } foreach (var resourceFolder in profile.ResourceFolders) { files.Add(NewFile(resourceFolder.MakeRelative(rootDir) + "/**/*.*", "Resources")); } var targetProfile = new PackageProfile(profile.Name); if (profile.AssetFolders.Count > 0) { targetProfile.AssetFolders.Add(new AssetFolder(target)); } if (profile.ResourceFolders.Count > 0) { targetProfile.ResourceFolders.Add("Resources"); } newPackage.Profiles.Add(targetProfile); } //Handle RootAssets foreach (var rootAsset in package.RootAssets) { newPackage.RootAssets.Add(rootAsset); } // Handle templates var targetFolder = new TemplateFolder("Templates"); foreach (var templateFolder in package.TemplateFolders) { var source = templateFolder.Path.MakeRelative(rootDir) + "/**"; UDirectory target = targetFolder.Path; if (templateFolder.Group != null) { target = UPath.Combine(target, templateFolder.Group); } var excludeFiles = templateFolder.Exclude; files.Add(NewFile(source, target, excludeFiles)); // Add template files foreach (var templateFile in templateFolder.Files) { var newTemplateFile = templateFile.MakeRelative(templateFolder.Path); if (templateFolder.Group != null) { newTemplateFile = UPath.Combine(templateFolder.Group, newTemplateFile); } newTemplateFile = UPath.Combine(targetFolder.Path, newTemplateFile); targetFolder.Files.Add(newTemplateFile); } } // Create temp package for archive newPackage.TemplateFolders.Add(targetFolder); var newPackageFileName = "temp" + Guid.NewGuid() + ".xkpkg"; newPackage.FullPath = package.RootDirectory + "/" + newPackageFileName; var result = new LoggerResult(); newPackage.Save(result); if (result.HasErrors) { throw new InvalidOperationException(result.ToText()); // TODO throw error } files.Add(NewFile(newPackageFileName, package.Meta.Name + Package.PackageFileExtension)); // Add files builder.PopulateFiles(package.RootDirectory, files); outputDirectory = outputDirectory ?? Environment.CurrentDirectory; // Save the nupkg var outputPath = GetOutputPath(builder, outputDirectory); bool isExistingPackage = File.Exists(outputPath); if (isExistingPackage) { File.Delete(outputPath); } try { using (Stream stream = File.Create(outputPath)) { builder.Save(stream); } } catch { if (!isExistingPackage && File.Exists(outputPath)) { File.Delete(outputPath); } throw; } File.Delete(newPackage.FullPath); }
public int Run(string[] args) { clock = Stopwatch.StartNew(); // TODO this is hardcoded. Check how to make this dynamic instead. RuntimeHelpers.RunModuleConstructor(typeof(IProceduralModel).Module.ModuleHandle); RuntimeHelpers.RunModuleConstructor(typeof(MaterialKeys).Module.ModuleHandle); RuntimeHelpers.RunModuleConstructor(typeof(SpriteFontAsset).Module.ModuleHandle); RuntimeHelpers.RunModuleConstructor(typeof(ModelAsset).Module.ModuleHandle); RuntimeHelpers.RunModuleConstructor(typeof(SpriteStudioAnimationAsset).Module.ModuleHandle); RuntimeHelpers.RunModuleConstructor(typeof(ParticleSystem).Module.ModuleHandle); //var project = new Package(); //project.Save("test.sdpkg"); //Thread.Sleep(10000); //var spriteFontAsset = StaticFontAsset.New(); //Content.Save("test.sdfnt", spriteFontAsset); //project.Refresh(); //args = new string[] { "test.sdpkg", "-o:app_data", "-b:tmp", "-t:1" }; var exeName = Path.GetFileName(Assembly.GetExecutingAssembly().Location); var showHelp = false; var packMode = false; var updateGeneratedFilesMode = false; var buildEngineLogger = GlobalLogger.GetLogger("BuildEngine"); var options = new PackageBuilderOptions(new ForwardingLoggerResult(buildEngineLogger)); var p = new OptionSet { "Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) All Rights Reserved", "Stride Build Tool - Version: " + String.Format( "{0}.{1}.{2}", typeof(Program).Assembly.GetName().Version.Major, typeof(Program).Assembly.GetName().Version.Minor, typeof(Program).Assembly.GetName().Version.Build) + string.Empty, string.Format("Usage: {0} inputPackageFile [options]* -b buildPath", exeName), string.Empty, "=== Options ===", string.Empty, { "h|help", "Show this message and exit", v => showHelp = v != null }, { "v|verbose", "Show more verbose progress logs", v => options.Verbose = v != null }, { "d|debug", "Show debug logs (imply verbose)", v => options.Debug = v != null }, { "log", "Enable file logging", v => options.EnableFileLogging = v != null }, { "disable-auto-compile", "Disable auto-compile of projects", v => options.DisableAutoCompileProjects = v != null }, { "project-configuration=", "Project configuration", v => options.ProjectConfiguration = v }, { "platform=", "Platform name", v => options.Platform = (PlatformType)Enum.Parse(typeof(PlatformType), v) }, { "solution-file=", "Solution File Name", v => options.SolutionFile = v }, { "package-id=", "Package Id from the solution file", v => options.PackageId = Guid.Parse(v) }, { "package-file=", "Input Package File Name", v => options.PackageFile = v }, { "msbuild-uptodatecheck-filebase=", "BuildUpToDate File base for MSBuild; it will create one .inputs and one .outputs files", v => options.MSBuildUpToDateCheckFileBase = v }, { "o|output-path=", "Output path", v => options.OutputDirectory = v }, { "b|build-path=", "Build path", v => options.BuildDirectory = v }, { "log-file=", "Log build in a custom file.", v => { options.EnableFileLogging = v != null; options.CustomLogFileName = v; } }, { "monitor-pipe=", "Monitor pipe.", v => { if (!string.IsNullOrEmpty(v)) { options.MonitorPipeNames.Add(v); } } }, { "slave=", "Slave pipe", v => options.SlavePipe = v }, // Benlitz: I don't think this should be documented { "server=", "This Compiler is launched as a server", v => { } }, { "pack", "Special mode to copy assets and resources in a folder for NuGet packaging", v => packMode = true }, { "updated-generated-files", "Special mode to update generated files (such as .sdsl.cs)", v => updateGeneratedFilesMode = true }, { "t|threads=", "Number of threads to create. Default value is the number of hardware threads available.", v => options.ThreadCount = int.Parse(v) }, { "test=", "Run a test session.", v => options.TestName = v }, { "property:", "Properties. Format is name1=value1;name2=value2", v => { if (!string.IsNullOrEmpty(v)) { foreach (var nameValue in v.Split(new [] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { var equalIndex = nameValue.IndexOf('='); if (equalIndex == -1) { throw new OptionException("Expect name1=value1;name2=value2 format.", "property"); } var name = nameValue.Substring(0, equalIndex); var value = nameValue.Substring(equalIndex + 1); if (value != string.Empty) { options.Properties.Add(name, value); } } } } }, { "compile-property:", "Compile properties. Format is name1=value1;name2=value2", v => { if (!string.IsNullOrEmpty(v)) { if (options.ExtraCompileProperties == null) { options.ExtraCompileProperties = new Dictionary <string, string>(); } foreach (var nameValue in v.Split(new [] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { var equalIndex = nameValue.IndexOf('='); if (equalIndex == -1) { throw new OptionException("Expect name1=value1;name2=value2 format.", "property"); } options.ExtraCompileProperties.Add(nameValue.Substring(0, equalIndex), nameValue.Substring(equalIndex + 1)); } } } }, { "reattach-debugger=", "Reattach to a Visual Studio debugger", v => { int debuggerProcessId; if (!string.IsNullOrEmpty(v) && int.TryParse(v, out debuggerProcessId)) { if (!Debugger.IsAttached) { using (var debugger = VisualStudioDebugger.GetByProcess(debuggerProcessId)) { debugger?.Attach(); } } } } }, }; TextWriterLogListener fileLogListener = null; BuildResultCode exitCode; try { var unexpectedArgs = p.Parse(args); // Activate proper log level buildEngineLogger.ActivateLog(options.LoggerType); // Output logs to the console with colored messages if (options.SlavePipe == null) { globalLoggerOnGlobalMessageLogged = new ConsoleLogListener { LogMode = ConsoleLogMode.Always }; globalLoggerOnGlobalMessageLogged.TextFormatter = FormatLog; GlobalLogger.GlobalMessageLogged += globalLoggerOnGlobalMessageLogged; } if (updateGeneratedFilesMode) { PackageSessionPublicHelper.FindAndSetMSBuildVersion(); var csprojFile = options.PackageFile; var logger = new LoggerResult(); var projectDirectory = new UDirectory(Path.GetDirectoryName(csprojFile)); var package = Package.Load(logger, csprojFile, new PackageLoadParameters() { LoadMissingDependencies = false, AutoCompileProjects = false, LoadAssemblyReferences = false, AutoLoadTemporaryAssets = true, TemporaryAssetFilter = assetFile => AssetRegistry.IsProjectCodeGeneratorAssetFileExtension(assetFile.FilePath.GetFileExtension().ToLowerInvariant()) }); foreach (var assetItem in package.TemporaryAssets) { if (assetItem.Asset is IProjectFileGeneratorAsset projectGeneratorAsset) { try { options.Logger.Info($"Processing: {assetItem}"); projectGeneratorAsset.SaveGeneratedAsset(assetItem); } catch (Exception e) { options.Logger.Error($"Unhandled exception while updating generated files for {assetItem}", e); } } } return((int)BuildResultCode.Successful); } if (unexpectedArgs.Any()) { throw new OptionException("Unexpected arguments [{0}]".ToFormat(string.Join(", ", unexpectedArgs)), "args"); } try { options.ValidateOptions(); } catch (ArgumentException ex) { throw new OptionException(ex.Message, ex.ParamName); } if (showHelp) { p.WriteOptionDescriptions(Console.Out); return((int)BuildResultCode.Successful); } else if (packMode) { PackageSessionPublicHelper.FindAndSetMSBuildVersion(); var csprojFile = options.PackageFile; var intermediatePackagePath = options.BuildDirectory; var generatedItems = new List <(string SourcePath, string PackagePath)>(); var logger = new LoggerResult(); if (!PackAssetsHelper.Run(logger, csprojFile, intermediatePackagePath, generatedItems)) { foreach (var message in logger.Messages) { Console.WriteLine(message); } return((int)BuildResultCode.BuildError); } foreach (var generatedItem in generatedItems) { Console.WriteLine($"{generatedItem.SourcePath}|{generatedItem.PackagePath}"); } return((int)BuildResultCode.Successful); } // Also write logs from master process into a file if (options.SlavePipe == null) { if (options.EnableFileLogging) { string logFileName = options.CustomLogFileName; if (string.IsNullOrEmpty(logFileName)) { string inputName = Path.GetFileNameWithoutExtension(options.PackageFile); logFileName = "Logs/Build-" + inputName + "-" + DateTime.Now.ToString("yy-MM-dd-HH-mm") + ".txt"; } string dirName = Path.GetDirectoryName(logFileName); if (dirName != null) { Directory.CreateDirectory(dirName); } fileLogListener = new TextWriterLogListener(new FileStream(logFileName, FileMode.Create)) { TextFormatter = FormatLog }; GlobalLogger.GlobalMessageLogged += fileLogListener; } options.Logger.Info("BuildEngine arguments: " + string.Join(" ", args)); options.Logger.Info("Starting builder."); } else { IsSlave = true; } if (!string.IsNullOrEmpty(options.TestName)) { var test = new TestSession(); test.RunTest(options.TestName, options.Logger); exitCode = BuildResultCode.Successful; } else { builder = new PackageBuilder(options); if (!IsSlave) { Console.CancelKeyPress += OnConsoleOnCancelKeyPress; } exitCode = builder.Build(); } } catch (OptionException e) { options.Logger.Error($"Command option '{e.OptionName}': {e.Message}"); exitCode = BuildResultCode.CommandLineError; } catch (Exception e) { options.Logger.Error($"Unhandled exception", e); exitCode = BuildResultCode.BuildError; } finally { if (fileLogListener != null) { GlobalLogger.GlobalMessageLogged -= fileLogListener; fileLogListener.LogWriter.Close(); } // Output logs to the console with colored messages if (globalLoggerOnGlobalMessageLogged != null) { GlobalLogger.GlobalMessageLogged -= globalLoggerOnGlobalMessageLogged; } if (builder != null && !IsSlave) { Console.CancelKeyPress -= OnConsoleOnCancelKeyPress; } // Reset cache hold by YamlSerializer YamlSerializer.Default.ResetCache(); } return((int)exitCode); }
/// <summary> /// Initializes a new instance of the <see cref="AssetPackageViewModel"/> class. /// </summary> /// <param name="serviceProvider">The service provider for this view model.</param> /// <param name="packageLocation">The directory containing this package.</param> /// <param name="initiallySelected">Indicates whether this plaform should be initially selected.</param> public AssetPackageViewModel(IViewModelServiceProvider serviceProvider, string name, UDirectory packageLocation, bool initiallySelected) : base(serviceProvider) { PackageName = name; PackageLocation = packageLocation; IsSelected = initiallySelected; }
public static void Build(Package package, string specialVersion = null, string outputDirectory = null) { if (package == null) { throw new ArgumentNullException("package"); } var meta = new NuGet.ManifestMetadata(); package.Meta.ToNugetManifest(meta); // Override version with task SpecialVersion (if specified by user) if (specialVersion != null) { meta.Version = new PackageVersion(package.Meta.Version.ToString().Split('-').First() + "-" + specialVersion).ToString(); } var builder = new NuGet.PackageBuilder(); builder.Populate(meta); var currentAssemblyLocation = Assembly.GetExecutingAssembly().Location; var mainPlatformDirectory = Path.GetFileName(Path.GetDirectoryName(currentAssemblyLocation)); // TODO this is not working // We are excluding everything that is in a folder that starts with a dot (ie. .shadow, .vs) var files = new List <NuGet.ManifestFile>() { NewFile(@"Bin\**\*.exe", "Bin", @"Bin\**\.*\**\*.exe"), NewFile(@"Bin\**\*.vsix", "Bin", @"Bin\**\.*\**\*.vsix"), NewFile(@"Bin\**\*.so", "Bin", @"Bin\**\.*\**\*.so"), NewFile(@"Bin\**\*.a", "Bin", @"Bin\**\.*\**\*.a"), NewFile(@"Bin\**\*.md", "Bin", @"Bin\**\.*\**\*.md"), NewFile(@"Bin\**\*.html", "Bin", @"Bin\**\.*\**\*.html"), NewFile(@"Bin\**\*.config", "Bin", @"Bin\**\.*\**\*.config"), NewFile(@"Bin\**\*.dll", "Bin", @"Bin\**\.*\**\*.dll"), NewFile(@"Bin\**\*.xml", "Bin", @"Bin\**\.*\**\*.xml"), NewFile(@"Bin\**\*.usrdoc", "Bin", @"Bin\**\.*\**\*.usrdoc"), NewFile(@"Bin\**\*.winmd", "Bin", @"Bin\**\.*\**\*.winmd"), NewFile(@"Bin\**\*.sh", "Bin", @"Bin\**\.*\**\*.sh"), NewFile(@"Bin\**\*.json", "Bin", @"Bin\**\.*\**\*.json"), NewFile(@"deps\AssemblyProcessor\*.exe", @"deps/AssemblyProcessor"), NewFile(@"deps\AssemblyProcessor\*.dll", @"deps/AssemblyProcessor"), NewFile(@"deps\CoreFX\**\*.*", @"deps\CoreFX"), NewFile($@"Bin\{mainPlatformDirectory}\ios-tcprelay\*.py", $@"Bin\{mainPlatformDirectory}\ios-tcprelay"), NewFile(@"Targets\*.targets", "Targets"), NewFile($@"Bin\{mainPlatformDirectory}\SiliconStudio.*.pdb", $@"Bin\{mainPlatformDirectory}", @"Bin\**\SiliconStudio.Xenko.Importer*.pdb;Bin\**\SiliconStudio.Xenko.Assimp.Translation.pdb"), }; // Handle Assets var rootDir = package.RootDirectory; var newPackage = new Package { Meta = package.Meta }; foreach (var profile in package.Profiles) { var target = "Assets/" + profile.Name; foreach (var assetFolder in profile.AssetFolders) { // TODO: handle exclude in asset folders //files.Add(NewFile(source, target, @"**\*.cs;**\*.hlsl;**\*.csproj;**\*.csproj.user;**\obj\**")); files.Add(NewFile(assetFolder.Path.MakeRelative(rootDir) + "/**/*.xksl", target)); files.Add(NewFile(assetFolder.Path.MakeRelative(rootDir) + "/**/*.xkfx", target)); files.Add(NewFile(assetFolder.Path.MakeRelative(rootDir) + "/**/*.xkfnt", target)); } var targetProfile = new PackageProfile(profile.Name); targetProfile.AssetFolders.Add(new AssetFolder(target)); newPackage.Profiles.Add(targetProfile); } //Handle RootAssets foreach (var rootAsset in package.RootAssets) { newPackage.RootAssets.Add(rootAsset); } // Handle templates var targetFolder = new TemplateFolder("Templates"); foreach (var templateFolder in package.TemplateFolders) { var source = templateFolder.Path.MakeRelative(rootDir) + "/**"; UDirectory target = targetFolder.Path; if (templateFolder.Group != null) { target = UPath.Combine(target, templateFolder.Group); } var excludeFiles = templateFolder.Exclude; files.Add(NewFile(source, target, excludeFiles)); // Add template files foreach (var templateFile in templateFolder.Files) { var newTemplateFile = templateFile.MakeRelative(templateFolder.Path); if (templateFolder.Group != null) { newTemplateFile = UPath.Combine(templateFolder.Group, newTemplateFile); } newTemplateFile = UPath.Combine(targetFolder.Path, newTemplateFile); targetFolder.Files.Add(newTemplateFile); } } // Create temp package for archive newPackage.TemplateFolders.Add(targetFolder); var newPackageFileName = "temp" + Guid.NewGuid() + ".xkpkg"; newPackage.FullPath = package.RootDirectory + "/" + newPackageFileName; var result = newPackage.Save(); if (result.HasErrors) { throw new InvalidOperationException(result.ToText()); // TODO throw error } files.Add(NewFile(newPackageFileName, package.Meta.Name + Package.PackageFileExtension)); // Add files builder.PopulateFiles(package.RootDirectory, files); outputDirectory = outputDirectory ?? Environment.CurrentDirectory; // Save the nupkg var outputPath = GetOutputPath(builder, outputDirectory); bool isExistingPackage = File.Exists(outputPath); if (isExistingPackage) { File.Delete(outputPath); } try { using (Stream stream = File.Create(outputPath)) { builder.Save(stream); } } catch { if (!isExistingPackage && File.Exists(outputPath)) { File.Delete(outputPath); } throw; } File.Delete(newPackage.FullPath); }
static EditorSettings() { DefaultTextEditor = new SettingsKey <UFile>("ExternalTools/DefaultTextEditor", SettingsContainer, new UFile(@"%windir%\system32\notepad.exe")) { DisplayName = $"{ExternalTools}/{Tr._p("Settings", "Default text editor")}", }; ShaderEditor = new SettingsKey <UFile>("ExternalTools/ShaderEditor", SettingsContainer, new UFile(@"%windir%\system32\notepad.exe")) { DisplayName = $"{ExternalTools}/{Tr._p("Settings", "Shader editor")}", }; DefaultIDE = new SettingsKey <string>("ExternalTools/DefaultIDE", SettingsContainer, VisualStudioVersions.DefaultIDE.DisplayName) { GetAcceptableValues = () => { var names = new List <string> { VisualStudioVersions.DefaultIDE.DisplayName }; names.AddRange(VisualStudioVersions.AvailableVisualStudioInstances.Where(x => x.HasDevenv).Select(x => x.DisplayName)); return(names); }, DisplayName = $"{ExternalTools}/{Tr._p("Settings", "Default IDE")}", }; AskBeforeDeletingAssets = new SettingsKey <bool>("Interface/AskBeforeDeletingAssets", SettingsContainer, true) { DisplayName = $"{Interface}/{Tr._p("Settings", "Ask before deleting assets")}", Description = Tr._p("Settings", "Ask before deleting assets"), }; AskBeforeReloadingAssemblies = new SettingsKey <bool>("Interface/AskBeforeReloadingAssemblies", SettingsContainer, true) { DisplayName = $"{Interface}/{Tr._p("Settings", "Ask before reloading assemblies")}", Description = Tr._p("Settings", "Ask before reloading assemblies"), }; AutoReloadAssemblies = new SettingsKey <bool>("Interface/AutoReloadAssemblies", SettingsContainer, true) { DisplayName = $"{Interface}/{Tr._p("Settings", "Automatically reload assemblies")}", Description = Tr._p("Settings", "Automatically reload assemblies"), }; AskBeforeSavingNewScripts = new SettingsKey <bool>("Interface/AskBeforeSavingNewScripts", SettingsContainer, true) { DisplayName = $"{Interface}/{Tr._p("Settings", "Ask before saving new scripts")}", Description = Tr._p("Settings", "Ask before saving new scripts"), }; StoreCrashEmail = new SettingsKey <string>("Interface/StoreCrashEmail", SettingsContainer, "") { DisplayName = $"{Interface}/{Tr._p("Settings", "Crash report e-mail")}", Description = Tr._p("Settings", "Crash report e-mail"), }; Language = new SettingsKey <SupportedLanguage>("Interface/Language", SettingsContainer, SupportedLanguage.MachineDefault) { DisplayName = $"{Interface}/{Tr._p("Settings", "Language")}", }; ResetEditorLayout = new SettingsCommand("Interface/ResetEditorLayout") { ActionName = Tr._p("Settings", "Reset"), DisplayName = $"{Interface}/{Tr._p("Settings", "Reset Game Studio layout")}" }; FallbackBuildCacheDirectory = new UDirectory(Path.Combine(EditorPath.DefaultTempPath, "BuildCache")); UseEffectCompilerServer = new SettingsKey <bool>("Tools/UseEffectCompilerServer", SettingsContainer, true) { DisplayName = $"{Tools}/{Tr._p("Settings", "Use effect compiler server for mobile platforms")}", }; ReloadLastSession = new SettingsKey <bool>("Interface/ReloadLastSession", SettingsContainer, false) { DisplayName = $"{Interface}/{Tr._p("Settings", "Automatically reload last session at startup")}", }; }
/// <summary> /// Fills the builder with the list of files that are part of this new package. /// </summary> /// <param name="rootDirectory">The root location where files are located.</param> /// <param name="files">The files to include to the builder.</param> public void PopulateFiles(UDirectory rootDirectory, List <ManifestFile> files) { ((PackageBuilder)Builder).PopulateFiles(rootDirectory, ToManifestFiles(files)); }
public void TestGetParent() { var dirPath1 = new UDirectory(@"E:\a\b"); var dirPathParent1 = dirPath1.GetParent(); Assert.AreEqual(@"E:/a", dirPathParent1.FullPath); dirPathParent1 = dirPathParent1.GetParent(); Assert.AreEqual(@"E:", dirPathParent1.FullPath); dirPathParent1 = dirPathParent1.GetParent(); Assert.AreEqual(UDirectory.Empty, dirPathParent1); dirPath1 = new UDirectory(@"/a/b"); dirPathParent1 = dirPath1.GetParent(); Assert.AreEqual(@"/a", dirPathParent1.FullPath); dirPathParent1 = dirPathParent1.GetParent(); Assert.AreEqual(@"/", dirPathParent1.FullPath); dirPathParent1 = dirPathParent1.GetParent(); Assert.AreEqual(UDirectory.Empty, dirPathParent1); // Test on file var filePath1 = new UFile(@"/a/b.txt"); dirPathParent1 = filePath1.GetParent(); Assert.AreEqual(@"/a", dirPathParent1.FullPath); }
/// <summary> /// Initializes a new instance of the <see cref="PackageLoadingAssetFile"/> class. /// </summary> /// <param name="filePath">The file path.</param> /// <param name="sourceFolder">The source folder.</param> public PackageLoadingAssetFile([NotNull] UFile filePath, UDirectory sourceFolder) { FilePath = filePath; OriginalFilePath = FilePath; SourceFolder = sourceFolder; }
public void TestMakeRelativeWithDrive() { UPath assetPath2 = null; UPath newAssetPath2 = null; var dir1 = new UDirectory("C:/a/b/c"); // Test direct relative assetPath2 = new UFile("C:/a/b/c/test.txt"); newAssetPath2 = assetPath2.MakeRelative(dir1); Assert.AreEqual("test.txt", newAssetPath2.FullPath); // Test direct relative + subdir assetPath2 = new UFile("C:/a/b/c/test/test.txt"); newAssetPath2 = assetPath2.MakeRelative(dir1); Assert.AreEqual("test/test.txt", newAssetPath2.FullPath); // Test relative 1 assetPath2 = new UFile("C:/a/b/test.txt"); newAssetPath2 = assetPath2.MakeRelative(dir1); Assert.AreEqual("../test.txt", newAssetPath2.FullPath); // Test relative 2 assetPath2 = new UFile("C:/a/test.txt"); newAssetPath2 = assetPath2.MakeRelative(dir1); Assert.AreEqual("../../test.txt", newAssetPath2.FullPath); // Test relative 3 assetPath2 = new UFile("C:/test.txt"); newAssetPath2 = assetPath2.MakeRelative(dir1); Assert.AreEqual("../../../test.txt", newAssetPath2.FullPath); // Test already relative assetPath2 = new UFile("../test.txt"); newAssetPath2 = assetPath2.MakeRelative(dir1); Assert.AreEqual("../test.txt", newAssetPath2.FullPath); // Test no path in common assetPath2 = new UFile("E:/e/f/g/test.txt"); newAssetPath2 = assetPath2.MakeRelative(dir1); Assert.AreEqual("E:/e/f/g/test.txt", newAssetPath2.FullPath); // Test no root path single file assetPath2 = new UFile("E:/test.txt"); newAssetPath2 = assetPath2.MakeRelative(dir1); Assert.AreEqual("E:/test.txt", newAssetPath2.FullPath); }
private static void GenerateUnitTestProject(string outputDirectory, string templateFile, string name, string projectNamespace) { var projectTemplate = ProjectTemplate.Load(templateFile); // Force reference to Xenko.Assets (to have acess to SolutionPlatform) projectTemplate.Assemblies.Add(typeof(GraphicsProfile).Assembly.FullName); projectTemplate.Assemblies.Add(typeof(XenkoConfig).Assembly.FullName); var options = new Dictionary <string, object>(); // When generating over an existing set of files, retrieve the existing IDs // for better incrementality Guid projectGuid, assetId; GetExistingGuid(outputDirectory, name + ".Windows.csproj", out projectGuid); GetExistingAssetId(outputDirectory, name + ".xkpkg", out assetId); var session = new PackageSession(); var result = new LoggerResult(); var templateGeneratorParameters = new SessionTemplateGeneratorParameters(); templateGeneratorParameters.OutputDirectory = outputDirectory; templateGeneratorParameters.Session = session; templateGeneratorParameters.Name = name; templateGeneratorParameters.Logger = result; templateGeneratorParameters.Description = new TemplateDescription(); templateGeneratorParameters.Id = assetId; if (!PackageUnitTestGenerator.Default.PrepareForRun(templateGeneratorParameters).Result) { Console.WriteLine(@"Error generating package: PackageUnitTestGenerator.PrepareForRun returned false"); return; } if (!PackageUnitTestGenerator.Default.Run(templateGeneratorParameters)) { Console.WriteLine(@"Error generating package: PackageUnitTestGenerator.Run returned false"); return; } if (result.HasErrors) { Console.WriteLine($"Error generating package: {result.ToText()}"); return; } var package = session.LocalPackages.Single(); var previousCurrent = session.CurrentPackage; session.CurrentPackage = package; // Compute Xenko Sdk relative path // We are supposed to be in standard output binary folder, so Xenko root should be at ..\.. var xenkoPath = UPath.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), new UDirectory(@"..\..")); var xenkoRelativePath = new UDirectory(xenkoPath) .MakeRelative(outputDirectory) .ToString() .Replace('/', '\\'); xenkoRelativePath = xenkoRelativePath.TrimEnd('\\'); options["Namespace"] = projectNamespace ?? name; options["Package"] = package; options["Platforms"] = new List <SolutionPlatform>(AssetRegistry.SupportedPlatforms); options["XenkoSdkRelativeDir"] = xenkoRelativePath; // Generate project template result = projectTemplate.Generate(outputDirectory, name, projectGuid, options); if (result.HasErrors) { Console.WriteLine("Error generating solution: {0}", result.ToText()); return; } var sharedProfile = package.Profiles.FindSharedProfile(); // Setup the assets folder Directory.CreateDirectory(UPath.Combine(outputDirectory, (UDirectory)"Assets/Shared")); // Add Windows test as Shared library var projectWindowsRef = new ProjectReference(projectGuid, UPath.Combine(outputDirectory, (UFile)(name + ".Windows.csproj")), Xenko.Core.Assets.ProjectType.Library); sharedProfile.ProjectReferences.Add(projectWindowsRef); // Generate executable projects for each platform foreach (var platform in AssetRegistry.SupportedPlatforms) { var platformProfile = new PackageProfile(platform.Name) { Platform = platform.Type }; platformProfile.AssetFolders.Add(new AssetFolder("Assets/" + platform.Name)); // Log progress var projectName = name + "." + platform.Type; // Create project reference var projectPlatformRef = new ProjectReference(projectGuid, UPath.Combine(outputDirectory, (UFile)(projectName + ".csproj")), Xenko.Core.Assets.ProjectType.Executable); platformProfile.ProjectReferences.Add(projectPlatformRef); package.Profiles.Add(platformProfile); } session.CurrentPackage = previousCurrent; session.Save(result); if (result.HasErrors) { Console.WriteLine("Error saving package: {0}", result.ToText()); return; } }
private static void GenerateUnitTestProject(string outputDirectory, string templateFile, string name, string projectNamespace) { var projectTemplate = ProjectTemplate.Load(templateFile); // Force reference to Stride.Assets (to have acess to SolutionPlatform) projectTemplate.Assemblies.Add(typeof(GraphicsProfile).Assembly.FullName); projectTemplate.Assemblies.Add(typeof(StrideConfig).Assembly.FullName); var options = new Dictionary <string, object>(); // When generating over an existing set of files, retrieve the existing IDs // for better incrementality Guid projectGuid, assetId; GetExistingGuid(outputDirectory, name + ".Windows.csproj", out projectGuid); GetExistingAssetId(outputDirectory, name + ".sdpkg", out assetId); var session = new PackageSession(); var result = new LoggerResult(); var templateGeneratorParameters = new SessionTemplateGeneratorParameters(); templateGeneratorParameters.OutputDirectory = outputDirectory; templateGeneratorParameters.Session = session; templateGeneratorParameters.Name = name; templateGeneratorParameters.Logger = result; templateGeneratorParameters.Description = new TemplateDescription(); templateGeneratorParameters.Id = assetId; templateGeneratorParameters.Namespace = projectNamespace; if (!PackageUnitTestGenerator.Default.PrepareForRun(templateGeneratorParameters).Result) { Console.WriteLine(@"Error generating package: PackageUnitTestGenerator.PrepareForRun returned false"); return; } if (!PackageUnitTestGenerator.Default.Run(templateGeneratorParameters)) { Console.WriteLine(@"Error generating package: PackageUnitTestGenerator.Run returned false"); return; } if (result.HasErrors) { Console.WriteLine($"Error generating package: {result.ToText()}"); return; } var project = session.Projects.OfType <SolutionProject>().Single(); var previousCurrent = session.CurrentProject; session.CurrentProject = project; // Compute Stride Sdk relative path // We are supposed to be in standard output binary folder, so Stride root should be at ..\.. var stridePath = UPath.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), new UDirectory(@"..\..")); var strideRelativePath = new UDirectory(stridePath) .MakeRelative(outputDirectory) .ToString() .Replace('/', '\\'); strideRelativePath = strideRelativePath.TrimEnd('\\'); options["Namespace"] = projectNamespace ?? name; options["Package"] = project.Package; options["Platforms"] = new List <SolutionPlatform>(AssetRegistry.SupportedPlatforms); options["StrideSdkRelativeDir"] = strideRelativePath; // Generate project template result = projectTemplate.Generate(outputDirectory, name, projectGuid, options); if (result.HasErrors) { Console.WriteLine("Error generating solution: {0}", result.ToText()); return; } // Setup the assets folder Directory.CreateDirectory(UPath.Combine(outputDirectory, (UDirectory)"Assets/Shared")); session.CurrentProject = previousCurrent; session.Save(result); if (result.HasErrors) { Console.WriteLine("Error saving package: {0}", result.ToText()); return; } }
public override void VisitCollectionItem(IEnumerable collection, CollectionDescriptor descriptor, int index, object item, ITypeDescriptor itemDescriptor) { base.VisitCollectionItem(collection, descriptor, index, item, itemDescriptor); var assetReference = item as AssetReference; var assetBase = item as AssetBase; var attachedReference = AttachedReferenceManager.GetAttachedReference(item); // We cannot set links if we do not have indexer accessor if (!descriptor.HasIndexerAccessors) { return; } if (assetReference != null) { AddLink(assetReference, (guid, location) => { var link = AssetReference.New(descriptor.ElementType, guid ?? assetReference.Id, location); descriptor.SetValue(collection, index, link); return(link); }); } else if (assetBase != null) { AddLink(assetBase, (guid, location) => { var link = new AssetBase(location, assetBase.Asset); descriptor.SetValue(collection, index, link); return(link); }); } else if (attachedReference != null) { AddLink(attachedReference, (guid, location) => { var link = guid.HasValue && guid.Value != Guid.Empty ? AttachedReferenceManager.CreateProxyObject(descriptor.ElementType, guid.Value, location) : null; if (link != null) { IdentifiableHelper.SetId(link, IdentifiableHelper.GetId(item)); } descriptor.SetValue(collection, index, link); return(link); }); } else if (item is UFile) { AddLink(item, (guid, location) => { var link = new UFile(location); descriptor.SetValue(collection, index, link); return(link); }); } else if (item is UDirectory) { AddLink(item, (guid, location) => { var link = new UDirectory(location); descriptor.SetValue(collection, index, link); return(link); }); } }
/// <summary> /// Launch <paramref name="exePath"/> on remote host using credentials stored in EditorSettings. /// Before launching all the files requires by <paramref name="exePath"/> are copied over to host /// using the location specified in EditorSettings.Location. If <paramref name="isCoreCLR"/> is set /// all the Stride native libraries are copied over to the current directory of the game on the remote /// host via the `CoreCLRSetup` script. /// </summary> /// <param name="logger">Logger to show progress and any issues that may occur.</param> /// <param name="exePath">Path on the local machine where the executable was compiled.</param> /// <param name="isCoreCLR">Is <paramref name="exePath"/> executed against .NET Core?</param> /// <returns>True when launch was successful, false otherwise.</returns> internal static bool Launch([NotNull] LoggerResult logger, [NotNull] UFile exePath, bool isCoreCLR) { if (logger == null) { throw new ArgumentNullException(nameof(logger)); } if (exePath == null) { throw new ArgumentNullException(nameof(exePath)); } var host = StrideEditorSettings.Host.GetValue(); var username = StrideEditorSettings.Username.GetValue(); var port = StrideEditorSettings.Port.GetValue(); var password = Decrypt(StrideEditorSettings.Password.GetValue()); var location = new UDirectory(StrideEditorSettings.Location.GetValue()); var display = StrideEditorSettings.Display.GetValue(); var connectInfo = NewConnectionInfo(host, port, username, password); if (SyncTo(connectInfo, exePath.GetFullDirectory(), UPath.Combine(location, new UDirectory(exePath.GetFileNameWithoutExtension())), logger)) { var sshClient = new SshClient(connectInfo); try { sshClient.Connect(); if (sshClient.IsConnected) { string cmdString; SshCommand cmd; // Due to lack of Dllmap config for CoreCLR, we have to ensure that our native libraries // are copied next to the executable. The CoreCLRSetup script will check the 32-bit vs 64-bit // of the `dotnet` runner and copy the .so files from the proper x86 or x64 directory. if (isCoreCLR) { cmdString = "bash -c 'source /etc/profile ; cd " + location + "/" + exePath.GetFileNameWithoutExtension() + ";" + "sh ./CoreCLRSetup.sh'"; cmd = sshClient.CreateCommand(cmdString); cmd.Execute(); var err = cmd.Error; if (!string.IsNullOrEmpty(err)) { logger.Error(err); // We don't exit here in case of failure, we just print the error and continue // Users can then try to fix the issue directly on the remote host. } else { err = cmd.Result; if (!string.IsNullOrEmpty(err)) { logger.Info(err); } } } // Try to get the main IP of the machine var ipv4 = GetAllLocalIPv4().FirstOrDefault(); var connectionRouter = string.Empty; if (!string.IsNullOrEmpty(ipv4)) { connectionRouter = " StrideConnectionRouterRemoteIP=" + ipv4; } var dotnetEngine = StrideEditorSettings.UseCoreCLR.GetValue() ? " dotnet " : " mono "; if (!string.IsNullOrEmpty(display)) { display = " DISPLAY=" + display; } else { display = " DISPLAY=:0.0"; } cmdString = "bash -c 'source /etc/profile ; cd " + location + "/" + exePath.GetFileNameWithoutExtension() + ";" + display + connectionRouter + dotnetEngine + "./" + exePath.GetFileName() + "'"; cmd = sshClient.CreateCommand(cmdString); cmd.BeginExecute((callback) => { var res = cmd.Error; if (!string.IsNullOrEmpty(res)) { logger.Error(res); } else { res = cmd.Result; if (!string.IsNullOrEmpty(res)) { logger.Info(res); } } // Dispose of our resources as soon as we are done. cmd.Dispose(); sshClient.Dispose(); }); return(true); } } catch (Exception) { var message = Tr._p("Message", "Unable to launch {0} on host {1}"); logger.Error(string.Format(message, exePath, host)); } } return(false); }
public override void VisitDictionaryKeyValue(object dictionaryObj, DictionaryDescriptor descriptor, object key, ITypeDescriptor keyDescriptor, object value, ITypeDescriptor valueDescriptor) { base.VisitDictionaryKeyValue(dictionaryObj, descriptor, key, keyDescriptor, value, valueDescriptor); var assetReference = value as AssetReference; var assetBase = value as AssetBase; var attachedReference = AttachedReferenceManager.GetAttachedReference(value); if (assetReference != null) { AddLink(assetReference, (guid, location) => { var newValue = AssetReference.New(descriptor.ValueType, guid ?? assetReference.Id, location); descriptor.SetValue(dictionaryObj, key, newValue); return(newValue); }); } else if (assetBase != null) { AddLink(assetBase, (guid, location) => { var newValue = new AssetBase(location, assetBase.Asset); descriptor.SetValue(dictionaryObj, key, newValue); return(newValue); }); } else if (attachedReference != null) { AddLink(attachedReference, (guid, location) => { object newValue = guid.HasValue && guid.Value != Guid.Empty ? AttachedReferenceManager.CreateProxyObject(descriptor.ValueType, guid.Value, location) : null; if (newValue != null) { IdentifiableHelper.SetId(newValue, IdentifiableHelper.GetId(value)); } descriptor.SetValue(dictionaryObj, key, newValue); return(newValue); }); } else if (value is UFile) { AddLink(value, (guid, location) => { var newValue = new UFile(location); descriptor.SetValue(dictionaryObj, key, newValue); return(newValue); }); } else if (value is UDirectory) { AddLink(value, (guid, location) => { var newValue = new UDirectory(location); descriptor.SetValue(dictionaryObj, key, newValue); return(newValue); }); } }
/// <summary> /// Copy any referenced asset packages to the project's folder /// </summary> private static void CopyAssetPacks(SessionTemplateGeneratorParameters parameters, Package package) { var logger = parameters.Logger; var presentationPackageFile = PackageStore.Instance.GetPackageFileName("Stride.Samples.Templates", new PackageVersionRange(new PackageVersion(Stride.Samples.Templates.ThisPackageVersion.Current))); var assetPackagesDir = UDirectory.Combine(presentationPackageFile.GetFullDirectory(), @"Templates\Samples\Templates\Packs"); var assetPacks = parameters.TryGetTag(AssetsKey); if (assetPacks == null) { return; } try { var outAssetDir = UPath.Combine(package.RootDirectory, (UDirectory)"Assets"); var outResourceDir = UPath.Combine(package.RootDirectory, (UDirectory)"Resources"); foreach (var uDirectory in assetPacks) { var packageDir = UDirectory.Combine(assetPackagesDir, uDirectory); var inputAssetDir = UDirectory.Combine(packageDir, "Assets"); foreach (var directory in FileUtility.EnumerateDirectories(inputAssetDir, SearchDirection.Down)) { foreach (var file in directory.GetFiles()) { var relativeFile = new UFile(file.FullName).MakeRelative(inputAssetDir); var outputFile = UPath.Combine(outAssetDir, relativeFile); var outputFileDirectory = outputFile.GetParent(); if (!Directory.Exists(outputFileDirectory)) { Directory.CreateDirectory(outputFileDirectory); } File.Copy(file.FullName, outputFile, true); } } var inputResourceDir = UDirectory.Combine(packageDir, "Resources"); foreach (var directory in FileUtility.EnumerateDirectories(inputResourceDir, SearchDirection.Down)) { foreach (var file in directory.GetFiles()) { var relativeFile = new UFile(file.FullName).MakeRelative(inputResourceDir); var outputFile = UPath.Combine(outResourceDir, relativeFile); { // Create the output directory if needed var outputFileDirectory = outputFile.GetParent(); if (!Directory.Exists(outputFileDirectory)) { Directory.CreateDirectory(outputFileDirectory); } } File.Copy(file.FullName, outputFile, true); } } } } catch (Exception ex) { logger.Error("Unexpected exception while copying asset packages", ex); } }
public override void VisitObjectMember(object container, ObjectDescriptor containerDescriptor, IMemberDescriptor member, object value) { base.VisitObjectMember(container, containerDescriptor, member, value); var assetReference = value as AssetReference; var assetBase = value as AssetBase; var attachedReference = AttachedReferenceManager.GetAttachedReference(value); if (assetReference != null) { AddLink(assetReference, (guid, location) => { var newValue = AssetReference.New(member.Type, guid ?? assetReference.Id, location); member.Set(container, newValue); return(newValue); }); } else if (assetBase != null) { AddLink(assetBase, (guid, location) => { var newValue = new AssetBase(location, assetBase.Asset); member.Set(container, newValue); return(newValue); }); } else if (attachedReference != null) { AddLink(attachedReference, (guid, location) => { object newValue = guid.HasValue && guid.Value != Guid.Empty ? AttachedReferenceManager.CreateProxyObject(member.Type, guid.Value, location) : null; if (newValue != null) { IdentifiableHelper.SetId(newValue, IdentifiableHelper.GetId(value)); } member.Set(container, newValue); return(newValue); }); } else if (value is UFile) { AddLink(value, (guid, location) => { var newValue = new UFile(location); member.Set(container, newValue); return(newValue); }); } else if (value is UDirectory) { AddLink(value, (guid, location) => { var newValue = new UDirectory(location); member.Set(container, newValue); return(newValue); }); } }
internal StrideDevVersionViewModel(LauncherViewModel launcher, NugetStore store, [CanBeNull] NugetLocalPackage localPackage, UDirectory path, bool isDevRedirect) : base(launcher, store, localPackage, localPackage.Id, int.MaxValue, devMinorCounter--) { this.path = path; this.localPackage = localPackage; this.isDevRedirect = isDevRedirect; DownloadCommand.IsEnabled = false; // Update initial status (IsVisible will be set to true) UpdateStatus(); }
/// <summary> /// Initializes a new instance of the <see cref="TemplateFolder"/> class. /// </summary> /// <param name="path">The path.</param> public TemplateFolder(UDirectory path) { Path = path; Files = new List <UFile>(); }
private static void GenerateUnitTestProject(string outputDirectory, string templateFile, string name) { var projectTemplate = ProjectTemplate.Load(templateFile); // Force reference to Paradox.Assets (to have acess to SolutionPlatform) projectTemplate.Assemblies.Add(typeof(GraphicsProfile).Assembly.FullName); projectTemplate.Assemblies.Add(typeof(ParadoxConfig).Assembly.FullName); var options = new Dictionary <string, object>(); var session = new PackageSession(); var result = new LoggerResult(); var templateGeneratorParameters = new TemplateGeneratorParameters(); templateGeneratorParameters.OutputDirectory = outputDirectory; templateGeneratorParameters.Session = session; templateGeneratorParameters.Name = name; templateGeneratorParameters.Logger = result; templateGeneratorParameters.Description = new TemplateDescription(); PackageUnitTestGenerator.Default.Generate(templateGeneratorParameters); if (result.HasErrors) { Console.WriteLine("Error generating package: {0}", result.ToText()); return; } var package = templateGeneratorParameters.Package; var previousCurrent = session.CurrentPackage; session.CurrentPackage = package; // Compute Paradox Sdk relative path // We are supposed to be in standard output binary folder, so Paradox root should be at ..\.. var paradoxPath = UDirectory.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), new UDirectory(@"..\..")); var paradoxRelativePath = new UDirectory(paradoxPath) .MakeRelative(outputDirectory) .ToString() .Replace('/', '\\'); paradoxRelativePath = paradoxRelativePath.TrimEnd('\\'); options["Namespace"] = name; options["Package"] = package; options["Platforms"] = new List <SolutionPlatform>(AssetRegistry.SupportedPlatforms); options["ParadoxSdkRelativeDir"] = paradoxRelativePath; // Generate project template var projectGuid = Guid.NewGuid(); result = projectTemplate.Generate(outputDirectory, name, projectGuid, options); if (result.HasErrors) { Console.WriteLine("Error generating solution: {0}", result.ToText()); return; } var sharedProfile = package.Profiles.FindSharedProfile(); // Setup the assets folder Directory.CreateDirectory(UPath.Combine(outputDirectory, (UDirectory)"Assets/Shared")); // Add Windows test as Shared library var projectWindowsRef = new ProjectReference(); projectWindowsRef.Id = projectGuid; projectWindowsRef.Location = UPath.Combine(outputDirectory, (UFile)(name + ".Windows.csproj")); projectWindowsRef.Type = SiliconStudio.Assets.ProjectType.Library; sharedProfile.ProjectReferences.Add(projectWindowsRef); // Generate executable projects for each platform foreach (var platform in AssetRegistry.SupportedPlatforms) { var platformProfile = new PackageProfile(platform.Name) { Platform = platform.Type }; platformProfile.AssetFolders.Add(new AssetFolder("Assets/" + platform.Name)); // Log progress var projectName = name + "." + platform.Type; // Create project reference var projectPlatformRef = new ProjectReference(); projectPlatformRef.Id = projectGuid; projectPlatformRef.Location = UPath.Combine(outputDirectory, (UFile)(projectName + ".csproj")); projectPlatformRef.Type = SiliconStudio.Assets.ProjectType.Executable; platformProfile.ProjectReferences.Add(projectPlatformRef); // Add build configuration per platform platform.Properties.CopyTo(platformProfile.Properties, true); package.Profiles.Add(platformProfile); } session.CurrentPackage = previousCurrent; result = session.Save(); if (result.HasErrors) { Console.WriteLine("Error saving package: {0}", result.ToText()); return; } }
public PackageLoadingAssetFile(UFile filePath, UDirectory sourceFolder, UFile projectFile) { FilePath = filePath; SourceFolder = sourceFolder; ProjectFile = projectFile; }
private static PackageSession GenerateSample(UDirectory outputPath, Guid templateGuid, string sampleName, LoggerResult logger) { // Make output path absolute if (!outputPath.IsAbsolute) { outputPath = UPath.Combine(Environment.CurrentDirectory, outputPath); } Console.WriteLine(@"Bootstrapping: " + sampleName); var session = new PackageSession(); var generator = TemplateSampleGenerator.Default; // Ensure progress is shown while it is happening. logger.MessageLogged += (sender, eventArgs) => Console.WriteLine(eventArgs.Message.Text); var parameters = new SessionTemplateGeneratorParameters { Session = session }; parameters.Unattended = true; TemplateSampleGenerator.SetParameters( parameters, AssetRegistry.SupportedPlatforms.Where(p => p.Type == Core.PlatformType.Windows).Select(x => new SelectedSolutionPlatform(x, x.Templates.FirstOrDefault())).ToList(), addGamesTesting: true); session.SolutionPath = UPath.Combine <UFile>(outputPath, sampleName + ".sln"); // Properly delete previous version if (Directory.Exists(outputPath)) { try { Directory.Delete(outputPath, true); } catch { logger.Warning($"Unable to delete directory [{outputPath}]."); } } // Load templates StrideDefaultAssetsPlugin.LoadDefaultTemplates(); var strideTemplates = TemplateManager.FindTemplates(session); parameters.Description = strideTemplates.First(x => x.Id == templateGuid); parameters.Name = sampleName; parameters.Namespace = sampleName; parameters.OutputDirectory = outputPath; parameters.Logger = logger; if (!generator.PrepareForRun(parameters).Result) { logger.Error("PrepareForRun returned false for the TemplateSampleGenerator"); } if (!generator.Run(parameters)) { logger.Error("Run returned false for the TemplateSampleGenerator"); } var updaterTemplate = strideTemplates.First(x => x.FullPath.ToString().EndsWith("UpdatePlatforms.sdtpl")); parameters.Description = updaterTemplate; if (logger.HasErrors) { throw new InvalidOperationException($"Error generating sample {sampleName} from template:\r\n{logger.ToText()}"); } return(session); }
/// <summary> /// Generate the build step corresponding to raw imports of the current package file. /// </summary> /// <param name="context">The compilation context</param> /// <param name="result">The compilation current result</param> private void GenerateRawImportBuildSteps(AssetCompilerContext context, AssetCompilerResult result) { if (context.Package.RootDirectory == null) { return; } foreach (var profile in context.Package.Profiles) { foreach (var sourceFolder in profile.AssetFolders) { var baseDirectory = Path.GetFullPath(context.Package.RootDirectory); // Use sub directory baseDirectory = Path.Combine(baseDirectory, sourceFolder.Path); if (!Directory.Exists(baseDirectory)) { continue; } var baseUDirectory = new UDirectory(baseDirectory); var hashSet = new HashSet <string>(); // Imports explicit foreach (var rawImport in sourceFolder.RawImports) { var sourceDirectory = baseUDirectory; if (!string.IsNullOrEmpty(rawImport.SourceDirectory)) { sourceDirectory = UPath.Combine(sourceDirectory, rawImport.SourceDirectory); } if (!Directory.Exists(sourceDirectory)) { result.Error("Unable to find raw import directory [{0}]", sourceDirectory); continue; } var files = Directory.EnumerateFiles(sourceDirectory, "*.*", SearchOption.AllDirectories).ToList(); var importRegexes = rawImport.Patterns.Select(x => new Regex(Selectors.PathSelector.TransformToRegex(x))).ToArray(); foreach (var file in files) { var pathToFileRelativeToProject = new UFile(file).MakeRelative(sourceDirectory); var outputPath = pathToFileRelativeToProject; if (!string.IsNullOrEmpty(rawImport.TargetLocation)) { outputPath = UPath.Combine(rawImport.TargetLocation, outputPath); } foreach (var importRegex in importRegexes) { if (importRegex.Match(pathToFileRelativeToProject).Success&& hashSet.Add(outputPath)) { result.BuildSteps.Add(new ImportStreamCommand { SourcePath = file, Location = outputPath, }); break; } } } } } } }
public void TestWithSimpleDirectory() { var assetPath = new UDirectory("/a/b/c"); Assert.AreEqual("/a/b/c", assetPath.GetDirectory()); Assert.AreEqual("/a/b/c", assetPath.FullPath); var directory = new UDirectory("/a"); Assert.AreEqual("/a", directory.GetDirectory()); }
/// <summary> /// Fills the builder with the list of files that are part of this new package. /// </summary> /// <param name="rootDirectory">The root location where files are located.</param> /// <param name="files">The files to include to the builder.</param> public void PopulateFiles(UDirectory rootDirectory, List <ManifestFile> files) { Builder.PopulateFiles(rootDirectory, ToManifsetFiles(files)); }
public void TestMakeRelative() { UPath assetPath2 = null; UPath newAssetPath2 = null; var dir1 = new UDirectory("/a/b/c"); var assetDir2 = new UDirectory("/a/b/c"); newAssetPath2 = dir1.MakeRelative(assetDir2); Assert.AreEqual(".", newAssetPath2.FullPath); var assetDir3 = new UDirectory("/a/b"); newAssetPath2 = dir1.MakeRelative(assetDir3); Assert.AreEqual("c", newAssetPath2.FullPath); var assetDir4 = new UDirectory("/a/b/c/d"); newAssetPath2 = dir1.MakeRelative(assetDir4); Assert.AreEqual("..", newAssetPath2.FullPath); // Test direct relative assetPath2 = new UFile("/a/b/c/test.txt"); newAssetPath2 = assetPath2.MakeRelative(dir1); Assert.AreEqual("test.txt", newAssetPath2.FullPath); // Test direct relative + subdir assetPath2 = new UFile("/a/b/c/test/test.txt"); newAssetPath2 = assetPath2.MakeRelative(dir1); Assert.AreEqual("test/test.txt", newAssetPath2.FullPath); // Test relative 1 assetPath2 = new UFile("/a/b/test.txt"); newAssetPath2 = assetPath2.MakeRelative(dir1); Assert.AreEqual("../test.txt", newAssetPath2.FullPath); // Test relative 2 assetPath2 = new UFile("/a/test.txt"); newAssetPath2 = assetPath2.MakeRelative(dir1); Assert.AreEqual("../../test.txt", newAssetPath2.FullPath); // Test relative 3 assetPath2 = new UFile("/test.txt"); newAssetPath2 = assetPath2.MakeRelative(dir1); Assert.AreEqual("../../../test.txt", newAssetPath2.FullPath); // Test already relative assetPath2 = new UFile("../test.txt"); newAssetPath2 = assetPath2.MakeRelative(dir1); Assert.AreEqual("../test.txt", newAssetPath2.FullPath); // Test only root path in common assetPath2 = new UFile("/e/f/g/test.txt"); newAssetPath2 = assetPath2.MakeRelative(dir1); Assert.AreEqual("../../../e/f/g/test.txt", newAssetPath2.FullPath); // Test only root path in common with single file assetPath2 = new UFile("/test.txt"); newAssetPath2 = assetPath2.MakeRelative(dir1); Assert.AreEqual("../../../test.txt", newAssetPath2.FullPath); }
public static void Build(Package package, string outputDirectory = null) { if (package == null) { throw new ArgumentNullException("package"); } var meta = new NuGet.ManifestMetadata(); package.Meta.ToNugetManifest(meta); var builder = new NuGet.PackageBuilder(); builder.Populate(meta); // TODO this is not working var files = new List <NuGet.ManifestFile>() { NewFile(@"Bin\**\*.exe", "Bin"), NewFile(@"Bin\**\*.vsix", "Bin"), NewFile(@"Bin\**\*.so", "Bin"), NewFile(@"Bin\**\*.a", "Bin"), NewFile(@"Bin\**\*.md", "Bin"), NewFile(@"Bin\**\*.html", "Bin"), NewFile(@"Bin\**\*.config", "Bin"), NewFile(@"Bin\**\*.dll", "Bin"), NewFile(@"Bin\**\*.xml", "Bin"), NewFile(@"Bin\**\*.usrdoc", "Bin"), NewFile(@"Bin\**\*.winmd", "Bin"), NewFile(@"Targets\*.targets", "Targets"), }; // Handle Assets var rootDir = package.RootDirectory; var newPackage = new Package { Meta = package.Meta }; foreach (var profile in package.Profiles) { var target = "Assets/" + profile.Name; foreach (var assetFolder in profile.AssetFolders) { // TODO: handle exclude in asset folders //files.Add(NewFile(source, target, @"**\*.cs;**\*.hlsl;**\*.csproj;**\*.csproj.user;**\obj\**")); files.Add(NewFile(assetFolder.Path.MakeRelative(rootDir) + "/**/*.pdxsl", target)); files.Add(NewFile(assetFolder.Path.MakeRelative(rootDir) + "/**/*.pdxfx", target)); } var targetProfile = new PackageProfile(profile.Name); targetProfile.AssetFolders.Add(new AssetFolder(target)); newPackage.Profiles.Add(targetProfile); } // Handle templates var targetFolder = new TemplateFolder("Templates"); foreach (var templateFolder in package.TemplateFolders) { var source = templateFolder.Path.MakeRelative(rootDir) + "/**"; UDirectory target = targetFolder.Path; if (templateFolder.Group != null) { target = UPath.Combine(target, templateFolder.Group); } var excludeFiles = templateFolder.Exclude; files.Add(NewFile(source, target, excludeFiles)); // Add template files foreach (var templateFile in templateFolder.Files) { var newTemplateFile = templateFile.MakeRelative(templateFolder.Path); if (templateFolder.Group != null) { newTemplateFile = UPath.Combine(templateFolder.Group, newTemplateFile); } newTemplateFile = UPath.Combine(targetFolder.Path, newTemplateFile); targetFolder.Files.Add(newTemplateFile); } } // Create temp package for archive newPackage.TemplateFolders.Add(targetFolder); var newPackageFileName = "temp" + Guid.NewGuid() + ".pdxpkg"; newPackage.FullPath = package.RootDirectory + "/" + newPackageFileName; var result = newPackage.Save(); if (result.HasErrors) { throw new InvalidOperationException(result.ToText()); // TODO throw error } files.Add(NewFile(newPackageFileName, package.Meta.Name + Package.PackageFileExtension)); // Add files builder.PopulateFiles(package.RootDirectory, files); outputDirectory = outputDirectory ?? Environment.CurrentDirectory; // Save the nupkg var outputPath = GetOutputPath(builder, outputDirectory); bool isExistingPackage = File.Exists(outputPath); if (isExistingPackage) { File.Delete(outputPath); } try { using (Stream stream = File.Create(outputPath)) { builder.Save(stream); } } catch { if (!isExistingPackage && File.Exists(outputPath)) { File.Delete(outputPath); } throw; } File.Delete(newPackage.FullPath); }
public void TestContains() { var dir1 = new UDirectory("C:/a/b/c"); Assert.IsTrue(dir1.Contains(new UFile("C:/a/b/c/d"))); Assert.IsTrue(dir1.Contains(new UFile("C:/a/b/c/d/e"))); Assert.IsTrue(dir1.Contains(new UDirectory("C:/a/b/c/d"))); Assert.IsTrue(dir1.Contains(new UDirectory("C:/a/b/c/d/e"))); Assert.IsFalse(dir1.Contains(new UFile("C:/a/b/x"))); Assert.IsFalse(dir1.Contains(new UFile("C:/a/b/cx"))); }
/// <summary> /// Initializes a new instance of the <see cref="PackageLoadingAssetFile"/> class. /// </summary> /// <param name="filePath">The file path.</param> /// <param name="sourceFolder">The source folder.</param> public PackageLoadingAssetFile(UFile filePath, UDirectory sourceFolder) { FilePath = filePath; SourceFolder = sourceFolder; }