Exemplo n.º 1
0
        public static void Extract(Core.ILogger logger, Core.Paths paths, List <string> filePaths, Dictionary <string, Core.Project> projects, Dictionary <string, string> filters, string configPlatform = "Debug|AnyCPU")
        {
            var skipped = new List <string>();

            foreach (var filePath in filePaths)
            {
                var ext = System.IO.Path.GetExtension(filePath);
                if (ext == ".sln")
                {
                    Extract(logger, paths, filePath, projects, filters, configPlatform);
                    continue;
                }

                skipped.Add(filePath);
            }

            filePaths.Clear();
            filePaths.AddRange(skipped);


            if (filePaths.Count > 0)
            {
                SetSolutionDir(paths, filePaths[0], string.Empty);
            }

            ExtractProjects(logger, paths, filePaths, projects, filters, configPlatform);
            paths.Remove("$(ProjectDir)");
        }
Exemplo n.º 2
0
        static private void Files(Core.ILogger logger, Core.Paths paths, string fileName, string direc, List <KeyValuePair <string, string> > fileNames, List <string> extensions, List <string> projectExts)
        {
            var ext = System.IO.Path.GetExtension(fileName);

            if (projectExts.Contains(ext))
            {
                logger.Info("Appended for reading \"{0}\"", fileName);
                if (!extensions.Contains(ext))
                {
                    extensions.Add(ext);
                }

                fileNames.Add(new KeyValuePair <string, string>(fileName, direc));
                SetSolutionDir(paths, fileName, direc);
            }
            else if (ext == ".sln")
            {
                logger.Info("Reading projects from \"{0}\"", fileName);
                direc = System.IO.Path.GetDirectoryName(fileName);
                foreach (var name in ReadVisualStudioSolution(logger, fileName))
                {
                    Files(logger, paths, name, direc, fileNames, extensions, projectExts);
                }

                SetSolutionDir(paths, fileName, direc);
            }
        }
Exemplo n.º 3
0
        public static List <string> ReadVisualStudioSolution(Core.ILogger logger, string slnfilename)
        {
            List <string> projects = new List <string>();
            var           direc    = System.IO.Path.GetDirectoryName(slnfilename);

            foreach (var line in System.IO.File.ReadAllLines(slnfilename))
            {
                if (line.Length <= 10)
                {
                    continue;
                }

                if (line.Substring(0, 10) != "Project(\"{")
                {
                    continue;
                }

                var bits     = line.Split(',');
                var filename = bits[1].Trim().Substring(1);
                filename = filename.Substring(0, filename.Length - 1);
                var ext = System.IO.Path.GetExtension(filename);
                if (ext == ".csproj" || ext == ".shproj" || ext == ".vbproj" || ext == ".vcxproj")
                {
                    projects.Add(System.IO.Path.GetFullPath(System.IO.Path.Combine(direc, filename)));
                    logger.Info("Appended for reading \"{0}\"", filename);
                }
            }

            return(projects);
        }
