Пример #1
0
    public void ShouldNotCreateXsd_OnlySolutionWideConfig()
    {
        // Deliberately not writing the file in the project dir.
        if (File.Exists(xmlPath))
        {
            File.Delete(xmlPath);
        }
        File.WriteAllText(slnXmlPath, @"
<Weavers>
  <TestWeaver />
</Weavers>
");

        var weavers = new[]
        {
            new WeaverEntry
            {
                AssemblyPath = @"something\TestWeaver.Fody.dll"
            }
        };

        var configFiles = ConfigFileFinder.FindWeaverConfigFiles(slnDir, testDir, new MockBuildLogger()).ToArray();

        ConfigFileFinder.EnsureSchemaIsUpToDate(slnDir, testDir, weavers, true);

        Assert.Single(configFiles);
        Assert.Equal(slnXmlPath, configFiles[0].FilePath);

        Assert.False(File.Exists(slnXsdPath));

        var xml = XDocumentEx.Load(slnXmlPath);

        Assert.NotNull(xml.Root);
        Assert.Null(xml.Root.Attribute(schemaInstanceNamespace + "noNamespaceSchemaLocation"));
    }
Пример #2
0
    static void CreateSchemaForConfig(string projectConfigFilePath, IEnumerable <WeaverEntry> weavers)
    {
        var schema = XDocument.Parse(Fody.Properties.Resources.FodyWeavers_SchemaTemplate);

        var baseNode = schema.Descendants().First(item => item.Name == schemaNamespace.GetName("all"));

        var fragments = weavers.Select(CreateItemFragment);

        baseNode.Add(fragments);

        var filePath = Path.ChangeExtension(projectConfigFilePath, ".xsd");

        const SaveOptions saveOptions = SaveOptions.OmitDuplicateNamespaces | SaveOptions.DisableFormatting;

        if (File.Exists(filePath))
        {
            try
            {
                var existing = XDocumentEx.Load(filePath).ToString(saveOptions);
                if (string.Equals(existing, schema.ToString(saveOptions)))
                {
                    // don't touch existing file if it is up to date
                    return;
                }
            }
            catch
            {
                // invalid xsd, overwrite always...
            }
        }

        schema.Save(filePath, SaveOptions.OmitDuplicateNamespaces);
    }
Пример #3
0
    static void CreateSchemaForConfig(string projectConfigFilePath, IEnumerable <string> wellKnownWeaverFiles, IEnumerable <WeaverEntry> weavers)
    {
        var weaverFiles = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

        weaverFiles.MergeItemsFrom(weavers, GetWeaverName, weaver => weaver.AssemblyPath);
        weaverFiles.MergeItemsFrom(wellKnownWeaverFiles, WeaverNameFromFilePath);

        var schema = XDocument.Parse(Fody.Properties.Resources.FodyWeavers_SchemaTemplate);

        var baseNode = schema.Descendants().FirstOrDefault(item => item.Name == schemaNamespace.GetName("all"));

        var fragments = weaverFiles.Select(CreateItemFragment);

        baseNode.Add(fragments);

        var filePath = Path.ChangeExtension(projectConfigFilePath, ".xsd");

        try
        {
            if (File.Exists(filePath))
            {
                if (string.Equals(XDocumentEx.Load(filePath).ToString(SaveOptions.OmitDuplicateNamespaces | SaveOptions.DisableFormatting), schema.ToString(SaveOptions.OmitDuplicateNamespaces | SaveOptions.DisableFormatting)))
                {
                    // don't touch existing file if it is up to date
                    return;
                }
            }
        }
        catch
        {
            // invalid xsd, overwrite always...
        }

        schema.Save(filePath, SaveOptions.OmitDuplicateNamespaces);
    }
Пример #4
0
    public static void EnsureSchemaIsUpToDate(string projectDirectory, IEnumerable <WeaverEntry> weavers, bool defaultGenerateXsd)
    {
        try
        {
            var projectConfigFilePath = Path.Combine(projectDirectory, FodyWeaversConfigFileName);

            var doc = XDocumentEx.Load(projectConfigFilePath);

            if (!ShouldGenerateXsd(doc, defaultGenerateXsd))
            {
                return;
            }

            var hasNamespace = doc.Root.Attributes()
                               .Any(attr => !attr.IsNamespaceDeclaration &&
                                    attr.Name.LocalName == "noNamespaceSchemaLocation" &&
                                    string.Equals(attr.Value, "FodyWeavers.xsd", StringComparison.OrdinalIgnoreCase));

            if (!hasNamespace)
            {
                doc.Root.Add(SchemaInstanceAttributes);
                doc.Save(projectConfigFilePath);
            }

            CreateSchemaForConfig(projectConfigFilePath, weavers);
        }
        catch
        {
            //TODO: anything wrong with the existing, ignore here, we will warn later...
        }
    }
Пример #5
0
    public void ShouldOptOutOfXsdThroughMSBuildProperty()
    {
        File.WriteAllText(xmlPath, @"
<Weavers>
  <TestWeaver />
</Weavers>
");

        var weavers = new[] { new WeaverEntry {
                                  AssemblyPath = @"something\TestWeaver.Fody.dll"
                              } };

        var configFiles = ConfigFileFinder.FindWeaverConfigFiles(Guid.NewGuid().ToString(), testDir, new Mock <BuildLogger>().Object).ToArray();

        ConfigFileFinder.EnsureSchemaIsUpToDate(testDir, weavers, false);

        Assert.Single(configFiles);
        Assert.Equal(xmlPath, configFiles[0].FilePath);

        Assert.False(File.Exists(xsdPath));

        var xml = XDocumentEx.Load(xmlPath);

        Assert.NotNull(xml.Root);
        Assert.Null(xml.Root.Attribute(schemaInstanceNamespace + "noNamespaceSchemaLocation"));
    }
Пример #6
0
    public void XmlConfigShouldOverrideMSBuildPropertyForXsdGeneration()
    {
        File.WriteAllText(xmlPath, @"
<Weavers GenerateXsd=""true"">
  <TestWeaver />
</Weavers>
");

        var weavers = new[] { new WeaverEntry {
                                  AssemblyPath = @"something\TestWeaver.Fody.dll"
                              } };

        var configs = ConfigFileFinder.FindWeaverConfigFiles(Guid.NewGuid().ToString(), testDir, new Mock <BuildLogger>().Object).ToArray();

        ConfigFileFinder.EnsureSchemaIsUpToDate(testDir, weavers, false);

        Assert.Single(configs);
        Assert.Equal(xmlPath, configs[0].FilePath);

        Assert.True(File.Exists(xsdPath));

        var xml = XDocumentEx.Load(xmlPath);

        Assert.NotNull(xml.Root);
        Assert.Equal("FodyWeavers.xsd", xml.Root.Attribute(schemaInstanceNamespace + "noNamespaceSchemaLocation")?.Value);
    }
Пример #7
0
    public void ShouldOptOutOfXsd()
    {
        File.WriteAllText(xmlPath, @"
<Weavers GenerateXsd=""false"">
  <TestWeaver />
</Weavers>
");

        var weavers = new[]
        {
            new WeaverEntry
            {
                AssemblyPath = @"something\TestWeaver.Fody.dll"
            }
        };

        var configFiles = ConfigFileFinder.FindWeaverConfigFiles(slnDir, testDir, new MockBuildLogger()).ToArray();

        ConfigFileFinder.EnsureSchemaIsUpToDate(slnDir, testDir, weavers, true);

        Assert.Single(configFiles);
        Assert.Equal(xmlPath, configFiles[0].FilePath);

        Assert.False(File.Exists(xsdPath));

        var xml = XDocumentEx.Load(xmlPath);

        Assert.NotNull(xml.Root);
        Assert.Null(xml.Root.Attribute(schemaInstanceNamespace + "noNamespaceSchemaLocation"));
    }
Пример #8
0
    public static void EnsureSchemaIsUpToDate(string projectDirectory, IEnumerable <WeaverEntry> weavers, bool defaultGenerateXsd)
    {
        var projectConfigFilePath = Path.Combine(projectDirectory, FodyWeaversConfigFileName);

        try
        {
            var doc = XDocumentEx.Load(projectConfigFilePath);

            if (!ShouldGenerateXsd(doc, defaultGenerateXsd))
            {
                return;
            }

            var hasNamespace = doc.Root.Attributes()
                               .Any(attr => !attr.IsNamespaceDeclaration &&
                                    attr.Name.LocalName == "noNamespaceSchemaLocation" &&
                                    string.Equals(attr.Value, "FodyWeavers.xsd", StringComparison.OrdinalIgnoreCase));

            if (!hasNamespace)
            {
                doc.Root.Add(SchemaInstanceAttributes);
                doc.Save(projectConfigFilePath);
            }

            CreateSchemaForConfig(projectConfigFilePath, weavers);
        }
        catch (Exception exception)
        {
            throw new WeavingException($"Failed to update schema for ({projectConfigFilePath}). Exception message: {exception.Message}");
        }
    }
Пример #9
0
    public void Invalid()
    {
        var path = @"Fody\ProjectWeaversReaderTests\Invalid.txt";

        var exception = Assert.Throws <WeavingException>(() => XDocumentEx.Load(path));

        Approvals.Verify(exception.Message);
    }
Пример #10
0
    public Task Invalid()
    {
        var path = @"Fody\ProjectWeaversReaderTests\Invalid.txt";

        var exception = Assert.ThrowsAny <Exception>(() => XDocumentEx.Load(path));

        return(VerifyXunit.Verifier.Verify(exception !.Message));
    }
Пример #11
0
    public void Invalid()
    {
        var currentDirectory = AssemblyLocation.CurrentDirectory;
        var path             = Path.Combine(currentDirectory, @"Fody\ProjectWeaversReaderTests\Invalid.txt");

        var exception = Assert.Throws <WeavingException>(() => XDocumentEx.Load(path));

        Approvals.Verify(exception.Message.Replace(currentDirectory, ""));
    }
Пример #12
0
 public static XDocument GetDocument(string configFile)
 {
     try
     {
         return(XDocumentEx.Load(configFile));
     }
     catch (XmlException exception)
     {
         throw new WeavingException($"Could not read '{configFile}' because it has invalid xml. Message: '{exception.Message}'.");
     }
 }
Пример #13
0
 public static bool ExtractVerifyAssemblyFromConfigs(List <string> weaverConfigs)
 {
     foreach (var configFile in weaverConfigs)
     {
         var configXml = XDocumentEx.Load(configFile);
         var element   = configXml.Root;
         if (element.TryReadBool("VerifyAssembly", out var value))
         {
             return(value);
         }
     }
     return(false);
 }
Пример #14
0
        /// <summary>
        /// コンストラクタ
        /// </summary>
        /// <param name="modDirPath">Modのフォルダパス(絶対パスで指定すること)</param>
        public ModInfo(string modDirPath)
        {
            var contentXmlPatth = Path.Combine(modDirPath, "content.xml");
            var xml             = XDocumentEx.Load(contentXmlPatth);

            ID      = xml.Root?.Attribute("id")?.Value ?? "";
            Name    = xml.Root?.Attribute("name")?.Value ?? "";
            Author  = xml.Root?.Attribute("author")?.Value ?? "";
            Version = xml.Root?.Attribute("version")?.Value ?? "";
            Date    = xml.Root?.Attribute("date")?.Value ?? "";
            Enabled = xml.Root?.Attribute("enabled")?.Value ?? "";
            Save    = xml.Root?.Attribute("save")?.Value ?? "";
        }
Пример #15
0
 public static IEnumerable <string> ExtractVerifyIgnoreCodesConfigs(List <string> weaverConfigs)
 {
     foreach (var configFile in weaverConfigs)
     {
         var configXml    = XDocumentEx.Load(configFile);
         var element      = configXml.Root;
         var codesConfigs = (string)element.Attribute("VerifyIgnoreCodes");
         if (string.IsNullOrWhiteSpace(codesConfigs))
         {
             continue;
         }
         foreach (var value in codesConfigs.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
         {
             yield return(value);
         }
     }
 }
Пример #16
0
    static string Inner(string nugetConfigPath)
    {
        if (!File.Exists(nugetConfigPath))
        {
            return(null);
        }

        XDocument xDocument;

        try
        {
            xDocument = XDocumentEx.Load(nugetConfigPath);
        }
        catch (XmlException)
        {
            return(null);
        }

        var repositoryPath = xDocument.Descendants("repositoryPath")
                             .Select(x => x.Value)
                             .FirstOrDefault(x => !string.IsNullOrWhiteSpace(x));

        if (repositoryPath != null)
        {
            return(Path.Combine(Path.GetDirectoryName(nugetConfigPath), repositoryPath));
        }

        repositoryPath = xDocument.Descendants("add")
                         .Where(x => string.Equals((string)x.Attribute("key"), "repositoryPath", StringComparison.OrdinalIgnoreCase))
                         .Select(x => x.Attribute("value"))
                         .Where(x => x != null)
                         .Select(x => x.Value)
                         .FirstOrDefault();
        if (repositoryPath == null)
        {
            return(null);
        }

        if (repositoryPath.StartsWith("$\\"))
        {
            return(repositoryPath.Replace("$", Path.Combine(Path.GetDirectoryName(nugetConfigPath))));
        }

        return(Path.Combine(Path.GetDirectoryName(nugetConfigPath), repositoryPath));
    }
Пример #17
0
    public void ShouldOptOutOfXsd()
    {
        File.WriteAllText(xmlPath, @"
<Weavers GenerateXsd=""false"">
  <TestWeaver />
</Weavers>
");

        var wellKnownWeaverFiles = new[] { @"something\TestWeaver.Fody.dll" };

        var configs = ConfigFile.FindWeaverConfigs(Guid.NewGuid().ToString(), testDir, new Mock <BuildLogger>().Object, wellKnownWeaverFiles, true);

        ConfigFile.EnsureSchemaIsUpToDate(testDir, wellKnownWeaverFiles, null, true);

        Assert.Single(configs);
        Assert.Equal(xmlPath, configs[0]);

        Assert.False(File.Exists(xsdPath));

        var xml = XDocumentEx.Load(xmlPath);

        Assert.NotNull(xml.Root);
        Assert.Null(xml.Root.Attribute(schemaInstanceNamespace + "noNamespaceSchemaLocation"));
    }
Пример #18
0
    public void ShouldCreateXsd()
    {
        File.WriteAllText(xmlPath, @"
<Weavers>
  <TestWeaver />
</Weavers>
");

        File.WriteAllText(Path.Combine(testDir, "WeaverWithSchema.Fody.xcf"), @"
<xs:complexType xmlns:xs=""http://www.w3.org/2001/XMLSchema"">
  <xs:attribute name=""TestAttribute"" type=""xs:string"" />
</xs:complexType>
");

        var weavers = new[]
        {
            new WeaverEntry {
                AssemblyPath = @"something\TestWeaver.Fody.dll"
            },
            new WeaverEntry {
                AssemblyPath = Path.Combine(testDir, "WeaverWithSchema.Fody.dll")
            }
        };

        var configFiles = ConfigFileFinder.FindWeaverConfigFiles(Guid.NewGuid().ToString(), testDir, new Mock <BuildLogger>().Object).ToArray();

        ConfigFileFinder.EnsureSchemaIsUpToDate(testDir, weavers, true);

        Assert.Single(configFiles);
        Assert.False(configFiles[0].IsGlobal);
        Assert.Equal(xmlPath, configFiles[0].FilePath);

        Assert.True(File.Exists(xsdPath));

        var xml = XDocumentEx.Load(xmlPath);

        Assert.NotNull(xml.Root);
        Assert.Equal("FodyWeavers.xsd", xml.Root.Attribute(schemaInstanceNamespace + "noNamespaceSchemaLocation")?.Value);

        var xsd = XDocumentEx.Load(xsdPath);

        Assert.NotNull(xsd.Root);
        var elements = xsd.Root.Descendants(schemaNamespace + "all").First().Elements().ToList();

        Assert.Equal(2, elements.Count);

        var defaultElem = elements[0];

        Assert.Equal("element", defaultElem.Name.LocalName);
        Assert.Equal("TestWeaver", defaultElem.Attribute("name")?.Value);
        Assert.Equal("xs:anyType", defaultElem.Attribute("type")?.Value);
        Assert.Equal("0", defaultElem.Attribute("minOccurs")?.Value);
        Assert.Equal("1", defaultElem.Attribute("maxOccurs")?.Value);

        var elemWithSchema = elements[1];

        Assert.Equal("element", elemWithSchema.Name.LocalName);
        Assert.Equal("WeaverWithSchema", elemWithSchema.Attribute("name")?.Value);
        Assert.Null(elemWithSchema.Attribute("type"));
        Assert.Equal("0", elemWithSchema.Attribute("minOccurs")?.Value);
        Assert.Equal("1", elemWithSchema.Attribute("maxOccurs")?.Value);

        var elemWithSchemaType = Assert.Single(elemWithSchema.Elements());

        Assert.NotNull(elemWithSchemaType);
        Assert.Equal("complexType", elemWithSchemaType.Name.LocalName);

        var elemWithSchemaTypeAttr = Assert.Single(elemWithSchemaType.Elements());

        Assert.NotNull(elemWithSchemaTypeAttr);
        Assert.Equal("attribute", elemWithSchemaTypeAttr.Name.LocalName);
        Assert.Equal("TestAttribute", elemWithSchemaTypeAttr.Attribute("name")?.Value);
    }
Пример #19
0
 public WeaverConfigFile(string filePath, bool allowExtraEntries = false)
 {
     AllowExtraEntries = allowExtraEntries;
     FilePath          = filePath;
     Document          = XDocumentEx.Load(FilePath);
 }
Пример #20
0
        public void Utf8WithBom(string source)
        {
            var stream = new MemoryStream(Bom.Concat(Encoding.UTF8.GetBytes(source)).ToArray());

            XDocumentEx.Load(stream);
        }
Пример #21
0
        public void Utf8(string source)
        {
            var stream = new MemoryStream(Encoding.UTF8.GetBytes(source));

            XDocumentEx.Load(stream);
        }
Пример #22
0
 public WeaverConfigFile(string filePath)
 {
     FilePath = filePath;
     Document = XDocumentEx.Load(FilePath);
 }