-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFileContent.cs
More file actions
69 lines (60 loc) · 2.19 KB
/
FileContent.cs
File metadata and controls
69 lines (60 loc) · 2.19 KB
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
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using Avalonia.Controls;
using AvaloniaEdit;
namespace ScriptRunner.GUI;
public class FileContent : IControlRecord
{
private readonly string _extension;
private readonly bool _useWslPath;
public Control Control { get; set; }
public string FileName { get; set; }
public FileContent(string extension, bool useWslPath)
{
_extension = extension;
_useWslPath = useWslPath;
FileName = GetFileContentStoragePath("temp." + extension);
}
public string GetFormattedValue()
{
var fileContent = Control switch
{
TextBox textBox => textBox.Text,
TextEditor textEditor => textEditor.Text,
_ => ((TextBox)Control).Text
};
var hash = string.IsNullOrWhiteSpace(fileContent)? "EMPTY" : ComputeSHA256(fileContent).Substring(0,10);
FileName = GetFileContentStoragePath(hash + "." + _extension);
File.WriteAllText(FileName, fileContent, Encoding.UTF8);
return _useWslPath ? WslPathConverter.ConvertToWslPath(FileName) : FileName;
}
private static string GetFileContentStoragePath(string fileName)
{
var appDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "ScriptRunner", "FileContentStorage");
if (Directory.Exists(appDataPath) == false)
{
Directory.CreateDirectory(appDataPath);
}
return Path.Combine(appDataPath, fileName);
}
static string ComputeSHA256(string input)
{
using var sha256 = SHA256.Create();
byte[] bytes = Encoding.UTF8.GetBytes(input);
byte[] hashBytes = sha256.ComputeHash(bytes);
return BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
}
public string Name { get; set; }
public bool MaskingRequired { get; set; }
}
public static class WslPathConverter
{
public static string ConvertToWslPath(string fileName)
{
var driveLetter = char.ToLower(fileName[0]);
var pathWithoutDrive = fileName.Substring(2).Replace('\\', '/');
return $"/mnt/host/{driveLetter}{pathWithoutDrive}";
}
}