1 // 2 // Copyright (c) 2010-2018 Antmicro 3 // Copyright (c) 2011-2015 Realtime Embedded 4 // 5 // This file is licensed under the MIT License. 6 // Full license text is available in 'licenses/MIT.txt'. 7 // 8 9 using System; 10 using System.Linq; 11 using System.Collections.Generic; 12 using System.IO; 13 using Antmicro.Renode.Exceptions; 14 using Antmicro.Renode.Utilities; 15 16 namespace Antmicro.Renode.UserInterface 17 { 18 public class MonitorPath 19 { 20 private List<string> pathEntries = new List<string>(); 21 private List<string> defaultPath = new List<string>(); 22 private readonly string startingWorkingDirectory; 23 private readonly char[] pathSeparator = new []{';'}; 24 private Stack<string> workingDirectory = new Stack<string>(); 25 26 public String CurrentWorkingDirectory 27 { 28 get{ return workingDirectory.Peek();} 29 } 30 PushWorkingDirectory(string path)31 public void PushWorkingDirectory(string path) 32 { 33 Environment.CurrentDirectory = System.IO.Path.Combine(CurrentWorkingDirectory, path); 34 workingDirectory.Push(Environment.CurrentDirectory); 35 } 36 PopWorkingDirectory()37 public string PopWorkingDirectory() 38 { 39 Environment.CurrentDirectory = workingDirectory.Pop(); 40 return Environment.CurrentDirectory; 41 } 42 43 public IEnumerable<string> PathElements 44 { 45 get{ return pathEntries;} 46 } 47 GetDirEntries(string path)48 private List<string> GetDirEntries(string path) 49 { 50 var split = path.Split(pathSeparator, StringSplitOptions.RemoveEmptyEntries).Distinct(); 51 var current = new List<string>(); 52 foreach (string entry in split) 53 { 54 var curentry = entry;//System.IO.Path.Combine(Environment.CurrentDirectory, entry); 55 if (curentry.StartsWith("./")) 56 { 57 curentry = curentry.Length > 2 ? curentry.Substring(2) : "."; 58 } 59 if (!Directory.Exists(curentry)) 60 { 61 throw new RecoverableException(String.Format("Entry {0} does not exist or is not a directory.", curentry)); 62 } 63 current.Add(curentry); 64 } 65 return current; 66 } 67 68 public String Path 69 { 70 get 71 { 72 return pathEntries.Aggregate((x,y) => x + ';' + y); 73 } 74 set 75 { 76 pathEntries = GetDirEntries(value); 77 } 78 } 79 80 public String DefaultPath 81 { 82 get{ return defaultPath.Aggregate((x,y) => x + ';' + y);} 83 private set 84 { 85 defaultPath = GetDirEntries(value); 86 } 87 } 88 Append(string path)89 public void Append(string path) 90 { 91 pathEntries.AddRange(GetDirEntries(path)); 92 } 93 Reset()94 public void Reset() 95 { 96 Path = DefaultPath; 97 workingDirectory.Push(startingWorkingDirectory); 98 Append(CurrentWorkingDirectory); 99 } 100 MonitorPath(string currentWorkingDirectory)101 public MonitorPath(string currentWorkingDirectory) 102 { 103 startingWorkingDirectory = currentWorkingDirectory; 104 if(Misc.TryGetRootDirectory(out var rootDirectory)) 105 { 106 defaultPath = new List<string> { rootDirectory }; 107 } 108 else 109 { 110 DefaultPath = "."; 111 } 112 Reset(); 113 } 114 } 115 } 116 117