A game about forced loneliness, made by TACStudios
1using System; 2using System.IO; 3using UnityEditor.ShaderGraph.Serialization; 4using Debug = UnityEngine.Debug; 5using UnityEditor.VersionControl; 6using System.Text; 7 8namespace UnityEditor.ShaderGraph 9{ 10 static class FileUtilities 11 { 12 // if successfully written to disk, returns the serialized file contents as a string 13 // on failure, returns null 14 public static string WriteShaderGraphToDisk(string path, GraphData data) 15 { 16 if (data == null) 17 { 18 // Returning false may be better than throwing this exception, in terms of preserving data. 19 // But if GraphData is null, it's likely we don't have any data to preserve anyways. 20 // So this exception seems fine for now. 21 throw new ArgumentNullException(nameof(data)); 22 } 23 24 var text = MultiJson.Serialize(data); 25 if (WriteToDisk(path, text)) 26 return text; 27 else 28 return null; 29 } 30 31 // returns true if successfully written to disk 32 public static bool WriteToDisk(string path, string text) 33 { 34 CheckoutIfValid(path); 35 36 while (true) 37 { 38 try 39 { 40 File.WriteAllText(path, text); 41 } 42 catch (Exception e) 43 { 44 if (e.GetBaseException() is UnauthorizedAccessException && 45 (File.GetAttributes(path) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) 46 { 47 if (EditorUtility.DisplayDialog("File is Read-Only", path, "Make Writeable", "Cancel Save")) 48 { 49 // make writeable 50 FileInfo fileInfo = new FileInfo(path); 51 fileInfo.IsReadOnly = false; 52 continue; // retry save 53 } 54 else 55 return false; 56 } 57 58 Debug.LogException(e); 59 60 if (EditorUtility.DisplayDialog("Exception While Saving", e.ToString(), "Retry", "Cancel")) 61 continue; // retry save 62 else 63 return false; 64 } 65 break; // no exception, file save success! 66 } 67 68 return true; 69 } 70 71 // returns contents of the asset file as a string, or null if any error or exception occurred 72 public static string SafeReadAllText(string assetPath) 73 { 74 string result = null; 75 try 76 { 77 result = File.ReadAllText(assetPath, Encoding.UTF8); 78 } 79 catch 80 { 81 result = null; 82 } 83 return result; 84 } 85 86 static void CheckoutIfValid(string path) 87 { 88 if (VersionControl.Provider.enabled && VersionControl.Provider.isActive) 89 { 90 var asset = VersionControl.Provider.GetAssetByPath(path); 91 if (asset != null) 92 { 93 if (!VersionControl.Provider.IsOpenForEdit(asset)) 94 { 95 var task = VersionControl.Provider.Checkout(asset, VersionControl.CheckoutMode.Asset); 96 task.Wait(); 97 98 if (!task.success) 99 Debug.Log(task.text + " " + task.resultCode); 100 } 101 } 102 } 103 } 104 } 105}