Exemplo n.º 4
0
        public Core.Project Extract(Core.ILogger logger, Core.Paths paths, string filePath, Dictionary <string, string> filters, Dictionary <Core.Project, List <string> > dependencies, Dictionary <string, string> mapping)
        {
            var sourceDirec = paths.Value("SolutionDir");
            var proj        = this;

            var project = new Core.Cpp();

            project.IncludeDirectories.AddRange(proj.Includes());
            project.CompileDefinitions.AddRange(proj.CompileDefinitions());
            if (project.CompileDefinitions.Contains("_CONSOLE"))
            {
                project.CompileDefinitions.Remove("_CONSOLE");
                project.IsExe = true;
            }

            dependencies[project] = proj.Dependencies();

            foreach (var type in new string[] { "ClInclude", "ClCompile" })
            {
                foreach (var pair2 in proj.Files(false, type, sourceDirec))
                {
                    var fullName = pair2.Key;
                    var filter   = pair2.Value;

                    logger.Info("Appended \"{0}\"", fullName);
                    project.FilePaths.Add(fullName);
                    filters.Add(fullName, filter);
                }
            }

            mapping[filePath] = proj.Name;

            return(project);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Generate treescheme json for a given type.
        /// </summary>
        /// <param name="rootAliasTypeName">Fullname of the type to use as the root of the tree</param>
        /// <param name="fieldSource">Enum to indicator how to find fields on types</param>
        /// <param name="typeIgnorePattern">Optional regex pattern to ignore types</param>
        /// <param name="nodeCommentProvider">Optional provider of node-comments</param>
        /// <param name="logger">Optional logger for diagnostic output</param>
        /// <returns>Json string representing the scheme</returns>
        public static string GenerateScheme(
            string rootAliasTypeName,
            FieldSource fieldSource,
            Regex typeIgnorePattern = null,
            INodeCommentProvider nodeCommentProvider = null,
            Core.ILogger logger = null)
        {
            try
            {
                // Gather all the types.
                var typeCollection = TypeCollection.Create(AppDomain.CurrentDomain.GetAssemblies(), logger);

                // Create mapping context.
                var context = Context.Create(
                    typeCollection,
                    fieldSource,
                    typeIgnorePattern,
                    nodeCommentProvider,
                    logger);

                // Map the tree.
                var tree = TreeMapper.MapTree(context, rootAliasTypeName);

                // Serialize the scheme.
                return(JsonSerializer.ToJson(tree, JsonSerializer.Mode.Pretty));
            }
            catch (Exception e)
            {
                logger?.LogCritical($"Failed to generate scheme: {e.Message.ToDistinctLines()}");
                return(null);
            }
        }
        private static AssemblyLoadContext CreateLoadContext(string assemblyPath, Core.ILogger logger = null)
        {
            var validatedPath = ValidateFilePath(assemblyPath, logger);

            if (validatedPath == null)
            {
                return(null);
            }

            var mainAssemblyName = Path.GetFileNameWithoutExtension(validatedPath);
            var builder          = new AssemblyLoadContextBuilder();

            // Set base directory.
            var baseDir = Path.GetDirectoryName(validatedPath);

            builder.SetBaseDirectory(baseDir);
            logger?.LogTrace($"Base directory: '{baseDir}'");

            // Add deps file as a source for finding dependencies.
            var depsJsonFile = Path.Combine(baseDir, $"{mainAssemblyName}.deps.json");

            if (File.Exists(depsJsonFile))
            {
                builder.AddDependencyContext(depsJsonFile);
                logger?.LogTrace($"Added '{depsJsonFile}' as a deps file dependency");
            }

            // Add runtimeconfig file as a source for finding dependencies.
            var pluginRuntimeConfigFile = Path.Combine(baseDir, $"{mainAssemblyName}.runtimeconfig.json");

            builder.TryAddAdditionalProbingPathFromRuntimeConfig(pluginRuntimeConfigFile, includeDevConfig: true, out _);

            return(builder.Build());
        }
Exemplo n.º 7
0
        /// <summary>
        /// Generate treescheme json file for a given type.
        /// </summary>
        /// <param name="rootAliasTypeName">Fullname of the type to use as the root of the tree</param>
        /// <param name="fieldSource">Enum to indicator how to find fields on types</param>
        /// <param name="outputPath">Path to save the output file relative to the Assets directory</param>
        /// <param name="typeIgnorePattern">Optional regex pattern to ignore types</param>
        /// <param name="nodeCommentProvider">Optional provider of node-comments</param>
        /// <param name="logger">Optional logger for diagnostic output</param>
        public static void GenerateSchemeToFile(
            string rootAliasTypeName,
            FieldSource fieldSource,
            string outputPath,
            Regex typeIgnorePattern = null,
            INodeCommentProvider nodeCommentProvider = null,
            Core.ILogger logger = null)
        {
            // Generate the json.
            var json = GenerateScheme(
                rootAliasTypeName, fieldSource, typeIgnorePattern, nodeCommentProvider, logger);

            if (json != null)
            {
                // Write the file.
                try
                {
                    var fullPath  = Path.Combine(UnityEngine.Application.dataPath, outputPath);
                    var outputDir = Path.GetDirectoryName(fullPath);
                    if (!Directory.Exists(outputDir))
                    {
                        logger?.LogDebug($"Creating output directory: '{outputDir}'");
                        Directory.CreateDirectory(outputDir);
                    }

                    File.WriteAllText(fullPath, json);
                    logger?.LogInformation($"Saved scheme: '{outputPath}'");
                }
                catch (Exception e)
                {
                    logger?.LogCritical($"Failed to save file: {e.Message.ToDistinctLines()}");
                }
            }
        }
Exemplo n.º 8
0
        public static void MainFunc(string[] args, Core.ILogger logger)
        {
            var state = new CMakeParser.State(logger, args[0], (args.Length > 1) ? args[1] : string.Empty, new Core.Paths());
            var cmake = Instance(state, logger);

            cmake.Read();
        }
Exemplo n.º 9
0
        private static CMakeParser.CMakeLists Instance(CMakeParser.State state, Core.ILogger logger)
        {
            var lists = new CMakeParser.CMakeLists(state);

            var addBinary      = new CMakeParser.AddBinary(new AddBinaryHandler(logger));
            var binaryCommands = new string[] { "add_executable", "add_library", "catkin_add_gtest" };

            foreach (var command in binaryCommands)
            {
                lists.AddCommand(command, addBinary);
            }

            var ignore         = new CMakeParser.Ignore();
            var ignoreCommands = new string[] { "target_link_libraries", "add_dependencies", "add_test", "function", "endfunction", "option", "enable_testing", "configure_file", "find_package", "catkin_package", "install", "project", "string", "message", "cmake_minimum_required", "set_target_properties", "list", "add_custom_command", "add_custom_target", "execute_process", "find_library", "generate_messages", "add_action_files" };

            foreach (var command in ignoreCommands)
            {
                lists.AddCommand(command, ignore);
            }

            lists.AddCommand("set", new CMakeParser.Set());

            lists.AddCommand("file", new CMakeParser.File());

            lists.AddCommand("source_group", new CMakeParser.SourceGroup(new SourceGroupHandler(logger)));

            lists.AddCommand("include_directories", new CMakeParser.IncludeDirectories());

            lists.AddCommand("add_compile_definitions", new CMakeParser.AddCompileDefinitions());

            return(lists);
        }
Exemplo n.º 10
0
        private static void ExtractProjects(Core.ILogger logger, Core.Paths paths, List <string> filePaths, Dictionary <string, Core.Project> projects, Dictionary <string, string> filters, string configPlatform)
        {
            var dependencies = new Dictionary <Core.Project, List <string> >();
            var mapping      = new Dictionary <string, string>();

            foreach (var proj in ExtractProjects(logger, paths, filePaths, configPlatform))
            {
                if (proj.Value is VCProj vcProj)
                {
                    projects[proj.Value.Name] = vcProj.Extract(logger, paths, proj.Key, filters, dependencies, mapping);
                }
                else if (proj.Value is NetProj netProj)
                {
                    projects[proj.Value.Name] = netProj.Extract(logger, paths, proj.Key, dependencies, mapping);
                }
            }

            foreach (var dep in dependencies)
            {
                var proj = dep.Key;
                foreach (var filePath in dep.Value)
                {
                    if (mapping.ContainsKey(filePath))
                    {
                        proj.Dependencies.Add(mapping[filePath]);
                    }
                }
            }
        }
Exemplo n.º 11
0
        public static void MainFunc(string[] args, Core.ILogger logger)
        {
            logger.Info("Visual Studio solution command line application for creating CMake files");
            logger.Info("Copyright (c) 2020 Zebedee Mason");

            bool printUsage = false;

            if (args.Length == 2 || args.Length == 3)
            {
                if (!System.IO.File.Exists(args[0]))
                {
                    logger.Info("First argument is not an existing file");
                    printUsage = true;
                }
                else if (System.IO.Path.GetExtension(args[0]) != ".sln")
                {
                    logger.Info("First argument is not an sln file");
                    printUsage = true;
                }

                if (args.Length == 3 && !System.IO.Directory.Exists(args[2]))
                {
                    logger.Info("Third argument is not an existing directory");
                    printUsage = true;
                }
            }
            else
            {
                printUsage = true;
            }

            if (printUsage)
            {
                logger.Info("Create CMakeLists.txt files");
                logger.Info("Usage:");
                logger.Info("  ProjectIO.VisualStudioToCMake.exe <Visual Studio solution> <configuration|platform> [root directory if different from sln file path]");
                return;
            }

            var filePaths = new List <string> {
                args[0]
            };
            var projects = new Dictionary <string, Core.Project>();
            var filters  = new Dictionary <string, string>();
            var paths    = new Core.Paths();

            VisualStudio.Solution.Extract(logger, paths, filePaths, projects, filters, args[1]);

            var rootDirec = System.IO.Path.GetDirectoryName(args[0]);

            if (args.Length == 3)
            {
                rootDirec = args[2];
            }

            string name = System.IO.Path.GetFileNameWithoutExtension(args[0]);

            CMakeProject.Assemble(rootDirec, name, projects);
        }
        private static IReadOnlyList <Assembly> LoadAssemblyFromName(
            AssemblyLoadContext loadContext,
            AssemblyName assemblyName,
            IEnumerable <string> dependencyDirectories,
            Core.ILogger logger = null)
        {
            // If assembly exists in any of the dependency paths then load it from there.
            var dependencyPath = dependencyDirectories.
                                 Select(d =>
            {
                try
                {
                    return
                    (Directory.EnumerateFiles(d, $"{assemblyName.Name}.dll", SearchOption.AllDirectories).
                     FirstOrDefault());
                }
                catch (Exception)
                {
                    return(null);
                }
            }).
                                 Where(p => p != null).
                                 FirstOrDefault();

            if (!string.IsNullOrEmpty(dependencyPath))
            {
                return(LoadAssemblyFromPath(loadContext, dependencyPath, dependencyDirectories, logger));
            }

            // Otherwise load by name from the context.
            var output = new List <Assembly>();

            try
            {
                output.Add(loadContext.LoadFromAssemblyName(assemblyName));
                logger?.LogTrace($"Loaded assembly: '{output[0].FullName}'");
            }
            catch (Exception e)
            {
                if (logger != null)
                {
                    logger?.LogWarning($"Failed to load assembly: {e.Message.ToDistinctLines()}");
                }
                return(Array.Empty <Assembly>());
            }

            // Load referenced assemblies.
            foreach (var referencedAssemblyName in output[0].GetReferencedAssemblies())
            {
                if (!IsAssemblyLoaded(referencedAssemblyName))
                {
                    output.AddRange(
                        LoadAssemblyFromName(loadContext, referencedAssemblyName, dependencyDirectories, logger));
                }
            }

            return(output);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="Application"/> class.
        /// </summary>
        /// <param name="logger">Optional logger to use during execution</param>
        public Application(ILogger <Application> logger)
        {
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            this.logger = new LoggerAdapter(logger);
        }
Exemplo n.º 14
0
 public Proj(Core.ILogger logger, string path, Core.Paths paths, string configPlatform)
 {
     _logger         = logger;
     _filePath       = path;
     _paths          = paths;
     _configPlatform = configPlatform;
     _xml            = new XMLUtils(path);
     _paths.Add("ProjectDir", System.IO.Path.GetDirectoryName(_filePath));
 }
Exemplo n.º 15
0
 public State(State state)
 {
     Variables          = state.Variables.ToDictionary(entry => entry.Key, entry => entry.Value);
     Properties         = state.Properties.ToDictionary(entry => entry.Key, entry => entry.Value);
     Switches           = state.Switches.ToDictionary(entry => entry.Key, entry => entry.Value);
     IncludeDirectories = state.IncludeDirectories.ToList();
     CompileDefinitions = state.CompileDefinitions.ToList();
     _logger            = state._logger;
     _paths             = state._paths;
 }
Exemplo n.º 16
0
        private static void Extract(Core.ILogger logger, Core.Paths paths, string solutionPath, Dictionary <string, Core.Project> projects, Dictionary <string, string> filters, string configPlatform)
        {
            logger.Info("Reading projects from \"{0}\"", solutionPath);
            var direc = System.IO.Path.GetDirectoryName(solutionPath);

            SetSolutionDir(paths, solutionPath, direc);
            var filePaths = ReadVisualStudioSolution(logger, solutionPath);

            ExtractProjects(logger, paths, filePaths, projects, filters, configPlatform);
        }
Exemplo n.º 17
0
        public static string Extract(Core.ILogger logger, Core.Paths paths, List <string> filePaths, Dictionary <string, Core.Project> projects, Dictionary <string, string> filters)
        {
            string lists = string.Empty;
            string cache = string.Empty;

            foreach (var filePath in filePaths)
            {
                if (lists.Length == 0 && System.IO.Path.GetFileName(filePath) == "CMakeLists.txt")
                {
                    lists = filePath;
                }

                if (cache.Length == 0 && System.IO.Path.GetFileName(filePath) == "CMakeCache.txt")
                {
                    cache = filePath;
                }
            }

            if (lists.Length == 0)
            {
                return("solution");
            }

            logger.Info("Appended for reading \"{0}\"", lists);

            var sourceDirec = System.IO.Path.GetDirectoryName(lists);

            paths.Add("PROJECT_SOURCE_DIR", sourceDirec);
            filePaths.Remove(lists);

            var binaryDirec = string.Empty;

            if (cache.Length != 0)
            {
                binaryDirec = System.IO.Path.GetDirectoryName(cache);
                paths.Add("PROJECT_BINARY_DIR", binaryDirec);
                filePaths.Remove(cache);
            }

            logger.Info("Reading CMake");
            var state = new State(logger, sourceDirec, binaryDirec, paths);

            state.ReadCache(cache);

            var builder = Instance(state, projects, filters, logger);

            builder.Read();

            if (state.Variables.ContainsKey("${CMAKE_PROJECT_NAME}"))
            {
                return(state.Variables["${CMAKE_PROJECT_NAME}"]);
            }

            return("solution");
        }
 public DocumentDbReadModelRepository(
     IDocumentDbSettings settings,
     IReliableReadWriteDocumentClientFactory clientFactory,
     Core.ILogger logger,
     ITelemetryLogger telemetryLogger)
 {
     Settings         = settings;
     ClientFactory    = clientFactory;
     Logger           = logger ?? throw new ArgumentNullException(nameof(logger));
     _telemetryLogger = telemetryLogger;
 }
Exemplo n.º 19
0
        public override Core.Project Extract(Core.ILogger logger, Core.Paths paths, string filePath, Dictionary <Core.Project, List <string> > dependencies, Dictionary <string, string> mapping)
        {
            var proj = this;

            var project = new Core.VBasic();

            dependencies[project] = proj.Dependencies();
            proj.Compiles(project.FilePaths, logger, paths);
            mapping[filePath] = proj.Name;

            return(project);
        }
Exemplo n.º 20
0
        public State(Core.ILogger logger, string sourceDirec, string binaryDirec, Core.Paths paths)
        {
            Variables["${PROJECT_SOURCE_DIR}"]       = sourceDirec;
            Variables["${PROJECT_BINARY_DIR}"]       = binaryDirec;
            Variables["${CMAKE_CURRENT_LIST_DIR}"]   = "${PROJECT_SOURCE_DIR}";
            Variables["${CMAKE_CURRENT_SOURCE_DIR}"] = "${PROJECT_SOURCE_DIR}";
            Variables["${CMAKE_CURRENT_BINARY_DIR}"] = "${PROJECT_BINARY_DIR}";

            Switches["WIN32"] = true;
            Switches["UNIX"]  = false;

            _logger = logger;
            _paths  = paths;
        }
        private IEnumerable <IDnlibDef> InjectType(ModuleDef m, Core.ILogger l, params TypeDefUser[] types)
        {
            List <IDnlibDef> ret = new List <IDnlibDef>();

            foreach (TypeDefUser type in types)
            {
                m.Types.Add(type);
                l.Debug("Added attribute " + type);

                ret.AddRange(InjectHelper.Inject(type, type, m));
            }

            return(ret);
        }
Exemplo n.º 22
0
        public void DotNetCompiles(Proj project, List <string> files, Core.ILogger logger, Core.Paths filePath)
        {
            var list  = Compiles("Compile");
            var direc = System.IO.Path.GetDirectoryName(project.FilePath);

            filePath.Add("ProjectDir", direc);
            foreach (var link in list)
            {
                var trimmed = link;
                trimmed = trimmed.Replace("$(MSBuildThisFileDirectory)", direc + "\\");
                var file = filePath.RemoveAliases(trimmed);

                if (!System.IO.Path.IsPathRooted(file))
                {
                    file = System.IO.Path.Combine(direc, trimmed);
                }

                if (file.Contains("*"))
                {
                    var directory = System.IO.Path.GetDirectoryName(file);
                    var pattern   = System.IO.Path.GetFileName(file);
                    try
                    {
                        foreach (var name in System.IO.Directory.GetFiles(directory, pattern))
                        {
                            logger.Info("Appended \"{0}\"", name);
                            files.Add(name);
                        }
                    }
                    catch
                    {
                    }
                }
                else if (file.Length > 0)
                {
                    if (!System.IO.File.Exists(file))
                    {
                        logger.Warn("Cannot find \"{0}\"", file);
                        continue;
                    }

                    logger.Info("Appended \"{0}\"", file);
                    files.Add(file);
                }
            }

            filePath.Remove("ProjectDir");
        }
        private static IEnumerable <IDnlibDef> InjectType(ModuleDef m, Core.ILogger l, params Type[] types)
        {
            List <IDnlibDef> ret = new List <IDnlibDef>();

            foreach (TypeDef type in types.Select(RuntimeHelper.GetType))
            {
                var newType = new TypeDefUser(DefaultNamespace, type.Name);
                m.Types.Add(newType);
                l.Debug("Added type " + newType);

                ret.Add(newType);
                ret.AddRange(InjectHelper.Inject(type, newType, m));
            }

            return(ret);
        }
Exemplo n.º 24
0
        public static Dictionary <string, Proj> ExtractProjects(Core.ILogger logger, Core.Paths paths, List <string> filePaths, string configPlatform = "Debug|AnyCPU")
        {
            var projects = new Dictionary <string, Proj>();
            var skipped  = new List <string>();

            foreach (var filePath in filePaths)
            {
                var ext = System.IO.Path.GetExtension(filePath);

                if (ext == ".vcxproj")
                {
                    logger.Info("Appended for reading \"{0}\"", filePath);
                    logger.Info("Reading Visual C++");
                    var proj = new VCProj(logger, filePath, paths, configPlatform);
                    projects[filePath] = proj;
                    continue;
                }

                if (ext == ".csproj")
                {
                    var proj = new CSProj(logger, filePath, paths, configPlatform);
                    projects[filePath] = proj;
                    continue;
                }

                if (ext == ".shproj")
                {
                    var proj = new SHProj(logger, filePath, paths, configPlatform);
                    projects[filePath] = proj;
                    continue;
                }

                if (ext == ".vbproj")
                {
                    var proj = new VBProj(logger, filePath, paths, configPlatform);
                    projects[filePath] = proj;
                    continue;
                }

                skipped.Add(filePath);
            }

            filePaths.Clear();
            filePaths.AddRange(skipped);

            return(projects);
        }
        /// <summary>
        /// Attempt to load a <see cref="ITypeCollection"/> from a Assembly path.
        /// </summary>
        /// <param name="assemblyPath">Path to the assembly file</param>
        /// <param name="dependencyDirectories">List of directories to search for dependant assemblies</param>
        /// <param name="logger">Optional logger to provide diagnostic output</param>
        /// <returns><see cref="ITypeCollection"/> if successfull otherwise null</returns>
        internal static ITypeCollection TryLoad(
            string assemblyPath,
            IEnumerable <string> dependencyDirectories,
            Core.ILogger logger = null)
        {
            if (assemblyPath == null)
            {
                throw new ArgumentNullException(nameof(assemblyPath));
            }
            if (dependencyDirectories == null)
            {
                throw new ArgumentNullException(nameof(dependencyDirectories));
            }

            // Verify that dependency paths exists.
            foreach (var dependencyDirectory in dependencyDirectories)
            {
                if (!Directory.Exists(dependencyDirectory))
                {
                    logger?.LogCritical($"Dependency directory '{dependencyDirectory}' cannot be found");
                    return(null);
                }
            }

            // Create load context.
            var loadContext = CreateLoadContext(assemblyPath, logger);

            if (loadContext == null)
            {
                return(null);
            }

            // Load assemblies.
            var assemblies = LoadAssemblyFromPath(loadContext, assemblyPath, dependencyDirectories, logger);

            logger?.LogDebug($"Loaded {assemblies.Count} assemblies");

            // Load types.
            var typeCollection = TypeCollection.Create(assemblies, logger);

            logger?.LogDebug($"Loaded {typeCollection.TypeCount} types");
            return(typeCollection);
        }
        private static IReadOnlyList <Assembly> LoadAssemblyFromPath(
            AssemblyLoadContext loadContext,
            string path,
            IEnumerable <string> dependencyDirectories,
            Core.ILogger logger = null)
        {
            // Validate path.
            var validatedPath = ValidateFilePath(path, logger);

            if (validatedPath == null)
            {
                return(Array.Empty <Assembly>());
            }

            // Load assembly.
            var output = new List <Assembly>();

            try
            {
                output.Add(loadContext.LoadFromAssemblyPath(validatedPath));
                logger?.LogTrace($"Loaded assembly: '{output[0].FullName}'");
            }
            catch (Exception e)
            {
                if (logger != null)
                {
                    logger?.LogWarning($"Failed to load assembly: {e.Message.ToDistinctLines()}");
                }
                return(Array.Empty <Assembly>());
            }

            // Load referenced assemblies.
            foreach (var referencedAssemblyName in output[0].GetReferencedAssemblies())
            {
                if (!IsAssemblyLoaded(referencedAssemblyName))
                {
                    output.AddRange(
                        LoadAssemblyFromName(loadContext, referencedAssemblyName, dependencyDirectories, logger));
                }
            }

            return(output);
        }
        private static string ValidateFilePath(string path, Core.ILogger logger = null)
        {
            // Determine full-path.
            string fullPath;

            try
            {
                fullPath = Path.GetFullPath(path);
            }
            catch
            {
                logger?.LogCritical($"Unable to determine absolute path for: '{path}'");
                return(null);
            }

            // Validate file existence.
            if (!File.Exists(fullPath))
            {
                logger?.LogCritical($"No file found at path: '{fullPath}'");
                return(null);
            }

            return(fullPath);
        }
Exemplo n.º 28
0
        public void Setup(ViewRegistry registry, Core.ILogger logger)
        {
            if (logger == null)
            {
                logger = new NullLogger();
            }
            _logger = logger;

            foreach (TypeBinding bindingData in registry.Bindings)
            {
                Type type = Type.GetType(bindingData.TypeName);
                if (type == null)
                {
                    _logger.LogError(string.Format(
                                         "Could not get type for qualified name '{0}'",
                                         bindingData.TypeName
                                         ));
                    continue;
                }
                var binding = new Binding();
                binding.Targets.AddRange(bindingData.Targets);
                _bindings.Add(type, binding);
            }
        }
Exemplo n.º 29
0
        private static void MainFunc(string[] args, Core.ILogger logger)
        {
            logger.Info("VStoVS command line application for creating a Visual Studio solution from a Visual Studio solution!");
            logger.Info("Copyright (c) 2020 Zebedee Mason");

            bool printUsage = false;

            if (args.Length > 3)
            {
                if (!System.IO.Directory.Exists(args[0]))
                {
                    logger.Info("First argument is not an output directory");
                    printUsage = true;
                }
                else if (!System.IO.Directory.Exists(args[1]))
                {
                    logger.Info("Second argument is not a template directory");
                    printUsage = true;
                }
                else if (System.IO.Path.GetExtension(args[2]) != ".sln" && System.IO.File.Exists(args[2]))
                {
                    logger.Info("Third argument is not an existing sln file");
                    printUsage = true;
                }
                else
                {
                    foreach (var fileName in VisualStudio.Writer.Templates)
                    {
                        if (!System.IO.File.Exists(System.IO.Path.Combine(args[1], fileName)))
                        {
                            logger.Info(string.Format("Second argument is not a directory containing {0}", fileName));
                            printUsage = true;
                        }
                    }
                }
            }
            else
            {
                printUsage = true;
            }

            if (printUsage)
            {
                logger.Info("Create a Visual Studio solution");
                logger.Info("Usage:");
                logger.Info("  ProjectIO.VStoVS.exe <output directory> <template directory> <Visual Studio solution> <configuration|platform>");
                return;
            }

            var filePaths = new List <string> {
                args[2]
            };
            var projects = new Dictionary <string, Core.Project>();
            var filters  = new Dictionary <string, string>();
            var paths    = new Core.Paths();

            VisualStudio.Solution.Extract(logger, paths, filePaths, projects, filters, args[3]);

            var solutionName = System.IO.Path.GetFileNameWithoutExtension(args[2]);
            var solution     = new VisualStudio.Writer(projects, filters);

            solution.Write(solutionName, args[0], args[1]);
        }
Exemplo n.º 30
0
        public static void Extract(Core.ILogger logger, Core.Paths paths, string filePath, Dictionary <string, Core.Project> projects, Dictionary <Core.Project, List <string> > dependencies, Dictionary <string, string> mapping, string configPlatform)
        {
            var proj = new VBProj(logger, filePath, paths, configPlatform);

            projects[proj.Name] = proj.Extract(logger, paths, filePath, dependencies, mapping);
        }