public void WhenInitializedParameterLessItWillContainDefaultValues()
 {
     var instance = new ProjectFileInfo();
     Assert.AreEqual("Project", instance.DefaultFileName);
     Assert.AreEqual("Game Project", instance.Description);
     Assert.AreEqual("atp", instance.Extension);
 }
 public bool TryGetProject(string projectFilePath, out ProjectFileInfo projectFileInfo) => _projectFiles.TryGetValue(projectFilePath, out projectFileInfo);
        private void UpdateProject(ProjectFileInfo projectFileInfo)
        {
            var project = _workspace.CurrentSolution.GetProject(projectFileInfo.WorkspaceId);

            var unusedDocuments = project.Documents.ToDictionary(d => d.FilePath, d => d.Id);

            foreach (var file in projectFileInfo.SourceFiles)
            {
                if (unusedDocuments.Remove(file))
                {
                    continue;
                }

                using (var stream = File.OpenRead(file))
                {
                    var sourceText = SourceText.From(stream, encoding: Encoding.UTF8);
                    var id         = DocumentId.CreateNewId(projectFileInfo.WorkspaceId);
                    var version    = VersionStamp.Create();

                    var loader = TextLoader.From(TextAndVersion.Create(sourceText, version));

                    _workspace.AddDocument(DocumentInfo.Create(id, file, filePath: file, loader: loader));
                }
            }

            if (projectFileInfo.SpecifiedLanguageVersion.HasValue || projectFileInfo.DefineConstants != null)
            {
                var parseOptions = projectFileInfo.SpecifiedLanguageVersion.HasValue
                    ? new CSharpParseOptions(projectFileInfo.SpecifiedLanguageVersion.Value)
                    : new CSharpParseOptions();
                if (projectFileInfo.DefineConstants != null && projectFileInfo.DefineConstants.Any())
                {
                    parseOptions = parseOptions.WithPreprocessorSymbols(projectFileInfo.DefineConstants);
                }
                if (projectFileInfo.GenerateXmlDocumentation)
                {
                    parseOptions = parseOptions.WithDocumentationMode(DocumentationMode.Diagnose);
                }
                _workspace.SetParseOptions(project.Id, parseOptions);
            }

            foreach (var unused in unusedDocuments)
            {
                _workspace.RemoveDocument(unused.Value);
            }

            var unusedProjectReferences = new HashSet <ProjectReference>(project.ProjectReferences);

            foreach (var projectReferencePath in projectFileInfo.ProjectReferences)
            {
                ProjectFileInfo projectReferenceInfo;
                if (_context.Projects.TryGetValue(projectReferencePath, out projectReferenceInfo))
                {
                    var reference = new ProjectReference(projectReferenceInfo.WorkspaceId);

                    if (unusedProjectReferences.Remove(reference))
                    {
                        // This reference already exists
                        continue;
                    }

                    _workspace.AddProjectReference(project.Id, reference);
                }
                else
                {
                    _logger.LogWarning($"Unable to resolve project reference '{projectReferencePath}' for '{projectFileInfo}'.");
                }
            }

            foreach (var unused in unusedProjectReferences)
            {
                _workspace.RemoveProjectReference(project.Id, unused);
            }

            var unusedReferences = new HashSet <MetadataReference>(project.MetadataReferences);

            foreach (var referencePath in projectFileInfo.References)
            {
                if (!File.Exists(referencePath))
                {
                    _logger.LogWarning($"Unable to resolve assembly '{referencePath}'");
                }
                else
                {
                    var metadataReference = _metadataReferenceCache.GetMetadataReference(referencePath);

                    if (unusedReferences.Remove(metadataReference))
                    {
                        continue;
                    }

                    _logger.LogDebug($"Adding reference '{referencePath}' to '{projectFileInfo.ProjectFilePath}'.");
                    _workspace.AddMetadataReference(project.Id, metadataReference);
                }
            }

            foreach (var reference in unusedReferences)
            {
                _workspace.RemoveMetadataReference(project.Id, reference);
            }
        }
            private async Task <ResolvedReferences> ResolveReferencesAsync(ProjectId id, ProjectFileInfo projectFileInfo, CommandLineArguments commandLineArgs, CancellationToken cancellationToken)
            {
                // First, gather all of the metadata references from the command-line arguments.
                var resolvedMetadataReferences = commandLineArgs.ResolveMetadataReferences(
                    new WorkspaceMetadataFileReferenceResolver(
                        metadataService: GetWorkspaceService <IMetadataService>(),
                        pathResolver: new RelativePathResolver(commandLineArgs.ReferencePaths, commandLineArgs.BaseDirectory)));

                var builder = new ResolvedReferencesBuilder(resolvedMetadataReferences);

                var projectDirectory = Path.GetDirectoryName(projectFileInfo.FilePath);

                // Next, iterate through all project references in the file and create project references.
                foreach (var projectFileReference in projectFileInfo.ProjectReferences)
                {
                    var aliases = projectFileReference.Aliases;

                    if (_pathResolver.TryGetAbsoluteProjectPath(projectFileReference.Path, baseDirectory: projectDirectory, _discoveredProjectOptions.OnPathFailure, out var projectReferencePath))
                    {
                        // The easiest case is to add a reference to a project we already know about.
                        if (TryAddReferenceToKnownProject(id, projectReferencePath, aliases, builder))
                        {
                            continue;
                        }

                        // If we don't know how to load a project (that is, it's not a language we support), we can still
                        // attempt to verify that its output exists on disk and is included in our set of metadata references.
                        // If it is, we'll just leave it in place.
                        if (!IsProjectLoadable(projectReferencePath) &&
                            await VerifyUnloadableProjectOutputExistsAsync(projectReferencePath, builder, cancellationToken).ConfigureAwait(false))
                        {
                            continue;
                        }

                        // If metadata is preferred, see if the project reference's output exists on disk and is included
                        // in our metadata references. If it is, don't create a project reference; we'll just use the metadata.
                        if (_preferMetadataForReferencesOfDiscoveredProjects &&
                            await VerifyProjectOutputExistsAsync(projectReferencePath, builder, cancellationToken).ConfigureAwait(false))
                        {
                            continue;
                        }

                        // Finally, we'll try to load and reference the project.
                        if (await TryLoadAndAddReferenceAsync(id, projectReferencePath, aliases, builder, cancellationToken).ConfigureAwait(false))
                        {
                            continue;
                        }
                    }

                    // We weren't able to handle this project reference, so add it without further processing.
                    var unknownProjectId    = _projectMap.GetOrCreateProjectId(projectFileReference.Path);
                    var newProjectReference = CreateProjectReference(@from: id, to: unknownProjectId, aliases);
                    builder.AddProjectReference(newProjectReference);
                }

                // Are there still any unresolved metadata references? If so, remove them and report diagnostics.
                foreach (var unresolvedMetadataReference in builder.GetUnresolvedMetadataReferences())
                {
                    var filePath = unresolvedMetadataReference.Reference;

                    builder.Remove(filePath);

                    _diagnosticReporter.Report(new ProjectDiagnostic(
                                                   WorkspaceDiagnosticKind.Warning,
                                                   string.Format(WorkspaceMSBuildResources.Unresolved_metadata_reference_removed_from_project_0, filePath),
                                                   id));
                }

                return(builder.ToResolvedReferences());
            }
