22using System . Collections . Generic ;
33using System . IO ;
44using System . Text . Json ;
5+ using System . Text . Json . Serialization ;
56using System . Threading . Tasks ;
67using Avalonia . CpuLimiter . Models ;
78
89namespace Avalonia . CpuLimiter . Services ;
910
11+ [ JsonSourceGenerationOptions ( WriteIndented = true ) ]
12+ [ JsonSerializable ( typeof ( IEnumerable < HistoryItem > ) ) ]
13+ internal partial class SourceGenerationContext : JsonSerializerContext
14+ {
15+
16+ }
17+
1018public class HistoryItemFileService
1119{
1220 private static string _configPath =
@@ -19,9 +27,9 @@ public static async Task SaveHistoryToFileAsync(IEnumerable<HistoryItem>? histor
1927 if ( ! Directory . Exists ( Path . GetDirectoryName ( _configPath ) ) )
2028 Directory . CreateDirectory ( Path . GetDirectoryName ( _configPath ) ! ) ;
2129
22- using ( FileStream fs = File . Open ( _configPath , FileMode . Create ) )
30+ await using ( FileStream fs = File . Open ( _configPath , FileMode . Create ) )
2331 {
24- await JsonSerializer . SerializeAsync ( fs , historyItems , _jsonSerializerOptions ) ;
32+ await JsonSerializer . SerializeAsync ( fs , historyItems , SourceGenerationContext . Default . IEnumerableHistoryItem ! ) ;
2533 }
2634 }
2735
@@ -32,9 +40,12 @@ public static async Task SaveHistoryToFileAsync(IEnumerable<HistoryItem>? histor
3240 {
3341 try
3442 {
35- using ( FileStream fs = File . OpenRead ( _configPath ) )
43+ if ( ! File . Exists ( _configPath ) )
44+ return null ;
45+
46+ await using ( FileStream fs = File . OpenRead ( _configPath ) )
3647 {
37- return await JsonSerializer . DeserializeAsync < IEnumerable < HistoryItem > > ( fs , _jsonSerializerOptions ) ;
48+ return await JsonSerializer . DeserializeAsync < IEnumerable < HistoryItem > > ( fs , SourceGenerationContext . Default . IEnumerableHistoryItem ! ) ;
3849 }
3950 }
4051 catch ( Exception e ) when ( e is FileNotFoundException or DirectoryNotFoundException )
@@ -44,6 +55,7 @@ public static async Task SaveHistoryToFileAsync(IEnumerable<HistoryItem>? histor
4455 }
4556 }
4657
58+ // this option is conflicting with Sourcegenerator
4759 private static JsonSerializerOptions _jsonSerializerOptions = new ( )
4860 {
4961 WriteIndented = true
0 commit comments