Compare commits
6
Commits
v0.1.0
...
b5614ff59b
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b5614ff59b | ||
|
|
e2bb0298b1 | ||
|
|
01367edaa9 | ||
|
|
31fc58d9c7 | ||
|
|
e934eb9629 | ||
|
|
6050a70f4b |
No files matched your search
@@ -0,0 +1,171 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using YKanBan.Export;
|
||||||
|
using YKanBan.Models;
|
||||||
|
|
||||||
|
namespace YKanBan.Tests.Export;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Tests for the Markdown exporter. Mutates the global Resources.Culture,
|
||||||
|
/// therefore marked DoNotParallelize. Asserts real localized output for
|
||||||
|
/// both supported languages.
|
||||||
|
/// </summary>
|
||||||
|
[TestClass]
|
||||||
|
[DoNotParallelize]
|
||||||
|
public class MarkdownExporterTests
|
||||||
|
{
|
||||||
|
private static readonly DateTimeOffset ExportedAt = new(2026, 9, 30, 14, 25, 37, TimeSpan.Zero);
|
||||||
|
|
||||||
|
/// <summary>A local wall-clock moment, matching the exporter's conversion path.</summary>
|
||||||
|
private static DateTimeOffset Local(int year, int month, int day, int hour, int minute) =>
|
||||||
|
new DateTimeOffset(new DateTime(year, month, day, hour, minute, 0)).ToLocalTime();
|
||||||
|
|
||||||
|
/// <summary>Unix seconds for a local wall-clock time.</summary>
|
||||||
|
private static long UnixTimeOf(int year, int month, int day, int hour, int minute) =>
|
||||||
|
Local(year, month, day, hour, minute).ToUnixTimeSeconds();
|
||||||
|
|
||||||
|
/// <summary>Builds the board fixture: one working column with two cards, one empty column, two tags.</summary>
|
||||||
|
private static (IReadOnlyList<ColumnModel> Columns, IReadOnlyList<CardModel> Cards, IReadOnlyList<(TagModel, long)> Tags) CreateBoard()
|
||||||
|
{
|
||||||
|
long created = UnixTimeOf(2026, 9, 1, 10, 0);
|
||||||
|
long updated = UnixTimeOf(2026, 9, 28, 18, 30);
|
||||||
|
|
||||||
|
var columns = new List<ColumnModel>
|
||||||
|
{
|
||||||
|
new(1, "In Progress", "The work column", 100, 100),
|
||||||
|
new(2, "Empty", string.Empty, 100, 100),
|
||||||
|
};
|
||||||
|
var bug = new TagModel(1, "bug", RgbColor.Parse("#ff0000"), string.Empty);
|
||||||
|
var ui = new TagModel(2, "ui", RgbColor.Parse("#00ff00"), "Interface work");
|
||||||
|
var cards = new List<CardModel>
|
||||||
|
{
|
||||||
|
new(61, 1, "Fix login", "Body text", created, updated, [bug, ui]),
|
||||||
|
new(62, 1, string.Empty, string.Empty, created, updated, []),
|
||||||
|
};
|
||||||
|
var tags = new List<(TagModel, long)> { (bug, 1), (ui, 1) };
|
||||||
|
return (columns, cards, tags);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Export(CultureInfo culture)
|
||||||
|
{
|
||||||
|
CultureInfo? original = Resources.Culture;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Resources.Culture = culture;
|
||||||
|
(IReadOnlyList<ColumnModel> columns, IReadOnlyList<CardModel> cards, IReadOnlyList<(TagModel, long)> tags) = CreateBoard();
|
||||||
|
return MarkdownExporter.Export("MyRepo", columns, cards, tags, ExportedAt);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Resources.Culture = original;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Normalize(string text) => text.Replace("\r\n", "\n");
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void EnglishOutputMatchesTemplate()
|
||||||
|
{
|
||||||
|
string created = Local(2026, 9, 1, 10, 0).ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
|
||||||
|
string updated = Local(2026, 9, 28, 18, 30).ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
|
||||||
|
|
||||||
|
string expected = Normalize($"""
|
||||||
|
# MyRepo
|
||||||
|
> Exported at: 2026-09-30 14:25:37
|
||||||
|
|
||||||
|
## Column: In Progress (2)
|
||||||
|
The work column
|
||||||
|
|
||||||
|
### #61 Fix login
|
||||||
|
Body text
|
||||||
|
- Tags: `bug` `ui`
|
||||||
|
- Created: {created} Modified: {updated}
|
||||||
|
|
||||||
|
### #62
|
||||||
|
- Created: {created} Modified: {updated}
|
||||||
|
|
||||||
|
## Column: Empty (0)
|
||||||
|
|
||||||
|
## Tags
|
||||||
|
| Name | Color | Description | Usage |
|
||||||
|
|---|---|---|---|
|
||||||
|
| bug | #ff0000 | | 1 |
|
||||||
|
| ui | #00ff00 | Interface work | 1 |
|
||||||
|
""");
|
||||||
|
|
||||||
|
Assert.AreEqual(expected + "\n", Normalize(Export(new CultureInfo("en"))));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void ChineseOutputMatchesTemplate()
|
||||||
|
{
|
||||||
|
var chinese = new CultureInfo("zh-Hans");
|
||||||
|
string created = Local(2026, 9, 1, 10, 0).ToString("yyyy年M月d日 HH:mm", chinese);
|
||||||
|
string updated = Local(2026, 9, 28, 18, 30).ToString("yyyy年M月d日 HH:mm", chinese);
|
||||||
|
|
||||||
|
string expected = Normalize($"""
|
||||||
|
# MyRepo
|
||||||
|
> 导出时间:2026年9月30日 14:25
|
||||||
|
|
||||||
|
## 列:In Progress(2)
|
||||||
|
The work column
|
||||||
|
|
||||||
|
### #61 Fix login
|
||||||
|
Body text
|
||||||
|
- 标签:`bug` `ui`
|
||||||
|
- 创建:{created} 修改:{updated}
|
||||||
|
|
||||||
|
### #62
|
||||||
|
- 创建:{created} 修改:{updated}
|
||||||
|
|
||||||
|
## 列:Empty(0)
|
||||||
|
|
||||||
|
## 标签总表
|
||||||
|
| 名称 | 颜色 | 描述 | 使用数 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| bug | #ff0000 | | 1 |
|
||||||
|
| ui | #00ff00 | Interface work | 1 |
|
||||||
|
""");
|
||||||
|
|
||||||
|
Assert.AreEqual(expected + "\n", Normalize(Export(new CultureInfo("zh-Hans"))));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void FileNameFollowsLanguage()
|
||||||
|
{
|
||||||
|
CultureInfo? original = Resources.Culture;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Resources.Culture = new CultureInfo("en");
|
||||||
|
Assert.AreEqual("MyRepo-export-20260930-142537.md", MarkdownExporter.BuildFileName("MyRepo", ExportedAt));
|
||||||
|
|
||||||
|
Resources.Culture = new CultureInfo("zh-Hans");
|
||||||
|
Assert.AreEqual("MyRepo-导出-20260930-142537.md", MarkdownExporter.BuildFileName("MyRepo", ExportedAt));
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Resources.Culture = original;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TagTableCellsEscapePipesAndLineBreaks()
|
||||||
|
{
|
||||||
|
CultureInfo? original = Resources.Culture;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Resources.Culture = new CultureInfo("en");
|
||||||
|
var tag = new TagModel(1, "a|b", RgbColor.Parse("#112233"), "first\nsecond");
|
||||||
|
string markdown = MarkdownExporter.Export("W",
|
||||||
|
[new ColumnModel(1, "C", string.Empty, 1, 1)],
|
||||||
|
[],
|
||||||
|
[(tag, 0L)],
|
||||||
|
ExportedAt);
|
||||||
|
|
||||||
|
StringAssert.Contains(markdown, "| a\\|b | #112233 | first second | 0 |");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Resources.Culture = original;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
using YKanBan.Models;
|
||||||
|
|
||||||
|
namespace YKanBan.Tests.Models;
|
||||||
|
|
||||||
|
/// <summary>Tests for the RGB color value type and its #RRGGBB text conversions.</summary>
|
||||||
|
[TestClass]
|
||||||
|
public class RgbColorTests
|
||||||
|
{
|
||||||
|
[TestMethod]
|
||||||
|
public void ParseExtractsComponents()
|
||||||
|
{
|
||||||
|
RgbColor color = RgbColor.Parse("#ff0a00");
|
||||||
|
Assert.AreEqual(new RgbColor(0xFF, 0x0A, 0x00), color);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void ParseAcceptsUppercaseAndMixedCaseHex()
|
||||||
|
{
|
||||||
|
Assert.AreEqual(new RgbColor(0xAB, 0xCD, 0xEF), RgbColor.Parse("#ABCDEF"));
|
||||||
|
Assert.AreEqual(new RgbColor(0xAB, 0xCD, 0xEF), RgbColor.Parse("#aBcDeF"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[DataRow("ff0000")]
|
||||||
|
[DataRow("#ff000")]
|
||||||
|
[DataRow("#ff00000")]
|
||||||
|
[DataRow("#gg0000")]
|
||||||
|
[DataRow("#ff 000")]
|
||||||
|
[DataRow(" #ff0000")]
|
||||||
|
[DataRow("#ff0000 ")]
|
||||||
|
[DataRow("#")]
|
||||||
|
[DataRow("")]
|
||||||
|
public void TryParseRejectsMalformedText(string text)
|
||||||
|
{
|
||||||
|
Assert.IsFalse(RgbColor.TryParse(text, out _));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TryParseRejectsNull()
|
||||||
|
{
|
||||||
|
Assert.IsFalse(RgbColor.TryParse(null, out _));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void ParseThrowsFormatExceptionForMalformedText()
|
||||||
|
{
|
||||||
|
Assert.ThrowsExactly<FormatException>(() => RgbColor.Parse("red"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void ToStringProducesCanonicalLowercaseForm()
|
||||||
|
{
|
||||||
|
Assert.AreEqual("#ee0a0a", new RgbColor(0xEE, 0x0A, 0x0A).ToString());
|
||||||
|
|
||||||
|
// Uppercase input normalizes to the canonical lowercase output.
|
||||||
|
Assert.AreEqual("#ee0a0a", RgbColor.Parse("#EE0A0A").ToString());
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void EqualityComparesComponents()
|
||||||
|
{
|
||||||
|
Assert.AreEqual(RgbColor.Parse("#ff0000"), RgbColor.Parse("#FF0000"));
|
||||||
|
Assert.AreNotEqual(RgbColor.Parse("#ff0000"), RgbColor.Parse("#ff0001"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TextRoundTripPreservesColor()
|
||||||
|
{
|
||||||
|
RgbColor original = new(0x12, 0x34, 0x56);
|
||||||
|
Assert.AreEqual(original, RgbColor.Parse(original.ToString()));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
using YKanBan.Platform;
|
||||||
|
using YKanBan.Tests.TestUtilities;
|
||||||
|
|
||||||
|
namespace YKanBan.Tests.Platform;
|
||||||
|
|
||||||
|
/// <summary>Tests for path normalization and platform-parameterized comparison.</summary>
|
||||||
|
[TestClass]
|
||||||
|
public class PathComparerTests
|
||||||
|
{
|
||||||
|
[TestMethod]
|
||||||
|
public void OrdinalComparerTreatsCaseAsSignificant()
|
||||||
|
{
|
||||||
|
// Unix-style rule, injected so it is testable on any host.
|
||||||
|
var comparer = new PathComparer(ignoreCase: false);
|
||||||
|
Assert.IsFalse(comparer.Equals(@"C:\A", @"C:\a"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void IgnoreCaseComparerTreatsCaseAsInsignificant()
|
||||||
|
{
|
||||||
|
// Windows-style rule.
|
||||||
|
var comparer = new PathComparer(ignoreCase: true);
|
||||||
|
Assert.IsTrue(comparer.Equals(@"C:\A", @"c:\a"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void EqualPathsProduceEqualHashCodes()
|
||||||
|
{
|
||||||
|
var comparer = new PathComparer(ignoreCase: true);
|
||||||
|
Assert.AreEqual(
|
||||||
|
comparer.GetHashCode(@"C:\Users\Data\MyRepo"),
|
||||||
|
comparer.GetHashCode(@"c:\users\data\myrepo"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void RelativeSegmentsCollapse()
|
||||||
|
{
|
||||||
|
var comparer = new PathComparer(ignoreCase: true);
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
|
||||||
|
string viaParent = Path.Combine(directory.FullPath, "x", "..", "a");
|
||||||
|
string direct = Path.Combine(directory.FullPath, "a");
|
||||||
|
|
||||||
|
Assert.IsTrue(comparer.Equals(viaParent, direct));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void SeparatorStylesUnify()
|
||||||
|
{
|
||||||
|
var comparer = new PathComparer(ignoreCase: true);
|
||||||
|
|
||||||
|
Assert.IsTrue(comparer.Equals(@"C:\a/b\c", @"C:\a\b\c"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TrailingSeparatorIsTrimmedForNonRoots()
|
||||||
|
{
|
||||||
|
var comparer = new PathComparer(ignoreCase: true);
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
|
||||||
|
string withTrailing = directory.FullPath + Path.DirectorySeparatorChar;
|
||||||
|
Assert.IsTrue(comparer.Equals(withTrailing, directory.FullPath));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void NormalizeReturnsCanonicalAbsoluteForm()
|
||||||
|
{
|
||||||
|
var comparer = new PathComparer(ignoreCase: false);
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
|
||||||
|
string withRelativeSegment = Path.Combine(directory.FullPath, "sub", "..");
|
||||||
|
Assert.AreEqual(directory.FullPath, comparer.Normalize(withRelativeSegment));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void RootPathKeepsItsTrailingSeparator()
|
||||||
|
{
|
||||||
|
var comparer = new PathComparer(ignoreCase: true);
|
||||||
|
|
||||||
|
Assert.AreEqual(@"C:\", comparer.Normalize(@"C:\"));
|
||||||
|
Assert.AreEqual(@"C:\x", comparer.Normalize(@"C:\x\"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void ForCurrentPlatformMatchesHostRule()
|
||||||
|
{
|
||||||
|
PathComparer comparer = PathComparer.ForCurrentPlatform();
|
||||||
|
|
||||||
|
Assert.AreEqual(
|
||||||
|
OperatingSystem.IsWindows(),
|
||||||
|
comparer.Equals(@"C:\Same", @"c:\same"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
using YKanBan.Search;
|
||||||
|
|
||||||
|
namespace YKanBan.Tests.Search;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Structural comparer for search AST nodes, used by assertions only. The
|
||||||
|
/// AST records compare by reference for their Terms collections by design
|
||||||
|
/// (see the YYC MARK note in SearchNodes.cs), so tests provide equality
|
||||||
|
/// explicitly.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class SearchNodeComparer : IEqualityComparer<SearchNode>
|
||||||
|
{
|
||||||
|
/// <summary>Shared comparer instance.</summary>
|
||||||
|
public static SearchNodeComparer Instance { get; } = new();
|
||||||
|
|
||||||
|
/// <summary>Determines structural equality of two nodes.</summary>
|
||||||
|
public bool Equals(SearchNode? x, SearchNode? y)
|
||||||
|
{
|
||||||
|
if (ReferenceEquals(x, y))
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (x is null || y is null || x.GetType() != y.GetType())
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (x, y) switch
|
||||||
|
{
|
||||||
|
(SearchNode.Or a, SearchNode.Or b) => SequencesEqual(a.Terms, b.Terms),
|
||||||
|
(SearchNode.And a, SearchNode.And b) => SequencesEqual(a.Terms, b.Terms),
|
||||||
|
(SearchNode.FreeText a, SearchNode.FreeText b) => a.Text == b.Text,
|
||||||
|
(SearchNode.FieldText a, SearchNode.FieldText b) => a.Field == b.Field && a.Text == b.Text,
|
||||||
|
(SearchNode.TagName a, SearchNode.TagName b) => a.Name == b.Name,
|
||||||
|
(SearchNode.ColumnTitle a, SearchNode.ColumnTitle b) => a.Title == b.Title,
|
||||||
|
(SearchNode.CardId a, SearchNode.CardId b) => a.Id == b.Id,
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Not supported: the comparer exists for assertions, not hashing.</summary>
|
||||||
|
public int GetHashCode(SearchNode obj) =>
|
||||||
|
throw new NotSupportedException("Structural comparison for assertions only; hashing is not supported.");
|
||||||
|
|
||||||
|
/// <summary>Order-sensitive element-wise comparison.</summary>
|
||||||
|
private static bool SequencesEqual(IReadOnlyList<SearchNode> x, IReadOnlyList<SearchNode> y)
|
||||||
|
{
|
||||||
|
if (x.Count != y.Count)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return Enumerable.Zip(x, y, (a, b) => (a, b)).All(pair => Instance.Equals(pair.a, pair.b));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,222 @@
|
|||||||
|
using YKanBan.Search;
|
||||||
|
|
||||||
|
namespace YKanBan.Tests.Search;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Tests for the search parser: the full grammar branches plus the strict
|
||||||
|
/// failure behavior (malformed input always throws SearchSyntaxException).
|
||||||
|
/// </summary>
|
||||||
|
[TestClass]
|
||||||
|
public class SearchQueryParserTests
|
||||||
|
{
|
||||||
|
/// <summary>Parses and asserts structural equality against the expected AST.</summary>
|
||||||
|
private static void AssertParsesTo(SearchNode expected, string text)
|
||||||
|
{
|
||||||
|
SearchNode? parsed = SearchQueryParser.Parse(text);
|
||||||
|
Assert.IsNotNull(parsed, $"Blank-looking input: '{text}'.");
|
||||||
|
Assert.AreEqual(expected, parsed, SearchNodeComparer.Instance);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Asserts that the input violates the grammar.</summary>
|
||||||
|
private static void AssertSyntaxError(string text)
|
||||||
|
{
|
||||||
|
Assert.ThrowsExactly<SearchSyntaxException>(() => SearchQueryParser.Parse(text));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void BlankInputReturnsNull()
|
||||||
|
{
|
||||||
|
Assert.IsNull(SearchQueryParser.Parse(string.Empty));
|
||||||
|
Assert.IsNull(SearchQueryParser.Parse(" "));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void SingleWordIsFreeText()
|
||||||
|
{
|
||||||
|
AssertParsesTo(new SearchNode.FreeText("login"), "login");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void AdjacentWordsAreImplicitAnd()
|
||||||
|
{
|
||||||
|
AssertParsesTo(
|
||||||
|
new SearchNode.And([new SearchNode.FreeText("fix"), new SearchNode.FreeText("login")]),
|
||||||
|
"fix login");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void ExplicitAndKeyword()
|
||||||
|
{
|
||||||
|
AssertParsesTo(
|
||||||
|
new SearchNode.And([new SearchNode.FreeText("a"), new SearchNode.FreeText("b")]),
|
||||||
|
"a AND b");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void OrKeyword()
|
||||||
|
{
|
||||||
|
AssertParsesTo(
|
||||||
|
new SearchNode.Or([new SearchNode.FreeText("a"), new SearchNode.FreeText("b")]),
|
||||||
|
"a OR b");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void ImplicitAndBindsTighterThanOr()
|
||||||
|
{
|
||||||
|
AssertParsesTo(
|
||||||
|
new SearchNode.Or([
|
||||||
|
new SearchNode.And([new SearchNode.FreeText("a"), new SearchNode.FreeText("b")]),
|
||||||
|
new SearchNode.FreeText("c")]),
|
||||||
|
"a b OR c");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void ParenthesesForceGrouping()
|
||||||
|
{
|
||||||
|
AssertParsesTo(
|
||||||
|
new SearchNode.And([
|
||||||
|
new SearchNode.FreeText("a"),
|
||||||
|
new SearchNode.Or([new SearchNode.FreeText("b"), new SearchNode.FreeText("c")])]),
|
||||||
|
"a (b OR c)");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void NestedParenthesesCollapse()
|
||||||
|
{
|
||||||
|
AssertParsesTo(
|
||||||
|
new SearchNode.Or([new SearchNode.FreeText("a"), new SearchNode.FreeText("b")]),
|
||||||
|
"((a OR b))");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void LowercaseKeywordsArePlainWords()
|
||||||
|
{
|
||||||
|
AssertParsesTo(
|
||||||
|
new SearchNode.And([
|
||||||
|
new SearchNode.FreeText("a"),
|
||||||
|
new SearchNode.FreeText("and"),
|
||||||
|
new SearchNode.FreeText("or"),
|
||||||
|
new SearchNode.FreeText("b")]),
|
||||||
|
"a and or b");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void PhraseIsFreeText()
|
||||||
|
{
|
||||||
|
AssertParsesTo(new SearchNode.FreeText("hello world"), "\"hello world\"");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void PhraseSupportsEscapes()
|
||||||
|
{
|
||||||
|
// Escaped quote, escaped backslash, and a lone backslash kept literally.
|
||||||
|
AssertParsesTo(new SearchNode.FreeText("a\"b"), "\"a\\\"b\"");
|
||||||
|
AssertParsesTo(new SearchNode.FreeText("a\\b"), "\"a\\\\b\"");
|
||||||
|
AssertParsesTo(new SearchNode.FreeText("C:\\x"), "\"C:\\x\"");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TagQualifier()
|
||||||
|
{
|
||||||
|
AssertParsesTo(new SearchNode.TagName("bug"), "tag:bug");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TagQualifierAcceptsPhraseValue()
|
||||||
|
{
|
||||||
|
AssertParsesTo(new SearchNode.TagName("a b"), "tag:\"a b\"");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TitleAndContentQualifiers()
|
||||||
|
{
|
||||||
|
AssertParsesTo(new SearchNode.FieldText(SearchField.Title, "foo"), "title:foo");
|
||||||
|
AssertParsesTo(new SearchNode.FieldText(SearchField.Content, "foo"), "content:foo");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void ColumnQualifierAcceptsPhraseValue()
|
||||||
|
{
|
||||||
|
AssertParsesTo(new SearchNode.ColumnTitle("To Do"), "column:\"To Do\"");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void IdQualifierParsesNumber()
|
||||||
|
{
|
||||||
|
AssertParsesTo(new SearchNode.CardId(42), "id:42");
|
||||||
|
AssertParsesTo(new SearchNode.CardId(12), "id:\"12\"");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void QualifierKeysAreCaseSensitive()
|
||||||
|
{
|
||||||
|
AssertParsesTo(new SearchNode.FreeText("Tag:x"), "Tag:x");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void UnterminatedPhraseIsAnError()
|
||||||
|
{
|
||||||
|
AssertSyntaxError("\"abc def");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void UnbalancedOpenParenIsAnError()
|
||||||
|
{
|
||||||
|
AssertSyntaxError("(a");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void StrayCloseParenIsAnError()
|
||||||
|
{
|
||||||
|
AssertSyntaxError("a)");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void EmptyParensAreAnError()
|
||||||
|
{
|
||||||
|
AssertSyntaxError("()");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void DanglingOrIsAnError()
|
||||||
|
{
|
||||||
|
AssertSyntaxError("a OR");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void DanglingAndIsAnError()
|
||||||
|
{
|
||||||
|
AssertSyntaxError("a AND");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void LeadingAndIsAnError()
|
||||||
|
{
|
||||||
|
AssertSyntaxError("AND a");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void OperatorAtOperandPositionIsAnError()
|
||||||
|
{
|
||||||
|
AssertSyntaxError("a AND OR b");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void QualifierWithoutValueIsAnError()
|
||||||
|
{
|
||||||
|
AssertSyntaxError("tag:");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void NonNumericIdIsAnError()
|
||||||
|
{
|
||||||
|
AssertSyntaxError("id:12x");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void SyntaxErrorCarriesDescriptiveMessage()
|
||||||
|
{
|
||||||
|
SearchSyntaxException ex = Assert.ThrowsExactly<SearchSyntaxException>(() => SearchQueryParser.Parse("a AND"));
|
||||||
|
Assert.IsFalse(string.IsNullOrEmpty(ex.Message));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
using Microsoft.Data.Sqlite;
|
||||||
|
using YKanBan.Search;
|
||||||
|
using YKanBan.Storage;
|
||||||
|
using YKanBan.Storage.Workspace;
|
||||||
|
using YKanBan.Tests.TestUtilities;
|
||||||
|
|
||||||
|
namespace YKanBan.Tests.Search;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Tests for the query-to-SQL compiler, executed end-to-end against a
|
||||||
|
/// fixture workspace database.
|
||||||
|
/// </summary>
|
||||||
|
[TestClass]
|
||||||
|
public class SearchSqlCompilerTests
|
||||||
|
{
|
||||||
|
/// <summary>Owns a workspace with a fixed card/tag fixture.</summary>
|
||||||
|
private sealed class SearchFixture : IDisposable
|
||||||
|
{
|
||||||
|
public TempDirectory Directory { get; } = new();
|
||||||
|
|
||||||
|
public SqliteConnection Connection { get; }
|
||||||
|
|
||||||
|
public SearchFixture()
|
||||||
|
{
|
||||||
|
WorkspaceInitializer.Initialize(Directory.FullPath);
|
||||||
|
using (SqliteConnection setup = SqliteTestHelper.OpenWorkspace(Directory.FullPath))
|
||||||
|
{
|
||||||
|
// Columns: 1 "To Do", 2 "In Progress".
|
||||||
|
SqliteTestHelper.Exec(setup, "INSERT INTO columns (title, description, created_at, updated_at) VALUES ('To Do', '', 1, 1);");
|
||||||
|
SqliteTestHelper.Exec(setup, "INSERT INTO columns (title, description, created_at, updated_at) VALUES ('In Progress', '', 1, 1);");
|
||||||
|
|
||||||
|
// Cards: 1 titled, 2 title-or-content matches, 3 untitled, 4 wildcard chars.
|
||||||
|
SqliteTestHelper.Exec(setup, "INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES (1, 'Fix login', 'Cannot sign in', 1, 1);");
|
||||||
|
SqliteTestHelper.Exec(setup, "INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES (2, 'Green apple', 'the apple pie', 1, 1);");
|
||||||
|
SqliteTestHelper.Exec(setup, "INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES (2, '', 'banana split', 1, 1);");
|
||||||
|
SqliteTestHelper.Exec(setup, "INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES (1, '100% done', 'a_b test', 1, 1);");
|
||||||
|
|
||||||
|
// Tags: mixed case names plus one containing spaces.
|
||||||
|
SqliteTestHelper.Exec(setup, "INSERT INTO tags (name, color, description) VALUES ('Bug', '#ff0000', '');");
|
||||||
|
SqliteTestHelper.Exec(setup, "INSERT INTO tags (name, color, description) VALUES ('UI', '#00ff00', '');");
|
||||||
|
SqliteTestHelper.Exec(setup, "INSERT INTO tags (name, color, description) VALUES ('release notes', '#0000ff', '');");
|
||||||
|
SqliteTestHelper.Exec(setup, "INSERT INTO card_tags (card_id, tag_id) VALUES (1, 1);");
|
||||||
|
SqliteTestHelper.Exec(setup, "INSERT INTO card_tags (card_id, tag_id) VALUES (2, 2);");
|
||||||
|
SqliteTestHelper.Exec(setup, "INSERT INTO card_tags (card_id, tag_id) VALUES (3, 2);");
|
||||||
|
SqliteTestHelper.Exec(setup, "INSERT INTO card_tags (card_id, tag_id) VALUES (4, 3);");
|
||||||
|
}
|
||||||
|
|
||||||
|
Connection = SqliteTestHelper.OpenWorkspace(Directory.FullPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Runs a query and returns the ids of the matching cards.</summary>
|
||||||
|
public List<long> Search(string queryText)
|
||||||
|
{
|
||||||
|
SearchNode? query = SearchQueryParser.Parse(queryText);
|
||||||
|
Assert.IsNotNull(query, "Blank fixture queries are not expected here.");
|
||||||
|
CompiledSearch compiled = SearchSqlCompiler.Compile(query);
|
||||||
|
|
||||||
|
using var command = Connection.CreateCommand();
|
||||||
|
command.CommandText = $"SELECT c.id FROM cards c WHERE {compiled.Predicate} ORDER BY c.id ASC;";
|
||||||
|
foreach ((string name, object value) in compiled.Parameters)
|
||||||
|
{
|
||||||
|
command.Parameters.AddWithValue(name, value);
|
||||||
|
}
|
||||||
|
using var reader = command.ExecuteReader();
|
||||||
|
|
||||||
|
var ids = new List<long>();
|
||||||
|
while (reader.Read())
|
||||||
|
{
|
||||||
|
ids.Add(reader.GetInt64(0));
|
||||||
|
}
|
||||||
|
return ids;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
Connection.Dispose();
|
||||||
|
Directory.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void FreeTextMatchesTitleOrContentCaseInsensitively()
|
||||||
|
{
|
||||||
|
using var fixture = new SearchFixture();
|
||||||
|
CollectionAssert.AreEqual(new[] { 2L }, fixture.Search("apple"));
|
||||||
|
CollectionAssert.AreEqual(new[] { 1L }, fixture.Search("login"));
|
||||||
|
CollectionAssert.AreEqual(new[] { 2L }, fixture.Search("APPLE"));
|
||||||
|
CollectionAssert.AreEqual(new[] { 2L }, fixture.Search("pie"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void FieldQualifiersScopeToTheirField()
|
||||||
|
{
|
||||||
|
using var fixture = new SearchFixture();
|
||||||
|
CollectionAssert.AreEqual(new[] { 2L }, fixture.Search("title:apple"));
|
||||||
|
CollectionAssert.AreEqual(new[] { 3L }, fixture.Search("content:banana"));
|
||||||
|
Assert.AreEqual(0, fixture.Search("title:pie").Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TagQualifierMatchesExactlyAndCaseInsensitively()
|
||||||
|
{
|
||||||
|
using var fixture = new SearchFixture();
|
||||||
|
CollectionAssert.AreEqual(new[] { 1L }, fixture.Search("tag:bug"));
|
||||||
|
CollectionAssert.AreEqual(new[] { 2L, 3L }, fixture.Search("tag:ui"));
|
||||||
|
CollectionAssert.AreEqual(new[] { 4L }, fixture.Search("tag:\"release notes\""));
|
||||||
|
|
||||||
|
// Exact match: prefixes and substrings do not hit.
|
||||||
|
Assert.AreEqual(0, fixture.Search("tag:bu").Count);
|
||||||
|
Assert.AreEqual(0, fixture.Search("tag:release").Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void ColumnQualifierMatchesColumnTitleExactly()
|
||||||
|
{
|
||||||
|
using var fixture = new SearchFixture();
|
||||||
|
CollectionAssert.AreEqual(new[] { 1L, 4L }, fixture.Search("column:\"to do\""));
|
||||||
|
CollectionAssert.AreEqual(new[] { 2L, 3L }, fixture.Search("column:\"in progress\""));
|
||||||
|
|
||||||
|
// Not a prefix or substring match.
|
||||||
|
Assert.AreEqual(0, fixture.Search("column:To").Count);
|
||||||
|
Assert.AreEqual(0, fixture.Search("column:progress").Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void IdQualifierMatchesExactly()
|
||||||
|
{
|
||||||
|
using var fixture = new SearchFixture();
|
||||||
|
CollectionAssert.AreEqual(new[] { 3L }, fixture.Search("id:3"));
|
||||||
|
Assert.AreEqual(0, fixture.Search("id:99").Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void AndOrCombination()
|
||||||
|
{
|
||||||
|
using var fixture = new SearchFixture();
|
||||||
|
CollectionAssert.AreEqual(new[] { 2L, 3L }, fixture.Search("apple OR banana"));
|
||||||
|
CollectionAssert.AreEqual(new[] { 2L }, fixture.Search("apple AND id:2"));
|
||||||
|
Assert.AreEqual(0, fixture.Search("apple AND id:1").Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void ParenthesizedGrouping()
|
||||||
|
{
|
||||||
|
using var fixture = new SearchFixture();
|
||||||
|
|
||||||
|
// (apple OR banana) hits cards 2,3; intersected with column "In Progress" (2,3).
|
||||||
|
CollectionAssert.AreEqual(new[] { 2L, 3L }, fixture.Search("(apple OR banana) AND column:\"In Progress\""));
|
||||||
|
|
||||||
|
// ...while column "To Do" holds cards 1,4 — the intersection is empty.
|
||||||
|
Assert.AreEqual(0, fixture.Search("(apple OR banana) AND column:\"To Do\"").Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void LikeWildcardsInUserTextMatchLiterally()
|
||||||
|
{
|
||||||
|
using var fixture = new SearchFixture();
|
||||||
|
CollectionAssert.AreEqual(new[] { 4L }, fixture.Search("100%"));
|
||||||
|
CollectionAssert.AreEqual(new[] { 4L }, fixture.Search("a_b"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void CompiledPredicateUsesNamedParameters()
|
||||||
|
{
|
||||||
|
CompiledSearch compiled = SearchSqlCompiler.Compile(new SearchNode.FreeText("x"));
|
||||||
|
|
||||||
|
StringAssert.Contains(compiled.Predicate, "$p0");
|
||||||
|
StringAssert.Contains(compiled.Predicate, "$p1");
|
||||||
|
Assert.AreEqual(2, compiled.Parameters.Count);
|
||||||
|
Assert.AreEqual("%x%", compiled.Parameters[0].Value);
|
||||||
|
Assert.AreEqual("%x%", compiled.Parameters[1].Value);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
namespace YKanBan.Tests;
|
||||||
|
|
||||||
|
[TestClass]
|
||||||
|
public class SmokeTests
|
||||||
|
{
|
||||||
|
[TestMethod]
|
||||||
|
public void ThirdPartyPackagesResolve()
|
||||||
|
{
|
||||||
|
Assert.IsNotNull(typeof(Pidgin.Parser).Assembly);
|
||||||
|
Assert.IsNotNull(typeof(Newtonsoft.Json.JsonConvert).Assembly);
|
||||||
|
Assert.IsNotNull(typeof(Microsoft.Data.Sqlite.SqliteConnection).Assembly);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,169 @@
|
|||||||
|
using YKanBan.Storage.AppData;
|
||||||
|
using YKanBan.Tests.TestUtilities;
|
||||||
|
|
||||||
|
namespace YKanBan.Tests.Storage.AppData;
|
||||||
|
|
||||||
|
/// <summary>Tests for app.json load/save and its degradation rules.</summary>
|
||||||
|
[TestClass]
|
||||||
|
public class AppConfigStoreTests
|
||||||
|
{
|
||||||
|
[TestMethod]
|
||||||
|
public void MissingFileYieldsDefaults()
|
||||||
|
{
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
var store = new AppConfigStore(Path.Combine(directory.FullPath, "app.json"));
|
||||||
|
|
||||||
|
AppConfig config = store.Load();
|
||||||
|
Assert.AreEqual(AppConfig.CurrentFormatVersion, config.Version);
|
||||||
|
Assert.AreEqual("en", config.Language);
|
||||||
|
Assert.AreEqual(ThemeOption.FollowSystem, config.Theme);
|
||||||
|
Assert.AreEqual(CardSortOption.Id, config.Sort.Card);
|
||||||
|
Assert.AreEqual(SidebarSortOption.NameAsc, config.Sort.Sidebar);
|
||||||
|
Assert.AreEqual(ColumnWidthPreset.Standard, config.ColumnWidth.Preset);
|
||||||
|
Assert.AreEqual(320, config.ColumnWidth.CustomPixels);
|
||||||
|
Assert.IsTrue(config.Confirmations.DeleteCard);
|
||||||
|
Assert.IsTrue(config.Confirmations.DeleteColumn);
|
||||||
|
Assert.IsTrue(config.Confirmations.DeleteTag);
|
||||||
|
Assert.IsTrue(config.Confirmations.DiscardEdit);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void CorruptJsonIsBackedUpAndDefaultsAreUsed()
|
||||||
|
{
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
string path = Path.Combine(directory.FullPath, "app.json");
|
||||||
|
File.WriteAllText(path, "{{{ not json");
|
||||||
|
var store = new AppConfigStore(path);
|
||||||
|
|
||||||
|
AppConfig config = store.Load();
|
||||||
|
|
||||||
|
Assert.AreEqual("en", config.Language);
|
||||||
|
Assert.IsTrue(File.Exists(path + ".bak"));
|
||||||
|
Assert.AreEqual("{{{ not json", File.ReadAllText(path + ".bak"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void WrongShapeJsonIsBackedUpAndDefaultsAreUsed()
|
||||||
|
{
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
string path = Path.Combine(directory.FullPath, "app.json");
|
||||||
|
File.WriteAllText(path, "[1, 2, 3]");
|
||||||
|
var store = new AppConfigStore(path);
|
||||||
|
|
||||||
|
AppConfig config = store.Load();
|
||||||
|
|
||||||
|
Assert.AreEqual(AppConfig.CurrentFormatVersion, config.Version);
|
||||||
|
Assert.IsTrue(File.Exists(path + ".bak"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void SaveAndLoadRoundTripsAllSettings()
|
||||||
|
{
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
var store = new AppConfigStore(Path.Combine(directory.FullPath, "app.json"));
|
||||||
|
|
||||||
|
store.Save(new AppConfig
|
||||||
|
{
|
||||||
|
Language = "zh-Hans",
|
||||||
|
Theme = ThemeOption.Dark,
|
||||||
|
Sort = new SortSettings
|
||||||
|
{
|
||||||
|
Card = CardSortOption.Title,
|
||||||
|
Sidebar = SidebarSortOption.RecentlyUpdated,
|
||||||
|
},
|
||||||
|
ColumnWidth = new ColumnWidthSettings
|
||||||
|
{
|
||||||
|
Preset = ColumnWidthPreset.Custom,
|
||||||
|
CustomPixels = 500,
|
||||||
|
},
|
||||||
|
Confirmations = new ConfirmationSettings
|
||||||
|
{
|
||||||
|
DeleteCard = false,
|
||||||
|
DeleteColumn = false,
|
||||||
|
DeleteTag = false,
|
||||||
|
DiscardEdit = false,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
AppConfig loaded = store.Load();
|
||||||
|
|
||||||
|
Assert.AreEqual("zh-Hans", loaded.Language);
|
||||||
|
Assert.AreEqual(ThemeOption.Dark, loaded.Theme);
|
||||||
|
Assert.AreEqual(CardSortOption.Title, loaded.Sort.Card);
|
||||||
|
Assert.AreEqual(SidebarSortOption.RecentlyUpdated, loaded.Sort.Sidebar);
|
||||||
|
Assert.AreEqual(ColumnWidthPreset.Custom, loaded.ColumnWidth.Preset);
|
||||||
|
Assert.AreEqual(500, loaded.ColumnWidth.CustomPixels);
|
||||||
|
Assert.IsFalse(loaded.Confirmations.DeleteCard);
|
||||||
|
Assert.IsFalse(loaded.Confirmations.DeleteColumn);
|
||||||
|
Assert.IsFalse(loaded.Confirmations.DeleteTag);
|
||||||
|
Assert.IsFalse(loaded.Confirmations.DiscardEdit);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void SaveWritesKebabCaseNamesAndVersionField()
|
||||||
|
{
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
string path = Path.Combine(directory.FullPath, "app.json");
|
||||||
|
var store = new AppConfigStore(path);
|
||||||
|
|
||||||
|
store.Save(new AppConfig());
|
||||||
|
string json = File.ReadAllText(path);
|
||||||
|
|
||||||
|
// Keys and enum values are serialized in kebab-case; "version" is the migration hook.
|
||||||
|
Assert.IsTrue(json.Contains($"\"version\": {AppConfig.CurrentFormatVersion}"));
|
||||||
|
Assert.IsTrue(json.Contains("\"language\": \"en\""));
|
||||||
|
Assert.IsTrue(json.Contains("\"theme\": \"follow-system\""));
|
||||||
|
Assert.IsTrue(json.Contains("\"sort\":"));
|
||||||
|
Assert.IsTrue(json.Contains("\"card\": \"id\""));
|
||||||
|
Assert.IsTrue(json.Contains("\"sidebar\": \"name-asc\""));
|
||||||
|
Assert.IsTrue(json.Contains("\"column-width\":"));
|
||||||
|
Assert.IsTrue(json.Contains("\"preset\": \"standard\""));
|
||||||
|
Assert.IsTrue(json.Contains("\"custom-pixels\": 320"));
|
||||||
|
Assert.IsTrue(json.Contains("\"confirmations\":"));
|
||||||
|
Assert.IsTrue(json.Contains("\"delete-card\": true"));
|
||||||
|
Assert.IsTrue(json.Contains("\"delete-column\": true"));
|
||||||
|
Assert.IsTrue(json.Contains("\"delete-tag\": true"));
|
||||||
|
Assert.IsTrue(json.Contains("\"discard-edit\": true"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void MissingSectionsFallBackToTheirDefaults()
|
||||||
|
{
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
string path = Path.Combine(directory.FullPath, "app.json");
|
||||||
|
File.WriteAllText(path, $$"""
|
||||||
|
{
|
||||||
|
"version": {{AppConfig.CurrentFormatVersion}},
|
||||||
|
"language": "zh-Hans"
|
||||||
|
}
|
||||||
|
""");
|
||||||
|
var store = new AppConfigStore(path);
|
||||||
|
|
||||||
|
AppConfig config = store.Load();
|
||||||
|
|
||||||
|
// The present field loads; absent sections each fall back to defaults.
|
||||||
|
Assert.AreEqual("zh-Hans", config.Language);
|
||||||
|
Assert.AreEqual(CardSortOption.Id, config.Sort.Card);
|
||||||
|
Assert.AreEqual(ColumnWidthPreset.Standard, config.ColumnWidth.Preset);
|
||||||
|
Assert.IsTrue(config.Confirmations.DeleteCard);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void LoadPreservesUnknownFieldsTolerantly()
|
||||||
|
{
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
string path = Path.Combine(directory.FullPath, "app.json");
|
||||||
|
// A newer version writes an unknown field plus a known one.
|
||||||
|
File.WriteAllText(path, $$"""
|
||||||
|
{
|
||||||
|
"version": {{AppConfig.CurrentFormatVersion}},
|
||||||
|
"language": "zh-Hans",
|
||||||
|
"some-future-field": 42
|
||||||
|
}
|
||||||
|
""");
|
||||||
|
var store = new AppConfigStore(path);
|
||||||
|
|
||||||
|
AppConfig config = store.Load();
|
||||||
|
|
||||||
|
Assert.AreEqual("zh-Hans", config.Language);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
using Microsoft.Data.Sqlite;
|
||||||
|
using YKanBan.Storage;
|
||||||
|
using YKanBan.Storage.AppData;
|
||||||
|
using YKanBan.Tests.TestUtilities;
|
||||||
|
|
||||||
|
namespace YKanBan.Tests.Storage.AppData;
|
||||||
|
|
||||||
|
/// <summary>Tests for the global app.db workspace registry.</summary>
|
||||||
|
[TestClass]
|
||||||
|
public class AppDatabaseTests
|
||||||
|
{
|
||||||
|
private static string DatabasePath(TempDirectory directory)
|
||||||
|
=> Path.Combine(directory.FullPath, "app.db");
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void UpsertInsertsRowWithTimestamps()
|
||||||
|
{
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
long now = 1000;
|
||||||
|
using var db = new AppDatabase(DatabasePath(directory), () => now);
|
||||||
|
|
||||||
|
db.UpsertWorkspace(@"C:\work\repo");
|
||||||
|
|
||||||
|
IReadOnlyList<WorkspaceRecord> records = db.GetWorkspaces();
|
||||||
|
Assert.AreEqual(1, records.Count);
|
||||||
|
Assert.AreEqual(@"C:\work\repo", records[0].Path);
|
||||||
|
Assert.AreEqual(1000L, records[0].AddedAt);
|
||||||
|
Assert.AreEqual(1000L, records[0].LastEditedAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void RepeatedUpsertKeepsOriginalAddedAt()
|
||||||
|
{
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
long now = 1000;
|
||||||
|
using var db = new AppDatabase(DatabasePath(directory), () => now);
|
||||||
|
|
||||||
|
db.UpsertWorkspace(@"C:\work\repo");
|
||||||
|
now = 2000;
|
||||||
|
db.UpsertWorkspace(@"C:\work\repo");
|
||||||
|
|
||||||
|
WorkspaceRecord record = db.GetWorkspaces().Single();
|
||||||
|
Assert.AreEqual(1000L, record.AddedAt);
|
||||||
|
Assert.AreEqual(2000L, record.LastEditedAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TouchRefreshesLastEditedAt()
|
||||||
|
{
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
long now = 1000;
|
||||||
|
using var db = new AppDatabase(DatabasePath(directory), () => now);
|
||||||
|
|
||||||
|
db.UpsertWorkspace(@"C:\work\repo");
|
||||||
|
now = 2500;
|
||||||
|
db.TouchLastEdited(@"C:\work\repo");
|
||||||
|
|
||||||
|
WorkspaceRecord record = db.GetWorkspaces().Single();
|
||||||
|
Assert.AreEqual(1000L, record.AddedAt);
|
||||||
|
Assert.AreEqual(2500L, record.LastEditedAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TouchOnUnknownPathRegistersTheWorkspace()
|
||||||
|
{
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
long now = 3000;
|
||||||
|
using var db = new AppDatabase(DatabasePath(directory), () => now);
|
||||||
|
|
||||||
|
// Self-healing: touching an unregistered workspace still leaves a valid row.
|
||||||
|
db.TouchLastEdited(@"C:\work\other");
|
||||||
|
|
||||||
|
WorkspaceRecord record = db.GetWorkspaces().Single();
|
||||||
|
Assert.AreEqual(3000L, record.AddedAt);
|
||||||
|
Assert.AreEqual(3000L, record.LastEditedAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void RemoveDeletesTheRow()
|
||||||
|
{
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
using var db = new AppDatabase(DatabasePath(directory));
|
||||||
|
|
||||||
|
db.UpsertWorkspace(@"C:\work\repo");
|
||||||
|
db.RemoveWorkspace(@"C:\work\repo");
|
||||||
|
|
||||||
|
Assert.AreEqual(0, db.GetWorkspaces().Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void RowsPersistAcrossReopen()
|
||||||
|
{
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
string path = DatabasePath(directory);
|
||||||
|
|
||||||
|
using (var db = new AppDatabase(path, () => 1000))
|
||||||
|
{
|
||||||
|
db.UpsertWorkspace(@"C:\work\repo");
|
||||||
|
}
|
||||||
|
|
||||||
|
using var reopened = new AppDatabase(path, () => 9999);
|
||||||
|
WorkspaceRecord record = reopened.GetWorkspaces().Single();
|
||||||
|
Assert.AreEqual(@"C:\work\repo", record.Path);
|
||||||
|
Assert.AreEqual(1000L, record.AddedAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void OpenMigratesToCurrentSchemaVersion()
|
||||||
|
{
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
string path = DatabasePath(directory);
|
||||||
|
using (var db = new AppDatabase(path))
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
using var raw = new SqliteConnection($"Data Source={path}");
|
||||||
|
raw.Open();
|
||||||
|
Assert.AreEqual(AppDatabase.CurrentSchemaVersion, SqliteDatabase.ReadUserVersion(raw));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void OpenAppliesWalJournalMode()
|
||||||
|
{
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
string path = DatabasePath(directory);
|
||||||
|
using (var db = new AppDatabase(path))
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
// WAL is a persistent property of the database file: a plain new
|
||||||
|
// connection reports it without any PRAGMA replay.
|
||||||
|
using var raw = new SqliteConnection($"Data Source={path}");
|
||||||
|
raw.Open();
|
||||||
|
Assert.AreEqual("wal", SqliteTestHelper.ScalarString(raw, "PRAGMA journal_mode;"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
using YKanBan.Storage;
|
||||||
|
using YKanBan.Storage.Workspace;
|
||||||
|
using YKanBan.Tests.TestUtilities;
|
||||||
|
|
||||||
|
namespace YKanBan.Tests.Storage;
|
||||||
|
|
||||||
|
/// <summary>Tests for PRAGMA application and user_version migration machinery.</summary>
|
||||||
|
[TestClass]
|
||||||
|
public class SqliteDatabaseTests
|
||||||
|
{
|
||||||
|
private static readonly SchemaMigration[] V1Only =
|
||||||
|
[
|
||||||
|
new SchemaMigration(1, "v1", "CREATE TABLE t1 (id INTEGER PRIMARY KEY);"),
|
||||||
|
];
|
||||||
|
|
||||||
|
private static readonly SchemaMigration[] V1AndV2 =
|
||||||
|
[
|
||||||
|
new SchemaMigration(1, "v1", "CREATE TABLE t1 (id INTEGER PRIMARY KEY);"),
|
||||||
|
new SchemaMigration(2, "v2", "CREATE TABLE t2 (id INTEGER PRIMARY KEY);"),
|
||||||
|
];
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void OpenAppliesMandatedPragmas()
|
||||||
|
{
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
string dbPath = Path.Combine(directory.FullPath, "test.db");
|
||||||
|
|
||||||
|
using var connection = SqliteDatabase.Open(dbPath, []);
|
||||||
|
Assert.AreEqual("wal", SqliteTestHelper.ScalarString(connection, "PRAGMA journal_mode;"));
|
||||||
|
Assert.AreEqual(1L, SqliteTestHelper.ScalarLong(connection, "PRAGMA synchronous;"));
|
||||||
|
Assert.AreEqual(1L, SqliteTestHelper.ScalarLong(connection, "PRAGMA foreign_keys;"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void OpenSetsUserVersionToLatestWorkspaceMigration()
|
||||||
|
{
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
string dbPath = Path.Combine(directory.FullPath, "test.db");
|
||||||
|
|
||||||
|
using var connection = SqliteDatabase.Open(dbPath, WorkspaceSchema.Migrations);
|
||||||
|
Assert.AreEqual(WorkspaceSchema.CurrentVersion, SqliteDatabase.ReadUserVersion(connection));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void MigrationsApplyIncrementallyOnReopen()
|
||||||
|
{
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
string dbPath = Path.Combine(directory.FullPath, "test.db");
|
||||||
|
|
||||||
|
// First open with only v1 available: v1 applied, v2 table absent.
|
||||||
|
using (var connection = SqliteDatabase.Open(dbPath, V1Only))
|
||||||
|
{
|
||||||
|
Assert.AreEqual(1L, SqliteDatabase.ReadUserVersion(connection));
|
||||||
|
Assert.IsTrue(SqliteTestHelper.TableExists(connection, "t1"));
|
||||||
|
Assert.IsFalse(SqliteTestHelper.TableExists(connection, "t2"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reopen with v1+v2: only v2 runs, v1 data untouched.
|
||||||
|
using (var connection = SqliteDatabase.Open(dbPath, V1AndV2))
|
||||||
|
{
|
||||||
|
Assert.AreEqual(2L, SqliteDatabase.ReadUserVersion(connection));
|
||||||
|
Assert.IsTrue(SqliteTestHelper.TableExists(connection, "t1"));
|
||||||
|
Assert.IsTrue(SqliteTestHelper.TableExists(connection, "t2"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void ReopenWithCurrentSchemaIsIdempotent()
|
||||||
|
{
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
string dbPath = Path.Combine(directory.FullPath, "test.db");
|
||||||
|
|
||||||
|
SqliteDatabase.Open(dbPath, V1AndV2).Dispose();
|
||||||
|
using (var connection = SqliteDatabase.Open(dbPath, V1AndV2))
|
||||||
|
{
|
||||||
|
// Still at version 2; re-running is a no-op.
|
||||||
|
Assert.AreEqual(2L, SqliteDatabase.ReadUserVersion(connection));
|
||||||
|
SqliteTestHelper.Exec(connection, "INSERT INTO t1 (id) VALUES (42);");
|
||||||
|
}
|
||||||
|
|
||||||
|
using (var connection = SqliteDatabase.Open(dbPath, V1AndV2))
|
||||||
|
{
|
||||||
|
Assert.AreEqual(42L, SqliteTestHelper.ScalarLong(connection, "SELECT id FROM t1;"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void NewerSchemaVersionIsRejected()
|
||||||
|
{
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
string dbPath = Path.Combine(directory.FullPath, "test.db");
|
||||||
|
|
||||||
|
// Simulate a database written by a newer build.
|
||||||
|
using (var connection = SqliteDatabase.Open(dbPath, []))
|
||||||
|
{
|
||||||
|
SqliteTestHelper.Exec(connection, "PRAGMA user_version=5;");
|
||||||
|
}
|
||||||
|
|
||||||
|
SchemaVersionException ex = Assert.ThrowsExactly<SchemaVersionException>(
|
||||||
|
() => SqliteDatabase.Open(dbPath, V1AndV2));
|
||||||
|
Assert.AreEqual(5L, ex.StoredVersion);
|
||||||
|
Assert.AreEqual(2, ex.SupportedVersion);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void NonContiguousMigrationListIsRejected()
|
||||||
|
{
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
string dbPath = Path.Combine(directory.FullPath, "test.db");
|
||||||
|
var bad = new[] { new SchemaMigration(2, "gap", "CREATE TABLE t (id INTEGER);") };
|
||||||
|
|
||||||
|
Assert.ThrowsExactly<ArgumentException>(() => SqliteDatabase.Open(dbPath, bad));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using YKanBan.Storage.Workspace;
|
||||||
|
using YKanBan.Tests.TestUtilities;
|
||||||
|
|
||||||
|
namespace YKanBan.Tests.Storage.Workspace;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Verifies that preset column titles follow the UI language active at
|
||||||
|
/// seeding time and then live as ordinary data. Mutates the global
|
||||||
|
/// Resources.Culture, therefore marked DoNotParallelize.
|
||||||
|
/// </summary>
|
||||||
|
[TestClass]
|
||||||
|
[DoNotParallelize]
|
||||||
|
public class PresetColumnCultureTests
|
||||||
|
{
|
||||||
|
[TestMethod]
|
||||||
|
public void PresetTitlesAreEnglishUnderEnglishCulture()
|
||||||
|
{
|
||||||
|
CultureInfo? original = Resources.Culture;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Resources.Culture = new CultureInfo("en");
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||||
|
WorkspacePreset.SeedColumns(directory.FullPath);
|
||||||
|
|
||||||
|
using var connection = SqliteTestHelper.OpenWorkspace(directory.FullPath);
|
||||||
|
CollectionAssert.AreEqual(
|
||||||
|
new[] { "To Do", "In Progress", "Done" },
|
||||||
|
SqliteTestHelper.GetColumnTitles(connection));
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Resources.Culture = original;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void PresetTitlesAreChineseUnderChineseCulture()
|
||||||
|
{
|
||||||
|
CultureInfo? original = Resources.Culture;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Resources.Culture = new CultureInfo("zh-Hans");
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||||
|
WorkspacePreset.SeedColumns(directory.FullPath);
|
||||||
|
|
||||||
|
using var connection = SqliteTestHelper.OpenWorkspace(directory.FullPath);
|
||||||
|
CollectionAssert.AreEqual(
|
||||||
|
new[] { "待办", "进行中", "已完成" },
|
||||||
|
SqliteTestHelper.GetColumnTitles(connection));
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Resources.Culture = original;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,191 @@
|
|||||||
|
using YKanBan.Platform;
|
||||||
|
using YKanBan.Storage;
|
||||||
|
using YKanBan.Storage.AppData;
|
||||||
|
using YKanBan.Storage.Workspace;
|
||||||
|
using YKanBan.Tests.TestUtilities;
|
||||||
|
|
||||||
|
namespace YKanBan.Tests.Storage.Workspace;
|
||||||
|
|
||||||
|
/// <summary>Tests for the fixed-capacity LRU workspace session pool.</summary>
|
||||||
|
[TestClass]
|
||||||
|
public class WorkspaceConnectionPoolTests
|
||||||
|
{
|
||||||
|
/// <summary>Owns three initialized workspaces (a, b, c), a registry and the pool under test.</summary>
|
||||||
|
private sealed class PoolFixture : IDisposable
|
||||||
|
{
|
||||||
|
public TempDirectory Directory { get; } = new();
|
||||||
|
|
||||||
|
public AppDatabase AppDb { get; }
|
||||||
|
|
||||||
|
public WorkspaceConnectionPool Pool { get; }
|
||||||
|
|
||||||
|
public PoolFixture(int capacity = 2)
|
||||||
|
{
|
||||||
|
foreach (string name in new[] { "a", "b", "c" })
|
||||||
|
{
|
||||||
|
string path = Path.Combine(Directory.FullPath, name);
|
||||||
|
System.IO.Directory.CreateDirectory(path);
|
||||||
|
WorkspaceInitializer.Initialize(path);
|
||||||
|
}
|
||||||
|
AppDb = new AppDatabase(Path.Combine(Directory.FullPath, "app.db"));
|
||||||
|
Pool = new WorkspaceConnectionPool(capacity, AppDb, new PathComparer(ignoreCase: true));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Workspace folder path by name.</summary>
|
||||||
|
public string Workspace(string name) => Path.Combine(Directory.FullPath, name);
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
Pool.Dispose();
|
||||||
|
AppDb.Dispose();
|
||||||
|
Directory.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void OpenBeyondCapacityEvictsLeastRecentlyUsed()
|
||||||
|
{
|
||||||
|
using var fixture = new PoolFixture(capacity: 2);
|
||||||
|
|
||||||
|
fixture.Pool.Open(fixture.Workspace("a"));
|
||||||
|
fixture.Pool.Open(fixture.Workspace("b"));
|
||||||
|
fixture.Pool.Open(fixture.Workspace("c"));
|
||||||
|
|
||||||
|
Assert.AreEqual(2, fixture.Pool.OpenCount);
|
||||||
|
Assert.IsNull(fixture.Pool.Find(fixture.Workspace("a")));
|
||||||
|
Assert.IsNotNull(fixture.Pool.Find(fixture.Workspace("b")));
|
||||||
|
Assert.IsNotNull(fixture.Pool.Find(fixture.Workspace("c")));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void OpenTwiceReturnsSameSession()
|
||||||
|
{
|
||||||
|
using var fixture = new PoolFixture();
|
||||||
|
|
||||||
|
WorkspaceSession first = fixture.Pool.Open(fixture.Workspace("a"));
|
||||||
|
WorkspaceSession second = fixture.Pool.Open(fixture.Workspace("a"));
|
||||||
|
|
||||||
|
Assert.AreSame(first, second);
|
||||||
|
Assert.AreEqual(1, fixture.Pool.OpenCount);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TouchPromotesRecency()
|
||||||
|
{
|
||||||
|
using var fixture = new PoolFixture(capacity: 2);
|
||||||
|
|
||||||
|
fixture.Pool.Open(fixture.Workspace("a"));
|
||||||
|
fixture.Pool.Open(fixture.Workspace("b"));
|
||||||
|
fixture.Pool.Touch(fixture.Workspace("a"));
|
||||||
|
fixture.Pool.Open(fixture.Workspace("c"));
|
||||||
|
|
||||||
|
// "a" was touched after "b" opened, so "b" is the LRU victim now.
|
||||||
|
Assert.IsNotNull(fixture.Pool.Find(fixture.Workspace("a")));
|
||||||
|
Assert.IsNull(fixture.Pool.Find(fixture.Workspace("b")));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void EvictedWorkspaceCanBeReopened()
|
||||||
|
{
|
||||||
|
using var fixture = new PoolFixture(capacity: 2);
|
||||||
|
|
||||||
|
fixture.Pool.Open(fixture.Workspace("a"));
|
||||||
|
fixture.Pool.Open(fixture.Workspace("b"));
|
||||||
|
fixture.Pool.Open(fixture.Workspace("c"));
|
||||||
|
|
||||||
|
// "a" was evicted; reopening it works and now evicts the LRU "b".
|
||||||
|
WorkspaceSession reopened = fixture.Pool.Open(fixture.Workspace("a"));
|
||||||
|
Assert.AreEqual("a", Path.GetFileName(reopened.FolderPath));
|
||||||
|
Assert.IsNull(fixture.Pool.Find(fixture.Workspace("b")));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void OpenRegistersWorkspaceInSidebarRegistry()
|
||||||
|
{
|
||||||
|
using var fixture = new PoolFixture();
|
||||||
|
|
||||||
|
fixture.Pool.Open(fixture.Workspace("a"));
|
||||||
|
fixture.Pool.Open(fixture.Workspace("b"));
|
||||||
|
|
||||||
|
IReadOnlyList<string> registered = fixture.AppDb.GetWorkspaces().Select(record => record.Path).ToList();
|
||||||
|
Assert.AreEqual(2, registered.Count);
|
||||||
|
Assert.IsTrue(registered.Contains(new PathComparer(ignoreCase: true).Normalize(fixture.Workspace("a"))));
|
||||||
|
Assert.IsTrue(registered.Contains(new PathComparer(ignoreCase: true).Normalize(fixture.Workspace("b"))));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void OpenMissingDirectoryThrows()
|
||||||
|
{
|
||||||
|
using var fixture = new PoolFixture();
|
||||||
|
string missing = Path.Combine(fixture.Directory.FullPath, "nowhere");
|
||||||
|
|
||||||
|
Assert.ThrowsExactly<WorkspaceDirectoryMissingException>(() => fixture.Pool.Open(missing));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void OpenFolderWithoutYkanbanThrows()
|
||||||
|
{
|
||||||
|
using var fixture = new PoolFixture();
|
||||||
|
string plain = Path.Combine(fixture.Directory.FullPath, "plain");
|
||||||
|
System.IO.Directory.CreateDirectory(plain);
|
||||||
|
|
||||||
|
Assert.ThrowsExactly<WorkspaceNotInitializedException>(() => fixture.Pool.Open(plain));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void OpenWithLockHeldElsewhereThrowsThenSucceedsAfterRelease()
|
||||||
|
{
|
||||||
|
using var fixture = new PoolFixture();
|
||||||
|
|
||||||
|
using WorkspaceLock holder = WorkspaceLock.Acquire(fixture.Workspace("a"));
|
||||||
|
Assert.ThrowsExactly<WorkspaceLockException>(() => fixture.Pool.Open(fixture.Workspace("a")));
|
||||||
|
|
||||||
|
holder.Dispose();
|
||||||
|
WorkspaceSession session = fixture.Pool.Open(fixture.Workspace("a"));
|
||||||
|
Assert.AreEqual("a", Path.GetFileName(session.FolderPath));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void RemoveReleasesResourcesAndForgetsRegistryEntry()
|
||||||
|
{
|
||||||
|
using var fixture = new PoolFixture();
|
||||||
|
|
||||||
|
fixture.Pool.Open(fixture.Workspace("a"));
|
||||||
|
Assert.IsTrue(fixture.Pool.Remove(fixture.Workspace("a")));
|
||||||
|
|
||||||
|
Assert.IsNull(fixture.Pool.Find(fixture.Workspace("a")));
|
||||||
|
Assert.AreEqual(0, fixture.AppDb.GetWorkspaces().Count);
|
||||||
|
|
||||||
|
// Resources are truly released: the lock can be taken again.
|
||||||
|
using WorkspaceLock reacquired = WorkspaceLock.Acquire(fixture.Workspace("a"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void PathEquivalentsShareOneSession()
|
||||||
|
{
|
||||||
|
using var fixture = new PoolFixture();
|
||||||
|
string path = fixture.Workspace("a");
|
||||||
|
string differentlyCased = Path.Combine(
|
||||||
|
Path.GetDirectoryName(path)!,
|
||||||
|
Path.GetFileName(path).ToUpperInvariant());
|
||||||
|
|
||||||
|
WorkspaceSession session = fixture.Pool.Open(path);
|
||||||
|
WorkspaceSession same = fixture.Pool.Open(differentlyCased);
|
||||||
|
|
||||||
|
Assert.AreSame(session, same);
|
||||||
|
Assert.AreEqual(1, fixture.Pool.OpenCount);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void DisposeReleasesAllLocks()
|
||||||
|
{
|
||||||
|
using var fixture = new PoolFixture();
|
||||||
|
|
||||||
|
fixture.Pool.Open(fixture.Workspace("a"));
|
||||||
|
fixture.Pool.Open(fixture.Workspace("b"));
|
||||||
|
fixture.Pool.Dispose();
|
||||||
|
|
||||||
|
using WorkspaceLock lockA = WorkspaceLock.Acquire(fixture.Workspace("a"));
|
||||||
|
using WorkspaceLock lockB = WorkspaceLock.Acquire(fixture.Workspace("b"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
using YKanBan.Storage;
|
||||||
|
using YKanBan.Storage.Workspace;
|
||||||
|
using YKanBan.Tests.TestUtilities;
|
||||||
|
|
||||||
|
namespace YKanBan.Tests.Storage.Workspace;
|
||||||
|
|
||||||
|
/// <summary>Tests for .ykanban folder and empty database creation.</summary>
|
||||||
|
[TestClass]
|
||||||
|
public class WorkspaceInitializerTests
|
||||||
|
{
|
||||||
|
[TestMethod]
|
||||||
|
public void InitializeCreatesYkanbanFolderAndDatabase()
|
||||||
|
{
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
|
||||||
|
Assert.IsFalse(WorkspaceInitializer.IsWorkspace(directory.FullPath));
|
||||||
|
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||||
|
|
||||||
|
Assert.IsTrue(WorkspaceInitializer.IsWorkspace(directory.FullPath));
|
||||||
|
Assert.IsTrue(File.Exists(WorkspacePaths.Database(directory.FullPath)));
|
||||||
|
// The lock file only appears once a WorkspaceLock is acquired.
|
||||||
|
Assert.IsFalse(File.Exists(WorkspacePaths.LockFile(directory.FullPath)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void InitializeLeavesDatabaseEmpty()
|
||||||
|
{
|
||||||
|
// Initialization creates structure only; preset content is seeded separately.
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||||
|
|
||||||
|
using var connection = SqliteTestHelper.OpenWorkspace(directory.FullPath);
|
||||||
|
Assert.AreEqual(0L, SqliteTestHelper.ScalarLong(connection, "SELECT COUNT(*) FROM columns;"));
|
||||||
|
Assert.AreEqual(0L, SqliteTestHelper.ScalarLong(connection, "SELECT COUNT(*) FROM cards;"));
|
||||||
|
Assert.AreEqual(0L, SqliteTestHelper.ScalarLong(connection, "SELECT COUNT(*) FROM tags;"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void InitializeThrowsWhenDirectoryIsMissing()
|
||||||
|
{
|
||||||
|
string missing = Path.Combine(Path.GetTempPath(), "ykanban-tests-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Assert.ThrowsExactly<WorkspaceDirectoryMissingException>(() => WorkspaceInitializer.Initialize(missing));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void InitializeThrowsWhenDatabaseAlreadyExists()
|
||||||
|
{
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||||
|
|
||||||
|
Assert.ThrowsExactly<InvalidOperationException>(() => WorkspaceInitializer.Initialize(directory.FullPath));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
using YKanBan.Storage;
|
||||||
|
using YKanBan.Storage.Workspace;
|
||||||
|
using YKanBan.Tests.TestUtilities;
|
||||||
|
|
||||||
|
namespace YKanBan.Tests.Storage.Workspace;
|
||||||
|
|
||||||
|
/// <summary>Tests for exclusive lock acquisition, diagnostics and release.</summary>
|
||||||
|
[TestClass]
|
||||||
|
public class WorkspaceLockTests
|
||||||
|
{
|
||||||
|
[TestMethod]
|
||||||
|
public void AcquireThenDisposeThenAcquireAgainSucceeds()
|
||||||
|
{
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||||
|
|
||||||
|
WorkspaceLock.Acquire(directory.FullPath).Dispose();
|
||||||
|
// Re-acquiring after release works: no stale lock residue survives.
|
||||||
|
WorkspaceLock.Acquire(directory.FullPath).Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void SecondAcquireWhileHeldThrows()
|
||||||
|
{
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||||
|
|
||||||
|
using WorkspaceLock first = WorkspaceLock.Acquire(directory.FullPath);
|
||||||
|
WorkspaceLockException ex = Assert.ThrowsExactly<WorkspaceLockException>(
|
||||||
|
() => WorkspaceLock.Acquire(directory.FullPath));
|
||||||
|
Assert.AreEqual(WorkspacePaths.LockFile(directory.FullPath), ex.LockFilePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void AcquireWithoutYkanbanThrowsNotInitialized()
|
||||||
|
{
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
Assert.ThrowsExactly<WorkspaceNotInitializedException>(
|
||||||
|
() => WorkspaceLock.Acquire(directory.FullPath));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void LockFileContainsHolderDiagnostics()
|
||||||
|
{
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||||
|
|
||||||
|
using (WorkspaceLock.Acquire(directory.FullPath))
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
// The file survives release and carries PID / machine name / time for humans.
|
||||||
|
string content = File.ReadAllText(WorkspacePaths.LockFile(directory.FullPath));
|
||||||
|
StringAssert.Contains(content, "pid=");
|
||||||
|
StringAssert.Contains(content, $"machine={Environment.MachineName}");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
using YKanBan.Storage.Workspace;
|
||||||
|
using YKanBan.Tests.TestUtilities;
|
||||||
|
|
||||||
|
namespace YKanBan.Tests.Storage.Workspace;
|
||||||
|
|
||||||
|
/// <summary>Tests for seeding preset workspace content.</summary>
|
||||||
|
[TestClass]
|
||||||
|
public class WorkspacePresetTests
|
||||||
|
{
|
||||||
|
[TestMethod]
|
||||||
|
public void SeedAddsThreeDistinctPresetColumns()
|
||||||
|
{
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||||
|
WorkspacePreset.SeedColumns(directory.FullPath);
|
||||||
|
|
||||||
|
using var connection = SqliteTestHelper.OpenWorkspace(directory.FullPath);
|
||||||
|
List<string> titles = SqliteTestHelper.GetColumnTitles(connection);
|
||||||
|
|
||||||
|
Assert.AreEqual(3, titles.Count);
|
||||||
|
Assert.AreEqual(titles.Count, titles.Distinct().Count());
|
||||||
|
Assert.IsTrue(titles.All(title => title.Length > 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void SeedPresetColumnsShareOneTimestamp()
|
||||||
|
{
|
||||||
|
using var directory = new TempDirectory();
|
||||||
|
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||||
|
WorkspacePreset.SeedColumns(directory.FullPath);
|
||||||
|
|
||||||
|
using var connection = SqliteTestHelper.OpenWorkspace(directory.FullPath);
|
||||||
|
|
||||||
|
// Creation writes created_at = updated_at; all three columns share one moment.
|
||||||
|
Assert.AreEqual(0L, SqliteTestHelper.ScalarLong(connection, "SELECT COUNT(*) FROM columns WHERE created_at <> updated_at;"));
|
||||||
|
Assert.AreEqual(3L, SqliteTestHelper.ScalarLong(connection, "SELECT COUNT(*) FROM columns WHERE created_at > 0;"));
|
||||||
|
Assert.AreEqual(1L, SqliteTestHelper.ScalarLong(connection, "SELECT COUNT(DISTINCT created_at) FROM columns;"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,275 @@
|
|||||||
|
using Microsoft.Data.Sqlite;
|
||||||
|
using YKanBan.Models;
|
||||||
|
using YKanBan.Storage.AppData;
|
||||||
|
using YKanBan.Storage.Workspace;
|
||||||
|
using YKanBan.Tests.TestUtilities;
|
||||||
|
|
||||||
|
namespace YKanBan.Tests.Storage.Workspace;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Tests for workspace CRUD, the three cascade chains, edit-confirm
|
||||||
|
/// transaction atomicity, timestamp refresh rules and the last_edited_at
|
||||||
|
/// write-through.
|
||||||
|
/// </summary>
|
||||||
|
[TestClass]
|
||||||
|
public class WorkspaceRepositoryTests
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Owns a workspace with fixed-timestamp fixture data (one column, one
|
||||||
|
/// card, two tags linked to the card), a fake-clock app.db and the
|
||||||
|
/// repository under test.
|
||||||
|
/// </summary>
|
||||||
|
private sealed class RepositoryFixture : IDisposable
|
||||||
|
{
|
||||||
|
public TempDirectory Directory { get; } = new();
|
||||||
|
|
||||||
|
public long Clock { get; set; } = 1000;
|
||||||
|
|
||||||
|
public AppDatabase AppDb { get; }
|
||||||
|
|
||||||
|
public WorkspaceRepository Repository { get; }
|
||||||
|
|
||||||
|
public long ColumnId { get; } = 1;
|
||||||
|
|
||||||
|
public long CardId { get; } = 1;
|
||||||
|
|
||||||
|
public long BugTagId { get; } = 1;
|
||||||
|
|
||||||
|
public long UiTagId { get; } = 2;
|
||||||
|
|
||||||
|
public RepositoryFixture()
|
||||||
|
{
|
||||||
|
WorkspaceInitializer.Initialize(Directory.FullPath);
|
||||||
|
|
||||||
|
// Fixture rows carry literal timestamps so refresh vs. no-refresh stays observable.
|
||||||
|
using SqliteConnection connection = SqliteTestHelper.OpenWorkspace(Directory.FullPath);
|
||||||
|
SqliteTestHelper.Exec(connection, "INSERT INTO columns (title, description, created_at, updated_at) VALUES ('Col', '', 100, 100);");
|
||||||
|
SqliteTestHelper.Exec(connection, "INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES (1, 'T', 'C', 100, 100);");
|
||||||
|
SqliteTestHelper.Exec(connection, "INSERT INTO tags (name, color, description) VALUES ('bug', '#ff0000', '');");
|
||||||
|
SqliteTestHelper.Exec(connection, "INSERT INTO tags (name, color, description) VALUES ('ui', '#00ff00', '');");
|
||||||
|
SqliteTestHelper.Exec(connection, "INSERT INTO card_tags (card_id, tag_id) VALUES (1, 1);");
|
||||||
|
SqliteTestHelper.Exec(connection, "INSERT INTO card_tags (card_id, tag_id) VALUES (1, 2);");
|
||||||
|
|
||||||
|
AppDb = new AppDatabase(Path.Combine(Directory.FullPath, "app.db"), () => Clock);
|
||||||
|
Repository = new WorkspaceRepository(Directory.FullPath, AppDb);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The last_edited_at currently mirrored into the registry.</summary>
|
||||||
|
public long LastEditedAt => AppDb.GetWorkspaces().Single().LastEditedAt;
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
Repository.Dispose();
|
||||||
|
AppDb.Dispose();
|
||||||
|
Directory.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void UpdateColumnWithoutChangeWritesNothing()
|
||||||
|
{
|
||||||
|
using var fixture = new RepositoryFixture();
|
||||||
|
ColumnModel before = fixture.Repository.GetColumn(fixture.ColumnId)!;
|
||||||
|
|
||||||
|
ColumnModel result = fixture.Repository.UpdateColumn(fixture.ColumnId, "Col", "");
|
||||||
|
|
||||||
|
Assert.AreEqual(before.UpdatedAt, result.UpdatedAt);
|
||||||
|
Assert.AreEqual(0, fixture.AppDb.GetWorkspaces().Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void UpdateColumnChangeRefreshesColumnTimestampAndLastEdited()
|
||||||
|
{
|
||||||
|
using var fixture = new RepositoryFixture();
|
||||||
|
fixture.Clock = 2000;
|
||||||
|
|
||||||
|
ColumnModel updated = fixture.Repository.UpdateColumn(fixture.ColumnId, "Col2", "desc");
|
||||||
|
|
||||||
|
Assert.IsTrue(updated.UpdatedAt > 100L);
|
||||||
|
Assert.AreEqual(2000L, fixture.LastEditedAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void DeleteColumnCascadesToCardsAndTagLinks()
|
||||||
|
{
|
||||||
|
using var fixture = new RepositoryFixture();
|
||||||
|
fixture.Clock = 2000;
|
||||||
|
|
||||||
|
Assert.IsTrue(fixture.Repository.DeleteColumn(fixture.ColumnId));
|
||||||
|
|
||||||
|
Assert.AreEqual(0, fixture.Repository.GetCards().Count);
|
||||||
|
// The tags themselves survive the column deletion.
|
||||||
|
Assert.AreEqual(2, fixture.Repository.GetTags().Count);
|
||||||
|
using SqliteConnection connection = SqliteTestHelper.OpenWorkspace(fixture.Directory.FullPath);
|
||||||
|
Assert.AreEqual(0L, SqliteTestHelper.ScalarLong(connection, "SELECT COUNT(*) FROM card_tags;"));
|
||||||
|
Assert.AreEqual(2000L, fixture.LastEditedAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void DeleteCardRemovesTagLinksButKeepsTags()
|
||||||
|
{
|
||||||
|
using var fixture = new RepositoryFixture();
|
||||||
|
|
||||||
|
Assert.IsTrue(fixture.Repository.DeleteCard(fixture.CardId));
|
||||||
|
|
||||||
|
Assert.IsNull(fixture.Repository.GetCard(fixture.CardId));
|
||||||
|
Assert.AreEqual(2, fixture.Repository.GetTags().Count);
|
||||||
|
using SqliteConnection connection = SqliteTestHelper.OpenWorkspace(fixture.Directory.FullPath);
|
||||||
|
Assert.AreEqual(0L, SqliteTestHelper.ScalarLong(connection, "SELECT COUNT(*) FROM card_tags;"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void DeleteTagDetachesFromCardsButKeepsCards()
|
||||||
|
{
|
||||||
|
using var fixture = new RepositoryFixture();
|
||||||
|
|
||||||
|
Assert.IsTrue(fixture.Repository.DeleteTag(fixture.BugTagId));
|
||||||
|
|
||||||
|
Assert.AreEqual(1, fixture.Repository.GetTags().Count);
|
||||||
|
CardModel card = fixture.Repository.GetCard(fixture.CardId)!;
|
||||||
|
Assert.AreEqual(1, card.Tags.Count);
|
||||||
|
Assert.AreEqual("ui", card.Tags[0].Name);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void UpdateCardWithoutEffectiveChangeWritesNothing()
|
||||||
|
{
|
||||||
|
using var fixture = new RepositoryFixture();
|
||||||
|
fixture.Clock = 2000;
|
||||||
|
CardModel before = fixture.Repository.GetCard(fixture.CardId)!;
|
||||||
|
|
||||||
|
CardModel result = fixture.Repository.UpdateCard(fixture.CardId, "T", "C", [fixture.BugTagId, fixture.UiTagId]);
|
||||||
|
|
||||||
|
Assert.AreEqual(before.UpdatedAt, result.UpdatedAt);
|
||||||
|
Assert.AreEqual(0, fixture.AppDb.GetWorkspaces().Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void UpdateCardTitleChangeRefreshesTimestampsAndLastEdited()
|
||||||
|
{
|
||||||
|
using var fixture = new RepositoryFixture();
|
||||||
|
fixture.Clock = 2000;
|
||||||
|
|
||||||
|
CardModel updated = fixture.Repository.UpdateCard(fixture.CardId, "T2", "C", [fixture.BugTagId, fixture.UiTagId]);
|
||||||
|
|
||||||
|
Assert.IsTrue(updated.UpdatedAt > 100L);
|
||||||
|
Assert.AreEqual(2000L, fixture.LastEditedAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void UpdateCardTagSetOnlyChangeStillRefreshesCardTimestamp()
|
||||||
|
{
|
||||||
|
using var fixture = new RepositoryFixture();
|
||||||
|
fixture.Clock = 2000;
|
||||||
|
|
||||||
|
CardModel updated = fixture.Repository.UpdateCard(fixture.CardId, "T", "C", [fixture.BugTagId]);
|
||||||
|
|
||||||
|
Assert.IsTrue(updated.UpdatedAt > 100L);
|
||||||
|
Assert.AreEqual(1, updated.Tags.Count);
|
||||||
|
Assert.AreEqual(2000L, fixture.LastEditedAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void UpdateCardWithUnknownTagRollsBackAtomically()
|
||||||
|
{
|
||||||
|
using var fixture = new RepositoryFixture();
|
||||||
|
fixture.Clock = 2000;
|
||||||
|
|
||||||
|
// Tag 999 does not exist: the FK fires mid-transaction and the whole edit must roll back.
|
||||||
|
Assert.ThrowsExactly<SqliteException>(() =>
|
||||||
|
fixture.Repository.UpdateCard(fixture.CardId, "TX", "CX", [fixture.BugTagId, 999]));
|
||||||
|
|
||||||
|
CardModel after = fixture.Repository.GetCard(fixture.CardId)!;
|
||||||
|
Assert.AreEqual("T", after.Title);
|
||||||
|
Assert.AreEqual("C", after.Content);
|
||||||
|
Assert.AreEqual(100L, after.UpdatedAt);
|
||||||
|
Assert.AreEqual(2, after.Tags.Count);
|
||||||
|
Assert.AreEqual(0, fixture.AppDb.GetWorkspaces().Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void MoveCardRefreshesLastEditedButNotCardTimestamp()
|
||||||
|
{
|
||||||
|
using var fixture = new RepositoryFixture();
|
||||||
|
long target = fixture.Repository.AddColumn("Target", "").Id;
|
||||||
|
fixture.Clock = 2000;
|
||||||
|
|
||||||
|
Assert.IsTrue(fixture.Repository.MoveCard(fixture.CardId, target));
|
||||||
|
|
||||||
|
CardModel moved = fixture.Repository.GetCard(fixture.CardId)!;
|
||||||
|
Assert.AreEqual(target, moved.ColumnId);
|
||||||
|
// The move is a write but deliberately leaves the card's updated_at alone.
|
||||||
|
Assert.AreEqual(100L, moved.UpdatedAt);
|
||||||
|
Assert.AreEqual(2000L, fixture.LastEditedAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void MoveCardToCurrentColumnWritesNothing()
|
||||||
|
{
|
||||||
|
using var fixture = new RepositoryFixture();
|
||||||
|
fixture.Clock = 2000;
|
||||||
|
|
||||||
|
Assert.IsFalse(fixture.Repository.MoveCard(fixture.CardId, fixture.ColumnId));
|
||||||
|
|
||||||
|
Assert.AreEqual(0, fixture.AppDb.GetWorkspaces().Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void AddCardCreatesWithEqualTimestampsAndLinkedTags()
|
||||||
|
{
|
||||||
|
using var fixture = new RepositoryFixture();
|
||||||
|
fixture.Clock = 2000;
|
||||||
|
|
||||||
|
CardModel card = fixture.Repository.AddCard(fixture.ColumnId, "N", "body", [fixture.UiTagId]);
|
||||||
|
|
||||||
|
Assert.IsTrue(card.CreatedAt > 0L);
|
||||||
|
Assert.AreEqual(card.CreatedAt, card.UpdatedAt);
|
||||||
|
Assert.AreEqual(1, card.Tags.Count);
|
||||||
|
Assert.AreEqual("ui", card.Tags[0].Name);
|
||||||
|
Assert.AreEqual(2000L, fixture.LastEditedAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void UpdateTagWithoutChangeWritesNothing()
|
||||||
|
{
|
||||||
|
using var fixture = new RepositoryFixture();
|
||||||
|
fixture.Clock = 2000;
|
||||||
|
|
||||||
|
TagModel result = fixture.Repository.UpdateTag(fixture.BugTagId, "bug", RgbColor.Parse("#ff0000"), "");
|
||||||
|
|
||||||
|
Assert.AreEqual("bug", result.Name);
|
||||||
|
Assert.AreEqual(0, fixture.AppDb.GetWorkspaces().Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void UpdateTagChangeWritesAndTouchesLastEdited()
|
||||||
|
{
|
||||||
|
using var fixture = new RepositoryFixture();
|
||||||
|
fixture.Clock = 3000;
|
||||||
|
|
||||||
|
TagModel updated = fixture.Repository.UpdateTag(fixture.BugTagId, "defect", RgbColor.Parse("#ee0a0a"), "desc");
|
||||||
|
|
||||||
|
Assert.AreEqual("defect", updated.Name);
|
||||||
|
Assert.AreEqual(new RgbColor(0xEE, 0x0A, 0x0A), updated.Color);
|
||||||
|
Assert.AreEqual("desc", updated.Description);
|
||||||
|
Assert.AreEqual(3000L, fixture.LastEditedAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void GetTagsWithUsageCountsAssignments()
|
||||||
|
{
|
||||||
|
using var fixture = new RepositoryFixture();
|
||||||
|
|
||||||
|
IReadOnlyList<(TagModel Tag, long UsageCount)> before = fixture.Repository.GetTagsWithUsage();
|
||||||
|
Assert.AreEqual(1L, before.Single(entry => entry.Tag.Name == "bug").UsageCount);
|
||||||
|
Assert.AreEqual(1L, before.Single(entry => entry.Tag.Name == "ui").UsageCount);
|
||||||
|
|
||||||
|
// Detaching one tag via an edit confirmation drops its usage to zero but keeps the tag.
|
||||||
|
fixture.Clock = 2000;
|
||||||
|
fixture.Repository.UpdateCard(fixture.CardId, "T", "C", [fixture.UiTagId]);
|
||||||
|
|
||||||
|
IReadOnlyList<(TagModel Tag, long UsageCount)> after = fixture.Repository.GetTagsWithUsage();
|
||||||
|
Assert.AreEqual(0L, after.Single(entry => entry.Tag.Name == "bug").UsageCount);
|
||||||
|
Assert.AreEqual(1L, after.Single(entry => entry.Tag.Name == "ui").UsageCount);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
using Microsoft.Data.Sqlite;
|
||||||
|
using YKanBan.Storage;
|
||||||
|
using YKanBan.Storage.Workspace;
|
||||||
|
using YKanBan.Tests.TestUtilities;
|
||||||
|
|
||||||
|
namespace YKanBan.Tests.Storage.Workspace;
|
||||||
|
|
||||||
|
/// <summary>Verifies that the DDL constraints reject invalid data at the door.</summary>
|
||||||
|
[TestClass]
|
||||||
|
public class WorkspaceSchemaTests
|
||||||
|
{
|
||||||
|
/// <summary>Owns a temp directory plus a fresh workspace-schema database for one test.</summary>
|
||||||
|
private sealed class FreshDatabase : IDisposable
|
||||||
|
{
|
||||||
|
public TempDirectory Directory { get; } = new();
|
||||||
|
|
||||||
|
public SqliteConnection Connection { get; }
|
||||||
|
|
||||||
|
public FreshDatabase()
|
||||||
|
{
|
||||||
|
Connection = SqliteDatabase.Open(
|
||||||
|
Path.Combine(Directory.FullPath, "ws.db"), WorkspaceSchema.Migrations);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
Connection.Dispose();
|
||||||
|
Directory.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void EmptyColumnTitleIsRejected()
|
||||||
|
{
|
||||||
|
using var db = new FreshDatabase();
|
||||||
|
using var connection = db.Connection;
|
||||||
|
Assert.ThrowsExactly<SqliteException>(() =>
|
||||||
|
SqliteTestHelper.Exec(connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('', 1, 1);"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void DuplicateColumnTitleIsRejected()
|
||||||
|
{
|
||||||
|
using var db = new FreshDatabase();
|
||||||
|
using var connection = db.Connection;
|
||||||
|
SqliteTestHelper.Exec(connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('Foo', 1, 1);");
|
||||||
|
Assert.ThrowsExactly<SqliteException>(() =>
|
||||||
|
SqliteTestHelper.Exec(connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('Foo', 1, 1);"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void ColumnTitlesCompareCaseSensitively()
|
||||||
|
{
|
||||||
|
using var db = new FreshDatabase();
|
||||||
|
using var connection = db.Connection;
|
||||||
|
// BINARY collation: 'Foo' and 'foo' are distinct titles.
|
||||||
|
SqliteTestHelper.Exec(connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('Foo', 1, 1);");
|
||||||
|
SqliteTestHelper.Exec(connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('foo', 1, 1);");
|
||||||
|
Assert.AreEqual(2L, SqliteTestHelper.ScalarLong(connection, "SELECT COUNT(*) FROM columns;"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void EmptyTagNameIsRejected()
|
||||||
|
{
|
||||||
|
using var db = new FreshDatabase();
|
||||||
|
using var connection = db.Connection;
|
||||||
|
Assert.ThrowsExactly<SqliteException>(() =>
|
||||||
|
SqliteTestHelper.Exec(connection, "INSERT INTO tags (name, color) VALUES ('', '#112233');"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TagNamesAcceptSpacesEmojiAndReservedWords()
|
||||||
|
{
|
||||||
|
using var db = new FreshDatabase();
|
||||||
|
using var connection = db.Connection;
|
||||||
|
// Tag names are fully open: no charset or length rules, no trimming.
|
||||||
|
foreach (string name in new[] { " ", "a b", "🏷️", "AND", "tag:with:colons" })
|
||||||
|
{
|
||||||
|
SqliteTestHelper.Exec(connection, "INSERT INTO tags (name, color) VALUES ($n, '#112233');", ("$n", name));
|
||||||
|
}
|
||||||
|
Assert.AreEqual(5L, SqliteTestHelper.ScalarLong(connection, "SELECT COUNT(*) FROM tags;"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void DuplicateTagNameIsRejected()
|
||||||
|
{
|
||||||
|
using var db = new FreshDatabase();
|
||||||
|
using var connection = db.Connection;
|
||||||
|
SqliteTestHelper.Exec(connection, "INSERT INTO tags (name, color) VALUES ('bug', '#112233');");
|
||||||
|
Assert.ThrowsExactly<SqliteException>(() =>
|
||||||
|
SqliteTestHelper.Exec(connection, "INSERT INTO tags (name, color) VALUES ('bug', '#445566');"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[DataRow("#000000")]
|
||||||
|
[DataRow("#FFFFFF")]
|
||||||
|
[DataRow("#a1B2c3")]
|
||||||
|
public void ValidTagColorsAreAccepted(string color)
|
||||||
|
{
|
||||||
|
using var db = new FreshDatabase();
|
||||||
|
using var connection = db.Connection;
|
||||||
|
int affected = SqliteTestHelper.Exec(connection, "INSERT INTO tags (name, color) VALUES ('x', $c);", ("$c", color));
|
||||||
|
Assert.AreEqual(1, affected);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[DataRow("112233")]
|
||||||
|
[DataRow("#11223")]
|
||||||
|
[DataRow("#1122334")]
|
||||||
|
[DataRow("#G1B2C3")]
|
||||||
|
[DataRow("#a1b2g3")]
|
||||||
|
[DataRow(" #112233")]
|
||||||
|
[DataRow("#112233 ")]
|
||||||
|
[DataRow("")]
|
||||||
|
public void InvalidTagColorsAreRejected(string color)
|
||||||
|
{
|
||||||
|
using var db = new FreshDatabase();
|
||||||
|
using var connection = db.Connection;
|
||||||
|
Assert.ThrowsExactly<SqliteException>(() =>
|
||||||
|
SqliteTestHelper.Exec(connection, "INSERT INTO tags (name, color) VALUES ('x', $c);", ("$c", color)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void CardRequiresExistingColumn()
|
||||||
|
{
|
||||||
|
using var db = new FreshDatabase();
|
||||||
|
using var connection = db.Connection;
|
||||||
|
// foreign_keys=ON makes the FK enforceable; this is the DDL contract behind the cascades.
|
||||||
|
Assert.ThrowsExactly<SqliteException>(() =>
|
||||||
|
SqliteTestHelper.Exec(connection, "INSERT INTO cards (column_id, created_at, updated_at) VALUES (999, 1, 1);"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void CardDefaultsToEmptyTitleAndContent()
|
||||||
|
{
|
||||||
|
using var db = new FreshDatabase();
|
||||||
|
using var connection = db.Connection;
|
||||||
|
SqliteTestHelper.Exec(connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('c', 1, 1);");
|
||||||
|
SqliteTestHelper.Exec(connection, "INSERT INTO cards (column_id, created_at, updated_at) VALUES (1, 1, 1);");
|
||||||
|
|
||||||
|
// No title is represented by the empty string.
|
||||||
|
Assert.AreEqual(string.Empty, SqliteTestHelper.ScalarString(connection, "SELECT title FROM cards WHERE id = 1;"));
|
||||||
|
Assert.AreEqual(string.Empty, SqliteTestHelper.ScalarString(connection, "SELECT content FROM cards WHERE id = 1;"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void CardTagDuplicateAssignmentIsRejected()
|
||||||
|
{
|
||||||
|
using var db = new FreshDatabase();
|
||||||
|
using var connection = db.Connection;
|
||||||
|
SqliteTestHelper.Exec(connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('c', 1, 1);");
|
||||||
|
SqliteTestHelper.Exec(connection, "INSERT INTO cards (column_id, created_at, updated_at) VALUES (1, 1, 1);");
|
||||||
|
SqliteTestHelper.Exec(connection, "INSERT INTO tags (name, color) VALUES ('bug', '#112233');");
|
||||||
|
SqliteTestHelper.Exec(connection, "INSERT INTO card_tags (card_id, tag_id) VALUES (1, 1);");
|
||||||
|
|
||||||
|
// Composite primary key: the same (card, tag) pair cannot be inserted twice.
|
||||||
|
Assert.ThrowsExactly<SqliteException>(() =>
|
||||||
|
SqliteTestHelper.Exec(connection, "INSERT INTO card_tags (card_id, tag_id) VALUES (1, 1);"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
using Microsoft.Data.Sqlite;
|
||||||
|
using YKanBan.Storage;
|
||||||
|
using YKanBan.Storage.Workspace;
|
||||||
|
|
||||||
|
namespace YKanBan.Tests.TestUtilities;
|
||||||
|
|
||||||
|
/// <summary>Shared helpers for storage tests.</summary>
|
||||||
|
public static class SqliteTestHelper
|
||||||
|
{
|
||||||
|
/// <summary>Executes a non-query SQL statement and returns the affected row count.</summary>
|
||||||
|
public static int Exec(SqliteConnection connection, string sql, params (string Name, object? Value)[] parameters)
|
||||||
|
{
|
||||||
|
using var command = connection.CreateCommand();
|
||||||
|
command.CommandText = sql;
|
||||||
|
foreach ((string name, object? value) in parameters)
|
||||||
|
{
|
||||||
|
command.Parameters.AddWithValue(name, value);
|
||||||
|
}
|
||||||
|
return command.ExecuteNonQuery();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Returns the scalar result of a SQL query as a string.</summary>
|
||||||
|
public static string ScalarString(SqliteConnection connection, string sql)
|
||||||
|
{
|
||||||
|
using var command = connection.CreateCommand();
|
||||||
|
command.CommandText = sql;
|
||||||
|
return (string)command.ExecuteScalar()!;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Returns the scalar result of a SQL query as a long.</summary>
|
||||||
|
public static long ScalarLong(SqliteConnection connection, string sql)
|
||||||
|
{
|
||||||
|
using var command = connection.CreateCommand();
|
||||||
|
command.CommandText = sql;
|
||||||
|
return (long)command.ExecuteScalar()!;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Returns true when a table with the given name exists.</summary>
|
||||||
|
public static bool TableExists(SqliteConnection connection, string tableName)
|
||||||
|
{
|
||||||
|
using var command = connection.CreateCommand();
|
||||||
|
command.CommandText = "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name=$name;";
|
||||||
|
command.Parameters.AddWithValue("$name", tableName);
|
||||||
|
return (long)command.ExecuteScalar()! == 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Returns the titles of all columns, ordered by id.</summary>
|
||||||
|
public static List<string> GetColumnTitles(SqliteConnection connection)
|
||||||
|
{
|
||||||
|
using var command = connection.CreateCommand();
|
||||||
|
command.CommandText = "SELECT title FROM columns ORDER BY id ASC;";
|
||||||
|
using var reader = command.ExecuteReader();
|
||||||
|
|
||||||
|
var titles = new List<string>();
|
||||||
|
while (reader.Read())
|
||||||
|
{
|
||||||
|
titles.Add(reader.GetString(0));
|
||||||
|
}
|
||||||
|
return titles;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Opens a workspace database with the real migration list.</summary>
|
||||||
|
public static SqliteConnection OpenWorkspace(string folderPath)
|
||||||
|
{
|
||||||
|
return SqliteDatabase.Open(WorkspacePaths.Database(folderPath), WorkspaceSchema.Migrations);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
namespace YKanBan.Tests.TestUtilities;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Creates a unique temporary directory per test instance and removes it on
|
||||||
|
/// disposal. Retries the deletion once because SQLite WAL files can linger
|
||||||
|
/// for a moment after connections close.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class TempDirectory : IDisposable
|
||||||
|
{
|
||||||
|
/// <summary>Unique directory path managed by this instance.</summary>
|
||||||
|
public string FullPath { get; }
|
||||||
|
|
||||||
|
public TempDirectory()
|
||||||
|
{
|
||||||
|
FullPath = Path.Combine(Path.GetTempPath(), "ykanban-tests-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(FullPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Directory.Delete(FullPath, recursive: true);
|
||||||
|
}
|
||||||
|
catch (IOException)
|
||||||
|
{
|
||||||
|
Thread.Sleep(100);
|
||||||
|
try { Directory.Delete(FullPath, recursive: true); } catch (IOException) { }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net9.0</TargetFramework>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<IsPackable>false</IsPackable>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="MSTest" Version="4.4.1" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\YKanBan\YKanBan.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
</Project>
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
<Solution>
|
<Solution>
|
||||||
<Project Path="YKanBan/YKanBan.csproj" />
|
<Project Path="YKanBan/YKanBan.csproj" />
|
||||||
|
<Project Path="YKanBan.Tests/YKanBan.Tests.csproj" />
|
||||||
</Solution>
|
</Solution>
|
||||||
@@ -1,13 +1,7 @@
|
|||||||
<Application xmlns="https://github.com/avaloniaui"
|
<Application xmlns="https://github.com/avaloniaui"
|
||||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||||
x:Class="YKanBan.App"
|
x:Class="YKanBan.App"
|
||||||
xmlns:local="using:YKanBan"
|
|
||||||
RequestedThemeVariant="Default">
|
RequestedThemeVariant="Default">
|
||||||
<!-- "Default" ThemeVariant follows system theme variant. "Dark" or "Light" are other available options. -->
|
|
||||||
|
|
||||||
<Application.DataTemplates>
|
|
||||||
<local:ViewLocator/>
|
|
||||||
</Application.DataTemplates>
|
|
||||||
|
|
||||||
<Application.Styles>
|
<Application.Styles>
|
||||||
<FluentTheme />
|
<FluentTheme />
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
|
using System.Linq;
|
||||||
using Avalonia;
|
using Avalonia;
|
||||||
using Avalonia.Controls.ApplicationLifetimes;
|
using Avalonia.Controls.ApplicationLifetimes;
|
||||||
using Avalonia.Data.Core;
|
using Avalonia.Data.Core;
|
||||||
using Avalonia.Data.Core.Plugins;
|
using Avalonia.Data.Core.Plugins;
|
||||||
using System.Linq;
|
|
||||||
using Avalonia.Markup.Xaml;
|
using Avalonia.Markup.Xaml;
|
||||||
using YKanBan.ViewModels;
|
using YKanBan.ViewModels;
|
||||||
using YKanBan.Views;
|
using YKanBan.Views;
|
||||||
@@ -20,8 +20,6 @@ public partial class App : Application
|
|||||||
{
|
{
|
||||||
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
|
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
|
||||||
{
|
{
|
||||||
// Avoid duplicate validations from both Avalonia and the CommunityToolkit.
|
|
||||||
// More info: https://docs.avaloniaui.net/docs/guides/development-guides/data-validation#manage-validationplugins
|
|
||||||
DisableAvaloniaDataAnnotationValidation();
|
DisableAvaloniaDataAnnotationValidation();
|
||||||
desktop.MainWindow = new MainWindow
|
desktop.MainWindow = new MainWindow
|
||||||
{
|
{
|
||||||
@@ -34,11 +32,9 @@ public partial class App : Application
|
|||||||
|
|
||||||
private void DisableAvaloniaDataAnnotationValidation()
|
private void DisableAvaloniaDataAnnotationValidation()
|
||||||
{
|
{
|
||||||
// Get an array of plugins to remove
|
|
||||||
var dataValidationPluginsToRemove =
|
var dataValidationPluginsToRemove =
|
||||||
BindingPlugins.DataValidators.OfType<DataAnnotationsValidationPlugin>().ToArray();
|
BindingPlugins.DataValidators.OfType<DataAnnotationsValidationPlugin>().ToArray();
|
||||||
|
|
||||||
// remove each entry found
|
|
||||||
foreach (var plugin in dataValidationPluginsToRemove)
|
foreach (var plugin in dataValidationPluginsToRemove)
|
||||||
{
|
{
|
||||||
BindingPlugins.DataValidators.Remove(plugin);
|
BindingPlugins.DataValidators.Remove(plugin);
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<root>
|
||||||
|
<resheader name="resmimetype">
|
||||||
|
<value>text/microsoft-resx</value>
|
||||||
|
</resheader>
|
||||||
|
<resheader name="version">
|
||||||
|
<value>2.0</value>
|
||||||
|
</resheader>
|
||||||
|
<resheader name="reader">
|
||||||
|
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||||
|
</resheader>
|
||||||
|
<resheader name="writer">
|
||||||
|
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||||
|
</resheader>
|
||||||
|
<data name="PresetColumn_Todo" xml:space="preserve">
|
||||||
|
<value>To Do</value>
|
||||||
|
</data>
|
||||||
|
<data name="PresetColumn_InProgress" xml:space="preserve">
|
||||||
|
<value>In Progress</value>
|
||||||
|
</data>
|
||||||
|
<data name="PresetColumn_Done" xml:space="preserve">
|
||||||
|
<value>Done</value>
|
||||||
|
</data>
|
||||||
|
<data name="Export_FileNamePattern" xml:space="preserve">
|
||||||
|
<value>{0}-export-{1:yyyyMMdd-HHmmss}.md</value>
|
||||||
|
</data>
|
||||||
|
<data name="Export_TimePattern" xml:space="preserve">
|
||||||
|
<value>yyyy-MM-dd HH:mm:ss</value>
|
||||||
|
</data>
|
||||||
|
<data name="Export_CardTimePattern" xml:space="preserve">
|
||||||
|
<value>yyyy-MM-dd HH:mm</value>
|
||||||
|
</data>
|
||||||
|
<data name="Export_WorkspaceHeading" xml:space="preserve">
|
||||||
|
<value># {0}</value>
|
||||||
|
</data>
|
||||||
|
<data name="Export_ExportedAtLine" xml:space="preserve">
|
||||||
|
<value>> Exported at: {0}</value>
|
||||||
|
</data>
|
||||||
|
<data name="Export_ColumnHeading" xml:space="preserve">
|
||||||
|
<value>## Column: {0} ({1})</value>
|
||||||
|
</data>
|
||||||
|
<data name="Export_TagsLine" xml:space="preserve">
|
||||||
|
<value>- Tags: {0}</value>
|
||||||
|
</data>
|
||||||
|
<data name="Export_CreatedModifiedLine" xml:space="preserve">
|
||||||
|
<value>- Created: {0} Modified: {1}</value>
|
||||||
|
</data>
|
||||||
|
<data name="Export_TagsSummaryHeading" xml:space="preserve">
|
||||||
|
<value>## Tags</value>
|
||||||
|
</data>
|
||||||
|
<data name="Export_TagsTableHeader" xml:space="preserve">
|
||||||
|
<value>| Name | Color | Description | Usage |</value>
|
||||||
|
</data>
|
||||||
|
</root>
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<root>
|
||||||
|
<resheader name="resmimetype">
|
||||||
|
<value>text/microsoft-resx</value>
|
||||||
|
</resheader>
|
||||||
|
<resheader name="version">
|
||||||
|
<value>2.0</value>
|
||||||
|
</resheader>
|
||||||
|
<resheader name="reader">
|
||||||
|
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||||
|
</resheader>
|
||||||
|
<resheader name="writer">
|
||||||
|
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||||
|
</resheader>
|
||||||
|
<data name="PresetColumn_Todo" xml:space="preserve">
|
||||||
|
<value>待办</value>
|
||||||
|
</data>
|
||||||
|
<data name="PresetColumn_InProgress" xml:space="preserve">
|
||||||
|
<value>进行中</value>
|
||||||
|
</data>
|
||||||
|
<data name="PresetColumn_Done" xml:space="preserve">
|
||||||
|
<value>已完成</value>
|
||||||
|
</data>
|
||||||
|
<data name="Export_FileNamePattern" xml:space="preserve">
|
||||||
|
<value>{0}-导出-{1:yyyyMMdd-HHmmss}.md</value>
|
||||||
|
</data>
|
||||||
|
<data name="Export_TimePattern" xml:space="preserve">
|
||||||
|
<value>yyyy年M月d日 HH:mm</value>
|
||||||
|
</data>
|
||||||
|
<data name="Export_CardTimePattern" xml:space="preserve">
|
||||||
|
<value>yyyy年M月d日 HH:mm</value>
|
||||||
|
</data>
|
||||||
|
<data name="Export_WorkspaceHeading" xml:space="preserve">
|
||||||
|
<value># {0}</value>
|
||||||
|
</data>
|
||||||
|
<data name="Export_ExportedAtLine" xml:space="preserve">
|
||||||
|
<value>> 导出时间:{0}</value>
|
||||||
|
</data>
|
||||||
|
<data name="Export_ColumnHeading" xml:space="preserve">
|
||||||
|
<value>## 列:{0}({1})</value>
|
||||||
|
</data>
|
||||||
|
<data name="Export_TagsLine" xml:space="preserve">
|
||||||
|
<value>- 标签:{0}</value>
|
||||||
|
</data>
|
||||||
|
<data name="Export_CreatedModifiedLine" xml:space="preserve">
|
||||||
|
<value>- 创建:{0} 修改:{1}</value>
|
||||||
|
</data>
|
||||||
|
<data name="Export_TagsSummaryHeading" xml:space="preserve">
|
||||||
|
<value>## 标签总表</value>
|
||||||
|
</data>
|
||||||
|
<data name="Export_TagsTableHeader" xml:space="preserve">
|
||||||
|
<value>| 名称 | 颜色 | 描述 | 使用数 |</value>
|
||||||
|
</data>
|
||||||
|
</root>
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Text;
|
||||||
|
using YKanBan.Models;
|
||||||
|
|
||||||
|
namespace YKanBan.Export;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Generates the human-readable Markdown snapshot of a whole board. All
|
||||||
|
/// template text and time formats come from the ResX resources in the
|
||||||
|
/// current UI language; the export timestamp uses the per-language pattern,
|
||||||
|
/// card timestamps use the shared minute-precision pattern. The output is
|
||||||
|
/// meant for reading only — there is no re-import.
|
||||||
|
/// </summary>
|
||||||
|
public static class MarkdownExporter
|
||||||
|
{
|
||||||
|
/// <summary>Renders the whole board to Markdown.</summary>
|
||||||
|
/// <param name="workspaceName">Workspace display name (the folder name).</param>
|
||||||
|
/// <param name="columns">All columns, in id order; empty columns are kept.</param>
|
||||||
|
/// <param name="cards">All cards; grouped by column, id order within a column.</param>
|
||||||
|
/// <param name="tags">All tags with usage counts, in id order.</param>
|
||||||
|
/// <param name="exportedAt">Export moment in local time.</param>
|
||||||
|
public static string Export(
|
||||||
|
string workspaceName,
|
||||||
|
IReadOnlyList<ColumnModel> columns,
|
||||||
|
IReadOnlyList<CardModel> cards,
|
||||||
|
IReadOnlyList<(TagModel Tag, long UsageCount)> tags,
|
||||||
|
DateTimeOffset exportedAt)
|
||||||
|
{
|
||||||
|
CultureInfo culture = Resources.Culture ?? CultureInfo.CurrentUICulture;
|
||||||
|
|
||||||
|
var builder = new StringBuilder();
|
||||||
|
|
||||||
|
// Header: workspace name and the export timestamp in the UI language's format.
|
||||||
|
builder.AppendLine(string.Format(culture, Resources.Export_WorkspaceHeading, workspaceName));
|
||||||
|
builder.AppendLine(string.Format(
|
||||||
|
culture, Resources.Export_ExportedAtLine, exportedAt.ToString(Resources.Export_TimePattern, culture)));
|
||||||
|
builder.AppendLine();
|
||||||
|
|
||||||
|
// Board body: every column in id order, empty ones included.
|
||||||
|
foreach (ColumnModel column in columns)
|
||||||
|
{
|
||||||
|
IReadOnlyList<CardModel> cardsInColumn = cards.Where(card => card.ColumnId == column.Id).ToArray();
|
||||||
|
builder.AppendLine(string.Format(culture, Resources.Export_ColumnHeading, column.Title, cardsInColumn.Count));
|
||||||
|
if (column.Description.Length > 0)
|
||||||
|
{
|
||||||
|
builder.AppendLine(SingleLine(column.Description));
|
||||||
|
}
|
||||||
|
builder.AppendLine();
|
||||||
|
|
||||||
|
foreach (CardModel card in cardsInColumn)
|
||||||
|
{
|
||||||
|
AppendCard(builder, card, culture);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
AppendTagTable(builder, tags, culture);
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Builds the default export file name in the UI language, e.g. "MyRepo-export-20260930-142537.md".</summary>
|
||||||
|
public static string BuildFileName(string workspaceName, DateTimeOffset exportedAt)
|
||||||
|
{
|
||||||
|
CultureInfo culture = Resources.Culture ?? CultureInfo.CurrentUICulture;
|
||||||
|
return string.Format(culture, Resources.Export_FileNamePattern, workspaceName, exportedAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Appends one card block: heading, body, tags line, timestamps line.</summary>
|
||||||
|
private static void AppendCard(StringBuilder builder, CardModel card, CultureInfo culture)
|
||||||
|
{
|
||||||
|
// Heading: "#id title"; an untitled card shows only the id.
|
||||||
|
builder.AppendLine(card.Title.Length == 0
|
||||||
|
? $"### #{card.Id}"
|
||||||
|
: $"### #{card.Id} {SingleLine(card.Title)}");
|
||||||
|
|
||||||
|
if (card.Content.Length > 0)
|
||||||
|
{
|
||||||
|
builder.AppendLine(card.Content);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (card.Tags.Count > 0)
|
||||||
|
{
|
||||||
|
string names = string.Join(" ", card.Tags.Select(tag => $"`{tag.Name}`"));
|
||||||
|
builder.AppendLine(string.Format(culture, Resources.Export_TagsLine, names));
|
||||||
|
}
|
||||||
|
|
||||||
|
string created = ToLocalTime(card.CreatedAt).ToString(Resources.Export_CardTimePattern, culture);
|
||||||
|
string updated = ToLocalTime(card.UpdatedAt).ToString(Resources.Export_CardTimePattern, culture);
|
||||||
|
builder.AppendLine(string.Format(culture, Resources.Export_CreatedModifiedLine, created, updated));
|
||||||
|
builder.AppendLine();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Appends the tag summary table with usage counts; tags with zero usage are included.</summary>
|
||||||
|
private static void AppendTagTable(
|
||||||
|
StringBuilder builder,
|
||||||
|
IReadOnlyList<(TagModel Tag, long UsageCount)> tags,
|
||||||
|
CultureInfo culture)
|
||||||
|
{
|
||||||
|
builder.AppendLine(Resources.Export_TagsSummaryHeading);
|
||||||
|
builder.AppendLine(Resources.Export_TagsTableHeader);
|
||||||
|
builder.AppendLine("|---|---|---|---|");
|
||||||
|
foreach ((TagModel tag, long usage) in tags)
|
||||||
|
{
|
||||||
|
// '|' and line breaks would break the table row; neutralize them.
|
||||||
|
builder.AppendLine($"| {Cell(tag.Name)} | {tag.Color} | {Cell(tag.Description)} | {usage} |");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Formats a table cell: single line with escaped pipe characters.</summary>
|
||||||
|
private static string Cell(string text) => SingleLine(text).Replace("|", "\\|");
|
||||||
|
|
||||||
|
/// <summary>Collapses line breaks so the text stays on one Markdown line.</summary>
|
||||||
|
private static string SingleLine(string text) => text.Replace("\r", string.Empty).Replace("\n", " ");
|
||||||
|
|
||||||
|
/// <summary>Converts stored Unix seconds to a local-time DateTimeOffset.</summary>
|
||||||
|
private static DateTimeOffset ToLocalTime(long unixSeconds) =>
|
||||||
|
DateTimeOffset.FromUnixTimeSeconds(unixSeconds).ToLocalTime();
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
namespace YKanBan.Models;
|
||||||
|
|
||||||
|
/// <summary>A card with its assigned tags loaded.</summary>
|
||||||
|
/// <param name="Id">Row id.</param>
|
||||||
|
/// <param name="ColumnId">Owning column.</param>
|
||||||
|
/// <param name="Title">Possibly empty; the empty string is the canonical "no title".</param>
|
||||||
|
/// <param name="Content">Multiline body, possibly empty.</param>
|
||||||
|
/// <param name="CreatedAt">Unix seconds of creation.</param>
|
||||||
|
/// <param name="UpdatedAt">Unix seconds of the last confirmed edit write.</param>
|
||||||
|
/// <param name="Tags">Tags assigned to this card, ordered by tag id.</param>
|
||||||
|
public sealed record CardModel(
|
||||||
|
long Id,
|
||||||
|
long ColumnId,
|
||||||
|
string Title,
|
||||||
|
string Content,
|
||||||
|
long CreatedAt,
|
||||||
|
long UpdatedAt,
|
||||||
|
IReadOnlyList<TagModel> Tags);
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
namespace YKanBan.Models;
|
||||||
|
|
||||||
|
/// <summary>A board column as stored in the workspace database.</summary>
|
||||||
|
/// <param name="Id">Row id.</param>
|
||||||
|
/// <param name="Title">Non-empty unique title.</param>
|
||||||
|
/// <param name="Description">Free-form description, possibly empty.</param>
|
||||||
|
/// <param name="CreatedAt">Unix seconds of creation.</param>
|
||||||
|
/// <param name="UpdatedAt">Unix seconds of the last title/description change.</param>
|
||||||
|
public sealed record ColumnModel(long Id, string Title, string Description, long CreatedAt, long UpdatedAt);
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
namespace YKanBan.Models;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// An RGB color without an alpha channel, stored as one byte per component
|
||||||
|
/// — mirroring the color structures of WinForms, WPF and Avalonia minus
|
||||||
|
/// the alpha byte. The type is total: every combination of components is
|
||||||
|
/// valid, and all validation happens at the text boundary. Converts to and
|
||||||
|
/// from the persisted "#RRGGBB" text form; ToString always produces the
|
||||||
|
/// canonical lowercase form (e.g. "#ff0a00").
|
||||||
|
/// </summary>
|
||||||
|
public readonly record struct RgbColor(byte R, byte G, byte B)
|
||||||
|
{
|
||||||
|
/// <summary>Parses a "#RRGGBB" text with case-insensitive hex digits.</summary>
|
||||||
|
/// <exception cref="FormatException">The text is not in #RRGGBB form.</exception>
|
||||||
|
public static RgbColor Parse(string text) =>
|
||||||
|
TryParse(text, out RgbColor color)
|
||||||
|
? color
|
||||||
|
: throw new FormatException($"Not a valid #RRGGBB color: '{text}'.");
|
||||||
|
|
||||||
|
/// <summary>Attempts to parse a "#RRGGBB" text; no whitespace tolerance.</summary>
|
||||||
|
public static bool TryParse(string? text, out RgbColor color)
|
||||||
|
{
|
||||||
|
color = default;
|
||||||
|
if (text is not { Length: 7 } || text[0] != '#')
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Two hex digits per component: R, G, B.
|
||||||
|
if (TryHexPair(text, 1, out byte r) && TryHexPair(text, 3, out byte g) && TryHexPair(text, 5, out byte b))
|
||||||
|
{
|
||||||
|
color = new RgbColor(r, g, b);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Returns the canonical lowercase "#RRGGBB" form used by the database and exports.</summary>
|
||||||
|
public override string ToString() => $"#{R:x2}{G:x2}{B:x2}";
|
||||||
|
|
||||||
|
/// <summary>Parses exactly two hex digits into a byte value.</summary>
|
||||||
|
private static bool TryHexPair(string text, int start, out byte value)
|
||||||
|
{
|
||||||
|
value = 0;
|
||||||
|
int high = HexDigit(text[start]);
|
||||||
|
int low = HexDigit(text[start + 1]);
|
||||||
|
if (high < 0 || low < 0)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
value = (byte)((high << 4) | low);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Converts one hex digit to its value; -1 for any other character.</summary>
|
||||||
|
private static int HexDigit(char character) => character switch
|
||||||
|
{
|
||||||
|
>= '0' and <= '9' => character - '0',
|
||||||
|
>= 'a' and <= 'f' => character - 'a' + 10,
|
||||||
|
>= 'A' and <= 'F' => character - 'A' + 10,
|
||||||
|
_ => -1,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
namespace YKanBan.Models;
|
||||||
|
|
||||||
|
/// <summary>A tag assignable to cards. Tags are never garbage-collected: unreferenced tags stay until deleted explicitly.</summary>
|
||||||
|
/// <param name="Id">Row id.</param>
|
||||||
|
/// <param name="Name">Arbitrary non-empty text; no charset or length rules.</param>
|
||||||
|
/// <param name="Color">The tag color; persisted as #RRGGBB text.</param>
|
||||||
|
/// <param name="Description">Free-form description, possibly empty.</param>
|
||||||
|
public sealed record TagModel(long Id, string Name, RgbColor Color, string Description);
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
namespace YKanBan.Platform;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Compares and normalizes workspace folder paths. Normalization produces
|
||||||
|
/// the canonical absolute form: separators unified by the operating system,
|
||||||
|
/// "." and ".." collapsed, trailing separator trimmed except on roots.
|
||||||
|
/// Symbolic links are deliberately NOT resolved. Case handling is an
|
||||||
|
/// injected platform rule — ignored on Windows, significant on Unix and
|
||||||
|
/// macOS — so the Unix behavior is testable on any host.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class PathComparer : IEqualityComparer<string>
|
||||||
|
{
|
||||||
|
private readonly StringComparison _comparison;
|
||||||
|
|
||||||
|
/// <summary>Creates a comparer with an explicit case-sensitivity rule.</summary>
|
||||||
|
/// <param name="ignoreCase">True for Windows-style path semantics.</param>
|
||||||
|
public PathComparer(bool ignoreCase)
|
||||||
|
{
|
||||||
|
_comparison = ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The comparer matching the current operating system's path semantics.</summary>
|
||||||
|
public static PathComparer ForCurrentPlatform() => new(OperatingSystem.IsWindows());
|
||||||
|
|
||||||
|
/// <summary>Returns the canonical absolute form used for storage and display.</summary>
|
||||||
|
public string Normalize(string path)
|
||||||
|
{
|
||||||
|
// GetFullPath makes the path absolute, collapses relative segments and
|
||||||
|
// unifies separators; it preserves a trailing separator, so trim it to
|
||||||
|
// keep the canonical form unique ("D:\repo" and "D:\repo\" are one path).
|
||||||
|
string full = Path.GetFullPath(path);
|
||||||
|
return TrimTrailingSeparator(full);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Determines whether two paths denote the same location under the configured platform rules.</summary>
|
||||||
|
public bool Equals(string? x, string? y)
|
||||||
|
{
|
||||||
|
if (x is null || y is null)
|
||||||
|
{
|
||||||
|
return ReferenceEquals(x, y);
|
||||||
|
}
|
||||||
|
return string.Equals(Normalize(x), Normalize(y), _comparison);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Returns a hash code consistent with <see cref="Equals(string?, string?)"/>.</summary>
|
||||||
|
public int GetHashCode(string path) => Normalize(path).GetHashCode(_comparison);
|
||||||
|
|
||||||
|
/// <summary>Removes trailing separators while keeping root forms intact ("C:\", "/").</summary>
|
||||||
|
private static string TrimTrailingSeparator(string fullPath)
|
||||||
|
{
|
||||||
|
bool isDriveRoot = fullPath.Length == 3
|
||||||
|
&& char.IsAsciiLetter(fullPath[0])
|
||||||
|
&& fullPath[1] == ':'
|
||||||
|
&& IsSeparator(fullPath[2]);
|
||||||
|
if (isDriveRoot || fullPath == "/")
|
||||||
|
{
|
||||||
|
return fullPath;
|
||||||
|
}
|
||||||
|
return fullPath.TrimEnd('/', '\\');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Returns true for both supported separator characters.</summary>
|
||||||
|
private static bool IsSeparator(char character) => character is '/' or '\\';
|
||||||
|
}
|
||||||
+2
-6
@@ -1,18 +1,14 @@
|
|||||||
using Avalonia;
|
using System;
|
||||||
using System;
|
using Avalonia;
|
||||||
|
|
||||||
namespace YKanBan;
|
namespace YKanBan;
|
||||||
|
|
||||||
sealed class Program
|
sealed class Program
|
||||||
{
|
{
|
||||||
// Initialization code. Don't use any Avalonia, third-party APIs or any
|
|
||||||
// SynchronizationContext-reliant code before AppMain is called: things aren't initialized
|
|
||||||
// yet and stuff might break.
|
|
||||||
[STAThread]
|
[STAThread]
|
||||||
public static void Main(string[] args) => BuildAvaloniaApp()
|
public static void Main(string[] args) => BuildAvaloniaApp()
|
||||||
.StartWithClassicDesktopLifetime(args);
|
.StartWithClassicDesktopLifetime(args);
|
||||||
|
|
||||||
// Avalonia configuration, don't remove; also used by visual designer.
|
|
||||||
public static AppBuilder BuildAvaloniaApp()
|
public static AppBuilder BuildAvaloniaApp()
|
||||||
=> AppBuilder.Configure<App>()
|
=> AppBuilder.Configure<App>()
|
||||||
.UsePlatformDetect()
|
.UsePlatformDetect()
|
||||||
|
|||||||
@@ -0,0 +1,73 @@
|
|||||||
|
using Pidgin;
|
||||||
|
|
||||||
|
namespace YKanBan.Search;
|
||||||
|
|
||||||
|
/// <summary>Lexical tokens of the search syntax.</summary>
|
||||||
|
public abstract record SearchToken
|
||||||
|
{
|
||||||
|
/// <summary>A bare word; qualifier detection happens later from the text.</summary>
|
||||||
|
public sealed record Word(string Text) : SearchToken;
|
||||||
|
|
||||||
|
/// <summary>A quoted phrase with escapes already resolved.</summary>
|
||||||
|
public sealed record Phrase(string Text) : SearchToken;
|
||||||
|
|
||||||
|
/// <summary>An opening parenthesis.</summary>
|
||||||
|
public sealed record OpenParen : SearchToken;
|
||||||
|
|
||||||
|
/// <summary>A closing parenthesis.</summary>
|
||||||
|
public sealed record CloseParen : SearchToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Pidgin-based lexer for the search syntax. Splits the input into words,
|
||||||
|
/// quoted phrases (with \" and \\ escapes) and parentheses; whitespace only
|
||||||
|
/// separates tokens. The lexer is total: it never rejects input — anything
|
||||||
|
/// the dedicated rules do not cover falls through to the word rule, and an
|
||||||
|
/// unterminated phrase simply extends to the end of the input.
|
||||||
|
/// </summary>
|
||||||
|
public static class SearchLexer
|
||||||
|
{
|
||||||
|
private static readonly Parser<char, char> PhraseCharacter =
|
||||||
|
Parser.Try(Parser.String("\\\"").Select(_ => '"'))
|
||||||
|
.Or(Parser.Try(Parser.String("\\\\").Select(_ => '\\')))
|
||||||
|
.Or(Parser.AnyCharExcept('"'));
|
||||||
|
|
||||||
|
private static readonly Parser<char, SearchToken> PhraseParser =
|
||||||
|
from openingQuote in Parser.Char('"')
|
||||||
|
from content in PhraseCharacter.Many()
|
||||||
|
from closingQuote in Parser.Char('"')
|
||||||
|
select (SearchToken)new SearchToken.Phrase(new string(content.ToArray()));
|
||||||
|
|
||||||
|
private static readonly Parser<char, SearchToken> OpenParenParser =
|
||||||
|
Parser.Char('(').Select(_ => (SearchToken)new SearchToken.OpenParen());
|
||||||
|
|
||||||
|
private static readonly Parser<char, SearchToken> CloseParenParser =
|
||||||
|
Parser.Char(')').Select(_ => (SearchToken)new SearchToken.CloseParen());
|
||||||
|
|
||||||
|
private static readonly Parser<char, SearchToken> WordParser =
|
||||||
|
Parser<char>.Token(c => !char.IsWhiteSpace(c) && c != '(' && c != ')' && c != '"')
|
||||||
|
.AtLeastOnce()
|
||||||
|
.Select(chars => (SearchToken)new SearchToken.Word(new string(chars.ToArray())));
|
||||||
|
|
||||||
|
private static readonly Parser<char, SearchToken> AnyCharacterAsWord =
|
||||||
|
Parser<char>.Any.Select(c => (SearchToken)new SearchToken.Word(c.ToString()));
|
||||||
|
|
||||||
|
private static readonly Parser<char, SearchToken> TokenParser =
|
||||||
|
Parser.SkipWhitespaces.Then(
|
||||||
|
PhraseParser
|
||||||
|
.Or(OpenParenParser)
|
||||||
|
.Or(CloseParenParser)
|
||||||
|
.Or(WordParser)
|
||||||
|
.Or(AnyCharacterAsWord));
|
||||||
|
|
||||||
|
private static readonly Parser<char, IReadOnlyList<SearchToken>> Lexer =
|
||||||
|
// Try(...) keeps a trailing-whitespace failure non-consuming so Many stops
|
||||||
|
// gracefully; the trailing Before(...) then swallows the leftover whitespace.
|
||||||
|
Parser.Try(TokenParser).Many()
|
||||||
|
.Before(Parser.SkipWhitespaces)
|
||||||
|
.Select(tokens => (IReadOnlyList<SearchToken>)tokens.ToList());
|
||||||
|
|
||||||
|
/// <summary>Tokenizes the search text; total over any input.</summary>
|
||||||
|
public static IReadOnlyList<SearchToken> Tokenize(string input) =>
|
||||||
|
Lexer.ParseOrThrow(input);
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
// YYC MARK: C# records synthesize equality by running EqualityComparer<T>.Default
|
||||||
|
// on each positional property. For collection properties (IReadOnlyList<>,
|
||||||
|
// ImmutableArray<>, arrays, ...) that comparer falls back to REFERENCE equality,
|
||||||
|
// so the And/Or nodes below deliberately do NOT compare structurally. The only
|
||||||
|
// structural comparison lives in the test helper (SearchNodeComparer); production
|
||||||
|
// code never compares AST nodes.
|
||||||
|
namespace YKanBan.Search;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Root of the search query AST. Search keywords are fixed English grammar
|
||||||
|
/// and are never localized.
|
||||||
|
/// </summary>
|
||||||
|
public abstract record SearchNode
|
||||||
|
{
|
||||||
|
/// <summary>Disjunction: matches when any term matches (OR).</summary>
|
||||||
|
public sealed record Or(IReadOnlyList<SearchNode> Terms) : SearchNode;
|
||||||
|
|
||||||
|
/// <summary>Conjunction: matches when all terms match (explicit AND or adjacency).</summary>
|
||||||
|
public sealed record And(IReadOnlyList<SearchNode> Terms) : SearchNode;
|
||||||
|
|
||||||
|
/// <summary>A bare word or phrase matched as a substring of the title OR content.</summary>
|
||||||
|
public sealed record FreeText(string Text) : SearchNode;
|
||||||
|
|
||||||
|
/// <summary>A substring match scoped to one card field.</summary>
|
||||||
|
public sealed record FieldText(SearchField Field, string Text) : SearchNode;
|
||||||
|
|
||||||
|
/// <summary>An exact, case-insensitive tag name match.</summary>
|
||||||
|
public sealed record TagName(string Name) : SearchNode;
|
||||||
|
|
||||||
|
/// <summary>An exact, case-insensitive column title match.</summary>
|
||||||
|
public sealed record ColumnTitle(string Title) : SearchNode;
|
||||||
|
|
||||||
|
/// <summary>An exact card id match.</summary>
|
||||||
|
public sealed record CardId(long Id) : SearchNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The card fields a <see cref="SearchNode.FieldText"/> atom can scope to.</summary>
|
||||||
|
public enum SearchField
|
||||||
|
{
|
||||||
|
/// <summary>The card title.</summary>
|
||||||
|
Title,
|
||||||
|
|
||||||
|
/// <summary>The card content body.</summary>
|
||||||
|
Content,
|
||||||
|
}
|
||||||
@@ -0,0 +1,194 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using Pidgin;
|
||||||
|
|
||||||
|
namespace YKanBan.Search;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Thrown when the search text violates the search grammar. Carries the
|
||||||
|
/// underlying parser's descriptive message (including the error position);
|
||||||
|
/// the UI surfaces it as a search error instead of coupling to Pidgin types.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class SearchSyntaxException : Exception
|
||||||
|
{
|
||||||
|
/// <summary>Creates an exception wrapping the original parse failure.</summary>
|
||||||
|
public SearchSyntaxException(string message, Exception innerException)
|
||||||
|
: base(message, innerException)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Parses the search grammar with Pidgin, strictly: any malformed input
|
||||||
|
/// (unbalanced parentheses, dangling operators, unterminated phrases,
|
||||||
|
/// qualifier keys without a value, non-numeric id values) raises
|
||||||
|
/// <see cref="SearchSyntaxException"/>. Only uppercase AND/OR are operators
|
||||||
|
/// (lowercase ones are plain words); AND — explicit or by adjacency — binds
|
||||||
|
/// tighter than OR; parentheses group. Blank input returns null and means
|
||||||
|
/// "show everything".
|
||||||
|
/// </summary>
|
||||||
|
public static class SearchQueryParser
|
||||||
|
{
|
||||||
|
/// <summary>Recognized qualifier kinds; extend <see cref="Qualifiers"/> to add new keys.</summary>
|
||||||
|
private enum QualifierKind
|
||||||
|
{
|
||||||
|
Tag,
|
||||||
|
Title,
|
||||||
|
Content,
|
||||||
|
Id,
|
||||||
|
Column,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The qualifier key table ("key:" prefixes); reserved for future keys like created:.</summary>
|
||||||
|
private static readonly (string Key, QualifierKind Kind)[] Qualifiers =
|
||||||
|
[
|
||||||
|
("tag", QualifierKind.Tag),
|
||||||
|
("title", QualifierKind.Title),
|
||||||
|
("content", QualifierKind.Content),
|
||||||
|
("id", QualifierKind.Id),
|
||||||
|
("column", QualifierKind.Column),
|
||||||
|
];
|
||||||
|
|
||||||
|
#region Token primitives
|
||||||
|
|
||||||
|
private static readonly Parser<SearchToken, SearchToken> AndKeyword =
|
||||||
|
Parser<SearchToken>.Token(new SearchToken.Word("AND"));
|
||||||
|
|
||||||
|
private static readonly Parser<SearchToken, SearchToken> OrKeyword =
|
||||||
|
Parser<SearchToken>.Token(new SearchToken.Word("OR"));
|
||||||
|
|
||||||
|
private static readonly Parser<SearchToken, SearchToken> OpenParen =
|
||||||
|
Parser<SearchToken>.Token((SearchToken)new SearchToken.OpenParen());
|
||||||
|
|
||||||
|
private static readonly Parser<SearchToken, SearchToken> CloseParen =
|
||||||
|
Parser<SearchToken>.Token((SearchToken)new SearchToken.CloseParen());
|
||||||
|
|
||||||
|
/// <summary>The text of a phrase token.</summary>
|
||||||
|
private static readonly Parser<SearchToken, string> PhraseText =
|
||||||
|
Parser<SearchToken>.Token(t => t is SearchToken.Phrase)
|
||||||
|
.Select(t => ((SearchToken.Phrase)t).Text);
|
||||||
|
|
||||||
|
/// <summary>The text of a word token, operator keywords excluded (they never start an operand).</summary>
|
||||||
|
private static readonly Parser<SearchToken, string> NonKeywordWord =
|
||||||
|
Parser<SearchToken>.Token(t => t is SearchToken.Word w && w.Text != "AND" && w.Text != "OR")
|
||||||
|
.Select(t => ((SearchToken.Word)t).Text);
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region Grammar
|
||||||
|
|
||||||
|
// A bare phrase matched against title or content.
|
||||||
|
private static readonly Parser<SearchToken, SearchNode> FreePhrase =
|
||||||
|
PhraseText.Select(text => (SearchNode)new SearchNode.FreeText(text));
|
||||||
|
|
||||||
|
// A bare word: a "key:value" qualifier when the prefix matches, otherwise free text.
|
||||||
|
private static readonly Parser<SearchToken, SearchNode> WordAtom =
|
||||||
|
NonKeywordWord.Bind(QualifierFrom);
|
||||||
|
|
||||||
|
// '(' orExpr ')' — the deferred method call breaks the
|
||||||
|
// Parenthesized → OrExpr → AndExpr → Operand → Parenthesized recursion cycle.
|
||||||
|
private static readonly Parser<SearchToken, SearchNode> Parenthesized =
|
||||||
|
OpenParen.Then(_ => OrExprDeferred()).Before(CloseParen);
|
||||||
|
|
||||||
|
// operand := '(' orExpr ')' | qualifier-or-word | phrase
|
||||||
|
private static readonly Parser<SearchToken, SearchNode> Operand =
|
||||||
|
Parenthesized.Or(WordAtom).Or(FreePhrase);
|
||||||
|
|
||||||
|
// One andExpr operand together with its optional explicit AND keyword.
|
||||||
|
private static readonly Parser<SearchToken, SearchNode> AndPrefixedOperand =
|
||||||
|
AndKeyword.Optional().Then(Operand);
|
||||||
|
|
||||||
|
// andExpr := operand (AND? operand)*
|
||||||
|
private static readonly Parser<SearchToken, SearchNode> AndExpr =
|
||||||
|
Operand.Bind(first =>
|
||||||
|
AndPrefixedOperand.Many()
|
||||||
|
.Select(rest => FoldAnd(first, rest)));
|
||||||
|
|
||||||
|
// orExpr := andExpr (OR andExpr)+
|
||||||
|
private static readonly Parser<SearchToken, SearchNode> OrExpr =
|
||||||
|
AndExpr.SeparatedAtLeastOnce(OrKeyword)
|
||||||
|
.Select(FoldOr);
|
||||||
|
|
||||||
|
// The full query: orExpr consuming the whole token stream.
|
||||||
|
private static readonly Parser<SearchToken, SearchNode> Query =
|
||||||
|
OrExpr.Before(Parser<SearchToken>.End);
|
||||||
|
|
||||||
|
/// <summary>Defers the OrExpr field read to parse time (recursion cycle breaker).</summary>
|
||||||
|
private static Parser<SearchToken, SearchNode> OrExprDeferred() => OrExpr;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
/// <summary>Parses a search box text; returns null for blank input (meaning: show everything).</summary>
|
||||||
|
/// <exception cref="SearchSyntaxException">The text violates the grammar.</exception>
|
||||||
|
public static SearchNode? Parse(string text)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(text))
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
List<SearchToken> tokens = SearchLexer.Tokenize(text).ToList();
|
||||||
|
return Query.ParseOrThrow(tokens);
|
||||||
|
}
|
||||||
|
catch (ParseException ex)
|
||||||
|
{
|
||||||
|
throw new SearchSyntaxException(ex.Message, ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Builds the parser for one word operand: qualifier atom or free text.</summary>
|
||||||
|
private static Parser<SearchToken, SearchNode> QualifierFrom(string word)
|
||||||
|
{
|
||||||
|
foreach ((string key, QualifierKind kind) in Qualifiers)
|
||||||
|
{
|
||||||
|
// Qualifier keys are case-sensitive lowercase grammar tokens.
|
||||||
|
if (!word.StartsWith(key + ":", StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
string value = word[(key.Length + 1)..];
|
||||||
|
|
||||||
|
// "key:" without an inline value takes the value from the following phrase, e.g. tag:"a b".
|
||||||
|
return value.Length == 0
|
||||||
|
? PhraseText.Bind(text => AtomParser(kind, text))
|
||||||
|
: AtomParser(kind, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
// No qualifier prefix: a plain free-text word.
|
||||||
|
return Parser<SearchToken>.Return<SearchNode>(new SearchNode.FreeText(word));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Builds the atom parser for a qualifier value, failing strictly on a non-numeric id.</summary>
|
||||||
|
private static Parser<SearchToken, SearchNode> AtomParser(QualifierKind kind, string value)
|
||||||
|
{
|
||||||
|
return AtomFrom(kind, value) is { } atom
|
||||||
|
? Parser<SearchToken>.Return(atom)
|
||||||
|
: Parser<SearchToken>.Fail<SearchNode>($"id: expects an integer, got '{value}'.");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Builds the atom for a qualifier value; null when an id value is not an integer.</summary>
|
||||||
|
private static SearchNode? AtomFrom(QualifierKind kind, string value) => kind switch
|
||||||
|
{
|
||||||
|
QualifierKind.Tag => new SearchNode.TagName(value),
|
||||||
|
QualifierKind.Title => new SearchNode.FieldText(SearchField.Title, value),
|
||||||
|
QualifierKind.Content => new SearchNode.FieldText(SearchField.Content, value),
|
||||||
|
QualifierKind.Column => new SearchNode.ColumnTitle(value),
|
||||||
|
QualifierKind.Id when long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out long id) => new SearchNode.CardId(id),
|
||||||
|
_ => null,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>Collapses an AND chain into a single node.</summary>
|
||||||
|
private static SearchNode FoldAnd(SearchNode first, IEnumerable<SearchNode> rest)
|
||||||
|
{
|
||||||
|
List<SearchNode> terms = [first, .. rest];
|
||||||
|
return terms.Count == 1 ? terms[0] : new SearchNode.And(terms);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Collapses an OR chain into a single node.</summary>
|
||||||
|
private static SearchNode FoldOr(IEnumerable<SearchNode> terms)
|
||||||
|
{
|
||||||
|
List<SearchNode> list = terms.ToList();
|
||||||
|
return list.Count == 1 ? list[0] : new SearchNode.Or(list);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
namespace YKanBan.Search;
|
||||||
|
|
||||||
|
/// <summary>A compiled search predicate: a SQL fragment over the "c" (cards) alias plus its bound parameters.</summary>
|
||||||
|
/// <param name="Predicate">SQL boolean expression; intended for "SELECT ... FROM cards c WHERE {Predicate}".</param>
|
||||||
|
/// <param name="Parameters">Named parameters referenced by the predicate, in order.</param>
|
||||||
|
public sealed record CompiledSearch(string Predicate, IReadOnlyList<(string Name, object Value)> Parameters);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Compiles a parsed search AST into a parameterized SQL predicate.
|
||||||
|
/// Matching is case-insensitive with SQLite's built-in ASCII semantics:
|
||||||
|
/// LIKE's default case folding plus COLLATE NOCASE for exact matches.
|
||||||
|
/// LIKE wildcards and the escape character in user text are escaped so they
|
||||||
|
/// match literally.
|
||||||
|
/// </summary>
|
||||||
|
public static class SearchSqlCompiler
|
||||||
|
{
|
||||||
|
/// <summary>Compiles the query into a SQL predicate.</summary>
|
||||||
|
public static CompiledSearch Compile(SearchNode query)
|
||||||
|
{
|
||||||
|
var parameters = new List<(string Name, object Value)>();
|
||||||
|
string predicate = Build(query, parameters);
|
||||||
|
return new CompiledSearch(predicate, parameters);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Recursively builds the SQL expression for one node.</summary>
|
||||||
|
private static string Build(SearchNode node, List<(string Name, object Value)> parameters)
|
||||||
|
{
|
||||||
|
switch (node)
|
||||||
|
{
|
||||||
|
case SearchNode.And and:
|
||||||
|
return "(" + string.Join(" AND ", and.Terms.Select(term => Build(term, parameters))) + ")";
|
||||||
|
|
||||||
|
case SearchNode.Or or:
|
||||||
|
return "(" + string.Join(" OR ", or.Terms.Select(term => Build(term, parameters))) + ")";
|
||||||
|
|
||||||
|
case SearchNode.FreeText freeText:
|
||||||
|
{
|
||||||
|
// A bare word matches a substring of the title OR the content.
|
||||||
|
string titleParam = AddParameter(parameters, "%" + EscapeLike(freeText.Text) + "%");
|
||||||
|
string contentParam = AddParameter(parameters, "%" + EscapeLike(freeText.Text) + "%");
|
||||||
|
return $"(c.title LIKE {titleParam} ESCAPE '\\' OR c.content LIKE {contentParam} ESCAPE '\\')";
|
||||||
|
}
|
||||||
|
|
||||||
|
case SearchNode.FieldText field:
|
||||||
|
{
|
||||||
|
string column = field.Field == SearchField.Title ? "c.title" : "c.content";
|
||||||
|
string param = AddParameter(parameters, "%" + EscapeLike(field.Text) + "%");
|
||||||
|
return $"{column} LIKE {param} ESCAPE '\\'";
|
||||||
|
}
|
||||||
|
|
||||||
|
case SearchNode.TagName tag:
|
||||||
|
{
|
||||||
|
string param = AddParameter(parameters, tag.Name);
|
||||||
|
return "EXISTS (SELECT 1 FROM card_tags ct JOIN tags t ON t.id = ct.tag_id " +
|
||||||
|
$"WHERE ct.card_id = c.id AND t.name COLLATE NOCASE = {param})";
|
||||||
|
}
|
||||||
|
|
||||||
|
case SearchNode.ColumnTitle column:
|
||||||
|
{
|
||||||
|
string param = AddParameter(parameters, column.Title);
|
||||||
|
return $"c.column_id IN (SELECT id FROM columns WHERE title COLLATE NOCASE = {param})";
|
||||||
|
}
|
||||||
|
|
||||||
|
case SearchNode.CardId id:
|
||||||
|
{
|
||||||
|
string param = AddParameter(parameters, id.Id);
|
||||||
|
return $"c.id = {param}";
|
||||||
|
}
|
||||||
|
|
||||||
|
default:
|
||||||
|
throw new InvalidOperationException($"Unsupported search node: {node.GetType().Name}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Binds a value under a fresh name and returns the SQL placeholder.</summary>
|
||||||
|
private static string AddParameter(List<(string Name, object Value)> parameters, object value)
|
||||||
|
{
|
||||||
|
string name = "$p" + parameters.Count.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||||
|
parameters.Add((name, value));
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Escapes LIKE wildcards and the escape character inside user text.</summary>
|
||||||
|
private static string EscapeLike(string text) =>
|
||||||
|
text.Replace("\\", "\\\\").Replace("%", "\\%").Replace("_", "\\_");
|
||||||
|
}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
using System.Runtime.Serialization;
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
|
||||||
|
namespace YKanBan.Storage.AppData;
|
||||||
|
|
||||||
|
/// <summary>Card ordering options. All orders fall back to id ascending.</summary>
|
||||||
|
public enum CardSortOption
|
||||||
|
{
|
||||||
|
/// <summary>Ascending primary key (default).</summary>
|
||||||
|
[EnumMember(Value = "id")]
|
||||||
|
Id,
|
||||||
|
|
||||||
|
/// <summary>Creation time, oldest first.</summary>
|
||||||
|
[EnumMember(Value = "created-at")]
|
||||||
|
CreatedAt,
|
||||||
|
|
||||||
|
/// <summary>Last modification time, most recent first.</summary>
|
||||||
|
[EnumMember(Value = "updated-at")]
|
||||||
|
UpdatedAt,
|
||||||
|
|
||||||
|
/// <summary>Title by code points (BINARY collation); empty titles sort first.</summary>
|
||||||
|
[EnumMember(Value = "title")]
|
||||||
|
Title,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Sidebar workspace list ordering.</summary>
|
||||||
|
public enum SidebarSortOption
|
||||||
|
{
|
||||||
|
/// <summary>Folder name A to Z.</summary>
|
||||||
|
[EnumMember(Value = "name-asc")]
|
||||||
|
NameAsc,
|
||||||
|
|
||||||
|
/// <summary>Folder name Z to A.</summary>
|
||||||
|
[EnumMember(Value = "name-desc")]
|
||||||
|
NameDesc,
|
||||||
|
|
||||||
|
/// <summary>By workspace last edit time, most recent first.</summary>
|
||||||
|
[EnumMember(Value = "recently-updated")]
|
||||||
|
RecentlyUpdated,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Column width presets. Custom uses a user-defined pixel width.</summary>
|
||||||
|
public enum ColumnWidthPreset
|
||||||
|
{
|
||||||
|
/// <summary>Narrow preset.</summary>
|
||||||
|
[EnumMember(Value = "narrow")]
|
||||||
|
Narrow,
|
||||||
|
|
||||||
|
/// <summary>Standard preset (320 px, the default).</summary>
|
||||||
|
[EnumMember(Value = "standard")]
|
||||||
|
Standard,
|
||||||
|
|
||||||
|
/// <summary>Wide preset.</summary>
|
||||||
|
[EnumMember(Value = "wide")]
|
||||||
|
Wide,
|
||||||
|
|
||||||
|
/// <summary>User-defined pixel width (160–720).</summary>
|
||||||
|
[EnumMember(Value = "custom")]
|
||||||
|
Custom,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>UI theme selection.</summary>
|
||||||
|
public enum ThemeOption
|
||||||
|
{
|
||||||
|
/// <summary>Always light.</summary>
|
||||||
|
[EnumMember(Value = "light")]
|
||||||
|
Light,
|
||||||
|
|
||||||
|
/// <summary>Always dark.</summary>
|
||||||
|
[EnumMember(Value = "dark")]
|
||||||
|
Dark,
|
||||||
|
|
||||||
|
/// <summary>Follow the operating system setting (default).</summary>
|
||||||
|
[EnumMember(Value = "follow-system")]
|
||||||
|
FollowSystem,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Card and sidebar list ordering settings.</summary>
|
||||||
|
public sealed class SortSettings
|
||||||
|
{
|
||||||
|
/// <summary>Card order used by all workspaces (global, not per workspace).</summary>
|
||||||
|
[JsonProperty("card")]
|
||||||
|
public CardSortOption Card { get; set; } = CardSortOption.Id;
|
||||||
|
|
||||||
|
/// <summary>Sidebar workspace list order.</summary>
|
||||||
|
[JsonProperty("sidebar")]
|
||||||
|
public SidebarSortOption Sidebar { get; set; } = SidebarSortOption.NameAsc;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Board column width settings.</summary>
|
||||||
|
public sealed class ColumnWidthSettings
|
||||||
|
{
|
||||||
|
/// <summary>Width preset applied globally.</summary>
|
||||||
|
[JsonProperty("preset")]
|
||||||
|
public ColumnWidthPreset Preset { get; set; } = ColumnWidthPreset.Standard;
|
||||||
|
|
||||||
|
/// <summary>Manual width in pixels used when <see cref="Preset"/> is Custom (range 160–720).</summary>
|
||||||
|
[JsonProperty("custom-pixels")]
|
||||||
|
public int CustomPixels { get; set; } = 320;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Confirmation-dialog toggles for destructive actions.</summary>
|
||||||
|
public sealed class ConfirmationSettings
|
||||||
|
{
|
||||||
|
/// <summary>Whether deleting a card asks for confirmation.</summary>
|
||||||
|
[JsonProperty("delete-card")]
|
||||||
|
public bool DeleteCard { get; set; } = true;
|
||||||
|
|
||||||
|
/// <summary>Whether deleting a column asks for confirmation.</summary>
|
||||||
|
[JsonProperty("delete-column")]
|
||||||
|
public bool DeleteColumn { get; set; } = true;
|
||||||
|
|
||||||
|
/// <summary>Whether deleting a tag asks for confirmation.</summary>
|
||||||
|
[JsonProperty("delete-tag")]
|
||||||
|
public bool DeleteTag { get; set; } = true;
|
||||||
|
|
||||||
|
/// <summary>Whether discarding card edits asks for confirmation.</summary>
|
||||||
|
[JsonProperty("discard-edit")]
|
||||||
|
public bool DiscardEdit { get; set; } = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Root object of app.json — the trivial KV configuration store. Serialized
|
||||||
|
/// as a whole with kebab-case names (declared via [JsonProperty] and
|
||||||
|
/// [EnumMember]); the "version" field is the migration hook for future
|
||||||
|
/// format changes.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class AppConfig
|
||||||
|
{
|
||||||
|
/// <summary>Current configuration format version.</summary>
|
||||||
|
public const int CurrentFormatVersion = 1;
|
||||||
|
|
||||||
|
/// <summary>Configuration format version of this file.</summary>
|
||||||
|
[JsonProperty("version")]
|
||||||
|
public int Version { get; set; } = CurrentFormatVersion;
|
||||||
|
|
||||||
|
/// <summary>UI language code: "en" (default) or "zh-Hans".</summary>
|
||||||
|
[JsonProperty("language")]
|
||||||
|
public string Language { get; set; } = "en";
|
||||||
|
|
||||||
|
/// <summary>UI theme selection (default: follow the system).</summary>
|
||||||
|
[JsonProperty("theme")]
|
||||||
|
public ThemeOption Theme { get; set; } = ThemeOption.FollowSystem;
|
||||||
|
|
||||||
|
/// <summary>Ordering settings.</summary>
|
||||||
|
[JsonProperty("sort")]
|
||||||
|
public SortSettings Sort { get; set; } = new();
|
||||||
|
|
||||||
|
/// <summary>Column width settings.</summary>
|
||||||
|
[JsonProperty("column-width")]
|
||||||
|
public ColumnWidthSettings ColumnWidth { get; set; } = new();
|
||||||
|
|
||||||
|
/// <summary>Confirmation-dialog settings.</summary>
|
||||||
|
[JsonProperty("confirmations")]
|
||||||
|
public ConfirmationSettings Confirmations { get; set; } = new();
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
using Newtonsoft.Json;
|
||||||
|
using Newtonsoft.Json.Converters;
|
||||||
|
|
||||||
|
namespace YKanBan.Storage.AppData;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Loads and saves app.json with graceful degradation: a missing file yields
|
||||||
|
/// defaults; a corrupt file is backed up to app.json.bak and then defaults
|
||||||
|
/// are used. Saving writes the file directly (no atomic replace) — losing
|
||||||
|
/// the last session's settings to a crash is an accepted trade-off.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class AppConfigStore
|
||||||
|
{
|
||||||
|
private static readonly JsonSerializerSettings SerializerSettings = new()
|
||||||
|
{
|
||||||
|
Formatting = Formatting.Indented,
|
||||||
|
NullValueHandling = NullValueHandling.Ignore,
|
||||||
|
|
||||||
|
// Enums round-trip through the kebab-case strings declared via [EnumMember].
|
||||||
|
Converters = { new StringEnumConverter() },
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>Creates a store bound to a specific app.json path.</summary>
|
||||||
|
public AppConfigStore(string filePath) => FilePath = filePath;
|
||||||
|
|
||||||
|
/// <summary>Full path of the managed app.json file.</summary>
|
||||||
|
public string FilePath { get; }
|
||||||
|
|
||||||
|
/// <summary>Loads the configuration: missing file → defaults; corrupt file → backup then defaults.</summary>
|
||||||
|
/// <exception cref="IOException">The file exists but cannot be read.</exception>
|
||||||
|
public AppConfig Load()
|
||||||
|
{
|
||||||
|
// Missing file is a normal first-run state: run with defaults.
|
||||||
|
if (!File.Exists(FilePath))
|
||||||
|
{
|
||||||
|
return new AppConfig();
|
||||||
|
}
|
||||||
|
|
||||||
|
string json = File.ReadAllText(FilePath);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// A JSON null literal deserializes to null; treat it like defaults.
|
||||||
|
AppConfig? config = JsonConvert.DeserializeObject<AppConfig>(json, SerializerSettings);
|
||||||
|
if (config is null)
|
||||||
|
{
|
||||||
|
return new AppConfig();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Older or hand-edited files may miss whole sections; each falls back to its defaults.
|
||||||
|
config.Sort ??= new SortSettings();
|
||||||
|
config.ColumnWidth ??= new ColumnWidthSettings();
|
||||||
|
config.Confirmations ??= new ConfirmationSettings();
|
||||||
|
return config;
|
||||||
|
}
|
||||||
|
catch (JsonException)
|
||||||
|
{
|
||||||
|
// Corrupt: keep a copy for inspection, then continue with defaults.
|
||||||
|
File.Copy(FilePath, FilePath + ".bak", overwrite: true);
|
||||||
|
return new AppConfig();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Writes the configuration directly to disk (no atomic replace).</summary>
|
||||||
|
public void Save(AppConfig config)
|
||||||
|
{
|
||||||
|
// Create the parent folder on demand; normally it exists already.
|
||||||
|
string? directory = Path.GetDirectoryName(FilePath);
|
||||||
|
if (!string.IsNullOrEmpty(directory))
|
||||||
|
{
|
||||||
|
Directory.CreateDirectory(directory);
|
||||||
|
}
|
||||||
|
File.WriteAllText(FilePath, JsonConvert.SerializeObject(config, SerializerSettings));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
using Microsoft.Data.Sqlite;
|
||||||
|
|
||||||
|
namespace YKanBan.Storage.AppData;
|
||||||
|
|
||||||
|
/// <summary>A known workspace row of the global app.db.</summary>
|
||||||
|
/// <param name="Path">Workspace folder path as registered.</param>
|
||||||
|
/// <param name="LastEditedAt">Unix seconds of the last successful data write to the workspace database.</param>
|
||||||
|
/// <param name="AddedAt">Unix seconds when the workspace was registered.</param>
|
||||||
|
public sealed record WorkspaceRecord(string Path, long LastEditedAt, long AddedAt);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Global application database (app.db): stores the persistent workspace
|
||||||
|
/// list. Any successful data write into a workspace database must be
|
||||||
|
/// mirrored here by refreshing last_edited_at (the write-through is wired
|
||||||
|
/// by the repository layer). Uses the same PRAGMA configuration as the
|
||||||
|
/// workspace databases.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class AppDatabase : IDisposable
|
||||||
|
{
|
||||||
|
/// <summary>Latest app.db schema version this build understands.</summary>
|
||||||
|
public const int CurrentSchemaVersion = 1;
|
||||||
|
|
||||||
|
private static readonly IReadOnlyList<SchemaMigration> Migrations = new SchemaMigration[]
|
||||||
|
{
|
||||||
|
new SchemaMigration(CurrentSchemaVersion, "initial schema", """
|
||||||
|
CREATE TABLE workspaces (
|
||||||
|
path TEXT PRIMARY KEY,
|
||||||
|
last_edited_at INTEGER NOT NULL,
|
||||||
|
added_at INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
"""),
|
||||||
|
};
|
||||||
|
|
||||||
|
private readonly SqliteConnection _connection;
|
||||||
|
private readonly Func<long> _unixNow;
|
||||||
|
private readonly object _gate = new();
|
||||||
|
|
||||||
|
/// <summary>Opens (creating if needed) the app.db file and applies pending migrations.</summary>
|
||||||
|
/// <param name="databasePath">Path of the app.db file.</param>
|
||||||
|
/// <param name="unixNow">Clock override for tests; defaults to real Unix time.</param>
|
||||||
|
public AppDatabase(string databasePath, Func<long>? unixNow = null)
|
||||||
|
{
|
||||||
|
// Ensure the application data folder exists before creating the database file.
|
||||||
|
string? directory = Path.GetDirectoryName(databasePath);
|
||||||
|
if (!string.IsNullOrEmpty(directory))
|
||||||
|
{
|
||||||
|
Directory.CreateDirectory(directory);
|
||||||
|
}
|
||||||
|
|
||||||
|
_unixNow = unixNow ?? (() => UnixTime.Now);
|
||||||
|
_connection = SqliteDatabase.Open(databasePath, Migrations);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Returns all known workspaces ordered by added_at ascending.</summary>
|
||||||
|
public IReadOnlyList<WorkspaceRecord> GetWorkspaces()
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
using var command = _connection.CreateCommand();
|
||||||
|
command.CommandText = "SELECT path, last_edited_at, added_at FROM workspaces ORDER BY added_at ASC, path ASC;";
|
||||||
|
using var reader = command.ExecuteReader();
|
||||||
|
|
||||||
|
var records = new List<WorkspaceRecord>();
|
||||||
|
while (reader.Read())
|
||||||
|
{
|
||||||
|
records.Add(new WorkspaceRecord(reader.GetString(0), reader.GetInt64(1), reader.GetInt64(2)));
|
||||||
|
}
|
||||||
|
return records;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Registers a workspace, or refreshes last_edited_at if it is already known.</summary>
|
||||||
|
public void UpsertWorkspace(string path)
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
long now = _unixNow();
|
||||||
|
using var command = _connection.CreateCommand();
|
||||||
|
// On conflict only last_edited_at moves; the original added_at is preserved.
|
||||||
|
command.CommandText = """
|
||||||
|
INSERT INTO workspaces (path, last_edited_at, added_at)
|
||||||
|
VALUES ($path, $now, $now)
|
||||||
|
ON CONFLICT(path) DO UPDATE SET last_edited_at = $now;
|
||||||
|
""";
|
||||||
|
command.Parameters.AddWithValue("$path", path);
|
||||||
|
command.Parameters.AddWithValue("$now", now);
|
||||||
|
command.ExecuteNonQuery();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Refreshes last_edited_at for a known workspace; registers it if the row is absent.</summary>
|
||||||
|
public void TouchLastEdited(string path)
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
using var command = _connection.CreateCommand();
|
||||||
|
command.CommandText = "UPDATE workspaces SET last_edited_at = $now WHERE path = $path;";
|
||||||
|
command.Parameters.AddWithValue("$path", path);
|
||||||
|
command.Parameters.AddWithValue("$now", _unixNow());
|
||||||
|
if (command.ExecuteNonQuery() == 0)
|
||||||
|
{
|
||||||
|
// Self-healing path: a workspace opened before registration still gets a row.
|
||||||
|
UpsertWorkspace(path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Forgets a workspace entry; the .ykanban folder itself is untouched.</summary>
|
||||||
|
public void RemoveWorkspace(string path)
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
using var command = _connection.CreateCommand();
|
||||||
|
command.CommandText = "DELETE FROM workspaces WHERE path = $path;";
|
||||||
|
command.Parameters.AddWithValue("$path", path);
|
||||||
|
command.ExecuteNonQuery();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Closes the underlying connection.</summary>
|
||||||
|
public void Dispose() => _connection.Dispose();
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
namespace YKanBan.Storage;
|
||||||
|
|
||||||
|
/// <summary>A single incremental schema step applied when the stored user_version is one below <see cref="Version"/>.</summary>
|
||||||
|
/// <param name="Version">Target user_version after applying this migration (contiguous, starting at 1).</param>
|
||||||
|
/// <param name="Name">Short human-readable identifier used for diagnostics.</param>
|
||||||
|
/// <param name="Sql">SQL script executed inside one transaction together with the user_version bump.</param>
|
||||||
|
public sealed record SchemaMigration(int Version, string Name, string Sql);
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
using Microsoft.Data.Sqlite;
|
||||||
|
|
||||||
|
namespace YKanBan.Storage;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Shared SQLite plumbing for both the per-workspace databases and the
|
||||||
|
/// global app.db: opens connections with the mandated PRAGMA configuration
|
||||||
|
/// (WAL journal, NORMAL synchronous mode, foreign keys on) and applies
|
||||||
|
/// incremental user_version migrations.
|
||||||
|
/// </summary>
|
||||||
|
public static class SqliteDatabase
|
||||||
|
{
|
||||||
|
/// <summary>Opens (creating if needed) a database file, applies PRAGMAs and pending migrations.</summary>
|
||||||
|
/// <param name="databasePath">Path of the SQLite database file.</param>
|
||||||
|
/// <param name="migrations">Contiguous migration list, ordered by version starting at 1.</param>
|
||||||
|
/// <returns>An open connection with all PRAGMAs applied and the schema migrated.</returns>
|
||||||
|
public static SqliteConnection Open(string databasePath, IReadOnlyList<SchemaMigration> migrations)
|
||||||
|
{
|
||||||
|
var connection = new SqliteConnection(new SqliteConnectionStringBuilder
|
||||||
|
{
|
||||||
|
DataSource = databasePath,
|
||||||
|
Mode = SqliteOpenMode.ReadWriteCreate,
|
||||||
|
Pooling = false,
|
||||||
|
}.ToString());
|
||||||
|
connection.Open();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
ApplyPragmas(connection);
|
||||||
|
ApplyMigrations(connection, migrations);
|
||||||
|
return connection;
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
connection.Dispose();
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Reads the stored PRAGMA user_version value.</summary>
|
||||||
|
public static long ReadUserVersion(SqliteConnection connection)
|
||||||
|
{
|
||||||
|
using var command = connection.CreateCommand();
|
||||||
|
command.CommandText = "PRAGMA user_version;";
|
||||||
|
return (long)command.ExecuteScalar()!;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Applies per-connection PRAGMAs. WAL itself is a persistent database property.</summary>
|
||||||
|
internal static void ApplyPragmas(SqliteConnection connection)
|
||||||
|
{
|
||||||
|
// WAL plus NORMAL synchronous is the chosen durability/performance trade-off;
|
||||||
|
// foreign_keys must be enabled on every connection or DDL-level cascades never fire.
|
||||||
|
Execute(connection, "PRAGMA journal_mode=WAL;");
|
||||||
|
Execute(connection, "PRAGMA synchronous=NORMAL;");
|
||||||
|
Execute(connection, "PRAGMA foreign_keys=ON;");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Runs every migration newer than the stored user_version, each in its own transaction.</summary>
|
||||||
|
/// <exception cref="SchemaVersionException">The database was written by a newer build.</exception>
|
||||||
|
/// <exception cref="ArgumentException">The migration list is not contiguous from version 1.</exception>
|
||||||
|
internal static void ApplyMigrations(SqliteConnection connection, IReadOnlyList<SchemaMigration> migrations)
|
||||||
|
{
|
||||||
|
// Contract check: the list must be contiguous and ordered, starting at version 1.
|
||||||
|
for (int index = 0; index < migrations.Count; index++)
|
||||||
|
{
|
||||||
|
if (migrations[index].Version != index + 1)
|
||||||
|
{
|
||||||
|
throw new ArgumentException("Migrations must be contiguous and start at version 1.", nameof(migrations));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
long current = ReadUserVersion(connection);
|
||||||
|
int latest = migrations.Count;
|
||||||
|
|
||||||
|
// A database written by a newer build cannot be managed by this one; refuse loudly.
|
||||||
|
if (current > latest)
|
||||||
|
{
|
||||||
|
throw new SchemaVersionException(current, latest);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply each pending migration atomically so a crash never leaves a half-migrated database.
|
||||||
|
foreach (SchemaMigration migration in migrations)
|
||||||
|
{
|
||||||
|
if (migration.Version <= current)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
using var transaction = connection.BeginTransaction();
|
||||||
|
Execute(connection, migration.Sql, transaction);
|
||||||
|
Execute(connection, $"PRAGMA user_version={migration.Version};", transaction);
|
||||||
|
transaction.Commit();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Executes a non-query SQL script, optionally inside an explicit transaction.</summary>
|
||||||
|
private static void Execute(SqliteConnection connection, string commandText, SqliteTransaction? transaction = null)
|
||||||
|
{
|
||||||
|
using var command = connection.CreateCommand();
|
||||||
|
command.Transaction = transaction;
|
||||||
|
command.CommandText = commandText;
|
||||||
|
command.ExecuteNonQuery();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
namespace YKanBan.Storage;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Typed exceptions thrown by the YKanBan storage and application layers.
|
||||||
|
/// Exception messages are always English and never localized; the UI maps
|
||||||
|
/// exception types to localized resource keys instead.
|
||||||
|
/// </summary>
|
||||||
|
public abstract class YKanBanException : Exception
|
||||||
|
{
|
||||||
|
/// <summary>Creates an exception with an English diagnostic message.</summary>
|
||||||
|
protected YKanBanException(string message, Exception? innerException = null)
|
||||||
|
: base(message, innerException)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Signals that the workspace folder does not exist on disk.</summary>
|
||||||
|
public sealed class WorkspaceDirectoryMissingException : YKanBanException
|
||||||
|
{
|
||||||
|
/// <summary>The folder path that was expected to exist.</summary>
|
||||||
|
public string FolderPath { get; }
|
||||||
|
|
||||||
|
/// <summary>Creates an exception for a folder that is absent on disk.</summary>
|
||||||
|
public WorkspaceDirectoryMissingException(string folderPath)
|
||||||
|
: base($"The folder does not exist: {folderPath}")
|
||||||
|
{
|
||||||
|
FolderPath = folderPath;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Signals that the folder has no .ykanban structure yet.</summary>
|
||||||
|
public sealed class WorkspaceNotInitializedException : YKanBanException
|
||||||
|
{
|
||||||
|
/// <summary>The folder path that lacks the .ykanban structure.</summary>
|
||||||
|
public string FolderPath { get; }
|
||||||
|
|
||||||
|
/// <summary>Creates an exception for a folder without .ykanban.</summary>
|
||||||
|
public WorkspaceNotInitializedException(string folderPath)
|
||||||
|
: base($"The folder is not a YKanBan workspace (missing .ykanban): {folderPath}")
|
||||||
|
{
|
||||||
|
FolderPath = folderPath;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Signals that another instance holds the workspace lock.</summary>
|
||||||
|
public sealed class WorkspaceLockException : YKanBanException
|
||||||
|
{
|
||||||
|
/// <summary>The lock file that could not be acquired.</summary>
|
||||||
|
public string LockFilePath { get; }
|
||||||
|
|
||||||
|
/// <summary>Best-effort diagnostics (PID/machine/time) read from the lock file, if readable.</summary>
|
||||||
|
public string? HolderDiagnostics { get; }
|
||||||
|
|
||||||
|
/// <summary>Creates an exception for a failed lock acquisition.</summary>
|
||||||
|
public WorkspaceLockException(string lockFilePath, string? holderDiagnostics, Exception innerException)
|
||||||
|
: base(BuildMessage(lockFilePath, holderDiagnostics), innerException)
|
||||||
|
{
|
||||||
|
LockFilePath = lockFilePath;
|
||||||
|
HolderDiagnostics = holderDiagnostics;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Composes the message, including holder details when they were readable.</summary>
|
||||||
|
private static string BuildMessage(string lockFilePath, string? holderDiagnostics)
|
||||||
|
{
|
||||||
|
string message = $"The workspace is locked by another instance: {lockFilePath}";
|
||||||
|
if (!string.IsNullOrEmpty(holderDiagnostics))
|
||||||
|
{
|
||||||
|
message += $" Lock holder: {holderDiagnostics}";
|
||||||
|
}
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Signals that the stored schema version is not manageable by this build.</summary>
|
||||||
|
public sealed class SchemaVersionException : YKanBanException
|
||||||
|
{
|
||||||
|
/// <summary>The user_version value found in the database.</summary>
|
||||||
|
public long StoredVersion { get; }
|
||||||
|
|
||||||
|
/// <summary>The latest schema version this build understands.</summary>
|
||||||
|
public int SupportedVersion { get; }
|
||||||
|
|
||||||
|
/// <summary>Creates an exception for an unmanageable schema version.</summary>
|
||||||
|
public SchemaVersionException(long storedVersion, int supportedVersion)
|
||||||
|
: base($"Database schema version {storedVersion} is newer than the latest supported version {supportedVersion}.")
|
||||||
|
{
|
||||||
|
StoredVersion = storedVersion;
|
||||||
|
SupportedVersion = supportedVersion;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
namespace YKanBan.Storage;
|
||||||
|
|
||||||
|
/// <summary>Provides the current Unix time; all persisted timestamps are INTEGER Unix seconds.</summary>
|
||||||
|
public static class UnixTime
|
||||||
|
{
|
||||||
|
/// <summary>Current UTC time as Unix seconds.</summary>
|
||||||
|
public static long Now => DateTimeOffset.UtcNow.ToUnixTimeSeconds();
|
||||||
|
}
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
using YKanBan.Platform;
|
||||||
|
using YKanBan.Storage.AppData;
|
||||||
|
|
||||||
|
namespace YKanBan.Storage.Workspace;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Fixed-capacity LRU pool of open workspace sessions (exclusive lock plus
|
||||||
|
/// repository per workspace). Opening a workspace also registers it in the
|
||||||
|
/// global app.db sidebar registry. Eviction — by capacity or explicitly —
|
||||||
|
/// only releases resources: the sidebar entry survives, and the workspace
|
||||||
|
/// can be reopened at any time (a lock held elsewhere then surfaces as a
|
||||||
|
/// lock conflict).
|
||||||
|
/// </summary>
|
||||||
|
public sealed class WorkspaceConnectionPool : IDisposable
|
||||||
|
{
|
||||||
|
private readonly object _gate = new();
|
||||||
|
private readonly int _capacity;
|
||||||
|
private readonly AppDatabase _appDatabase;
|
||||||
|
private readonly PathComparer _pathComparer;
|
||||||
|
private readonly Dictionary<string, LinkedListNode<WorkspaceSession>> _sessions;
|
||||||
|
private readonly LinkedList<WorkspaceSession> _recency = new();
|
||||||
|
|
||||||
|
/// <summary>Creates a pool.</summary>
|
||||||
|
/// <param name="capacity">Maximum number of simultaneously open workspaces.</param>
|
||||||
|
/// <param name="appDatabase">Global registry for sidebar entries and last_edited_at.</param>
|
||||||
|
/// <param name="pathComparer">Platform path rules used to identify workspaces.</param>
|
||||||
|
public WorkspaceConnectionPool(int capacity, AppDatabase appDatabase, PathComparer pathComparer)
|
||||||
|
{
|
||||||
|
ArgumentOutOfRangeException.ThrowIfLessThan(capacity, 1);
|
||||||
|
_capacity = capacity;
|
||||||
|
_appDatabase = appDatabase;
|
||||||
|
_pathComparer = pathComparer;
|
||||||
|
_sessions = new Dictionary<string, LinkedListNode<WorkspaceSession>>(pathComparer);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Number of currently open workspaces.</summary>
|
||||||
|
public int OpenCount
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
return _sessions.Count;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Returns the open session and marks it most recently used, or null when the workspace is not open.</summary>
|
||||||
|
public WorkspaceSession? Find(string folderPath)
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
if (_sessions.TryGetValue(_pathComparer.Normalize(folderPath), out LinkedListNode<WorkspaceSession>? node))
|
||||||
|
{
|
||||||
|
Promote(node);
|
||||||
|
return node.Value;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Records user activity (click/switch) for an open workspace; no-op when it is not open.</summary>
|
||||||
|
public void Touch(string folderPath) => Find(folderPath);
|
||||||
|
|
||||||
|
/// <summary>Opens the workspace session, or returns the existing one; evicts LRU entries beyond capacity.</summary>
|
||||||
|
/// <exception cref="WorkspaceDirectoryMissingException">The folder does not exist.</exception>
|
||||||
|
/// <exception cref="WorkspaceNotInitializedException">The folder has no .ykanban.</exception>
|
||||||
|
/// <exception cref="WorkspaceLockException">Another instance holds the lock.</exception>
|
||||||
|
public WorkspaceSession Open(string folderPath)
|
||||||
|
{
|
||||||
|
string canonical = _pathComparer.Normalize(folderPath);
|
||||||
|
|
||||||
|
// Fast path: already open → promote and return.
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
if (_sessions.TryGetValue(canonical, out LinkedListNode<WorkspaceSession>? open))
|
||||||
|
{
|
||||||
|
Promote(open);
|
||||||
|
return open.Value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate the folder state up front so callers get precise state errors.
|
||||||
|
if (!Directory.Exists(canonical))
|
||||||
|
{
|
||||||
|
throw new WorkspaceDirectoryMissingException(canonical);
|
||||||
|
}
|
||||||
|
if (!WorkspaceInitializer.IsWorkspace(canonical))
|
||||||
|
{
|
||||||
|
throw new WorkspaceNotInitializedException(canonical);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Acquire the exclusive lock before touching the database.
|
||||||
|
WorkspaceLock workspaceLock = WorkspaceLock.Acquire(canonical);
|
||||||
|
WorkspaceSession session;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var repository = new WorkspaceRepository(canonical, _appDatabase);
|
||||||
|
session = new WorkspaceSession
|
||||||
|
{
|
||||||
|
FolderPath = canonical,
|
||||||
|
Lock = workspaceLock,
|
||||||
|
Repository = repository,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
workspaceLock.Dispose();
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
// Re-check: another open may have won the race; the existing session wins.
|
||||||
|
if (_sessions.TryGetValue(canonical, out LinkedListNode<WorkspaceSession>? winner))
|
||||||
|
{
|
||||||
|
session.Dispose();
|
||||||
|
Promote(winner);
|
||||||
|
return winner.Value;
|
||||||
|
}
|
||||||
|
|
||||||
|
_sessions.Add(canonical, _recency.AddFirst(session));
|
||||||
|
|
||||||
|
// Evict least recently used entries beyond capacity; releases resources only.
|
||||||
|
while (_sessions.Count > _capacity)
|
||||||
|
{
|
||||||
|
LinkedListNode<WorkspaceSession> lru = _recency.Last!;
|
||||||
|
_recency.RemoveLast();
|
||||||
|
_sessions.Remove(lru.Value.FolderPath);
|
||||||
|
lru.Value.Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Opening registers the workspace in the persistent sidebar registry.
|
||||||
|
_appDatabase.UpsertWorkspace(canonical);
|
||||||
|
return session;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Releases a workspace's resources; the sidebar entry is kept. Returns true when it was open.</summary>
|
||||||
|
public bool Close(string folderPath)
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
if (!_sessions.Remove(_pathComparer.Normalize(folderPath), out LinkedListNode<WorkspaceSession>? node))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
_recency.Remove(node);
|
||||||
|
node.Value.Dispose();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Releases the workspace's resources and removes its sidebar entry. Returns true when it was open.</summary>
|
||||||
|
public bool Remove(string folderPath)
|
||||||
|
{
|
||||||
|
string canonical = _pathComparer.Normalize(folderPath);
|
||||||
|
bool wasOpen = Close(canonical);
|
||||||
|
_appDatabase.RemoveWorkspace(canonical);
|
||||||
|
return wasOpen;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Releases all sessions.</summary>
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
foreach (WorkspaceSession session in _recency)
|
||||||
|
{
|
||||||
|
session.Dispose();
|
||||||
|
}
|
||||||
|
_recency.Clear();
|
||||||
|
_sessions.Clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Moves a session node to the most-recently-used position.</summary>
|
||||||
|
private void Promote(LinkedListNode<WorkspaceSession> node)
|
||||||
|
{
|
||||||
|
_recency.Remove(node);
|
||||||
|
_recency.AddFirst(node);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
using Microsoft.Data.Sqlite;
|
||||||
|
|
||||||
|
namespace YKanBan.Storage.Workspace;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Creates the .ykanban structure for a folder: the folder itself and an
|
||||||
|
/// empty, fully migrated database. Seeding preset content is a separate
|
||||||
|
/// concern handled by <see cref="WorkspacePreset"/>.
|
||||||
|
/// </summary>
|
||||||
|
public static class WorkspaceInitializer
|
||||||
|
{
|
||||||
|
/// <summary>Returns true when the folder contains a .ykanban structure (no parent lookup).</summary>
|
||||||
|
public static bool IsWorkspace(string folderPath) => Directory.Exists(WorkspacePaths.Root(folderPath));
|
||||||
|
|
||||||
|
/// <summary>Initializes a fresh workspace: creates .ykanban and an empty migrated database.</summary>
|
||||||
|
/// <exception cref="WorkspaceDirectoryMissingException">The folder does not exist on disk.</exception>
|
||||||
|
/// <exception cref="InvalidOperationException">The workspace database already exists.</exception>
|
||||||
|
public static void Initialize(string folderPath)
|
||||||
|
{
|
||||||
|
if (!Directory.Exists(folderPath))
|
||||||
|
{
|
||||||
|
throw new WorkspaceDirectoryMissingException(folderPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
string databasePath = WorkspacePaths.Database(folderPath);
|
||||||
|
if (File.Exists(databasePath))
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException($"The workspace database already exists: {databasePath}");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create the .ykanban folder and the migrated, still empty database.
|
||||||
|
Directory.CreateDirectory(WorkspacePaths.Root(folderPath));
|
||||||
|
using SqliteConnection connection = SqliteDatabase.Open(databasePath, WorkspaceSchema.Migrations);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace YKanBan.Storage.Workspace;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Exclusive, OS-enforced lock over a workspace's ykanban.lock. The handle
|
||||||
|
/// is held until disposal; crashes and power loss release it automatically.
|
||||||
|
/// The lock file carries PID / machine name / time for human diagnostics
|
||||||
|
/// only.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class WorkspaceLock : IDisposable
|
||||||
|
{
|
||||||
|
private readonly FileStream _stream;
|
||||||
|
|
||||||
|
private WorkspaceLock(FileStream stream, string lockFilePath)
|
||||||
|
{
|
||||||
|
_stream = stream;
|
||||||
|
LockFilePath = lockFilePath;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Path of the lock file being held.</summary>
|
||||||
|
public string LockFilePath { get; }
|
||||||
|
|
||||||
|
/// <summary>Acquires the workspace lock or throws <see cref="WorkspaceLockException"/>.</summary>
|
||||||
|
/// <exception cref="WorkspaceNotInitializedException">The folder has no .ykanban structure.</exception>
|
||||||
|
/// <exception cref="WorkspaceLockException">Another instance holds the lock.</exception>
|
||||||
|
public static WorkspaceLock Acquire(string folderPath)
|
||||||
|
{
|
||||||
|
string lockFilePath = WorkspacePaths.LockFile(folderPath);
|
||||||
|
FileStream stream;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// FileShare.None gives the exclusive semantics; FileMode.Create truncates any stale content.
|
||||||
|
stream = new FileStream(lockFilePath, FileMode.Create, FileAccess.Write, FileShare.None);
|
||||||
|
}
|
||||||
|
catch (DirectoryNotFoundException)
|
||||||
|
{
|
||||||
|
throw new WorkspaceNotInitializedException(folderPath);
|
||||||
|
}
|
||||||
|
catch (IOException ex)
|
||||||
|
{
|
||||||
|
throw new WorkspaceLockException(lockFilePath, ReadDiagnosticsBestEffort(lockFilePath), ex);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write holder diagnostics so humans can identify the owning instance from the file alone.
|
||||||
|
string diagnostics = $"pid={Environment.ProcessId};machine={Environment.MachineName};time={DateTimeOffset.UtcNow:O}";
|
||||||
|
byte[] payload = Encoding.UTF8.GetBytes(diagnostics);
|
||||||
|
stream.Write(payload, 0, payload.Length);
|
||||||
|
stream.Flush();
|
||||||
|
return new WorkspaceLock(stream, lockFilePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Attempts to read holder diagnostics from a lock file we failed to acquire.</summary>
|
||||||
|
private static string? ReadDiagnosticsBestEffort(string lockFilePath)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return File.ReadAllText(lockFilePath);
|
||||||
|
}
|
||||||
|
catch (IOException)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
catch (UnauthorizedAccessException)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Releases the exclusive handle. The lock file itself is intentionally left on disk.</summary>
|
||||||
|
public void Dispose() => _stream.Dispose();
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
namespace YKanBan.Storage.Workspace;
|
||||||
|
|
||||||
|
/// <summary>Well-known file and folder names inside a workspace's .ykanban structure.</summary>
|
||||||
|
public static class WorkspacePaths
|
||||||
|
{
|
||||||
|
/// <summary>Name of the workspace root folder created inside a managed project.</summary>
|
||||||
|
public const string RootFolderName = ".ykanban";
|
||||||
|
|
||||||
|
/// <summary>Name of the SQLite database inside .ykanban.</summary>
|
||||||
|
public const string DatabaseFileName = "ykanban.db";
|
||||||
|
|
||||||
|
/// <summary>Name of the exclusive lock file inside .ykanban.</summary>
|
||||||
|
public const string LockFileName = "ykanban.lock";
|
||||||
|
|
||||||
|
/// <summary>Returns the .ykanban root path for a workspace folder.</summary>
|
||||||
|
public static string Root(string folderPath) => Path.Combine(folderPath, RootFolderName);
|
||||||
|
|
||||||
|
/// <summary>Returns the workspace database path for a workspace folder.</summary>
|
||||||
|
public static string Database(string folderPath) => Path.Combine(folderPath, RootFolderName, DatabaseFileName);
|
||||||
|
|
||||||
|
/// <summary>Returns the workspace lock file path for a workspace folder.</summary>
|
||||||
|
public static string LockFile(string folderPath) => Path.Combine(folderPath, RootFolderName, LockFileName);
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
using Microsoft.Data.Sqlite;
|
||||||
|
|
||||||
|
namespace YKanBan.Storage.Workspace;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Seeds initial workspace content. The three preset column titles are read
|
||||||
|
/// straight from the ResX resources in the UI language active at seeding
|
||||||
|
/// time, then stored as ordinary data that no longer follows language
|
||||||
|
/// switches.
|
||||||
|
/// </summary>
|
||||||
|
public static class WorkspacePreset
|
||||||
|
{
|
||||||
|
/// <summary>Inserts the three preset columns (To Do / In Progress / Done equivalents).</summary>
|
||||||
|
/// <exception cref="SqliteException">A title collides with an existing column.</exception>
|
||||||
|
public static void SeedColumns(string folderPath)
|
||||||
|
{
|
||||||
|
using SqliteConnection connection = SqliteDatabase.Open(
|
||||||
|
WorkspacePaths.Database(folderPath), WorkspaceSchema.Migrations);
|
||||||
|
|
||||||
|
long now = UnixTime.Now;
|
||||||
|
|
||||||
|
// Preset titles are data at creation time: whatever the current language says gets stored.
|
||||||
|
string[] titles =
|
||||||
|
[
|
||||||
|
Resources.PresetColumn_Todo,
|
||||||
|
Resources.PresetColumn_InProgress,
|
||||||
|
Resources.PresetColumn_Done,
|
||||||
|
];
|
||||||
|
|
||||||
|
// Insert all three in one transaction so a half-seeded workspace can never exist.
|
||||||
|
using var transaction = connection.BeginTransaction();
|
||||||
|
foreach (string title in titles)
|
||||||
|
{
|
||||||
|
using var command = connection.CreateCommand();
|
||||||
|
command.Transaction = transaction;
|
||||||
|
command.CommandText = """
|
||||||
|
INSERT INTO columns (title, description, created_at, updated_at)
|
||||||
|
VALUES ($title, '', $now, $now);
|
||||||
|
""";
|
||||||
|
command.Parameters.AddWithValue("$title", title);
|
||||||
|
command.Parameters.AddWithValue("$now", now);
|
||||||
|
command.ExecuteNonQuery();
|
||||||
|
}
|
||||||
|
transaction.Commit();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,446 @@
|
|||||||
|
using Microsoft.Data.Sqlite;
|
||||||
|
using YKanBan.Models;
|
||||||
|
using YKanBan.Storage.AppData;
|
||||||
|
|
||||||
|
namespace YKanBan.Storage.Workspace;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Data access for one open workspace database: CRUD for columns, cards and
|
||||||
|
/// tags, card moves and tag assignment, plus the write-through that
|
||||||
|
/// refreshes the workspace's last_edited_at in the global app.db after
|
||||||
|
/// every successful data write.
|
||||||
|
///
|
||||||
|
/// Timestamp rules:
|
||||||
|
/// - cards.updated_at refreshes only when a card edit is confirmed with
|
||||||
|
/// changes; moving a card to another column never refreshes it;
|
||||||
|
/// - columns.updated_at refreshes only when title or description changes;
|
||||||
|
/// - a confirmation with no effective change performs no write at all.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class WorkspaceRepository : IDisposable
|
||||||
|
{
|
||||||
|
private readonly string _folderPath;
|
||||||
|
private readonly AppDatabase _appDatabase;
|
||||||
|
private readonly SqliteConnection _connection;
|
||||||
|
|
||||||
|
/// <summary>Opens the repository over an initialized workspace database.</summary>
|
||||||
|
/// <param name="folderPath">Workspace folder; the exact value is used as the app.db registry key.</param>
|
||||||
|
/// <param name="appDatabase">Global registry refreshed after every successful write.</param>
|
||||||
|
public WorkspaceRepository(string folderPath, AppDatabase appDatabase)
|
||||||
|
{
|
||||||
|
_folderPath = folderPath;
|
||||||
|
_appDatabase = appDatabase;
|
||||||
|
_connection = SqliteDatabase.Open(WorkspacePaths.Database(folderPath), WorkspaceSchema.Migrations);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Closes the underlying connection.</summary>
|
||||||
|
public void Dispose() => _connection.Dispose();
|
||||||
|
|
||||||
|
#region Columns
|
||||||
|
|
||||||
|
/// <summary>Returns all columns ordered by id.</summary>
|
||||||
|
public IReadOnlyList<ColumnModel> GetColumns()
|
||||||
|
{
|
||||||
|
using var command = CreateCommand(
|
||||||
|
"SELECT id, title, description, created_at, updated_at FROM columns ORDER BY id ASC;");
|
||||||
|
using var reader = command.ExecuteReader();
|
||||||
|
|
||||||
|
var columns = new List<ColumnModel>();
|
||||||
|
while (reader.Read())
|
||||||
|
{
|
||||||
|
columns.Add(ReadColumn(reader));
|
||||||
|
}
|
||||||
|
return columns;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Returns the column with the given id, or null.</summary>
|
||||||
|
public ColumnModel? GetColumn(long columnId)
|
||||||
|
{
|
||||||
|
using var command = CreateCommand(
|
||||||
|
"SELECT id, title, description, created_at, updated_at FROM columns WHERE id = $id;");
|
||||||
|
command.Parameters.AddWithValue("$id", columnId);
|
||||||
|
using var reader = command.ExecuteReader();
|
||||||
|
return reader.Read() ? ReadColumn(reader) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Creates a column with created_at = updated_at.</summary>
|
||||||
|
/// <exception cref="SqliteException">The title is empty or not unique.</exception>
|
||||||
|
public ColumnModel AddColumn(string title, string description)
|
||||||
|
{
|
||||||
|
long now = UnixTime.Now;
|
||||||
|
using var transaction = _connection.BeginTransaction();
|
||||||
|
long id = ExecuteInsert(transaction,
|
||||||
|
"INSERT INTO columns (title, description, created_at, updated_at) VALUES ($title, $description, $now, $now);",
|
||||||
|
("$title", title), ("$description", description), ("$now", now));
|
||||||
|
transaction.Commit();
|
||||||
|
|
||||||
|
TouchEdited();
|
||||||
|
return new ColumnModel(id, title, description, now, now);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Rewrites title and description; a no-change call writes nothing.</summary>
|
||||||
|
/// <exception cref="InvalidOperationException">The column does not exist.</exception>
|
||||||
|
/// <exception cref="SqliteException">The new title is empty or not unique.</exception>
|
||||||
|
public ColumnModel UpdateColumn(long columnId, string title, string description)
|
||||||
|
{
|
||||||
|
ColumnModel existing = GetColumn(columnId)
|
||||||
|
?? throw new InvalidOperationException($"Column {columnId} does not exist.");
|
||||||
|
|
||||||
|
// Unchanged title and description: no write, no timestamps.
|
||||||
|
if (existing.Title == title && existing.Description == description)
|
||||||
|
{
|
||||||
|
return existing;
|
||||||
|
}
|
||||||
|
|
||||||
|
long now = UnixTime.Now;
|
||||||
|
using var command = CreateCommand(
|
||||||
|
"UPDATE columns SET title = $title, description = $description, updated_at = $now WHERE id = $id;");
|
||||||
|
command.Parameters.AddWithValue("$title", title);
|
||||||
|
command.Parameters.AddWithValue("$description", description);
|
||||||
|
command.Parameters.AddWithValue("$now", now);
|
||||||
|
command.Parameters.AddWithValue("$id", columnId);
|
||||||
|
command.ExecuteNonQuery();
|
||||||
|
|
||||||
|
TouchEdited();
|
||||||
|
return new ColumnModel(columnId, title, description, existing.CreatedAt, now);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Deletes a column; the DDL cascade removes its cards and their tag links. Returns true when a row was deleted.</summary>
|
||||||
|
public bool DeleteColumn(long columnId) => ExecuteDelete("DELETE FROM columns WHERE id = $id;", columnId);
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region Cards
|
||||||
|
|
||||||
|
/// <summary>Returns all cards with their tags loaded, ordered by id.</summary>
|
||||||
|
public IReadOnlyList<CardModel> GetCards()
|
||||||
|
{
|
||||||
|
using var command = CreateCommand("""
|
||||||
|
SELECT c.id, c.column_id, c.title, c.content, c.created_at, c.updated_at,
|
||||||
|
t.id, t.name, t.color, t.description
|
||||||
|
FROM cards c
|
||||||
|
LEFT JOIN card_tags ct ON ct.card_id = c.id
|
||||||
|
LEFT JOIN tags t ON t.id = ct.tag_id
|
||||||
|
ORDER BY c.id ASC;
|
||||||
|
""");
|
||||||
|
using var reader = command.ExecuteReader();
|
||||||
|
|
||||||
|
// Single grouped pass: one output card per distinct card id, its tags accumulated alongside.
|
||||||
|
var cards = new List<CardModel>();
|
||||||
|
var tagsByCard = new Dictionary<long, List<TagModel>>();
|
||||||
|
while (reader.Read())
|
||||||
|
{
|
||||||
|
long cardId = reader.GetInt64(0);
|
||||||
|
if (!tagsByCard.TryGetValue(cardId, out List<TagModel>? tags))
|
||||||
|
{
|
||||||
|
tags = new List<TagModel>();
|
||||||
|
tagsByCard[cardId] = tags;
|
||||||
|
cards.Add(new CardModel(
|
||||||
|
cardId,
|
||||||
|
reader.GetInt64(1),
|
||||||
|
reader.GetString(2),
|
||||||
|
reader.GetString(3),
|
||||||
|
reader.GetInt64(4),
|
||||||
|
reader.GetInt64(5),
|
||||||
|
tags));
|
||||||
|
}
|
||||||
|
if (!reader.IsDBNull(6))
|
||||||
|
{
|
||||||
|
tags.Add(new TagModel(reader.GetInt64(6), reader.GetString(7), RgbColor.Parse(reader.GetString(8)), reader.GetString(9)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return cards;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Returns the card with the given id (tags loaded), or null.</summary>
|
||||||
|
public CardModel? GetCard(long cardId)
|
||||||
|
{
|
||||||
|
using var command = CreateCommand("""
|
||||||
|
SELECT c.id, c.column_id, c.title, c.content, c.created_at, c.updated_at,
|
||||||
|
t.id, t.name, t.color, t.description
|
||||||
|
FROM cards c
|
||||||
|
LEFT JOIN card_tags ct ON ct.card_id = c.id
|
||||||
|
LEFT JOIN tags t ON t.id = ct.tag_id
|
||||||
|
WHERE c.id = $id
|
||||||
|
ORDER BY c.id ASC;
|
||||||
|
""");
|
||||||
|
command.Parameters.AddWithValue("$id", cardId);
|
||||||
|
using var reader = command.ExecuteReader();
|
||||||
|
|
||||||
|
CardModel? card = null;
|
||||||
|
var tags = new List<TagModel>();
|
||||||
|
while (reader.Read())
|
||||||
|
{
|
||||||
|
if (card is null)
|
||||||
|
{
|
||||||
|
card = new CardModel(
|
||||||
|
reader.GetInt64(0),
|
||||||
|
reader.GetInt64(1),
|
||||||
|
reader.GetString(2),
|
||||||
|
reader.GetString(3),
|
||||||
|
reader.GetInt64(4),
|
||||||
|
reader.GetInt64(5),
|
||||||
|
tags);
|
||||||
|
}
|
||||||
|
if (!reader.IsDBNull(6))
|
||||||
|
{
|
||||||
|
tags.Add(new TagModel(reader.GetInt64(6), reader.GetString(7), RgbColor.Parse(reader.GetString(8)), reader.GetString(9)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return card;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Creates a card with its initial tag assignment (created_at = updated_at).</summary>
|
||||||
|
/// <exception cref="SqliteException">The column does not exist, or a tag id does not exist.</exception>
|
||||||
|
public CardModel AddCard(long columnId, string title, string content, IReadOnlyCollection<long> tagIds)
|
||||||
|
{
|
||||||
|
long now = UnixTime.Now;
|
||||||
|
using var transaction = _connection.BeginTransaction();
|
||||||
|
long id = ExecuteInsert(transaction,
|
||||||
|
"INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES ($columnId, $title, $content, $now, $now);",
|
||||||
|
("$columnId", columnId), ("$title", title), ("$content", content), ("$now", now));
|
||||||
|
foreach (long tagId in tagIds.Distinct())
|
||||||
|
{
|
||||||
|
ExecuteNonQuery(transaction,
|
||||||
|
"INSERT INTO card_tags (card_id, tag_id) VALUES ($cardId, $tagId);",
|
||||||
|
("$cardId", id), ("$tagId", tagId));
|
||||||
|
}
|
||||||
|
transaction.Commit();
|
||||||
|
|
||||||
|
TouchEdited();
|
||||||
|
return new CardModel(id, columnId, title, content, now, now, LoadTags(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Applies one card edit confirmation as a single atomic unit: the card
|
||||||
|
/// row (title, content, refreshed updated_at) plus the complete tag
|
||||||
|
/// assignment. A confirmation with no effective change writes nothing;
|
||||||
|
/// a failure mid-way rolls the whole edit back.
|
||||||
|
/// </summary>
|
||||||
|
/// <exception cref="InvalidOperationException">The card does not exist.</exception>
|
||||||
|
/// <exception cref="SqliteException">A tag id does not exist; nothing is written.</exception>
|
||||||
|
public CardModel UpdateCard(long cardId, string title, string content, IReadOnlyCollection<long> tagIds)
|
||||||
|
{
|
||||||
|
CardModel existing = GetCard(cardId)
|
||||||
|
?? throw new InvalidOperationException($"Card {cardId} does not exist.");
|
||||||
|
|
||||||
|
// No change in title, content or tag set: no write, no timestamps.
|
||||||
|
bool tagsChanged = !tagIds.Distinct().ToHashSet().SetEquals(existing.Tags.Select(tag => tag.Id));
|
||||||
|
if (existing.Title == title && existing.Content == content && !tagsChanged)
|
||||||
|
{
|
||||||
|
return existing;
|
||||||
|
}
|
||||||
|
|
||||||
|
long now = UnixTime.Now;
|
||||||
|
using var transaction = _connection.BeginTransaction();
|
||||||
|
// The confirm write refreshes updated_at even when only the tag set changed.
|
||||||
|
ExecuteNonQuery(transaction,
|
||||||
|
"UPDATE cards SET title = $title, content = $content, updated_at = $now WHERE id = $id;",
|
||||||
|
("$title", title), ("$content", content), ("$now", now), ("$id", cardId));
|
||||||
|
// Tag assignment is rewritten wholesale; card_tags carries nothing beyond the pair.
|
||||||
|
ExecuteNonQuery(transaction, "DELETE FROM card_tags WHERE card_id = $id;", ("$id", cardId));
|
||||||
|
foreach (long tagId in tagIds.Distinct())
|
||||||
|
{
|
||||||
|
ExecuteNonQuery(transaction,
|
||||||
|
"INSERT INTO card_tags (card_id, tag_id) VALUES ($cardId, $tagId);",
|
||||||
|
("$cardId", cardId), ("$tagId", tagId));
|
||||||
|
}
|
||||||
|
transaction.Commit();
|
||||||
|
|
||||||
|
TouchEdited();
|
||||||
|
return new CardModel(cardId, existing.ColumnId, title, content, existing.CreatedAt, now, LoadTags(cardId));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Moves a card to another column. This is a data write (refreshes the
|
||||||
|
/// workspace last_edited_at) but deliberately does NOT refresh the
|
||||||
|
/// card's updated_at; moving to the current column is a no-write no-op.
|
||||||
|
/// Returns true when the card moved.
|
||||||
|
/// </summary>
|
||||||
|
public bool MoveCard(long cardId, long targetColumnId)
|
||||||
|
{
|
||||||
|
using var command = CreateCommand(
|
||||||
|
"UPDATE cards SET column_id = $columnId WHERE id = $id AND column_id <> $columnId;");
|
||||||
|
command.Parameters.AddWithValue("$columnId", targetColumnId);
|
||||||
|
command.Parameters.AddWithValue("$id", cardId);
|
||||||
|
bool moved = command.ExecuteNonQuery() > 0;
|
||||||
|
if (moved)
|
||||||
|
{
|
||||||
|
TouchEdited();
|
||||||
|
}
|
||||||
|
return moved;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Deletes a card; the DDL cascade removes its tag links. Returns true when a row was deleted.</summary>
|
||||||
|
public bool DeleteCard(long cardId) => ExecuteDelete("DELETE FROM cards WHERE id = $id;", cardId);
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region Tags
|
||||||
|
|
||||||
|
/// <summary>Returns all tags ordered by id; unreferenced tags are included.</summary>
|
||||||
|
public IReadOnlyList<TagModel> GetTags()
|
||||||
|
{
|
||||||
|
using var command = CreateCommand(
|
||||||
|
"SELECT id, name, color, description FROM tags ORDER BY id ASC;");
|
||||||
|
using var reader = command.ExecuteReader();
|
||||||
|
|
||||||
|
var tags = new List<TagModel>();
|
||||||
|
while (reader.Read())
|
||||||
|
{
|
||||||
|
tags.Add(ReadTag(reader));
|
||||||
|
}
|
||||||
|
return tags;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Returns every tag together with the number of cards using it, ordered by id.</summary>
|
||||||
|
public IReadOnlyList<(TagModel Tag, long UsageCount)> GetTagsWithUsage()
|
||||||
|
{
|
||||||
|
using var command = CreateCommand("""
|
||||||
|
SELECT t.id, t.name, t.color, t.description, COUNT(ct.card_id)
|
||||||
|
FROM tags t
|
||||||
|
LEFT JOIN card_tags ct ON ct.tag_id = t.id
|
||||||
|
GROUP BY t.id, t.name, t.color, t.description
|
||||||
|
ORDER BY t.id ASC;
|
||||||
|
""");
|
||||||
|
using var reader = command.ExecuteReader();
|
||||||
|
|
||||||
|
var tags = new List<(TagModel Tag, long UsageCount)>();
|
||||||
|
while (reader.Read())
|
||||||
|
{
|
||||||
|
tags.Add((ReadTag(reader), reader.GetInt64(4)));
|
||||||
|
}
|
||||||
|
return tags;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Creates a tag.</summary>
|
||||||
|
/// <exception cref="SqliteException">The name is empty/not unique.</exception>
|
||||||
|
public TagModel AddTag(string name, RgbColor color, string description)
|
||||||
|
{
|
||||||
|
using var transaction = _connection.BeginTransaction();
|
||||||
|
long id = ExecuteInsert(transaction,
|
||||||
|
"INSERT INTO tags (name, color, description) VALUES ($name, $color, $description);",
|
||||||
|
("$name", name), ("$color", color.ToString()), ("$description", description));
|
||||||
|
transaction.Commit();
|
||||||
|
|
||||||
|
TouchEdited();
|
||||||
|
return new TagModel(id, name, color, description);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Rewrites name, color and description; a no-change call writes nothing.</summary>
|
||||||
|
/// <exception cref="InvalidOperationException">The tag does not exist.</exception>
|
||||||
|
/// <exception cref="SqliteException">The new name is empty/not unique.</exception>
|
||||||
|
public TagModel UpdateTag(long tagId, string name, RgbColor color, string description)
|
||||||
|
{
|
||||||
|
TagModel existing = GetTag(tagId)
|
||||||
|
?? throw new InvalidOperationException($"Tag {tagId} does not exist.");
|
||||||
|
|
||||||
|
// Unchanged name, color and description: no write.
|
||||||
|
if (existing.Name == name && existing.Color == color && existing.Description == description)
|
||||||
|
{
|
||||||
|
return existing;
|
||||||
|
}
|
||||||
|
|
||||||
|
using var command = CreateCommand(
|
||||||
|
"UPDATE tags SET name = $name, color = $color, description = $description WHERE id = $id;");
|
||||||
|
command.Parameters.AddWithValue("$name", name);
|
||||||
|
command.Parameters.AddWithValue("$color", color.ToString());
|
||||||
|
command.Parameters.AddWithValue("$description", description);
|
||||||
|
command.Parameters.AddWithValue("$id", tagId);
|
||||||
|
command.ExecuteNonQuery();
|
||||||
|
|
||||||
|
TouchEdited();
|
||||||
|
return new TagModel(tagId, name, color, description);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Deletes a tag; the DDL cascade removes its card links while the cards survive. Returns true when a row was deleted.</summary>
|
||||||
|
public bool DeleteTag(long tagId) => ExecuteDelete("DELETE FROM tags WHERE id = $id;", tagId);
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region Helpers
|
||||||
|
|
||||||
|
/// <summary>Returns the tag with the given id, or null.</summary>
|
||||||
|
private TagModel? GetTag(long tagId)
|
||||||
|
{
|
||||||
|
using var command = CreateCommand(
|
||||||
|
"SELECT id, name, color, description FROM tags WHERE id = $id;");
|
||||||
|
command.Parameters.AddWithValue("$id", tagId);
|
||||||
|
using var reader = command.ExecuteReader();
|
||||||
|
return reader.Read() ? ReadTag(reader) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Returns the tags currently assigned to a card, ordered by id.</summary>
|
||||||
|
private IReadOnlyList<TagModel> LoadTags(long cardId)
|
||||||
|
{
|
||||||
|
using var command = CreateCommand("""
|
||||||
|
SELECT t.id, t.name, t.color, t.description
|
||||||
|
FROM tags t
|
||||||
|
JOIN card_tags ct ON ct.tag_id = t.id
|
||||||
|
WHERE ct.card_id = $cardId
|
||||||
|
ORDER BY t.id ASC;
|
||||||
|
""");
|
||||||
|
command.Parameters.AddWithValue("$cardId", cardId);
|
||||||
|
using var reader = command.ExecuteReader();
|
||||||
|
|
||||||
|
var tags = new List<TagModel>();
|
||||||
|
while (reader.Read())
|
||||||
|
{
|
||||||
|
tags.Add(ReadTag(reader));
|
||||||
|
}
|
||||||
|
return tags;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Reads a columns row from the reader cursor.</summary>
|
||||||
|
private static ColumnModel ReadColumn(SqliteDataReader reader) =>
|
||||||
|
new(reader.GetInt64(0), reader.GetString(1), reader.GetString(2), reader.GetInt64(3), reader.GetInt64(4));
|
||||||
|
|
||||||
|
/// <summary>Reads a tags row from the reader cursor; color text converts to components.</summary>
|
||||||
|
private static TagModel ReadTag(SqliteDataReader reader) =>
|
||||||
|
new(reader.GetInt64(0), reader.GetString(1), RgbColor.Parse(reader.GetString(2)), reader.GetString(3));
|
||||||
|
|
||||||
|
/// <summary>Creates a command bound to this connection.</summary>
|
||||||
|
private SqliteCommand CreateCommand(string sql, SqliteTransaction? transaction = null)
|
||||||
|
{
|
||||||
|
SqliteCommand command = _connection.CreateCommand();
|
||||||
|
command.Transaction = transaction;
|
||||||
|
command.CommandText = sql;
|
||||||
|
return command;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Executes a parameterized non-query statement inside a transaction.</summary>
|
||||||
|
private void ExecuteNonQuery(SqliteTransaction transaction, string sql, params (string Name, object? Value)[] parameters)
|
||||||
|
{
|
||||||
|
using SqliteCommand command = CreateCommand(sql, transaction);
|
||||||
|
foreach ((string name, object? value) in parameters)
|
||||||
|
{
|
||||||
|
command.Parameters.AddWithValue(name, value);
|
||||||
|
}
|
||||||
|
command.ExecuteNonQuery();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Inserts a row inside a transaction and returns the generated rowid.</summary>
|
||||||
|
private long ExecuteInsert(SqliteTransaction transaction, string sql, params (string Name, object? Value)[] parameters)
|
||||||
|
{
|
||||||
|
ExecuteNonQuery(transaction, sql, parameters);
|
||||||
|
using SqliteCommand rowId = CreateCommand("SELECT last_insert_rowid();", transaction);
|
||||||
|
return (long)rowId.ExecuteScalar()!;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Deletes by id; refreshes last_edited_at only when a row was actually removed.</summary>
|
||||||
|
private bool ExecuteDelete(string sql, long id)
|
||||||
|
{
|
||||||
|
using SqliteCommand command = CreateCommand(sql);
|
||||||
|
command.Parameters.AddWithValue("$id", id);
|
||||||
|
if (command.ExecuteNonQuery() == 0)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
TouchEdited();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Mirrors a successful data write into the global registry.</summary>
|
||||||
|
private void TouchEdited() => _appDatabase.TouchLastEdited(_folderPath);
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
namespace YKanBan.Storage.Workspace;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Schema definitions for the per-workspace database. The board is a single
|
||||||
|
/// board with a columns → cards hierarchy. All data validation is expressed
|
||||||
|
/// in DDL (CHECK / UNIQUE / FOREIGN KEY) so that any row entering the
|
||||||
|
/// database is valid by construction; cascading deletes are covered by the
|
||||||
|
/// same DDL.
|
||||||
|
/// </summary>
|
||||||
|
public static class WorkspaceSchema
|
||||||
|
{
|
||||||
|
/// <summary>Latest workspace schema version this build understands.</summary>
|
||||||
|
public const int CurrentVersion = 1;
|
||||||
|
|
||||||
|
/// <summary>Ordered, contiguous migration list for the workspace database.</summary>
|
||||||
|
public static readonly IReadOnlyList<SchemaMigration> Migrations = new SchemaMigration[]
|
||||||
|
{
|
||||||
|
new SchemaMigration(1, "initial schema", """
|
||||||
|
CREATE TABLE columns (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
title TEXT NOT NULL UNIQUE CHECK (length(title) > 0),
|
||||||
|
description TEXT NOT NULL DEFAULT '',
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
updated_at INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE cards (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
column_id INTEGER NOT NULL REFERENCES columns (id) ON DELETE CASCADE,
|
||||||
|
title TEXT NOT NULL DEFAULT '',
|
||||||
|
content TEXT NOT NULL DEFAULT '',
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
updated_at INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE tags (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
name TEXT NOT NULL UNIQUE CHECK (length(name) > 0),
|
||||||
|
color TEXT NOT NULL CHECK (color GLOB '#[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f]'),
|
||||||
|
description TEXT NOT NULL DEFAULT ''
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE card_tags (
|
||||||
|
card_id INTEGER NOT NULL REFERENCES cards (id) ON DELETE CASCADE,
|
||||||
|
tag_id INTEGER NOT NULL REFERENCES tags (id) ON DELETE CASCADE,
|
||||||
|
PRIMARY KEY (card_id, tag_id)
|
||||||
|
);
|
||||||
|
"""),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
namespace YKanBan.Storage.Workspace;
|
||||||
|
|
||||||
|
/// <summary>One open workspace: the exclusive lock plus its repository.</summary>
|
||||||
|
public sealed class WorkspaceSession : IDisposable
|
||||||
|
{
|
||||||
|
/// <summary>Canonical workspace folder path.</summary>
|
||||||
|
public required string FolderPath { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The exclusive lock held while this session is open.</summary>
|
||||||
|
public required WorkspaceLock Lock { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The data access object for this workspace.</summary>
|
||||||
|
public required WorkspaceRepository Repository { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Disposes the repository, then releases the lock.</summary>
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
Repository.Dispose();
|
||||||
|
Lock.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
using System;
|
|
||||||
using Avalonia.Controls;
|
|
||||||
using Avalonia.Controls.Templates;
|
|
||||||
using YKanBan.ViewModels;
|
|
||||||
|
|
||||||
namespace YKanBan;
|
|
||||||
|
|
||||||
public class ViewLocator : IDataTemplate
|
|
||||||
{
|
|
||||||
|
|
||||||
public Control? Build(object? param)
|
|
||||||
{
|
|
||||||
if (param is null)
|
|
||||||
return null;
|
|
||||||
|
|
||||||
var name = param.GetType().FullName!.Replace("ViewModel", "View", StringComparison.Ordinal);
|
|
||||||
var type = Type.GetType(name);
|
|
||||||
|
|
||||||
if (type != null)
|
|
||||||
{
|
|
||||||
return (Control)Activator.CreateInstance(type)!;
|
|
||||||
}
|
|
||||||
|
|
||||||
return new TextBlock { Text = "Not Found: " + name };
|
|
||||||
}
|
|
||||||
|
|
||||||
public bool Match(object? data)
|
|
||||||
{
|
|
||||||
return data is ViewModelBase;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -2,5 +2,4 @@
|
|||||||
|
|
||||||
public partial class MainWindowViewModel : ViewModelBase
|
public partial class MainWindowViewModel : ViewModelBase
|
||||||
{
|
{
|
||||||
public string Greeting { get; } = "Welcome to Avalonia!";
|
|
||||||
}
|
}
|
||||||
@@ -6,15 +6,10 @@
|
|||||||
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
|
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
|
||||||
x:Class="YKanBan.Views.MainWindow"
|
x:Class="YKanBan.Views.MainWindow"
|
||||||
x:DataType="vm:MainWindowViewModel"
|
x:DataType="vm:MainWindowViewModel"
|
||||||
Icon="/Assets/avalonia-logo.ico"
|
|
||||||
Title="YKanBan">
|
Title="YKanBan">
|
||||||
|
|
||||||
<Design.DataContext>
|
<Design.DataContext>
|
||||||
<!-- This only sets the DataContext for the previewer in an IDE,
|
|
||||||
to set the actual DataContext for runtime, set the DataContext property in code (look at App.axaml.cs) -->
|
|
||||||
<vm:MainWindowViewModel/>
|
<vm:MainWindowViewModel/>
|
||||||
</Design.DataContext>
|
</Design.DataContext>
|
||||||
|
|
||||||
<TextBlock Text="{Binding Greeting}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
|
|
||||||
|
|
||||||
</Window>
|
</Window>
|
||||||
+25
-3
@@ -2,6 +2,7 @@
|
|||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<OutputType>WinExe</OutputType>
|
<OutputType>WinExe</OutputType>
|
||||||
<TargetFramework>net9.0</TargetFramework>
|
<TargetFramework>net9.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<BuiltInComInteropSupport>true</BuiltInComInteropSupport>
|
<BuiltInComInteropSupport>true</BuiltInComInteropSupport>
|
||||||
<ApplicationManifest>app.manifest</ApplicationManifest>
|
<ApplicationManifest>app.manifest</ApplicationManifest>
|
||||||
@@ -9,8 +10,24 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<Folder Include="Models\" />
|
<AvaloniaResource Include="Assets\**" Exclude="Assets\Locales\**" />
|
||||||
<AvaloniaResource Include="Assets\**" />
|
</ItemGroup>
|
||||||
|
|
||||||
|
<!--Strongly-typed ResX resources generated by the cross-platform MSBuild generator.
|
||||||
|
LogicalName is pinned so the manifest names stay stable despite the Assets/Locales location.-->
|
||||||
|
<ItemGroup>
|
||||||
|
<EmbeddedResource Update="Assets/Locales/Resources.resx">
|
||||||
|
<Generator>MSBuild:Compile</Generator>
|
||||||
|
<StronglyTypedFileName>$(IntermediateOutputPath)Resources.Designer.cs</StronglyTypedFileName>
|
||||||
|
<StronglyTypedNamespace>YKanBan</StronglyTypedNamespace>
|
||||||
|
<StronglyTypedClassName>Resources</StronglyTypedClassName>
|
||||||
|
<StronglyTypedLanguage>CSharp</StronglyTypedLanguage>
|
||||||
|
<PublicClass>true</PublicClass>
|
||||||
|
<LogicalName>YKanBan.Resources.resources</LogicalName>
|
||||||
|
</EmbeddedResource>
|
||||||
|
<EmbeddedResource Update="Assets/Locales/Resources.zh-Hans.resx">
|
||||||
|
<LogicalName>YKanBan.Resources.zh-Hans.resources</LogicalName>
|
||||||
|
</EmbeddedResource>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
@@ -18,11 +35,16 @@
|
|||||||
<PackageReference Include="Avalonia.Desktop" Version="11.3.6" />
|
<PackageReference Include="Avalonia.Desktop" Version="11.3.6" />
|
||||||
<PackageReference Include="Avalonia.Themes.Fluent" Version="11.3.6" />
|
<PackageReference Include="Avalonia.Themes.Fluent" Version="11.3.6" />
|
||||||
<PackageReference Include="Avalonia.Fonts.Inter" Version="11.3.6" />
|
<PackageReference Include="Avalonia.Fonts.Inter" Version="11.3.6" />
|
||||||
<!--Condition below is needed to remove Avalonia.Diagnostics package from build output in Release configuration.-->
|
<!--Exclude Avalonia.Diagnostics from Release build output.-->
|
||||||
<PackageReference Include="Avalonia.Diagnostics" Version="11.3.6">
|
<PackageReference Include="Avalonia.Diagnostics" Version="11.3.6">
|
||||||
<IncludeAssets Condition="'$(Configuration)' != 'Debug'">None</IncludeAssets>
|
<IncludeAssets Condition="'$(Configuration)' != 'Debug'">None</IncludeAssets>
|
||||||
<PrivateAssets Condition="'$(Configuration)' != 'Debug'">All</PrivateAssets>
|
<PrivateAssets Condition="'$(Configuration)' != 'Debug'">All</PrivateAssets>
|
||||||
</PackageReference>
|
</PackageReference>
|
||||||
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.2.1" />
|
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.2.1" />
|
||||||
|
<PackageReference Include="Semi.Avalonia" Version="11.2.1.10" />
|
||||||
|
<PackageReference Include="IconPacks.Avalonia.Lucide" Version="2.0.0" />
|
||||||
|
<PackageReference Include="Microsoft.Data.Sqlite" Version="9.0.20" />
|
||||||
|
<PackageReference Include="Pidgin" Version="3.5.1" />
|
||||||
|
<PackageReference Include="Newtonsoft.Json" Version="13.0.4" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
</Project>
|
</Project>
|
||||||
+339
@@ -0,0 +1,339 @@
|
|||||||
|
# YKanBan 项目计划(v1.7)
|
||||||
|
|
||||||
|
> 本文档是 YKanBan 的完整项目计划,由需求讨论定稿,供执行者照此实施。
|
||||||
|
> 所有设计决策均为定稿结论;如实施中发现问题,应回到计划维护者处修订,而不是自行偏离。
|
||||||
|
> v1.1 修订:数据模型细节定稿(字段更名与约束、时间戳刷新语义、级联清点、事务要求);搜索文法新增 `column:` 限定符与短语转义;列新增 description 字段;模态居中规则。
|
||||||
|
> v1.2 修订:全局存储拆分为 app.db(结构化)与 app.json(KV 配置,Newtonsoft.Json);CI 发布改为手动触发、仅上传 artifact。
|
||||||
|
> v1.3 修订:新增国际化章节(英文默认 + 简体中文,ResX 重启生效);导出文件名与时间戳 i18n 化。
|
||||||
|
> v1.4 修订:新增亮/暗/跟随系统主题(默认跟随系统,即时生效)与自定义颜色硬规则;窗口规则(标准 Avalonia Window,禁止无边框与自绘标题栏)。
|
||||||
|
> v1.5 修订:CI 改为单一手动 workflow(每 RID build→test→artifact);开发期测试一律本地 Windows,跨平台验证无限期推迟。
|
||||||
|
> v1.6 修订:**放弃分立项目原则**——合并为单项目 `YKanBan` + `YKanBan.Tests`;撤销 i18N provider 模式(直接读 ResX);Cli 彻底移除;测试纪律改为"不写 UI 交互测试"(接受测试连带 Avalonia 依赖)。
|
||||||
|
> v1.7 修订(终版):用户文档整合——取消 docs/SEARCH.md,全部用户须知(gitignore、WAL 三文件复制、搜索语法)合并为根目录 USAGE.md,README 引用之。
|
||||||
|
|
||||||
|
## 1. 项目概述
|
||||||
|
|
||||||
|
个人使用的本地/离线看板工具。跨平台桌面应用(Windows / Linux / macOS),类 Git 的工作方式:在被管理项目根目录下创建 `.ykanban` 文件夹存储看板数据。Avalonia UI,MVVM 模式,单实例程序。界面默认英文,附简体中文(ResX,切换重启生效,见 §8);主题支持亮色/暗色/跟随系统(默认跟随系统,即时生效,见 §5.10)。
|
||||||
|
|
||||||
|
## 2. 存储设计
|
||||||
|
|
||||||
|
### 2.1 存储模型(类 Git)
|
||||||
|
|
||||||
|
- 每个工作区(定义见 §4)= 一个其下存在 `.ykanban` 的路径;`.ykanban/` 内含 `ykanban.db`(SQLite 数据库)与 `ykanban.lock`(锁文件)
|
||||||
|
- 打开文件夹时**只检查当前目录**是否存在 `.ykanban`,不向上递归查找;不存在则询问用户是否在当前目录初始化
|
||||||
|
|
||||||
|
### 2.2 数据库配置
|
||||||
|
|
||||||
|
- `PRAGMA journal_mode=WAL` + `PRAGMA synchronous=NORMAL`
|
||||||
|
- 每个连接显式 `PRAGMA foreign_keys=ON`(Microsoft.Data.Sqlite 默认关闭,不开则外键与 CASCADE 均不生效)
|
||||||
|
- 不做退出时 checkpoint
|
||||||
|
- 备份/迁移必须同时复制 `ykanban.db`、`ykanban.db-wal`、`ykanban.db-shm` 三个文件(此要求写入 README 用户须知)
|
||||||
|
- `PRAGMA user_version` 管理 schema 版本,启动时按版本增量迁移
|
||||||
|
|
||||||
|
### 2.3 独占访问
|
||||||
|
|
||||||
|
- 每个 `.ykanban` 同一时刻仅允许一个 YKanBan 实例打开
|
||||||
|
- 机制:独占打开 `ykanban.lock`(.NET `FileStream` + `FileShare.None`)持有至退出;锁文件内写 PID/机器名/时间用于诊断;程序崩溃/断电由 OS 自动释放,无残留问题
|
||||||
|
- 锁冲突场景:主要为他机经网络共享打开同一 `.ykanban`;界面仅显示锁冲突提示页,不提供其他操作
|
||||||
|
|
||||||
|
### 2.4 与 Git 的关系
|
||||||
|
|
||||||
|
- `.ykanban` 不应提交进 Git,建议用户将其加入全局 gitignore(写入 README 用户须知,与 WAL 三文件复制要求并列)
|
||||||
|
|
||||||
|
## 3. 看板数据模型
|
||||||
|
|
||||||
|
单看板,列 → 卡片两级。时间戳一律 INTEGER Unix **秒**。
|
||||||
|
|
||||||
|
```
|
||||||
|
columns: id INTEGER PK AUTOINCREMENT,
|
||||||
|
title TEXT NOT NULL UNIQUE CHECK (length(title) > 0),
|
||||||
|
description TEXT NOT NULL DEFAULT '',
|
||||||
|
created_at INT NOT NULL, updated_at INT NOT NULL
|
||||||
|
cards: id INTEGER PK AUTOINCREMENT,
|
||||||
|
column_id INT NOT NULL → columns.id ON DELETE CASCADE,
|
||||||
|
title TEXT NOT NULL DEFAULT '',
|
||||||
|
content TEXT NOT NULL DEFAULT '',
|
||||||
|
created_at INT NOT NULL, updated_at INT NOT NULL
|
||||||
|
tags: id INTEGER PK AUTOINCREMENT,
|
||||||
|
name TEXT NOT NULL UNIQUE CHECK (length(name) > 0),
|
||||||
|
color TEXT NOT NULL CHECK (GLOB '#'+六位十六进制,即 #RRGGBB 形态),
|
||||||
|
description TEXT NOT NULL DEFAULT ''
|
||||||
|
card_tags: (card_id, tag_id) 复合主键,双向 ON DELETE CASCADE
|
||||||
|
```
|
||||||
|
|
||||||
|
行为约定:
|
||||||
|
|
||||||
|
- 数据校验尽量在 DDL 层完成(CHECK / UNIQUE / FOREIGN KEY),保证入库即合法:
|
||||||
|
- `columns.title`:非空、全表唯一(BINARY 严格比较),无字符集限制
|
||||||
|
- `tags.name`:仅要求非空串,**完全放开**——无字符集/长度限制,允许空格、emoji、保留字符;UI 输入不做 trim
|
||||||
|
- `tags.color`:仅接受 `#RRGGBB` 形态(GLOB 校验)
|
||||||
|
- 所有 description 字段无长度上限
|
||||||
|
- 时间戳刷新规则:
|
||||||
|
- `cards.updated_at` 仅在卡片编辑模态点"确认"写入时刷新(新建卡片时 created_at = updated_at)
|
||||||
|
- 菜单"移动到列"不刷新卡片 updated_at,但作为一次数据库写入会刷新工作区 `last_edited_at`(已接受的不对称)
|
||||||
|
- `columns.updated_at` 仅在列自身标题或 description 变更时刷新
|
||||||
|
- 编辑模态确认时内容无变化 → 不写库、不刷新时间戳
|
||||||
|
- 卡片编辑确认涉及 cards + card_tags 多表写入,必须包在单个事务中
|
||||||
|
- 级联删除全场景由 DDL 覆盖,无需触发器(前提 `PRAGMA foreign_keys=ON`):
|
||||||
|
|
||||||
|
| 删除操作 | 级联链 |
|
||||||
|
|---|---|
|
||||||
|
| 删 column | → 该列所有 cards → 这些卡片的 card_tags(级联链式传导) |
|
||||||
|
| 删 card | → 该卡的 card_tags |
|
||||||
|
| 删 tag | → 相关 card_tags(= 卡片卸载该标签,卡片保留) |
|
||||||
|
|
||||||
|
- 禁止手动排序:列内/列间顺序由显示规则计算(id 默认 / 创建时间 / 最后修改时间 / 标题字母序),界面随时可切换、不逐工作区记忆,全局一份存 `app.json`(见 §4.4);所有排序一律以 id 升序兜底;标题排序按码点(BINARY collation)
|
||||||
|
- 无标题的唯一表示是空串(`title TEXT NOT NULL DEFAULT ''`);无标题卡片列内不显示占位标题;按标题排序时视为空串
|
||||||
|
- 删列 → 级联删卡(UI 二次确认,提示将删 N 张卡片);卡片硬删除(二次确认)
|
||||||
|
- tag 永不自动清理(`tags` 表保留无引用标签),配标签管理界面
|
||||||
|
- 初始化预置三列:初始化时按当前语言直接从 ResX 资源读取(英文 To Do / In Progress / Done;中文 待办 / 进行中 / 已完成),随**创建时刻**的语言写入,此后即为数据、不再随语言切换变化(见 §8)
|
||||||
|
- 数量级参考:卡片 ≤ 10000,列 ≤ 100
|
||||||
|
|
||||||
|
## 4. 应用工作流与主界面骨架
|
||||||
|
|
||||||
|
**术语**:工作区 = 其下存在 `.ykanban` 的路径
|
||||||
|
|
||||||
|
### 4.1 单例与启动
|
||||||
|
|
||||||
|
- 封装为跨平台 `ISingleInstanceService`;平台相关代码集中于平台服务层
|
||||||
|
- 单例检测:.NET 命名 Mutex;IPC:命名管道
|
||||||
|
- `ykanban`(无参)→ 通知既有实例显示并置前窗口
|
||||||
|
- `ykanban <path>` → 置前并切换到该工作区(未打开则加入)
|
||||||
|
- 首次启动 → 欢迎页
|
||||||
|
- 路径比较:规范化绝对路径后比较,Windows 忽略大小写、Unix/macOS 区分大小写;不解析符号链接
|
||||||
|
|
||||||
|
### 4.2 侧边栏(自上而下)
|
||||||
|
|
||||||
|
- 欢迎页按钮、打开新项目按钮(弹出系统文件夹选择框)
|
||||||
|
- 分隔符 + 工作区列表(不限长、持久保存所有已知工作区)+ 列表排序选项(A-Z / Z-A / 最近更新 = 内容最后编辑时间)
|
||||||
|
- 底部:设置按钮 + 关于按钮(水平并排)
|
||||||
|
|
||||||
|
### 4.3 连接管理
|
||||||
|
|
||||||
|
- 容量 8 的 LRU 连接池(锁 + 数据库连接);淘汰仅释放资源,条目保留在侧边栏,点击重新打开(拿锁失败 → 锁冲突页)
|
||||||
|
- 活跃度事件:点击条目 / 打开 / 切换
|
||||||
|
- 移除工作区:释放资源 → 删除条目(无保存步骤)
|
||||||
|
|
||||||
|
### 4.4 全局存储
|
||||||
|
|
||||||
|
位置:`%APPDATA%/YKanBan/`(各平台等价目录)。分界原则:**结构化数据 → app.db 开新表;琐碎 KV 配置 → app.json**。
|
||||||
|
|
||||||
|
**`app.db`**(SQLite,同工作区库的 PRAGMA 配置):
|
||||||
|
|
||||||
|
```
|
||||||
|
workspaces(path TEXT PK, last_edited_at INT, added_at INT)
|
||||||
|
```
|
||||||
|
|
||||||
|
- 对工作区库的任何一次成功写入(卡片/列/标签增删改)均刷新 `last_edited_at`(频繁写入且需崩溃安全,留在 SQLite)
|
||||||
|
|
||||||
|
**`app.json`**(Newtonsoft.Json 14.0.1,回退 13.0.4):
|
||||||
|
|
||||||
|
- 强类型根对象 `AppConfig` 整体序列化,根含 `"version": 1` 迁移钩子
|
||||||
|
- 承载:语言(`Language`,`"en"` 默认)、主题(`Theme`,`"FollowSystem"` 默认)、卡片排序选择、列宽、四类确认开关、侧边栏列表排序选项等琐碎 KV
|
||||||
|
- 写入时机:**应用退出时一次性写盘**(直接写,不做原子替换);崩溃/断电丢失当次会话的设置变更(已接受:配置低价值)
|
||||||
|
- 读取:文件缺失 → 默认值启动照常运行(下次退出自然创建);解析失败 → 备份为 `app.json.bak` → 以默认值启动
|
||||||
|
|
||||||
|
### 4.5 看板核心界面状态页
|
||||||
|
|
||||||
|
正常看板 / 未初始化页(含初始化按钮)/ 锁冲突页(仅提示,无操作)/ 目录不存在错误页
|
||||||
|
|
||||||
|
## 5. 看板核心界面
|
||||||
|
|
||||||
|
### 5.1 顶部显示区域
|
||||||
|
|
||||||
|
- 工作区名称(= 文件夹名,侧边栏同此文字)+ 小一号字显示完整路径
|
||||||
|
- 最右侧:导出按钮
|
||||||
|
|
||||||
|
### 5.2 TabControl 两选项卡
|
||||||
|
|
||||||
|
**标签选项卡**(标签管理器,风格类 GitHub issue labels 页):
|
||||||
|
|
||||||
|
- 条目 = 颜色标记 + 名称 + 描述 + 使用数(N 张卡片)
|
||||||
|
- 支持新增、删除(提示"将从 N 张卡片移除该标签")、重命名、改颜色、改描述
|
||||||
|
|
||||||
|
**看板选项卡**:
|
||||||
|
|
||||||
|
- 搜索栏(点击搜索按钮才执行,无实时搜索,带 × 一键清空);右侧依次:新增列按钮、列宽调整按钮、排序 combobox
|
||||||
|
- 列宽:模态选择预设窄/标准/宽或手动像素值(范围 160–720,默认"标准"= 320),全局生效,持久化到 app.json
|
||||||
|
- 看板区域(与 GitHub Projects 基本一致):列左→右横排,卡片上→下展开;**无拖拽**
|
||||||
|
- 列右上角:+新建卡片、⋯菜单(编辑、删除);"编辑" = 标题 + description 编辑模态
|
||||||
|
- 卡右上角:⋯菜单(删除、移动到列…);点击卡片本体 → 编辑模态
|
||||||
|
- 卡片条目仅显示 3 样内容:`#id`(加粗)与标题同行(无标题则仅 `#61`;有标题如 `#61 Foo bar`)+ 内容按固定字数截断(约 200 字)。不显示标签、不显示时间戳
|
||||||
|
|
||||||
|
### 5.3 模态窗口原则
|
||||||
|
|
||||||
|
非 SPA。新增列 / 新增卡片 / 编辑卡片 / 各类删除确认等操作一律通过模态对话框弹出。
|
||||||
|
|
||||||
|
- 所有模态窗口在父窗口中央弹出(Avalonia `WindowStartupLocation="CenterOwner"` + `ShowDialog(owner)`)
|
||||||
|
- 新增列 / 编辑列模态:标题(必填,受 DDL 非空+唯一约束)+ description(可空)
|
||||||
|
|
||||||
|
### 5.4 卡片编辑模态
|
||||||
|
|
||||||
|
- 字段:标题(可空,空串 = 无标题)、内容(多行)、标签区、只读 `#id` / 创建时间 / 修改时间(新增时未生成则不显示)
|
||||||
|
- 底部:确认(当前数据一次性写入数据库)/ 取消(丢弃更改)
|
||||||
|
- 编辑对话框是一个工作单元:确认时一次性落库(单事务,见 §3),取消不产生任何写入;其余操作(删除、移动等)仍即时写库
|
||||||
|
- 确认时内容无变化 → 不写库、不刷新时间戳
|
||||||
|
- 标签指派:编辑模态标签区显示已指派标签(各带 × 移除),"添加标签"按钮弹**嵌套模态** = 已有标签搜索/列表 + 新建标签入口,选中即添加,可反复打开继续添加下一个
|
||||||
|
|
||||||
|
### 5.5 确认对话框开关
|
||||||
|
|
||||||
|
按类型分设独立开关:删除卡片 / 删除列 / 删除标签 / 丢弃编辑确认,承载于设置模态,存 app.json。
|
||||||
|
|
||||||
|
### 5.6 设置模态
|
||||||
|
|
||||||
|
入口 = 侧边栏底部"设置"按钮,承载各类全局设置:
|
||||||
|
|
||||||
|
- 语言选择(英文 / 简体中文),切换后显示"重启后生效"提示(提示文本本身为资源键)
|
||||||
|
- 主题选择(亮色 / 暗色 / 跟随系统),切换后**即时生效**,无重启提示(与语言项的行为差异)
|
||||||
|
- 四类确认开关(见 §5.5)
|
||||||
|
|
||||||
|
### 5.7 关于模态
|
||||||
|
|
||||||
|
应用名、版本号、仓库链接、许可证。入口与设置按钮水平并排。
|
||||||
|
|
||||||
|
### 5.8 欢迎页
|
||||||
|
|
||||||
|
极简:应用名/Logo 显示于提示语"从左侧打开或新建工作区"上方,别无他物。
|
||||||
|
|
||||||
|
### 5.9 导出
|
||||||
|
|
||||||
|
- 点击后弹系统保存文件对话框,默认文件名按当前语言生成(模式为资源键,**精确到秒**):英文 `MyRepo-export-20260930-142537.md`;中文 `MyRepo-导出-20260930-142537.md`
|
||||||
|
- 人类可读格式,无回导需求;模板文本直接读取 ResX 资源(见 §8),导出语言跟随当前界面语言:
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
# 工作区名
|
||||||
|
> 导出时间:2026-09-30 14:25:37 (时间戳格式随语言:英文 yyyy-MM-dd HH:mm:ss;中文 yyyy年M月d日 HH:mm)
|
||||||
|
|
||||||
|
## 列:进行中 (列按 id 序,标题后附卡片数;列 description 紧随标题下显示)
|
||||||
|
|
||||||
|
### #61 Foo bar
|
||||||
|
正文内容…
|
||||||
|
|
||||||
|
- 标签:`bug` `ui`
|
||||||
|
- 创建:2026-09-01 10:00 修改:2026-09-28 18:30
|
||||||
|
|
||||||
|
## 标签总表
|
||||||
|
| 名称 | 颜色 | 描述 | 使用数 |
|
||||||
|
```
|
||||||
|
|
||||||
|
- 空列也保留(体现看板结构);无标题卡片以 `### #61` 呈现
|
||||||
|
|
||||||
|
### 5.10 主题(亮 / 暗 / 跟随系统)
|
||||||
|
|
||||||
|
- 三态选项:亮色 / 暗色 / 跟随系统,**默认跟随系统**
|
||||||
|
- 机制:`Application.Current.RequestedThemeVariant` = `ThemeVariant.Light / Dark / Default`(Default = 继承系统偏好);Semi.Avalonia 两套配色经标准 ThemeVariant 机制生效,运行时切换**即时生效**(含支持平台上窗口标题栏装饰变体)
|
||||||
|
- 持久化:`AppConfig.Theme`(`"FollowSystem"` 默认 / `"Light"` / `"Dark"`)入 app.json,退出时落盘;启动时在主窗口创建前读取应用
|
||||||
|
- **自定义颜色硬规则**:界面中任何自定义 Brush/Color 资源必须以 `ThemeDictionaries` 成对定义 Light/Dark 两份并经 `DynamicResource` 引用,禁止裸用 `StaticResource` 引颜色,保证主题切换时界面完整变色
|
||||||
|
- 例外:标签颜色是用户数据(固定 `#RRGGBB`),两种主题下均直接显示原色,不做暗色变体
|
||||||
|
|
||||||
|
### 5.11 其他
|
||||||
|
|
||||||
|
- 主窗口尺寸/位置不持久化
|
||||||
|
- **窗口规则**:所有窗口直接使用标准 Avalonia Window(系统原生标题栏与装饰);禁止无边框窗口(borderless / chromeless),禁止自绘标题栏(关闭/最小化/最大化、拖拽区域等一律不做自定义实现)
|
||||||
|
|
||||||
|
## 6. 搜索语法
|
||||||
|
|
||||||
|
实现:Pidgin 库做 Lexer + Parser;语法文档并入根目录 `USAGE.md`(README 引用,见附录)。
|
||||||
|
|
||||||
|
### 6.1 文法(EBNF)
|
||||||
|
|
||||||
|
```
|
||||||
|
query := orExpr
|
||||||
|
orExpr := andExpr ( OR andExpr )*
|
||||||
|
andExpr := operand ( (AND)? operand )* ← 空格相邻 = 隐式 AND
|
||||||
|
operand := atom | '(' orExpr ')'
|
||||||
|
atom := word | phrase | qualifier
|
||||||
|
qualifier := key ':' (word | phrase)
|
||||||
|
key := tag | title | content | id | column
|
||||||
|
phrase := '"' 任意文本 '"' (内部支持转义:\" → 字面引号,\\ → 字面反斜杠)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.2 语义
|
||||||
|
|
||||||
|
- `AND`(含隐式空格)优先于 `OR`,括号强制结合
|
||||||
|
- 仅大写 `AND`/`OR` 为运算符,小写即普通裸词;搜索字面量大写 AND/OR 需加引号(写入文档)
|
||||||
|
- Atom 语义:裸词/短语 → 标题**或**内容子串匹配;`tag:` 标签精确匹配;`column:` 列标题精确匹配(列名 UNIQUE,无歧义);`title:` / `content:` 字段子串;`id:` 精确匹配;全部不区分大小写;引号支持含空格值
|
||||||
|
- 短语内部转义:`\"` → 字面引号,`\\` → 字面反斜杠;搜索含空格/保留字符/字面 `AND` 等特殊标签名时,用(必要时转义的)引号值(写入文档)
|
||||||
|
- 宽松降级:不可解析片段(括号不配对、运算符悬空等)退化为字面文本匹配,永不报错
|
||||||
|
- 无时间维度;解析器按可扩展限定符表设计(预留 `created:`、`NOT` 等扩展点)
|
||||||
|
- 搜索语法保留字**永不本地化**
|
||||||
|
|
||||||
|
### 6.3 交互
|
||||||
|
|
||||||
|
- 点搜索按钮才执行;空查询 = 全显;筛选后空列保留显示(维持看板结构感);切换工作区时清空重置
|
||||||
|
|
||||||
|
## 7. 技术选型
|
||||||
|
|
||||||
|
版本已经 NuGet 实测调研锁定:
|
||||||
|
|
||||||
|
| 包 | 版本 | 备注 |
|
||||||
|
|---|---|---|
|
||||||
|
| Avalonia | **11.3.6 锁定** | 不允许升级 |
|
||||||
|
| Semi.Avalonia | 11.2.1.10 | 11.3.x 全系依赖 Avalonia ≥ 11.3.7 会强制升级,故降用 11.2 线最新;含亮/暗两套配色 |
|
||||||
|
| IconPacks.Avalonia.Lucide | 2.0.0 | 仅此子库,不装全库 IconPacks.Avalonia |
|
||||||
|
| Microsoft.Data.Sqlite | 9.0.20 | 与 net9.0 对齐;手写 SQL |
|
||||||
|
| Pidgin | 3.5.1 | 搜索 Lexer + Parser |
|
||||||
|
| MSTest | 4.4.1 | 遇问题降 3.11.1 |
|
||||||
|
| Newtonsoft.Json | 14.0.1 | app.json 序列化;回退 13.0.4 |
|
||||||
|
| CommunityToolkit.Mvvm | 8.2.1 | 沿用现有 |
|
||||||
|
|
||||||
|
### 7.1 工程结构(单项目原则)
|
||||||
|
|
||||||
|
**不拆分 Lib/Gui**——本项目无明确前后端边界,强行二分只会制造功能归属争议。沿用现有 `YKanBan/` 项目**原地改造**(清理模板内容),重组为(同步更新 `YKanBan.slnx`):
|
||||||
|
|
||||||
|
- `YKanBan`:唯一应用项目——模型、schema/迁移、仓库层、搜索解析、导出、单例 IPC、平台服务层、Avalonia UI(MVVM);持有全部 ResX 资源;全部包依赖进同一 csproj
|
||||||
|
- `YKanBan.Tests`:MSTest 测试库,引用主项目(**连带 Avalonia 依赖,已接受**);纪律规则:**不编写任何 UI 交互测试**(窗口、模态、点击流、数据绑定、主题切换、状态页渲染一律人工验证;不引入 headless UI 测试基础设施)
|
||||||
|
|
||||||
|
**测试范围**:解析器(文法全分支 + 宽松降级 + SQL 编译)、schema/DDL 约束实测、`user_version` 迁移、PRAGMA 生效、锁文件独占与释放、app.json 缺失/损坏降级、CRUD 与三条级联链、编辑确认事务原子性、`last_edited_at` 写通、LRU 池、路径规范化比较(**平台规则以参数注入**,保证 Unix 分支在 Windows 本地可测)、导出结构与本地化断言(直接设 `Resources.Culture` 断言 en / zh-Hans 真实输出);单例 IPC 仅测协议编解码与命令行参数解析,进程互斥与窗口置前人工验证。一切测试在本地 Windows 运行。
|
||||||
|
|
||||||
|
### 7.2 平台与发布
|
||||||
|
|
||||||
|
- 锁文件、IPC、路径比较等平台相关代码集中于跨平台接口的平台服务层(内部组织习惯,非强制架构)
|
||||||
|
- 发布目标:win-x64 / linux-x64 / osx-x64 / osx-arm64
|
||||||
|
- **单一 GitHub workflow**:仅 `workflow_dispatch` 手动触发;4 RID 矩阵,每个平台作业依次执行 **build → test → 测试通过后上传该 RID 的 artifact**(压缩包);测试失败该 RID 不出产物;不创建 GitHub Release
|
||||||
|
- 开发机访问不到 GitHub:**禁止任何依赖 push 触发的 CI**
|
||||||
|
- 开发期测试策略:一切验证在**本地 Windows** 进行(`dotnet build` + `dotnet test`);各里程碑的"单测/人工"验证均指本地 Windows 执行;Linux/macOS 行为验证**无限期推迟**至程序完工后(明确接受平台 bug 风险)
|
||||||
|
|
||||||
|
## 8. 国际化(I18N)
|
||||||
|
|
||||||
|
### 8.1 语言与资源
|
||||||
|
|
||||||
|
- 支持语言:**英文(默认)+ 简体中文(zh-Hans)**,仅此两种
|
||||||
|
- ResX 位于唯一主项目:`Resources.resx`(英文 neutral,missing key 回落英文)+ `Resources.zh-Hans.resx`;XAML 用 `{x:Static lang:Resources.Key}`
|
||||||
|
- 公共 Resources 类用跨平台 MSBuild 方案生成(`Generator=MSBuild:Compile` + `StronglyTypedFileName`(写入 obj/)+ `StronglyTypedNamespace` + `StronglyTypedClassName=Resources` + `PublicClass=true`),不用 VS 专属生成器
|
||||||
|
- M5 起硬性规则:**所有 UI 文本一律资源键**,英文文本也只写在 Resources.resx,禁止硬编码
|
||||||
|
|
||||||
|
### 8.2 资源访问与异常策略
|
||||||
|
|
||||||
|
- 需要本地化文本的代码(Markdown 导出生成器、初始化预置列名等)**直接读取 ResX 资源**(`Resources` 类全局可用),无任何注入层;导出测试可直接设 `Resources.Culture` 断言 en / zh-Hans 真实输出
|
||||||
|
- 异常策略(保留):异常消息**一律英文、永不本地化**——异常携带本地化文本是坏实践(抛出与显示时刻 culture 不一致、日志难检索);对需区分展示的场景(锁冲突、未初始化、目录不存在、schema 版本问题等)定义**类型化异常**,UI 按异常类型映射资源键显示本地化文案
|
||||||
|
|
||||||
|
### 8.3 语言切换与启动时序
|
||||||
|
|
||||||
|
- `AppConfig.Language`(`"en"` 默认)存 app.json;设置模态中切换(英文/简体中文)并提示"重启后生效"
|
||||||
|
- 启动时序:读 app.json → 在 `OnFrameworkInitializationCompleted` **创建主窗口之前**设置 `Resources.Culture = new CultureInfo(language)` → 同时按 `CultureInfo.TextInfo.IsRightToLeft` 检测并设置主窗口 `FlowDirection`
|
||||||
|
- **RTL 检测代码必须实现**——当前两语言均为 LTR 也不许省略,作为未来语言扩展的基础设施
|
||||||
|
- 与 app.json 退出写盘策略天然吻合:切换语言 → 退出时落盘 → 重启生效
|
||||||
|
|
||||||
|
## 9. 里程碑
|
||||||
|
|
||||||
|
| 阶段 | 内容 | 验证 |
|
||||||
|
|---|---|---|
|
||||||
|
| M0 工程重组 | 现有项目原地改造(清理模板内容)+ 新建 `YKanBan.Tests`、按版本表装依赖 | 本地 Windows build + test 通过 |
|
||||||
|
| M1 存储层 | 工作区 schema(含 CHECK/UNIQUE 约束)+ user_version 迁移、PRAGMA、锁文件、app.db + app.json、初始化预置三列(列名直接读 ResX) | 单测 |
|
||||||
|
| M2 仓库层 | CRUD/移动/级联/标签指派、last_edited_at 写通、LRU 连接池、路径规范化比较(平台规则参数注入) | 单测 |
|
||||||
|
| M3 搜索与导出 | Pidgin 解析器、查询→SQL 编译、Markdown 导出(直接读 ResX,en / zh-Hans 输出均有测试) | 单测(解析全分支) |
|
||||||
|
| M4 单例 IPC | ISingleInstanceService、参数解析、窗口置前 | 单测 + 人工 |
|
||||||
|
| M5 GUI 框架 | 主题/图标接入、主窗口布局、侧边栏全套、欢迎页、设置/关于模态;**ResX 基础设施、语言设置项、RTL/FlowDirection 检测、全 UI 文本资源化(硬规则生效);亮/暗/跟随系统主题基础设施与设置项、ThemeDictionaries 颜色硬规则** | 人工 |
|
||||||
|
| M6 看板界面 | 顶部区、TabControl、状态页、看板 tab 全部交互与模态 | 人工 |
|
||||||
|
| M7 标签与搜索集成 | 标签 tab、搜索执行与空列保留、导出接线(含文件名/时间戳 i18n 模式) | 人工 |
|
||||||
|
| M8 发布与文档 | 单一 workflow(4 RID 矩阵 build→test→artifact)文件就绪(结构自查)、根目录 USAGE.md、README(引用 USAGE.md)、人工验收清单(含语言切换重启生效、导出语言跟随界面、主题三态切换三项) | workflow 结构自查通过;实际触发与产物验证视网络条件推迟 |
|
||||||
|
|
||||||
|
依赖链:M0 → M1 → M2 → M3 ∥ M4 → M5 → M6 → M7 → M8
|
||||||
|
|
||||||
|
## 附录:用户文档(USAGE.md)
|
||||||
|
|
||||||
|
`README.md` 引用根目录 `USAGE.md`;`USAGE.md` 必载以下三项:
|
||||||
|
|
||||||
|
1. `.ykanban` 不应提交进 Git,建议加入全局 gitignore
|
||||||
|
2. 备份/迁移必须同时复制 `ykanban.db`、`ykanban.db-wal`、`ykanban.db-shm` 三个文件
|
||||||
|
3. 搜索语法全文(文法、语义、转义规则、保留字说明,见 §6)
|
||||||
Reference in new issue
Block a user