Beispiel #5
0
            private Task <ProjectInfo> CreateProjectInfoAsync(ProjectFileInfo projectFileInfo, ProjectId projectId, bool addDiscriminator, CancellationToken cancellationToken)
            {
                var language    = projectFileInfo.Language;
                var projectPath = projectFileInfo.FilePath;

                var projectName = Path.GetFileNameWithoutExtension(projectPath);

                if (addDiscriminator && !string.IsNullOrWhiteSpace(projectFileInfo.TargetFramework))
                {
                    projectName += "(" + projectFileInfo.TargetFramework + ")";
                }

                var version = VersionStamp.Create(
                    FileUtilities.GetFileTimeStamp(projectPath));

                if (projectFileInfo.IsEmpty)
                {
                    var assemblyName = GetAssemblyNameFromProjectPath(projectPath);

                    var parseOptions = GetLanguageService <ISyntaxTreeFactoryService>(language)
                                       .GetDefaultParseOptions();
                    var compilationOptions = GetLanguageService <ICompilationFactoryService>(language)
                                             .GetDefaultCompilationOptions();

                    return(Task.FromResult(
                               ProjectInfo.Create(
                                   projectId,
                                   version,
                                   projectName,
                                   assemblyName: assemblyName,
                                   language: language,
                                   filePath: projectPath,
                                   outputFilePath: string.Empty,
                                   outputRefFilePath: string.Empty,
                                   compilationOptions: compilationOptions,
                                   parseOptions: parseOptions,
                                   documents: SpecializedCollections.EmptyEnumerable <DocumentInfo>(),
                                   projectReferences: SpecializedCollections.EmptyEnumerable <ProjectReference>(),
                                   metadataReferences: SpecializedCollections.EmptyEnumerable <MetadataReference>(),
                                   analyzerReferences: SpecializedCollections.EmptyEnumerable <AnalyzerReference>(),
                                   additionalDocuments: SpecializedCollections.EmptyEnumerable <DocumentInfo>(),
                                   isSubmission: false,
                                   hostObjectType: null)));
                }

                return(DoOperationAndReportProgressAsync(ProjectLoadOperation.Resolve, projectPath, projectFileInfo.TargetFramework, async() =>
                {
                    var projectDirectory = Path.GetDirectoryName(projectPath);

                    // parse command line arguments
                    var commandLineParser = GetLanguageService <ICommandLineParserService>(projectFileInfo.Language);

                    var commandLineArgs = commandLineParser.Parse(
                        arguments: projectFileInfo.CommandLineArgs,
                        baseDirectory: projectDirectory,
                        isInteractive: false,
                        sdkDirectory: RuntimeEnvironment.GetRuntimeDirectory());

                    var assemblyName = commandLineArgs.CompilationName;
                    if (string.IsNullOrWhiteSpace(assemblyName))
                    {
                        // if there isn't an assembly name, make one from the file path.
                        // Note: This may not be necessary any longer if the commmand line args
                        // always produce a valid compilation name.
                        assemblyName = GetAssemblyNameFromProjectPath(projectPath);
                    }

                    // Ensure sure that doc-comments are parsed
                    var parseOptions = commandLineArgs.ParseOptions;
                    if (parseOptions.DocumentationMode == DocumentationMode.None)
                    {
                        parseOptions = parseOptions.WithDocumentationMode(DocumentationMode.Parse);
                    }

                    // add all the extra options that are really behavior overrides
                    var metadataService = GetWorkspaceService <IMetadataService>();
                    var compilationOptions = commandLineArgs.CompilationOptions
                                             .WithXmlReferenceResolver(new XmlFileResolver(projectDirectory))
                                             .WithSourceReferenceResolver(new SourceFileResolver(ImmutableArray <string> .Empty, projectDirectory))
                                             // TODO: https://github.com/dotnet/roslyn/issues/4967
                                             .WithMetadataReferenceResolver(new WorkspaceMetadataFileReferenceResolver(metadataService, new RelativePathResolver(ImmutableArray <string> .Empty, projectDirectory)))
                                             .WithStrongNameProvider(new DesktopStrongNameProvider(commandLineArgs.KeyFileSearchPaths))
                                             .WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default);

                    var documents = CreateDocumentInfos(projectFileInfo.Documents, projectId, commandLineArgs.Encoding);
                    var additionalDocuments = CreateDocumentInfos(projectFileInfo.AdditionalDocuments, projectId, commandLineArgs.Encoding);
                    CheckForDuplicateDocuments(documents, additionalDocuments, projectPath, projectId);

                    var analyzerReferences = ResolveAnalyzerReferences(commandLineArgs);

                    var resolvedReferences = await ResolveReferencesAsync(projectId, projectFileInfo, commandLineArgs, cancellationToken).ConfigureAwait(false);

                    return ProjectInfo.Create(
                        projectId,
                        version,
                        projectName,
                        assemblyName,
                        language,
                        projectPath,
                        outputFilePath: projectFileInfo.OutputFilePath,
                        outputRefFilePath: projectFileInfo.OutputRefFilePath,
                        compilationOptions: compilationOptions,
                        parseOptions: parseOptions,
                        documents: documents,
                        projectReferences: resolvedReferences.ProjectReferences,
                        metadataReferences: resolvedReferences.MetadataReferences,
                        analyzerReferences: analyzerReferences,
                        additionalDocuments: additionalDocuments,
                        isSubmission: false,
                        hostObjectType: null)
                    .WithDefaultNamespace(projectFileInfo.DefaultNamespace);
                }));
            }
