示例#1
0
文件: Package.cs 项目: cg123/xenko
        /// <summary>
        /// Loads the assembly references that were not loaded before.
        /// </summary>
        /// <param name="log">The log.</param>
        /// <param name="loadParametersArg">The load parameters argument.</param>
        public void UpdateAssemblyReferences(ILogger log, PackageLoadParameters loadParametersArg = null)
        {
            if (State < PackageState.DependenciesReady)
                return;

            var loadParameters = loadParametersArg ?? PackageLoadParameters.Default();
            LoadAssemblyReferencesForPackage(log, loadParameters);
        }
示例#2
0
文件: Package.cs 项目: cg123/xenko
        private void LoadAssemblyReferencesForPackage(ILogger log, PackageLoadParameters loadParameters)
        {
            if (log == null) throw new ArgumentNullException(nameof(log));
            if (loadParameters == null) throw new ArgumentNullException(nameof(loadParameters));
            var assemblyContainer = loadParameters.AssemblyContainer ?? AssemblyContainer.Default;
            foreach (var profile in Profiles)
            {
                foreach (var projectReference in profile.ProjectReferences.Where(projectRef => projectRef.Type == ProjectType.Plugin || projectRef.Type == ProjectType.Library))
                {
                    // Check if already loaded
                    // TODO: More advanced cases: unload removed references, etc...
                    if (LoadedAssemblies.Any(x => x.ProjectReference == projectReference))
                        continue;

                    string assemblyPath = null;
                    var fullProjectLocation = UPath.Combine(RootDirectory, projectReference.Location);

                    try
                    {
                        var forwardingLogger = new ForwardingLoggerResult(log);
                        assemblyPath = VSProjectHelper.GetOrCompileProjectAssembly(fullProjectLocation, forwardingLogger, loadParameters.AutoCompileProjects, loadParameters.BuildConfiguration, extraProperties: loadParameters.ExtraCompileProperties, onlyErrors: true);
                        if (String.IsNullOrWhiteSpace(assemblyPath))
                        {
                            log.Error("Unable to locate assembly reference for project [{0}]", fullProjectLocation);
                            continue;
                        }

                        var loadedAssembly = new PackageLoadedAssembly(projectReference, assemblyPath);
                        LoadedAssemblies.Add(loadedAssembly);

                        if (!File.Exists(assemblyPath) || forwardingLogger.HasErrors)
                        {
                            log.Error("Unable to build assembly reference [{0}]", assemblyPath);
                            continue;
                        }

                        var assembly = assemblyContainer.LoadAssemblyFromPath(assemblyPath, log);
                        if (assembly == null)
                        {
                            log.Error("Unable to load assembly reference [{0}]", assemblyPath);
                        }

                        loadedAssembly.Assembly = assembly;

                        if (assembly != null)
                        {
                            // Register assembly in the registry
                            AssemblyRegistry.Register(assembly, AssemblyCommonCategories.Assets);
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Error("Unexpected error while loading project [{0}] or assembly reference [{1}]", ex, fullProjectLocation, assemblyPath);
                    }
                }
            }
        }
示例#3
0
        /// <summary>
        /// Make sure packages have their assets loaded.
        /// </summary>
        /// <param name="log">The log.</param>
        /// <param name="loadParametersArg">The load parameters argument.</param>
        public void LoadMissingAssets(ILogger log, PackageLoadParameters loadParametersArg = null)
        {
            var loadParameters = loadParametersArg ?? PackageLoadParameters.Default();

            var cancelToken = loadParameters.CancelToken;

            // Make a copy of Packages as it can be modified by PreLoadPackageDependencies
            var previousPackages = Packages.ToList();
            foreach (var package in previousPackages)
            {
                // Output the session only if there is no cancellation
                if (cancelToken.HasValue && cancelToken.Value.IsCancellationRequested)
                {
                    return;
                }

                TryLoadAssets(this, log, package, loadParameters);
            }
        }
示例#4
0
        private static Package PreLoadPackage(PackageSession session, ILogger log, string filePath, bool isSystemPackage, PackageCollection loadedPackages, PackageLoadParameters loadParameters)
        {
            if (session == null) throw new ArgumentNullException("session");
            if (log == null) throw new ArgumentNullException("log");
            if (filePath == null) throw new ArgumentNullException("filePath");
            if (loadedPackages == null) throw new ArgumentNullException("loadedPackages");
            if (loadParameters == null) throw new ArgumentNullException("loadParameters");

            try
            {
                var packageId = Package.GetPackageIdFromFile(filePath);

                // Check that the package was not already loaded, otherwise return the same instance
                if (session.Packages.ContainsById(packageId))
                {
                    return session.Packages.Find(packageId);
                }

                // Package is already loaded, use the instance 
                if (loadedPackages.ContainsById(packageId))
                {
                    return loadedPackages.Find(packageId);
                }

                // Load the package without loading any assets
                var package = Package.LoadRaw(log, filePath);
                package.IsSystem = isSystemPackage;

                // Convert UPath to absolute (Package only)
                // Removed for now because it is called again in PackageSession.LoadAssembliesAndAssets (and running it twice result in dirty package)
                // If we remove it from here (and call it only in the other method), templates are not loaded (Because they are loaded via the package store that do not use PreLoadPackage)
                //if (loadParameters.ConvertUPathToAbsolute)
                //{
                //    var analysis = new PackageAnalysis(package, new PackageAnalysisParameters()
                //    {
                //        ConvertUPathTo = UPathType.Absolute,
                //        SetDirtyFlagOnAssetWhenFixingAbsoluteUFile = true,
                //        IsProcessingUPaths = true,
                //    });
                //    analysis.Run(log);
                //}
                // If the package doesn't have a meta name, fix it here (This is supposed to be done in the above disabled analysis - but we still need to do it!)
                if (string.IsNullOrWhiteSpace(package.Meta.Name) && package.FullPath != null)
                {
                    package.Meta.Name = package.FullPath.GetFileName();
                    package.IsDirty = true;
                }

                // Add the package has loaded before loading dependencies
                loadedPackages.Add(package);

                // Package has been loaded, register it in constraints so that we force each subsequent loads to use this one (or fails if version doesn't match)
                session.constraintProvider.AddConstraint(package.Meta.Name, new VersionSpec(package.Meta.Version.ToSemanticVersion()));

                // Load package dependencies
                // This will perform necessary asset upgrades
                // TODO: We should probably split package loading in two recursive top-level passes (right now those two passes are mixed, making it more difficult to make proper checks)
                //   - First, load raw packages with their dependencies recursively, then resolve dependencies and constraints (and print errors/warnings)
                //   - Then, if everything is OK, load the actual references and assets for each packages
                PreLoadPackageDependencies(session, log, package, loadedPackages, loadParameters);

                // Add the package to the session but don't freeze it yet
                session.Packages.Add(package);

                return package;
            }
            catch (Exception ex)
            {
                log.Error("Error while pre-loading package [{0}]", ex, filePath);
            }

            return null;
        }
示例#5
0
        /// <summary>
        /// Loads only the package description but not assets or plugins.
        /// </summary>
        /// <param name="log">The log to receive error messages.</param>
        /// <param name="filePath">The file path.</param>
        /// <param name="loadParametersArg">The load parameters argument.</param>
        /// <returns>A package.</returns>
        /// <exception cref="System.ArgumentNullException">log
        /// or
        /// filePath</exception>
        public static Package Load(ILogger log, string filePath, PackageLoadParameters loadParametersArg = null)
        {
            if (log == null) throw new ArgumentNullException("log");
            if (filePath == null) throw new ArgumentNullException("filePath");

            filePath = FileUtility.GetAbsolutePath(filePath);

            if (!File.Exists(filePath))
            {
                log.Error("Package file [{0}] was not found", filePath);
                return null;
            }

            var loadParameters = loadParametersArg ?? PackageLoadParameters.Default();

            try
            {
                var package = AssetSerializer.Load<Package>(filePath);
                package.FullPath = filePath;
                package.IsDirty = false;

                // Load assembly references
                if (loadParameters.LoadAssemblyReferences)
                {
                    package.LoadAssemblyReferencesForPackage(log, loadParameters);
                }

                // Load assets
                if (loadParameters.AutoLoadTemporaryAssets)
                {
                    package.LoadTemporaryAssets(log, loadParameters.CancelToken);
                }

                // Convert UPath to absolute
                if (loadParameters.ConvertUPathToAbsolute)
                {
                    var analysis = new PackageAnalysis(package, new PackageAnalysisParameters()
                        {
                            ConvertUPathTo = UPathType.Absolute,
                            IsProcessingUPaths = true, // This is done already by Package.Load
                            SetDirtyFlagOnAssetWhenFixingAbsoluteUFile = true // When loading tag attributes that have an absolute file
                        });
                    analysis.Run(log);
                }

                // Load templates
                package.LoadTemplates(log);

                return package;
            }
            catch (Exception ex)
            {
                log.Error("Error while pre-loading package [{0}]", ex, filePath);
            }

            return null;
        }
示例#6
0
        /// <summary>
        /// Loads only the package description but not assets or plugins.
        /// </summary>
        /// <param name="log">The log to receive error messages.</param>
        /// <param name="filePath">The file path.</param>
        /// <param name="loadParametersArg">The load parameters argument.</param>
        /// <returns>A package.</returns>
        /// <exception cref="System.ArgumentNullException">log
        /// or
        /// filePath</exception>
        public static Package Load(ILogger log, string filePath, PackageLoadParameters loadParametersArg = null)
        {
            if (log == null)
            {
                throw new ArgumentNullException("log");
            }
            if (filePath == null)
            {
                throw new ArgumentNullException("filePath");
            }

            filePath = FileUtility.GetAbsolutePath(filePath);

            if (!File.Exists(filePath))
            {
                log.Error("Package file [{0}] was not found", filePath);
                return(null);
            }

            var loadParameters = loadParametersArg ?? PackageLoadParameters.Default();

            try
            {
                var package = AssetSerializer.Load <Package>(filePath);
                package.FullPath = filePath;
                package.IsDirty  = false;

                // Load assembly references
                if (loadParameters.LoadAssemblyReferences)
                {
                    package.LoadAssemblyReferencesForPackage(log, loadParameters);
                }

                // Load assets
                if (loadParameters.AutoLoadTemporaryAssets)
                {
                    package.LoadTemporaryAssets(log, loadParameters.CancelToken);
                }

                // Convert UPath to absolute
                if (loadParameters.ConvertUPathToAbsolute)
                {
                    var analysis = new PackageAnalysis(package, new PackageAnalysisParameters()
                    {
                        ConvertUPathTo     = UPathType.Absolute,
                        IsProcessingUPaths = true,                        // This is done already by Package.Load
                        SetDirtyFlagOnAssetWhenFixingAbsoluteUFile = true // When loading tag attributes that have an absolute file
                    });
                    analysis.Run(log);
                }

                // Load templates
                package.LoadTemplates(log);

                return(package);
            }
            catch (Exception ex)
            {
                log.Error("Error while pre-loading package [{0}]", ex, filePath);
            }

            return(null);
        }
示例#7
0
        /// <summary>
        /// Adds an existing package to the current session.
        /// </summary>
        /// <param name="packagePath">The package path.</param>
        /// <param name="logger">The session result.</param>
        /// <param name="loadParametersArg">The load parameters argument.</param>
        /// <exception cref="System.ArgumentNullException">packagePath</exception>
        /// <exception cref="System.ArgumentException">Invalid relative path. Expecting an absolute package path;packagePath</exception>
        /// <exception cref="System.IO.FileNotFoundException">Unable to find package</exception>
        public Package AddExistingPackage(UFile packagePath, ILogger logger, PackageLoadParameters loadParametersArg = null)
        {
            if (packagePath == null) throw new ArgumentNullException("packagePath");
            if (logger == null) throw new ArgumentNullException("logger");
            if (!packagePath.IsAbsolute) throw new ArgumentException("Invalid relative path. Expecting an absolute package path", "packagePath");
            if (!File.Exists(packagePath)) throw new FileNotFoundException("Unable to find package", packagePath);

            var loadParameters = loadParametersArg ?? PackageLoadParameters.Default();

            Package package;
            try
            {
                // Enable reference analysis caching during loading
                AssetReferenceAnalysis.EnableCaching = true;

                var packagesLoaded = new PackageCollection();

                package = PreLoadPackage(this, logger, packagePath, false, packagesLoaded, loadParameters);

                // Load all missing references/dependencies
                LoadMissingReferences(logger, loadParameters);

                // Load assets
                TryLoadAssets(this, logger, package, loadParameters);

                // Run analysis after
                foreach (var packageToAdd in packagesLoaded)
                {
                    var analysis = new PackageAnalysis(packageToAdd, GetPackageAnalysisParametersForLoad());
                    analysis.Run(logger);
                }
            }
            finally
            {
                // Disable reference analysis caching after loading
                AssetReferenceAnalysis.EnableCaching = false;
            }
            return package;
        }
示例#8
0
文件: Package.cs 项目: cg123/xenko
        /// <summary>
        /// Load only assembly references
        /// </summary>
        /// <param name="package">The package.</param>
        /// <param name="log">The log.</param>
        /// <param name="loadParametersArg">The load parameters argument.</param>
        /// <returns></returns>
        internal bool LoadAssemblies(ILogger log, PackageLoadParameters loadParametersArg)
        {
            var loadParameters = loadParametersArg ?? PackageLoadParameters.Default();

            try
            {
                // Load assembly references
                if (loadParameters.LoadAssemblyReferences)
                {
                    LoadAssemblyReferencesForPackage(log, loadParameters);
                }
                return true;
            }
            catch (Exception ex)
            {
                log.Error("Error while pre-loading package [{0}]", ex, FullPath);

                return false;
            }
        }
示例#9
0
        private static void PreLoadPackageDependencies(PackageSession session, ILogger log, Package package, PackageCollection loadedPackages, PackageLoadParameters loadParameters)
        {
            if (session == null) throw new ArgumentNullException("session");
            if (log == null) throw new ArgumentNullException("log");
            if (package == null) throw new ArgumentNullException("package");
            if (loadParameters == null) throw new ArgumentNullException("loadParameters");

            bool packageDependencyErrors = false;

            // TODO: Remove and recheck Dependencies Ready if some secondary packages are removed?
            if (package.State >= PackageState.DependenciesReady)
                return;

            // 1. Load store package
            foreach (var packageDependency in package.Meta.Dependencies)
            {
                var loadedPackage = session.Packages.Find(packageDependency);
                if (loadedPackage == null)
                {
                    var file = PackageStore.Instance.GetPackageFileName(packageDependency.Name, packageDependency.Version, session.constraintProvider);

                    if (file == null)
                    {
                        // TODO: We need to support automatic download of packages. This is not supported yet when only Xenko
                        // package is supposed to be installed, but It will be required for full store
                        log.Error("Unable to find package {0} not installed", packageDependency);
                        packageDependencyErrors = true;
                        continue;
                    }

                    // Recursive load of the system package
                    loadedPackage = PreLoadPackage(session, log, file, true, loadedPackages, loadParameters);
                }

                if (loadedPackage == null || loadedPackage.State < PackageState.DependenciesReady)
                    packageDependencyErrors = true;
            }

            // 2. Load local packages
            foreach (var packageReference in package.LocalDependencies)
            {
                // Check that the package was not already loaded, otherwise return the same instance
                if (session.Packages.ContainsById(packageReference.Id))
                {
                    continue;
                }

                // Expand the string of the location
                var newLocation = (UFile)AssetRegistry.ExpandString(session, packageReference.Location);

                var subPackageFilePath = package.RootDirectory != null ? UPath.Combine(package.RootDirectory, newLocation) : newLocation;

                // Recursive load
                var loadedPackage = PreLoadPackage(session, log, subPackageFilePath.FullPath, false, loadedPackages, loadParameters);

                if (loadedPackage == null || loadedPackage.State < PackageState.DependenciesReady)
                    packageDependencyErrors = true;
            }

            // 3. Update package state
            if (!packageDependencyErrors)
            {
                package.State = PackageState.DependenciesReady;
            }
        }
示例#10
0
 /// <summary>
 /// Adds an existing package to the current session.
 /// </summary>
 /// <param name="packagePath">The package path.</param>
 /// <param name="loadParameters">The load parameters.</param>
 /// <exception cref="System.ArgumentNullException">packagePath</exception>
 /// <exception cref="System.IO.FileNotFoundException">Unable to find package</exception>
 public LoggerResult AddExistingPackage(UFile packagePath, PackageLoadParameters loadParameters = null)
 {
     var loggerResult = new LoggerResult();
     AddExistingPackage(packagePath, loggerResult, loadParameters);
     return loggerResult;
 }
示例#11
0
        private static bool TryLoadAssets(PackageSession session, ILogger log, Package package, PackageLoadParameters loadParameters)
        {
            // Already loaded
            if (package.State >= PackageState.AssetsReady)
                return true;

            // Dependencies could not properly be loaded
            if (package.State < PackageState.DependenciesReady)
                return false;

            // A package upgrade has previously been tried and denied, so let's keep the package in this state
            if (package.State == PackageState.UpgradeFailed)
                return false;

            try
            {
                // First, check that dependencies have their assets loaded
                bool dependencyError = false;
                foreach (var dependency in package.FindDependencies(false, false))
                {
                    if (!TryLoadAssets(session, log, dependency, loadParameters))
                        dependencyError = true;
                }

                if (dependencyError)
                    return false;

                var pendingPackageUpgrades = new List<PendingPackageUpgrade>();

                // Note: Default state is upgrade failed (for early exit on error/exceptions)
                // We will update to success as soon as loading is finished.
                package.State = PackageState.UpgradeFailed;

                // Process store dependencies for upgraders
                foreach (var packageDependency in package.Meta.Dependencies)
                {
                    var dependencyPackage = session.Packages.Find(packageDependency);
                    if (dependencyPackage == null)
                    {
                        continue;
                    }

                    // Check for upgraders
                    var packageUpgrader = session.CheckPackageUpgrade(log, package, packageDependency, dependencyPackage);
                    if (packageUpgrader != null)
                    {
                        pendingPackageUpgrades.Add(new PendingPackageUpgrade(packageUpgrader, packageDependency, dependencyPackage));
                    }
                }

                // Prepare asset loading
                var newLoadParameters = loadParameters.Clone();
                newLoadParameters.AssemblyContainer = session.assemblyContainer;

                // Default package version override
                newLoadParameters.ExtraCompileProperties = new Dictionary<string, string>();
                var defaultPackageOverride = NugetStore.GetPackageVersionVariable(PackageStore.Instance.DefaultPackageName) + "Override";
                var defaultPackageVersion = PackageStore.Instance.DefaultPackageVersion.Version;
                newLoadParameters.ExtraCompileProperties.Add(defaultPackageOverride, new Version(defaultPackageVersion.Major, defaultPackageVersion.Minor).ToString());
                if (loadParameters.ExtraCompileProperties != null)
                {
                    foreach (var property in loadParameters.ExtraCompileProperties)
                    {
                        newLoadParameters.ExtraCompileProperties[property.Key] = property.Value;
                    }
                }

                if (pendingPackageUpgrades.Count > 0)
                {
                    var upgradeAllowed = true;
                    // Need upgrades, let's ask user confirmation
                    if (loadParameters.PackageUpgradeRequested != null)
                    {
                        upgradeAllowed = loadParameters.PackageUpgradeRequested(package, pendingPackageUpgrades);
                    }

                    if (!upgradeAllowed)
                    {
                        log.Error("Necessary package migration for [{0}] has not been allowed", package.Meta.Name);
                        return false;
                    }

                    // Perform pre assembly load upgrade
                    foreach (var pendingPackageUpgrade in pendingPackageUpgrades)
                    {
                        var packageUpgrader = pendingPackageUpgrade.PackageUpgrader;
                        var dependencyPackage = pendingPackageUpgrade.DependencyPackage;
                        if (!packageUpgrader.UpgradeBeforeAssembliesLoaded(session, log, package, pendingPackageUpgrade.Dependency, dependencyPackage))
                        {
                            log.Error("Error while upgrading package [{0}] for [{1}] from version [{2}] to [{3}]", package.Meta.Name, dependencyPackage.Meta.Name, pendingPackageUpgrade.Dependency.Version, dependencyPackage.Meta.Version);
                            return false;
                        }
                    }
                }

                // Load assemblies. Set the package filename to the path on disk, in case of renaming.
                // TODO: Could referenced projects be associated to other packages than this one?
                newLoadParameters.ExtraCompileProperties.Add("SiliconStudioCurrentPackagePath", package.FullPath);
                package.LoadAssemblies(log, newLoadParameters);

                // Load list of assets
                newLoadParameters.AssetFiles = Package.ListAssetFiles(log, package, loadParameters.CancelToken);

                if (pendingPackageUpgrades.Count > 0)
                {
                    // Perform upgrades
                    foreach (var pendingPackageUpgrade in pendingPackageUpgrades)
                    {
                        var packageUpgrader = pendingPackageUpgrade.PackageUpgrader;
                        var dependencyPackage = pendingPackageUpgrade.DependencyPackage;
                        if (!packageUpgrader.Upgrade(session, log, package, pendingPackageUpgrade.Dependency, dependencyPackage, newLoadParameters.AssetFiles))
                        {
                            log.Error("Error while upgrading package [{0}] for [{1}] from version [{2}] to [{3}]", package.Meta.Name, dependencyPackage.Meta.Name, pendingPackageUpgrade.Dependency.Version, dependencyPackage.Meta.Version);
                            return false;
                        }

                        // Update dependency to reflect new requirement
                        pendingPackageUpgrade.Dependency.Version = pendingPackageUpgrade.PackageUpgrader.Attribute.PackageUpdatedVersionRange;
                    }

                    // Mark package as dirty
                    package.IsDirty = true;
                }

                // Load assets
                package.LoadAssets(log, newLoadParameters);

                // Validate assets from package
                package.ValidateAssets(newLoadParameters.GenerateNewAssetIds);

                if (pendingPackageUpgrades.Count > 0)
                {
                    // Perform post asset load upgrade
                    foreach (var pendingPackageUpgrade in pendingPackageUpgrades)
                    {
                        var packageUpgrader = pendingPackageUpgrade.PackageUpgrader;
                        var dependencyPackage = pendingPackageUpgrade.DependencyPackage;
                        if (!packageUpgrader.UpgradeAfterAssetsLoaded(session, log, package, pendingPackageUpgrade.Dependency, dependencyPackage, pendingPackageUpgrade.DependencyVersionBeforeUpgrade))
                        {
                            log.Error("Error while upgrading package [{0}] for [{1}] from version [{2}] to [{3}]", package.Meta.Name, dependencyPackage.Meta.Name, pendingPackageUpgrade.Dependency.Version, dependencyPackage.Meta.Version);
                            return false;
                        }
                    }

                    // Mark package as dirty
                    package.IsDirty = true;
                }

                // Mark package as ready
                package.State = PackageState.AssetsReady;

                // Freeze the package after loading the assets
                session.FreezePackage(package);

                return true;
            }
            catch (Exception ex)
            {
                log.Error("Error while loading package [{0}]", ex, package);
                return false;
            }
        }
示例#12
0
 /// <summary>
 /// Second part of the package loading process, when references, assets and package analysis is done.
 /// </summary>
 /// <param name="package">The package.</param>
 /// <param name="log">The log.</param>
 /// <param name="loadParametersArg">The load parameters argument.</param>
 /// <returns></returns>
 internal bool LoadAssembliesAndAssets(ILogger log, PackageLoadParameters loadParametersArg)
 {
     return(LoadAssemblies(log, loadParametersArg) && LoadAssets(log, loadParametersArg));
 }
示例#13
0
        private void LoadAssemblyReferencesForPackage(ILogger log, PackageLoadParameters loadParameters)
        {
            if (log == null)
            {
                throw new ArgumentNullException("log");
            }
            if (loadParameters == null)
            {
                throw new ArgumentNullException("loadParameters");
            }
            var assemblyContainer = loadParameters.AssemblyContainer ?? AssemblyContainer.Default;

            foreach (var profile in Profiles)
            {
                foreach (var projectReference in profile.ProjectReferences.Where(projectRef => projectRef.Type == ProjectType.Plugin || projectRef.Type == ProjectType.Library))
                {
                    // Check if already loaded
                    // TODO: More advanced cases: unload removed references, etc...
                    if (loadedAssemblies.Any(x => x.ProjectReference == projectReference))
                    {
                        continue;
                    }

                    string assemblyPath        = null;
                    var    fullProjectLocation = UPath.Combine(RootDirectory, projectReference.Location);

                    try
                    {
                        var forwardingLogger = new ForwardingLoggerResult(log);
                        assemblyPath = VSProjectHelper.GetOrCompileProjectAssembly(fullProjectLocation, forwardingLogger, loadParameters.AutoCompileProjects, loadParameters.BuildConfiguration, extraProperties: loadParameters.ExtraCompileProperties, onlyErrors: true);
                        if (String.IsNullOrWhiteSpace(assemblyPath))
                        {
                            log.Error("Unable to locate assembly reference for project [{0}]", fullProjectLocation);
                            continue;
                        }

                        var loadedAssembly = new PackageLoadedAssembly(projectReference, assemblyPath);
                        loadedAssemblies.Add(loadedAssembly);

                        if (!File.Exists(assemblyPath) || forwardingLogger.HasErrors)
                        {
                            log.Error("Unable to build assembly reference [{0}]", assemblyPath);
                            continue;
                        }

                        var assembly = assemblyContainer.LoadAssemblyFromPath(assemblyPath, log);
                        if (assembly == null)
                        {
                            log.Error("Unable to load assembly reference [{0}]", assemblyPath);
                        }

                        loadedAssembly.Assembly = assembly;

                        if (assembly != null)
                        {
                            // Register assembly in the registry
                            AssemblyRegistry.Register(assembly, AssemblyCommonCategories.Assets);
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Error("Unexpected error while loading project [{0}] or assembly reference [{1}]", ex, fullProjectLocation, assemblyPath);
                    }
                }
            }
        }
示例#14
0
文件: Package.cs 项目: cg123/xenko
        /// <summary>
        /// Loads only the package description but not assets or plugins.
        /// </summary>
        /// <param name="log">The log to receive error messages.</param>
        /// <param name="filePath">The file path.</param>
        /// <param name="loadParametersArg">The load parameters argument.</param>
        /// <returns>A package.</returns>
        /// <exception cref="System.ArgumentNullException">log
        /// or
        /// filePath</exception>
        public static Package Load(ILogger log, string filePath, PackageLoadParameters loadParametersArg = null)
        {
            var package = LoadRaw(log, filePath);
            if (package != null)
            {
                if (!package.LoadAssembliesAndAssets(log, loadParametersArg))
                    package = null;
            }

            return package;
        }
示例#15
0
        /// <summary>
        /// Loads a package from specified file path.
        /// </summary>
        /// <param name="filePath">The file path to a package file.</param>
        /// <param name="sessionResult">The session result.</param>
        /// <param name="loadParameters">The load parameters.</param>
        /// <returns>A package.</returns>
        /// <exception cref="System.ArgumentNullException">filePath</exception>
        /// <exception cref="System.ArgumentException">File [{0}] must exist.ToFormat(filePath);filePath</exception>
        public static void Load(string filePath, PackageSessionResult sessionResult, PackageLoadParameters loadParameters = null)
        {
            if (filePath == null) throw new ArgumentNullException("filePath");
            if (sessionResult == null) throw new ArgumentNullException("sessionResult");

            // Make sure with have valid parameters
            loadParameters = loadParameters ?? PackageLoadParameters.Default();

            // Make sure to use a full path.
            filePath = FileUtility.GetAbsolutePath(filePath);

            if (!File.Exists(filePath)) throw new ArgumentException("File [{0}] must exist".ToFormat(filePath), "filePath");

            try
            {
                // Enable reference analysis caching during loading
                AssetReferenceAnalysis.EnableCaching = true;

                using (var profile = Profiler.Begin(PackageSessionProfilingKeys.Loading))
                {
                    sessionResult.Clear();
                    sessionResult.Progress("Loading..", 0, 1);

                    var session = new PackageSession();

                    var packagePaths = new List<string>();

                    // If we have a solution, load all packages
                    if (PackageSessionHelper.IsSolutionFile(filePath))
                    {
                        PackageSessionHelper.LoadSolution(session, filePath, packagePaths, sessionResult);
                    }
                    else if (PackageSessionHelper.IsPackageFile(filePath))
                    {
                        packagePaths.Add(filePath);
                    }
                    else
                    {
                        sessionResult.Error("Unsupported file extension (only .sln or {0} are supported)", Package.PackageFileExtension);
                        return;
                    }

                    var cancelToken = loadParameters.CancelToken;

                    // Load all packages
                    var packagesLoaded = new PackageCollection();
                    foreach (var packageFilePath in packagePaths)
                    {
                        PreLoadPackage(session, sessionResult, packageFilePath, false, packagesLoaded, loadParameters);

                        // Output the session only if there is no cancellation
                        if (cancelToken.HasValue && cancelToken.Value.IsCancellationRequested)
                        {
                            return;
                        }
                    }

                    // Load all missing references/dependencies
                    session.LoadMissingReferences(sessionResult, loadParameters);

                    // Fix relative references
                    var analysis = new PackageSessionAnalysis(session, GetPackageAnalysisParametersForLoad());
                    var analysisResults = analysis.Run();
                    analysisResults.CopyTo(sessionResult);

                    // Run custom package session analysis
                    foreach (var type in AssetRegistry.GetPackageSessionAnalysisTypes())
                    {
                        var pkgAnalysis = (PackageSessionAnalysisBase)Activator.CreateInstance(type);
                        pkgAnalysis.Session = session;
                        var results = pkgAnalysis.Run();
                        results.CopyTo(sessionResult);
                    }

                    // Output the session only if there is no cancellation
                    if (!cancelToken.HasValue || !cancelToken.Value.IsCancellationRequested)
                    {
                        sessionResult.Session = session;

                        // Defer the initialization of the dependency manager
                        //session.DependencyManager.InitializeDeferred();
                    }

                    // Setup the current package when loading it
                    if (packagePaths.Count == 1)
                    {
                        var currentPackagePath = new UFile(packagePaths[0]);
                        foreach (var package in packagesLoaded)
                        {
                            if (package.FullPath == currentPackagePath)
                            {
                                session.CurrentPackage = package;
                                break;
                            }
                        }
                    }

                    // The session is not dirty when loading it
                    session.IsDirty = false;
                }
            }
            finally
            {
                // Disable reference analysis caching after loading
                AssetReferenceAnalysis.EnableCaching = false;
            }
        }
示例#16
0
文件: Package.cs 项目: cg123/xenko
 /// <summary>
 /// Second part of the package loading process, when references, assets and package analysis is done.
 /// </summary>
 /// <param name="package">The package.</param>
 /// <param name="log">The log.</param>
 /// <param name="loadParametersArg">The load parameters argument.</param>
 /// <returns></returns>
 internal bool LoadAssembliesAndAssets(ILogger log, PackageLoadParameters loadParametersArg)
 {
     return LoadAssemblies(log, loadParametersArg) && LoadAssets(log, loadParametersArg);
 }
示例#17
0
 /// <summary>
 /// Loads a package from specified file path.
 /// </summary>
 /// <param name="filePath">The file path to a package file.</param>
 /// <param name="loadParameters">The load parameters.</param>
 /// <returns>A package.</returns>
 /// <exception cref="System.ArgumentNullException">filePath</exception>
 public static PackageSessionResult Load(string filePath, PackageLoadParameters loadParameters = null)
 {
     var result = new PackageSessionResult();
     Load(filePath, result, loadParameters);
     return result;
 }
示例#18
0
文件: Package.cs 项目: cg123/xenko
        /// <summary>
        /// Load assets and perform package analysis.
        /// </summary>
        /// <param name="package">The package.</param>
        /// <param name="log">The log.</param>
        /// <param name="loadParametersArg">The load parameters argument.</param>
        /// <returns></returns>
        internal bool LoadAssets(ILogger log, PackageLoadParameters loadParametersArg)
        {
            var loadParameters = loadParametersArg ?? PackageLoadParameters.Default();

            try
            {
                // Load assets
                if (loadParameters.AutoLoadTemporaryAssets)
                {
                    LoadTemporaryAssets(log, loadParameters.AssetFiles, loadParameters.CancelToken, loadParameters.AssetFilter);
                }

                // Convert UPath to absolute
                if (loadParameters.ConvertUPathToAbsolute)
                {
                    var analysis = new PackageAnalysis(this, new PackageAnalysisParameters()
                    {
                        ConvertUPathTo = UPathType.Absolute,
                        IsProcessingUPaths = true, // This is done already by Package.Load
                        SetDirtyFlagOnAssetWhenFixingAbsoluteUFile = true // When loading tag attributes that have an absolute file
                    });
                    analysis.Run(log);
                }

                // Load templates
                LoadTemplates(log);

                return true;
            }
            catch (Exception ex)
            {
                log.Error("Error while pre-loading package [{0}]", ex, FullPath);

                return false;
            }
        }
示例#19
0
 /// <summary>
 /// Make sure packages have their dependencies and assets loaded.
 /// </summary>
 /// <param name="log">The log.</param>
 /// <param name="loadParameters">The load parameters.</param>
 public void LoadMissingReferences(ILogger log, PackageLoadParameters loadParameters = null)
 {
     LoadMissingDependencies(log, loadParameters);
     LoadMissingAssets(log, loadParameters);
 }
示例#20
0
        private void LoadAssemblyReferencesForPackage(ILogger log, PackageLoadParameters loadParameters)
        {
            if (log == null) throw new ArgumentNullException("log");
            if (loadParameters == null) throw new ArgumentNullException("loadParameters");
            var assemblyContainer = loadParameters.AssemblyContainer ?? AssemblyContainer.Default;
            foreach (var profile in Profiles)
            {
                foreach (var projectReference in profile.ProjectReferences.Where(projectRef => projectRef.Type == ProjectType.Plugin || projectRef.Type == ProjectType.Library))
                {
                    string assemblyPath = null;
                    var fullProjectLocation = UPath.Combine(RootDirectory, projectReference.Location);
                    try
                    {
                        assemblyPath = VSProjectHelper.GetOrCompileProjectAssembly(fullProjectLocation, log, loadParameters.AutoCompileProjects, extraProperties: loadParameters.ExtraCompileProperties, onlyErrors: true);

                        if (String.IsNullOrWhiteSpace(assemblyPath))
                        {
                            log.Error("Unable to locate assembly reference for project [{0}]", fullProjectLocation);
                            continue;
                        }

                        if (!File.Exists(assemblyPath))
                        {
                            log.Error("Unable to build assembly reference [{0}]", assemblyPath);
                            continue;
                        }

                        var assembly = assemblyContainer.LoadAssemblyFromPath(assemblyPath, log);
                        if (assembly == null)
                        {
                            log.Error("Unable to load assembly reference [{0}]", assemblyPath);
                        }

                        if (assembly != null)
                        {
                            // Register assembly in the registry
                            AssemblyRegistry.Register(assembly, AssemblyCommonCategories.Assets);
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Error("Unexpected error while loading project [{0}] or assembly reference [{1}]", ex, fullProjectLocation, assemblyPath);
                    }
                }
            }
        }
示例#21
0
        private static Package PreLoadPackage(PackageSession session, ILogger log, string filePath, bool isSystemPackage, PackageCollection loadedPackages, PackageLoadParameters loadParameters)
        {
            if (session == null) throw new ArgumentNullException("session");
            if (log == null) throw new ArgumentNullException("log");
            if (filePath == null) throw new ArgumentNullException("filePath");
            if (loadedPackages == null) throw new ArgumentNullException("loadedPackages");
            if (loadParameters == null) throw new ArgumentNullException("loadParameters");

            try
            {
                var packageId = Package.GetPackageIdFromFile(filePath);

                // Check that the package was not already loaded, otherwise return the same instance
                if (session.Packages.ContainsById(packageId))
                {
                    return session.Packages.Find(packageId);
                }

                // Package is already loaded, use the instance 
                if (loadedPackages.ContainsById(packageId))
                {
                    return loadedPackages.Find(packageId);
                }

                // Load the package without loading assets
                var newLoadParameters = loadParameters.Clone();
                newLoadParameters.AssemblyContainer = session.assemblyContainer;

                // Load the package
                var package = Package.Load(log, filePath, newLoadParameters);
                package.IsSystem = isSystemPackage;

                // Add the package has loaded before loading dependencies
                loadedPackages.Add(package);

                // Package has been loaded, register it in constraints so that we force each subsequent loads to use this one (or fails if version doesn't match)
                session.constraintProvider.AddConstraint(package.Meta.Name, new VersionSpec(package.Meta.Version.ToSemanticVersion()));

                // Load package dependencies
                PreLoadPackageDependencies(session, log, package, loadedPackages, loadParameters);

                // Add the package to the session but don't freeze it yet
                session.Packages.Add(package);

                // Validate assets from package
                package.ValidateAssets(loadParameters.GenerateNewAssetIds);

                // Freeze the package after loading the assets
                session.FreezePackage(package);

                return package;
            }
            catch (Exception ex)
            {
                log.Error("Error while pre-loading package [{0}]", ex, filePath);
            }

            return null;
        }