Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion Semantics.Music/Section.cs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@
return false;
}

if (!Enum.TryParse<SectionType>(header[1..close], out SectionType type))
if (!TryParseSectionType(header[1..close], out SectionType type))
{
return false;
}
Expand Down Expand Up @@ -163,4 +163,25 @@
result = Create(type, progression, label, key);
return true;
}

// Enum.TryParse alone also takes integers, comma-separated name lists and padded names, all of
// which ToString never writes. Only the exact name of one declared member is a section type.
private static bool TryParseSectionType(string name, out SectionType type)
{
type = default;
if (name.Length == 0)
{
return false;
}

foreach (char c in name)

Check warning on line 177 in Semantics.Music/Section.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Loops should be simplified using the "Any" LINQ method

Check warning on line 177 in Semantics.Music/Section.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Loops should be simplified using the "Any" LINQ method

Check warning on line 177 in Semantics.Music/Section.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Loops should be simplified using the "Any" LINQ method

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_Semantics&issues=AaEfLPU4nkWHhoMFDVCT&open=AaEfLPU4nkWHhoMFDVCT&pullRequest=411
{
if (c is not ((>= 'A' and <= 'Z') or (>= 'a' and <= 'z')))
{
return false;
}
}

return Enum.TryParse(name, out type) && Enum.IsDefined(type);
}
}
22 changes: 22 additions & 0 deletions Semantics.Test/Music/SectionRoundTripTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,26 @@ public void RoundTripWithLabelAndKey()
Section s = Section.Create(SectionType.Chorus, SampleProgression(), "Chorus", Key.Create(PitchClass.Create(NoteLetter.A, Accidental.Natural), Mode.Aeolian));
Assert.AreEqual(s, Section.Parse(s.ToString()));
}

[TestMethod]
[DataRow("[Verse, Chorus]\n4/4 Dm7 / G7 /")]
[DataRow("[42]\n4/4 Dm7 / G7 /")]
[DataRow("[-1]\n4/4 Dm7 / G7 /")]
[DataRow("[ Verse ]\n4/4 Dm7 / G7 /")]
[DataRow("[verse]\n4/4 Dm7 / G7 /")]
public void TryParseRejectsHeaderThatIsNotOneSectionTypeName(string text)
{
Assert.IsFalse(Section.TryParse(text, out Section? result));
Assert.IsNull(result);
}

[TestMethod]
public void TryParseAcceptsEverySectionTypeName()
{
foreach (SectionType type in Enum.GetValues<SectionType>())
{
Section s = Section.Create(type, SampleProgression());
Assert.AreEqual(s, Section.Parse(s.ToString()));
}
}
}
Loading