Beispiel #6
0
        private void SetForm()
        {
            ProjectFolderRole role = this._TopFolder.ProjectFolderRole;

            this.cbRoles.IsEnabled = this._ProjectItem.IsFolder;

            this.chkSyncTemplate.IsEnabled = this._ProjectItem.IsFile && (role == ProjectFolderRole.ComponentLayout || role == ProjectFolderRole.PageLayout);
            if (role == ProjectFolderRole.ComponentLayout || role == ProjectFolderRole.PageLayout)
            {
                this.chkSyncTemplate.IsChecked = this._ProjectItem.IsSyncTemplate();
            }
            else
            {
                this.chkSyncTemplate.IsChecked = false;
            }

            this.btnDebug.IsEnabled = this._ProjectItem.IsFile && (role == ProjectFolderRole.ComponentLayout || role == ProjectFolderRole.PageLayout);
            if (this.btnDebug.IsEnabled)
            {
                ProjectFileInfo projectFile = (ProjectFileInfo)this._ProjectItem;
                this.btnDebug.Foreground = new SolidColorBrush(!string.IsNullOrEmpty(projectFile.TestItemTcmId) && !string.IsNullOrEmpty(projectFile.TestTemplateTcmId) ? Colors.Green : Colors.Red);
            }
            else
            {
                this.btnDebug.Foreground = new SolidColorBrush(Colors.Gray);
            }

            this.cbRoles.SelectedValue = role;

            if (role == ProjectFolderRole.Other)
            {
                return;
            }

            if (role == ProjectFolderRole.Binary)
            {
                this.txtTemplateFormat.Text      = String.Empty;
                this.txtTemplateFormat.IsEnabled = false;

                this.txtSchemaNames.Text      = String.Empty;
                this.txtSchemaNames.IsEnabled = false;

                if (this._ProjectItem.IsFolder)
                {
                    this.txtTitle.Text      = null;
                    this.txtTitle.IsEnabled = false;
                }
                else
                {
                    ProjectFileInfo file = (ProjectFileInfo)this._ProjectItem;

                    this.txtTitle.Text      = String.IsNullOrEmpty(file.Title) ? Path.GetFileNameWithoutExtension(file.Path) : file.Title;
                    file.Title              = String.IsNullOrEmpty(this.txtTitle.Text) ? null : this.txtTitle.Text;
                    this.txtTitle.IsEnabled = true;
                }

                this.txtTemplateTitle.Text      = null;
                this.txtTemplateTitle.IsEnabled = false;
            }
            else
            {
                if (this._ProjectItem.IsFolder)
                {
                    if (this._ProjectItem.Path == this._TopFolder.Path)
                    {
                        this.txtTemplateFormat.Text      = this._TopFolder.TemplateFormat.PrettyXml();
                        this.txtTemplateFormat.IsEnabled = true;
                    }
                    else
                    {
                        this.txtTemplateFormat.Text      = String.Empty;
                        this.txtTemplateFormat.IsEnabled = false;
                    }

                    this.txtSchemaNames.Text      = String.Empty;
                    this.txtSchemaNames.IsEnabled = false;

                    this.txtTitle.Text      = null;
                    this.txtTitle.IsEnabled = false;

                    this.txtTemplateTitle.Text      = null;
                    this.txtTemplateTitle.IsEnabled = false;
                }
                else
                {
                    ProjectFileInfo file = (ProjectFileInfo)this._ProjectItem;

                    this.txtTemplateFormat.Text      = this._TopFolder.TemplateFormat.PrettyXml();
                    this.txtTemplateFormat.IsEnabled = false;

                    this.txtSchemaNames.Text      = file.SchemaNames == null ? String.Empty : string.Join("\n", file.SchemaNames);
                    this.txtSchemaNames.IsEnabled = true;

                    string title = Path.GetFileNameWithoutExtension(file.Path);

                    this.txtTitle.Text      = String.IsNullOrEmpty(file.Title) ? (string.IsNullOrEmpty(title) ? null : title.Replace(" Layout", "") + " Layout") : file.Title;
                    file.Title              = String.IsNullOrEmpty(this.txtTitle.Text) ? null : this.txtTitle.Text;
                    this.txtTitle.IsEnabled = true;

                    this.txtTemplateTitle.Text      = String.IsNullOrEmpty(file.TemplateTitle) ? (string.IsNullOrEmpty(title) ? null : title.Replace(" Layout", "")) : file.TemplateTitle;
                    file.TemplateTitle              = String.IsNullOrEmpty(this.txtTemplateTitle.Text) ? null : this.txtTemplateTitle.Text;
                    this.txtTemplateTitle.IsEnabled = this.chkSyncTemplate.IsChecked == true;
                }
            }

            List <TridionFolderInfo> tridionFolders = this.TridionFolders.Where(x => x.TridionRole == this._TridionRole).ToList();

            this.lstTridionFolders.SelectedIndex = tridionFolders.Any(x => x.TcmId == this._TopFolder.TcmId) ? tridionFolders.FindIndex(x => x.TcmId == this._TopFolder.TcmId) : 0;
        }
