namespace Unosquare.Swan.Components
{
using System;
using System.IO;
using System.Linq;
using System.Xml.Linq;
///
/// Represents a CsProjFile (and FsProjFile) parser.
///
///
/// Based on https://github.com/maartenba/dotnetcli-init.
///
/// The type of CsProjMetadataBase.
///
public class CsProjFile
: IDisposable
where T : CsProjMetadataBase
{
private readonly Stream _stream;
private readonly bool _leaveOpen;
private readonly XDocument _xmlDocument;
///
/// Initializes a new instance of the class.
///
/// The filename.
public CsProjFile(string filename = null)
: this(OpenFile(filename))
{
// placeholder
}
///
/// Initializes a new instance of the class.
///
/// The stream.
/// if set to true [leave open].
/// Project file is not of the new .csproj type.
public CsProjFile(Stream stream, bool leaveOpen = false)
{
_stream = stream;
_leaveOpen = leaveOpen;
_xmlDocument = XDocument.Load(stream);
var projectElement = _xmlDocument.Descendants("Project").FirstOrDefault();
var sdkAttribute = projectElement?.Attribute("Sdk");
var sdk = sdkAttribute?.Value;
if (sdk != "Microsoft.NET.Sdk" && sdk != "Microsoft.NET.Sdk.Web")
{
throw new ArgumentException("Project file is not of the new .csproj type.");
}
Metadata = Activator.CreateInstance();
Metadata.SetData(_xmlDocument);
}
///
/// Gets the metadata.
///
///
/// The nu get metadata.
///
public T Metadata { get; }
///
/// Saves this instance.
///
public void Save()
{
_stream.SetLength(0);
_stream.Position = 0;
_xmlDocument.Save(_stream);
}
///
public void Dispose()
{
if (!_leaveOpen)
{
_stream?.Dispose();
}
}
private static FileStream OpenFile(string filename)
{
if (filename == null)
{
filename = Directory
.EnumerateFiles(Directory.GetCurrentDirectory(), "*.csproj", SearchOption.TopDirectoryOnly)
.FirstOrDefault();
}
if (filename == null)
{
filename = Directory
.EnumerateFiles(Directory.GetCurrentDirectory(), "*.fsproj", SearchOption.TopDirectoryOnly)
.FirstOrDefault();
}
if (string.IsNullOrWhiteSpace(filename))
throw new ArgumentNullException(nameof(filename));
return File.Open(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite);
}
}
}