-
Notifications
You must be signed in to change notification settings - Fork 3
/
Index.cs
executable file
·113 lines (103 loc) · 3.19 KB
/
Index.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Wolf
{
internal class Index
{
private Log _log;
private Config _config;
private readonly List<string> _tags = new();
private readonly List<Post> _posts = new();
internal Index(Log log, Config config)
{
_log = log;
_config = config;
}
internal void Add(string slug, string featuredImage, IEnumerable<string> lines)
{
var post = new Post
{
Slug = slug,
Title = slug,
FeaturedImage = featuredImage
};
if (lines != null)
{
foreach (var l in lines)
{
var i = l.IndexOf(':');
if (i >= 0)
{
var key = l.Substring(0, i).Trim().ToLower();
var value = l.Substring(i + 1).Trim();
switch (key)
{
case "title":
post.Title = value;
break;
case "published":
post.Published = DateTime.Parse(value, CultureInfo.InvariantCulture);
break;
case "image":
post.FeaturedImage = _config.ImagePrefix + slug + '/' + value;
break;
case "tags":
case "categories":
post.Tags = value.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
foreach (var tag in post.Tags)
{
if (_tags.Find(t => string.Equals(t, tag, StringComparison.CurrentCultureIgnoreCase)) == null)
{
_tags.Add(tag);
}
}
break;
default:
_log.Warning($"Unrecognized YAML header '{l}' in '{slug}'");
break;
}
}
}
}
_posts.Add(post);
}
internal void Save()
{
_posts.Sort(); // Post class implements "IComparable" on the publish date.
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
File.WriteAllText(PostsFileName, JsonConvert.SerializeObject(_posts, Formatting.Indented, settings));
if (_config.GenerateTagsFile)
{
// Report newly introduced tags in verbose mode.
if (_config.Verbose)
{
if (File.Exists(TagsFileName))
{
var oldTags = JsonConvert.DeserializeObject<List<string>>(File.ReadAllText(TagsFileName));
var newTags = _tags.Except(oldTags);
if (newTags.Any())
{
_log.Info("New tags were encountered:");
foreach (var t in newTags)
{
_log.Info($"- {t}");
}
}
}
}
_tags.Sort();
File.WriteAllText(TagsFileName, JsonConvert.SerializeObject(_tags, Formatting.Indented, settings));
}
}
private string PostsFileName => Path.Combine(_config.IndexDirectory, "posts.json");
private string TagsFileName => Path.Combine(_config.IndexDirectory, "tags.json");
}
}