| | 1 | | using System.Text.Json; |
| | 2 | | using Spdx3.Utility; |
| | 3 | | using File = Spdx3.Model.Software.Classes.File; |
| | 4 | |
|
| | 5 | | namespace Spdx3.Serialization; |
| | 6 | |
|
| | 7 | | public class Writer |
| | 8 | | { |
| | 9 | | /// <summary> |
| | 10 | | /// The catalog we're writing out |
| | 11 | | /// </summary> |
| | 12 | | private readonly Catalog _catalog; |
| | 13 | |
|
| | 14 | | /// <summary> |
| | 15 | | /// Serialization options |
| | 16 | | /// </summary> |
| 16 | 17 | | private JsonSerializerOptions Options { get; } = new() |
| 4 | 18 | | { |
| 4 | 19 | | WriteIndented = false, |
| 4 | 20 | | MaxDepth = 99 |
| 4 | 21 | | }; |
| | 22 | |
|
| | 23 | | /// <summary> |
| | 24 | | /// Constructor |
| | 25 | | /// </summary> |
| | 26 | | /// <param name="catalog">The catalog of objects to write</param> |
| 4 | 27 | | public Writer(Catalog catalog) |
| | 28 | | { |
| 4 | 29 | | _catalog = catalog; |
| 4 | 30 | | Options.Converters.Add(new SpdxModelConverterFactory()); |
| 4 | 31 | | Options.Converters.Add(new SpdxWrapperConverterFactory()); |
| 4 | 32 | | } |
| | 33 | |
|
| | 34 | | /// <summary> |
| | 35 | | /// Write the catalog to a string that is the content of an SPDX 3.0.1 compliant JSON file. |
| | 36 | | /// </summary> |
| | 37 | | /// <returns>The catalog as a string</returns> |
| | 38 | | public string WriteString() |
| | 39 | | { |
| | 40 | | // ReSharper disable once SuggestVarOrType_BuiltInTypes |
| 4 | 41 | | object obj = new SpdxWrapper(_catalog); |
| | 42 | | // ReSharper disable once RedundantTypeArgumentsOfMethod |
| 4 | 43 | | var result = JsonSerializer.Serialize<object>(obj, Options); |
| | 44 | |
|
| 4 | 45 | | return result; |
| | 46 | | } |
| | 47 | |
|
| | 48 | | /// <summary> |
| | 49 | | /// Write the catalog to an SPDX 3.0.1 compliant JSON file |
| | 50 | | /// </summary> |
| | 51 | | /// <param name="fileStream">The FileStream to write to</param> |
| | 52 | | /// <returns>The file we wrote to</returns> |
| | 53 | | public FileStream WriteFileStream(FileStream fileStream) |
| | 54 | | { |
| 2 | 55 | | using var writer = new StreamWriter(fileStream); |
| 2 | 56 | | writer.Write(WriteString()); |
| 2 | 57 | | return fileStream; |
| 2 | 58 | | } |
| | 59 | |
|
| | 60 | | /// <summary> |
| | 61 | | /// Create a new file and write the catalog to it as SPDX 3.0.1 compliant JSON |
| | 62 | | /// </summary> |
| | 63 | | /// <param name="fileName">The name of the new JSON file to create</param> |
| | 64 | | /// <returns>The file we created and wrote to</returns> |
| | 65 | | public FileInfo WriteFileName(string fileName) |
| | 66 | | { |
| 1 | 67 | | var fileStream = new FileStream(fileName, FileMode.Create); |
| 1 | 68 | | WriteFileStream(fileStream); |
| 1 | 69 | | return new FileInfo(fileName); |
| | 70 | | } |
| | 71 | | } |