Beispiel #7
0
        private static IEnumerable <ProjectContentItem> GetContentItems(XDocument document, ProjectFileInfo projectFileInfo)
        {
            var projectFileDirectoryPath = projectFileInfo.Value.Directory.FullName;
            var result       = document.ElementsBy(ParserHelper.Content);
            var contentItems = result.Select(
                item =>
            {
                var include  = item.AttributeBy(ParserHelper.Include).ValueOrDefault();
                var fileInfo = new FileInfo(Path.Combine(projectFileDirectoryPath, include));
                return(new ProjectContentItem(include, fileInfo));
            });

            return(contentItems);
        }
 private ProjectFileInfo LoadProject(string projectFilePath)
     => LoadOrReloadProject(projectFilePath, () => ProjectFileInfo.Load(projectFilePath, _projectLoader));
        public static void AddChildItems(ProjectFolderInfo projectFolder, string rootPath)
        {
            if (projectFolder == null)
                return;

            if (String.IsNullOrEmpty(projectFolder.FullPath))
                return;

            if (!Directory.Exists(projectFolder.FullPath))
                Directory.CreateDirectory(projectFolder.FullPath);

            ProjectFolderInfo topFolder = projectFolder.GetTopFolder();
            ProjectFolderRole role = topFolder.ProjectFolderRole;
            string[] extensions = role == Misc.ProjectFolderRole.Binary ? Const.Extensions.Keys.ToArray() : new[] { "*.cshtml" };
            string[] directories = Directory.GetDirectories(projectFolder.FullPath);
            string[] files = IO.Service.GetFiles(projectFolder.FullPath, extensions);

            if (directories.Length == 0 && files.Length == 0)
            {
                projectFolder.ChildItems = null;
                return;
            }

            List<ProjectItemInfo> newChildItems = new List<ProjectItemInfo>();

            foreach (string dir in directories)
            {
                ProjectFolderInfo childFolder = null;

                if (projectFolder.ChildItems != null)
                {
                    childFolder = projectFolder.ChildItems.FirstOrDefault(x => x.IsFolder && x.FullPath == dir) as ProjectFolderInfo;
                }

                if (childFolder == null)
                {
                    childFolder = new ProjectFolderInfo { RootPath = rootPath, Path = dir.Replace(rootPath, "").Trim('\\'), Checked = false };
                }

                childFolder.Parent = projectFolder;

                AddChildItems(childFolder, rootPath);

                newChildItems.Add(childFolder);
            }

            foreach (string file in files)
            {
                ProjectFileInfo childFile = null;

                if (projectFolder.ChildItems != null)
                {
                    childFile = projectFolder.ChildItems.FirstOrDefault(x => x.IsFile && x.FullPath == file) as ProjectFileInfo;
                }

                if (childFile == null)
                {
                    childFile = new ProjectFileInfo { RootPath = rootPath, Path = file.Replace(rootPath, "").Trim('\\'), Checked = false };
                }

                childFile.Parent = projectFolder;

                newChildItems.Add(childFile);
            }

            projectFolder.ChildItems = newChildItems.Count > 0 ? newChildItems : null;
        }
        public static ProjectFolderInfo GetRootTree(ProjectFolderInfo projectFolder, string fullPath)
        {
            if (projectFolder == null)
                return null;

            if (!Directory.Exists(fullPath))
                return null;

            if (!ExistFile(projectFolder, fullPath) && projectFolder.FullPath != fullPath)
                return null;

            if (projectFolder.FullPath == fullPath)
            {
                projectFolder.IsSelected = true;
                projectFolder.Expand();
                return projectFolder;
            }

            string rootPath = projectFolder.RootPath;

            ProjectFolderInfo parentFolder = new ProjectFolderInfo { RootPath = rootPath, Path = fullPath.Replace(rootPath, "").Trim('\\'), Checked = false };
            parentFolder.ChildItems = new List<ProjectItemInfo>();

            foreach (string childFolderPath in Directory.GetDirectories(fullPath))
            {
                ProjectFolderInfo childFolder = GetRootTree(projectFolder, childFolderPath);
                if (childFolder != null)
                {
                    childFolder.Parent = parentFolder;
                    parentFolder.ChildItems.Add(childFolder);
                }
            }

            foreach (string childFilePath in IO.Service.GetFiles(fullPath, projectFolder.ProjectFolderRole == Misc.ProjectFolderRole.Binary ? Const.Extensions.Keys.ToArray() : new[] { "*.cshtml" }))
            {
                ProjectFileInfo childFile = new ProjectFileInfo { RootPath = rootPath, Path = childFilePath.Replace(rootPath, "").Trim('\\'), Checked = false };
                childFile.Parent = parentFolder;
                parentFolder.ChildItems.Add(childFile);
            }

            if (parentFolder.ChildItems.Count == 0)
                parentFolder.ChildItems = null;

            return parentFolder;
        }
