| Name | Message | Date |
|---|---|---|
| 📄 NewNote.cs | 7 hours ago | |
| 📄 NotesCli.csproj | 14 hours ago | |
| 📄 packages.lock.json | 14 hours ago |
📄
src/NewNote.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Management.Automation; using Markdig; using Markdig.Extensions.Yaml; using Markdig.Syntax; using YamlDotNet.Serialization; using YamlDotNet.Serialization.Converters; namespace NotesCli; [Cmdlet(VerbsCommon.New, "Note", SupportsShouldProcess = true)] [Alias("nn")] public sealed class NewNote : PSCmdlet { private static readonly MarkdownPipeline markdownPipeline = new MarkdownPipelineBuilder() .UseYamlFrontMatter() .Build(); private static readonly IDeserializer yamlDeserializer = new DeserializerBuilder().Build(); private static readonly ISerializer yamlSerializer = new SerializerBuilder() .WithTypeConverter(new DateOnlyConverter(formats: "yyyy-MM-dd")) .Build(); [Parameter(HelpMessage = "Opens the newly created note for editing.")] public SwitchParameter Open { get; set; } = true; protected override void BeginProcessing() { var now = DateTimeOffset.Now; var frontmatter = GetPreviousFrontmatter() ?? []; frontmatter["date"] = DateOnly.FromDateTime(now.DateTime); var content = $""" --- {yamlSerializer.Serialize(frontmatter).TrimEnd()} --- """; var createdItems = InvokeProvider.Item.New( path: ".", name: $"{now:yyyy-MM-ddTHHmmss}.md", itemTypeName: "file", content: content ); if (createdItems is not [{ BaseObject: FileInfo createdItem }]) { return; } if (Open && ShouldProcess(createdItem.FullName, "Open")) { InvokeCommand.InvokeScript( $"{GetVariableValue("Env:EDITOR")} {createdItem.FullName}:{content.Count(c => c is '\n')}" ); } WriteObject(createdItem); } private Dictionary<string, object>? GetPreviousFrontmatter() { var previousNote = InvokeProvider .ChildItem.Get("*.md", recurse: false) .Select(i => i.BaseObject) .OfType<FileInfo>() .MaxBy(f => f.Name); if (previousNote is null) { return null; } string previousText; using (var reader = new StreamReader(previousNote.OpenRead())) { previousText = reader.ReadToEnd(); } var markdown = Markdown.Parse(previousText, markdownPipeline); var yamlBlock = markdown.Descendants<YamlFrontMatterBlock>().FirstOrDefault(); if (yamlBlock?.Lines.ToString() is not string yaml) { return null; } return yamlDeserializer.Deserialize<Dictionary<string, object>>(yaml); } }