ln.templates/ln.templates/html/FileSystemTemplateSource.cs

73 lines
2.4 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace ln.templates.html
{
public class FileSystemTemplateSource : ITemplateSource
{
public String BasePath { get; }
public bool Throws { get; }
Dictionary<string, TemplateDocument> templateDocuments = new Dictionary<string, TemplateDocument>();
public FileSystemTemplateSource(String path,bool throws)
:this(path)
{
Throws = throws;
}
public FileSystemTemplateSource(String path)
{
if (!Directory.Exists(path))
throw new FileNotFoundException();
BasePath = path;
}
public TemplateDocument GetTemplateByPath(string path) => GetTemplateByPath(path, Throws);
public TemplateDocument GetTemplateByPath(string path,bool _throw)
{
string templatePath = Path.Combine(BasePath, path);
if (!File.Exists(templatePath))
{
if (templateDocuments.ContainsKey(path))
templateDocuments.Remove(path);
if (_throw)
throw new FileNotFoundException();
return null;
}
if (!templateDocuments.TryGetValue(path,out TemplateDocument templateDocument))
{
templateDocument = ReadTemplateDocument(path);
templateDocuments[path] = templateDocument;
} else
{
DateTime templateDateTime = File.GetLastWriteTime(templatePath);
if (templateDateTime.Ticks != templateDocument.TemplateVersion)
{
templateDocument = ReadTemplateDocument(path);
templateDocuments[path] = templateDocument;
}
}
return templateDocument;
}
TemplateDocument ReadTemplateDocument(string path)
{
string templatePath = Path.Combine(BasePath, path);
TemplateReader templateReader = new TemplateReader();
using (StreamReader sr = new StreamReader(templatePath))
{
templateReader.Read(sr);
}
templateReader.TemplateDocument.TemplateVersion = File.GetLastWriteTime(templatePath).Ticks;
return templateReader.TemplateDocument;
}
}
}