Beispiel #11
0
        internal ProjectFile(
            ProjectFileInfo projectFileInfo,
            string assemblyName,
            IEnumerable <AssemblyReference> assemblyReferences,
            IEnumerable <ProjectReference> projectReferences,
            IEnumerable <ProjectType> projectTypes,
            IEnumerable <Import> imports,
            IEnumerable <CSharpFileInfo> csharpFileInfos,
            IEnumerable <XAMLFileInfo> xamlFileInfos,
            IEnumerable <ProjectContentItem> projectContentItems,
            string targetFrameworkVersion)
        {
            if (projectFileInfo == null)
            {
                throw new ArgumentNullException(nameof(projectFileInfo));
            }

            if (string.IsNullOrEmpty(assemblyName))
            {
                throw new ArgumentException("The assembly name must not be null or empty", nameof(assemblyName));
            }

            if (assemblyReferences == null)
            {
                throw new ArgumentNullException(nameof(assemblyReferences));
            }

            if (projectReferences == null)
            {
                throw new ArgumentNullException(nameof(projectReferences));
            }

            if (projectTypes == null)
            {
                throw new ArgumentNullException(nameof(projectTypes));
            }

            if (imports == null)
            {
                throw new ArgumentNullException(nameof(imports));
            }

            if (csharpFileInfos == null)
            {
                throw new ArgumentNullException(nameof(csharpFileInfos));
            }

            if (xamlFileInfos == null)
            {
                throw new ArgumentNullException(nameof(xamlFileInfos));
            }

            if (projectContentItems == null)
            {
                throw new ArgumentNullException(nameof(projectContentItems));
            }

            if (targetFrameworkVersion == null)
            {
                throw new ArgumentNullException(nameof(targetFrameworkVersion));
            }

            ProjectFileInfo        = projectFileInfo;
            AssemblyName           = assemblyName;
            AssemblyReferences     = assemblyReferences;
            ProjectReferences      = projectReferences;
            ProjectTypes           = projectTypes;
            Imports                = imports;
            CSharpFileInfos        = csharpFileInfos;
            XAMLFileInfos          = xamlFileInfos;
            ContentItems           = projectContentItems;
            TargetFrameworkVersion = targetFrameworkVersion;
        }
        private static void ReadProjectFile(XContainer file, ProjectFileInfo projectFileInfo, ref int segmentIdCounter)
        {
            foreach (var element in file.Elements())
            {
                if (string.Compare(element.Name.LocalName, "header", StringComparison.InvariantCultureIgnoreCase) == 0)
                {
                    foreach (var fileInfo in element.Elements())
                    {
                        if (string.Compare(fileInfo.Name.LocalName, "file-info", StringComparison.InvariantCultureIgnoreCase) == 0)
                        {
                            foreach (var value in fileInfo.Elements())
                            {
                                if (string.Compare(value.Name.LocalName, "value", StringComparison.InvariantCultureIgnoreCase) == 0)
                                {
                                    if (!value.HasAttributes)
                                    {
                                        continue;
                                    }

                                    SetFileInfoAttributes(projectFileInfo, value);
                                }
                            }
                        }

                        if (string.Compare(fileInfo.Name.LocalName, "filetype-info", StringComparison.InvariantCultureIgnoreCase) == 0)
                        {
                            var fileType = fileInfo.Elements().FirstOrDefault(a => string.Compare(a.Name.LocalName, "filetype-id", StringComparison.InvariantCultureIgnoreCase) == 0);
                            if (fileType != null)
                            {
                                projectFileInfo.FileTypeId = fileType.Value;
                            }
                        }

                        if (string.Compare(fileInfo.Name.LocalName, "cxt-defs", StringComparison.InvariantCultureIgnoreCase) == 0)
                        {
                            foreach (var cxtdef in fileInfo.Elements())
                            {
                                var contextDefinition = new ParagraphUnitContext();
                                foreach (var attribute in cxtdef.Attributes())
                                {
                                    if (string.Compare(attribute.Name.LocalName, "id", StringComparison.InvariantCultureIgnoreCase) == 0)
                                    {
                                        contextDefinition.Id = attribute.Value;
                                    }

                                    if (string.Compare(attribute.Name.LocalName, "type", StringComparison.InvariantCultureIgnoreCase) == 0)
                                    {
                                        contextDefinition.ContextType = attribute.Value;
                                    }

                                    if (string.Compare(attribute.Name.LocalName, "code", StringComparison.InvariantCultureIgnoreCase) == 0)
                                    {
                                        contextDefinition.DisplayCode = attribute.Value;
                                    }

                                    if (string.Compare(attribute.Name.LocalName, "descr", StringComparison.InvariantCultureIgnoreCase) == 0)
                                    {
                                        contextDefinition.Description = attribute.Value;
                                    }

                                    if (string.Compare(attribute.Name.LocalName, "color", StringComparison.InvariantCultureIgnoreCase) == 0)
                                    {
                                        contextDefinition.DisplayName = attribute.Value;
                                    }
                                }

                                var props = cxtdef.Elements().FirstOrDefault(a => string.Compare(a.Name.LocalName, "props", StringComparison.InvariantCultureIgnoreCase) == 0);
                                if (props != null)
                                {
                                    foreach (var value in props.Elements())
                                    {
                                        if (string.Compare(value.Name.LocalName, "value", StringComparison.InvariantCultureIgnoreCase) == 0)
                                        {
                                            if (!value.HasAttributes)
                                            {
                                                continue;
                                            }

                                            foreach (var attribute in value.Attributes())
                                            {
                                                if (!contextDefinition.MetaData.ContainsKey(attribute.Value))
                                                {
                                                    contextDefinition.MetaData.Add(attribute.Value, value.Value);
                                                }
                                            }
                                        }
                                    }

                                    projectFileInfo.ContextDefinitions.Add(contextDefinition);
                                }
                            }
                        }
                    }
                }

                if (string.Compare(element.Name.LocalName, "body", StringComparison.InvariantCultureIgnoreCase) == 0)
                {
                    foreach (var group in element.Elements())
                    {
                        if (string.Compare(group.Name.LocalName, "group", StringComparison.InvariantCultureIgnoreCase) == 0)
                        {
                            var contextDefinitions = new List <ParagraphUnitContext>();
                            var contexts           = group.Elements().FirstOrDefault(a => string.Compare(a.Name.LocalName, "cxts", StringComparison.InvariantCultureIgnoreCase) == 0);
                            if (contexts != null)
                            {
                                foreach (var value in contexts.Elements())
                                {
                                    if (string.Compare(value.Name.LocalName, "cxt", StringComparison.InvariantCultureIgnoreCase) == 0)
                                    {
                                        foreach (var attribute in value.Attributes())
                                        {
                                            if (string.Compare(attribute.Name.LocalName, "id", StringComparison.InvariantCultureIgnoreCase) == 0)
                                            {
                                                var contextDefinition = projectFileInfo.ContextDefinitions.FirstOrDefault(a => a.Id == attribute.Value);
                                                if (contextDefinition != null)
                                                {
                                                    contextDefinitions.Add(contextDefinition);
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            var transUnits = group.Elements().Where(a =>
                                                                    string.Compare(a.Name.LocalName, "trans-unit", StringComparison.InvariantCultureIgnoreCase) == 0);
                            foreach (var transUnit in transUnits)
                            {
                                var paragraphInfos = GetParagraphInfo(transUnit, ref segmentIdCounter);
                                paragraphInfos.ContextDefinitions = contextDefinitions;
                                projectFileInfo.ParagraphInfos.Add(paragraphInfos);
                            }
                        }
                        if (string.Compare(group.Name.LocalName, "trans-unit", StringComparison.InvariantCultureIgnoreCase) == 0)
                        {
                            var paragraphInfos = GetParagraphInfo(group, ref segmentIdCounter);
                            paragraphInfos.ContextDefinitions = new List <ParagraphUnitContext>();
                            projectFileInfo.ParagraphInfos.Add(paragraphInfos);
                        }
                    }
                }
            }
        }
 private ProjectFileInfo ReloadProject(ProjectFileInfo projectFileInfo)
     => LoadOrReloadProject(projectFileInfo.FilePath, () => projectFileInfo.Reload(_projectLoader));
        private void UpdateProject(ProjectFileInfo projectFileInfo)
        {
            var project = _workspace.CurrentSolution.GetProject(projectFileInfo.WorkspaceId);

            var unusedDocuments = project.Documents.ToDictionary(d => d.FilePath, d => d.Id);

            foreach (var file in projectFileInfo.SourceFiles)
            {
                if (unusedDocuments.Remove(file))
                {
                    continue;
                }

                using (var stream = File.OpenRead(file))
                {
                    var sourceText = SourceText.From(stream, encoding: Encoding.UTF8);
                    var id = DocumentId.CreateNewId(projectFileInfo.WorkspaceId);
                    var version = VersionStamp.Create();

                    var loader = TextLoader.From(TextAndVersion.Create(sourceText, version));

                    _workspace.AddDocument(DocumentInfo.Create(id, file, filePath: file, loader: loader));
                }
            }

            foreach (var unused in unusedDocuments)
            {
                _workspace.RemoveDocument(unused.Value);
            }

            var unusedProjectReferences = new HashSet<ProjectReference>(project.ProjectReferences);

            foreach (var projectReferencePath in projectFileInfo.ProjectReferences)
            {
                ProjectFileInfo projectReferenceInfo;
                if (_context.Projects.TryGetValue(projectReferencePath, out projectReferenceInfo))
                {
                    var reference = new ProjectReference(projectReferenceInfo.WorkspaceId);

                    if (unusedProjectReferences.Remove(reference))
                    {
                        // This reference already exists
                        continue;
                    }

                    _workspace.AddProjectReference(project.Id, reference);
                }
                else
                {
                    _logger.WriteWarning(string.Format("Unable to resolve project reference '{0}' for '{1}'.", projectReferencePath, projectFileInfo.ProjectFilePath));
                }
            }

            foreach (var unused in unusedProjectReferences)
            {
                _workspace.RemoveProjectReference(project.Id, unused);
            }

            var unusedAnalyzers = new Dictionary<string, AnalyzerReference>(project.AnalyzerReferences.ToDictionary(a => a.FullPath));

            foreach (var analyzerPath in projectFileInfo.Analyzers)
            {
                if (!File.Exists(analyzerPath))
                {
                    _logger.WriteWarning(string.Format("Unable to resolve assembly '{0}'", analyzerPath));
                }
                else
                {
                    if (unusedAnalyzers.Remove(analyzerPath))
                    {
                        continue;
                    }
#if ASPNET50
                    var analyzerReference = new AnalyzerFileReference(analyzerPath);
                    project.AddAnalyzerReference(analyzerReference);
#endif
                }
            }

            foreach (var analyzerReference in unusedAnalyzers.Values)
            {
                project.RemoveAnalyzerReference(analyzerReference);
            }

            var unusedReferences = new HashSet<MetadataReference>(project.MetadataReferences);

            foreach (var referencePath in projectFileInfo.References)
            {
                if (!File.Exists(referencePath))
                {
                    _logger.WriteWarning(string.Format("Unable to resolve assembly '{0}'", referencePath));
                }
                else
                {
                    var metadataReference = _metadataReferenceCache.GetMetadataReference(referencePath);

                    if (unusedReferences.Remove(metadataReference))
                    {
                        continue;
                    }

                    _logger.WriteVerbose(string.Format("Adding reference '{0}' to '{1}'.", referencePath, projectFileInfo.ProjectFilePath));
                    _workspace.AddMetadataReference(project.Id, metadataReference);
                }
            }

            foreach (var reference in unusedReferences)
            {
                _workspace.RemoveMetadataReference(project.Id, reference);
            }
        }
Beispiel #15
0
        private void UpdateProject(ProjectFileInfo projectFileInfo)
        {
            var project = _workspace.CurrentSolution.GetProject(projectFileInfo.WorkspaceId);

            var unusedDocuments = project.Documents.ToDictionary(d => d.FilePath, d => d.Id);

            foreach (var file in projectFileInfo.SourceFiles)
            {
                if (unusedDocuments.Remove(file))
                {
                    continue;
                }

                using (var stream = File.OpenRead(file))
                {
                    var sourceText = SourceText.From(stream, encoding: Encoding.UTF8);
                    var id         = DocumentId.CreateNewId(projectFileInfo.WorkspaceId);
                    var version    = VersionStamp.Create();

                    var loader = TextLoader.From(TextAndVersion.Create(sourceText, version));

                    _workspace.AddDocument(DocumentInfo.Create(id, file, filePath: file, loader: loader));
                }
            }

            foreach (var unused in unusedDocuments)
            {
                _workspace.RemoveDocument(unused.Value);
            }

            var unusedProjectReferences = new HashSet <ProjectReference>(project.ProjectReferences);

            foreach (var projectReferencePath in projectFileInfo.ProjectReferences)
            {
                ProjectFileInfo projectReferenceInfo;
                if (_context.Projects.TryGetValue(projectReferencePath, out projectReferenceInfo))
                {
                    var reference = new ProjectReference(projectReferenceInfo.WorkspaceId);

                    if (unusedProjectReferences.Remove(reference))
                    {
                        // This reference already exists
                        continue;
                    }

                    _workspace.AddProjectReference(project.Id, reference);
                }
                else
                {
                    _logger.WriteWarning(string.Format("Unable to resolve project reference '{0}' for '{1}'.", projectReferencePath, projectFileInfo.ProjectFilePath));
                }
            }

            foreach (var unused in unusedProjectReferences)
            {
                _workspace.RemoveProjectReference(project.Id, unused);
            }

            var unusedAnalyzers = new Dictionary <string, AnalyzerReference>(project.AnalyzerReferences.ToDictionary(a => a.FullPath));

            foreach (var analyzerPath in projectFileInfo.Analyzers)
            {
                if (!File.Exists(analyzerPath))
                {
                    _logger.WriteWarning(string.Format("Unable to resolve assembly '{0}'", analyzerPath));
                }
                else
                {
                    if (unusedAnalyzers.Remove(analyzerPath))
                    {
                        continue;
                    }
#if ASPNET50
                    var analyzerReference = new AnalyzerFileReference(analyzerPath);
                    project.AddAnalyzerReference(analyzerReference);
#endif
                }
            }

            foreach (var analyzerReference in unusedAnalyzers.Values)
            {
                project.RemoveAnalyzerReference(analyzerReference);
            }

            var unusedReferences = new HashSet <MetadataReference>(project.MetadataReferences);

            foreach (var referencePath in projectFileInfo.References)
            {
                if (!File.Exists(referencePath))
                {
                    _logger.WriteWarning(string.Format("Unable to resolve assembly '{0}'", referencePath));
                }
                else
                {
                    var metadataReference = _metadataReferenceCache.GetMetadataReference(referencePath);

                    if (unusedReferences.Remove(metadataReference))
                    {
                        continue;
                    }

                    _logger.WriteVerbose(string.Format("Adding reference '{0}' to '{1}'.", referencePath, projectFileInfo.ProjectFilePath));
                    _workspace.AddMetadataReference(project.Id, metadataReference);
                }
            }

            foreach (var reference in unusedReferences)
            {
                _workspace.RemoveMetadataReference(project.Id, reference);
            }
        }
        private void UpdateProject(ProjectFileInfo projectFileInfo)
        {
            var project = _workspace.CurrentSolution.GetProject(projectFileInfo.WorkspaceId);

            var unusedDocuments = project.Documents.ToDictionary(d => d.FilePath, d => d.Id);

            foreach (var file in projectFileInfo.SourceFiles)
            {
                if (unusedDocuments.Remove(file))
                {
                    continue;
                }

                using (var stream = File.OpenRead(file))
                {
                    var sourceText = SourceText.From(stream, encoding: Encoding.UTF8);
                    var id = DocumentId.CreateNewId(projectFileInfo.WorkspaceId);
                    var version = VersionStamp.Create();

                    var loader = TextLoader.From(TextAndVersion.Create(sourceText, version));

                    _workspace.AddDocument(DocumentInfo.Create(id, file, filePath: file, loader: loader));
                }
            }

            if (projectFileInfo.SpecifiedLanguageVersion.HasValue || projectFileInfo.DefineConstants != null)
            {
                var parseOptions = projectFileInfo.SpecifiedLanguageVersion.HasValue
                    ? new CSharpParseOptions(projectFileInfo.SpecifiedLanguageVersion.Value)
                    : new CSharpParseOptions();
                if (projectFileInfo.DefineConstants != null && projectFileInfo.DefineConstants.Any())
                {
                    parseOptions = parseOptions.WithPreprocessorSymbols(projectFileInfo.DefineConstants);
                }
                _workspace.SetParseOptions(project.Id, parseOptions);
            }

            foreach (var unused in unusedDocuments)
            {
                _workspace.RemoveDocument(unused.Value);
            }

            var unusedProjectReferences = new HashSet<ProjectReference>(project.ProjectReferences);

            foreach (var projectReferencePath in projectFileInfo.ProjectReferences)
            {
                ProjectFileInfo projectReferenceInfo;
                if (_context.Projects.TryGetValue(projectReferencePath, out projectReferenceInfo))
                {
                    var reference = new ProjectReference(projectReferenceInfo.WorkspaceId);

                    if (unusedProjectReferences.Remove(reference))
                    {
                        // This reference already exists
                        continue;
                    }

                    _workspace.AddProjectReference(project.Id, reference);
                }
                else
                {
                    _logger.LogWarning($"Unable to resolve project reference '{projectReferencePath}' for '{projectFileInfo}'.");
                }
            }

            foreach (var unused in unusedProjectReferences)
            {
                _workspace.RemoveProjectReference(project.Id, unused);
            }

            var unusedAnalyzers = new Dictionary<string, AnalyzerReference>(project.AnalyzerReferences.ToDictionary(a => a.FullPath));

            foreach (var analyzerPath in projectFileInfo.Analyzers)
            {
                if (!File.Exists(analyzerPath))
                {
                    _logger.LogWarning($"Unable to resolve assembly '{analyzerPath}'");
                }
                else
                {
                    if (unusedAnalyzers.Remove(analyzerPath))
                    {
                        continue;
                    }
#if DNX451
                    var analyzerReference = new AnalyzerFileReference(analyzerPath);
                    project.AddAnalyzerReference(analyzerReference);
#endif
                }
            }

            foreach (var analyzerReference in unusedAnalyzers.Values)
            {
                project.RemoveAnalyzerReference(analyzerReference);
            }

            var unusedReferences = new HashSet<MetadataReference>(project.MetadataReferences);

            foreach (var referencePath in projectFileInfo.References)
            {
                if (!File.Exists(referencePath))
                {
                    _logger.LogWarning($"Unable to resolve assembly '{referencePath}'");
                }
                else
                {
                    var metadataReference = _metadataReferenceCache.GetMetadataReference(referencePath);

                    if (unusedReferences.Remove(metadataReference))
                    {
                        continue;
                    }

                    _logger.LogVerbose($"Adding reference '{referencePath}' to '{projectFileInfo.ProjectFilePath}'.");
                    _workspace.AddMetadataReference(project.Id, metadataReference);
                }
            }

            foreach (var reference in unusedReferences)
            {
                _workspace.RemoveMetadataReference(project.Id, reference);
            }
        }
        private ImmutableArray <PackageReference> FindUnresolvedPackageReferencesInLockFile(ProjectFileInfo projectFile, LockFile lockFile)
        {
            var libraryMap = CreateLibraryMap(lockFile);

            var unresolved = ImmutableArray.CreateBuilder <PackageReference>();

            // Iterate through each package reference and see if we can find a library with the same name
            // that satisfies the reference's version range in the lock file.

            foreach (var reference in projectFile.PackageReferences)
            {
                if (!libraryMap.TryGetValue(reference.Dependency.Id, out var libraries))
                {
                    _logger.LogWarning($"{projectFile.Name}: Did not find '{reference.Dependency.Id}' in lock file.");
                    unresolved.Add(reference);
                }
                else
                {
                    var found = false;
                    foreach (var library in libraries)
                    {
                        if (reference.Dependency.VersionRange.Satisfies(library.Version))
                        {
                            found = true;
                            break;
                        }
                    }

                    if (!found)
                    {
                        var referenceText = reference.IsImplicitlyDefined
                            ? "implicit package reference"
                            : "package reference";

                        var versions = string.Join(", ", libraries.Select(l => '"' + l.Version.ToString() + '"'));

                        _logger.LogWarning($"{projectFile.Name}: Found {referenceText} '{reference.Dependency.Id}', but none of the versions in the lock file ({versions}) satisfy {reference.Dependency.VersionRange}");
                        unresolved.Add(reference);
                    }
                }
            }

            return(unresolved.ToImmutable());
        }