83 lines
2.6 KiB
C#
83 lines
2.6 KiB
C#
using System.Text.Json;
|
|
using MycroForge.CLI.Extensions;
|
|
|
|
namespace MycroForge.CLI;
|
|
|
|
public class ProjectContext
|
|
{
|
|
public string RootDirectory { get; private set; } = Environment.CurrentDirectory;
|
|
public string ConfigPath => Path.Combine(RootDirectory, "m4g.json");
|
|
public ProjectConfig Config { get; private set; } = default!;
|
|
|
|
private readonly ArgsContext _argsContext;
|
|
|
|
public ProjectContext(ArgsContext argsContext)
|
|
{
|
|
_argsContext = argsContext;
|
|
}
|
|
|
|
public async Task LoadConfig(bool force = false)
|
|
{
|
|
if (_argsContext.Args
|
|
is ["init", ..]
|
|
or ["-?", ..] or [.., "-?"]
|
|
or ["-h", ..] or [.., "-h"]
|
|
or ["--help"] or [.., "--help"]
|
|
or ["--version"] && !force)
|
|
return;
|
|
|
|
if (!File.Exists(ConfigPath))
|
|
throw new FileNotFoundException($"File {ConfigPath} does not exist.");
|
|
|
|
Config = (await JsonSerializer.DeserializeAsync<ProjectConfig>(
|
|
File.OpenRead(ConfigPath),
|
|
Shared.DefaultJsonSerializerOptions.CamelCasePrettyPrint
|
|
))!;
|
|
}
|
|
|
|
public void ChangeDirectory(string path)
|
|
{
|
|
Directory.SetCurrentDirectory(path);
|
|
RootDirectory = path;
|
|
}
|
|
|
|
public async Task CreateFile(string path, params string[] content)
|
|
{
|
|
var fullPath = Path.Combine(RootDirectory, path);
|
|
var fileInfo = new FileInfo(fullPath);
|
|
|
|
if (fileInfo.Exists) return;
|
|
|
|
Directory.CreateDirectory(fileInfo.Directory!.FullName);
|
|
await File.WriteAllTextAsync(fullPath, string.Join("\n", content));
|
|
await Bash.ExecuteAsync($"chmod 777 {fullPath}");
|
|
}
|
|
|
|
public async Task<string> ReadFile(string path)
|
|
{
|
|
var fullPath = Path.Combine(RootDirectory, path);
|
|
var fileInfo = new FileInfo(fullPath);
|
|
|
|
if (!fileInfo.Exists)
|
|
throw new Exception($"File {fullPath} does not exist.");
|
|
|
|
return await File.ReadAllTextAsync(fullPath);
|
|
}
|
|
|
|
public async Task WriteFile(string path, params string[] content)
|
|
{
|
|
var fullPath = Path.Combine(RootDirectory, path);
|
|
var fileInfo = new FileInfo(fullPath);
|
|
Directory.CreateDirectory(fileInfo.Directory!.FullName);
|
|
await File.WriteAllTextAsync(fullPath, string.Join("\n", content));
|
|
}
|
|
|
|
public async Task SaveConfig()
|
|
{
|
|
if (Config is not null)
|
|
{
|
|
var json = await Config.SerializeAsync(Shared.DefaultJsonSerializerOptions.CamelCasePrettyPrint);
|
|
await File.WriteAllTextAsync(ConfigPath, json);
|
|
}
|
|
}
|
|
} |