public void GetAbsolutePathTest() { // Mono has a bug so that Path.GetFullPath(Path.GetTempPath()) // doesn't return the same as GetFullPath(".") if Current Directory is Path.GetTempPath() string TempPathFullName = Helper.SetCurrentDirectory(Path.GetTempPath(), () => { return(Directory.GetCurrentDirectory()); }); string dirName = Path.GetRandomFileName(); string dirPath = Path.Combine(TempPathFullName, dirName); Helper.SetCurrentDirectory <Object>(Path.GetTempPath(), () => { try { Directory.CreateDirectory(dirPath); Assert.AreEqual(dirPath, FileSystemUtil.GetAbsolutePath(dirName)); return(null); } finally { Directory.Delete(dirPath, true); } }); }
public void CopyAndIgnoreDirectoryTest() { string temp_path = Path.GetTempPath(); string source_dir = Path.Combine(temp_path, Path.GetRandomFileName()); string dest_dir = Path.Combine(temp_path, Path.GetRandomFileName()); try { Directory.CreateDirectory(source_dir); string ignoredFile = "foobarbaz"; string notIgnoredFile = "NotToBeIgnored"; File.Create(Path.Combine(source_dir, ignoredFile)).Dispose(); File.Create(Path.Combine(source_dir, notIgnoredFile)).Dispose(); FileSystemUtil.CopyDirectory(source_dir, dest_dir, new string[] { "foo", "bar", "baz" }); Assert.IsFalse(File.Exists(Path.Combine(dest_dir, ignoredFile))); Assert.IsTrue(File.Exists(Path.Combine(dest_dir, notIgnoredFile))); } finally { Directory.Delete(source_dir, true); Directory.Delete(dest_dir, true); } }
public void GetFilesTest() { int file_amount = 5; string[] files = new string[file_amount]; string tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); try { Directory.CreateDirectory(tempDirectory); for (int i = 0; i < file_amount; i++) { string filename = Path.Combine(tempDirectory, Path.GetRandomFileName()); File.Create(filename).Dispose(); files[i] = filename; } CollectionAssert.AreEquivalent(files, FileSystemUtil.GetFiles(tempDirectory)); } finally { Directory.Delete(tempDirectory, true); } }
/// <summary> /// Captura o caminho do arquivo de configuração. /// </summary> /// <param name="path">Informação do arquivo do configuração.</param> /// <returns>Caminho do arquivo de configuração.</returns> internal static string GetLocalPath(string path) { if (path == null) { path = CONFIG_FILENAME; } if (FileSystemUtil.IsValidFilePath(path)) { return(path); } else if (FileSystemUtil.IsFileName(path)) { return(FileSystemUtil.DetermineFileLocation(path, CONFIG_FOLDERS)); } else if (FileSystemUtil.IsFolder(path)) { return(FileSystemUtil.CombinePathAndFileName(path, CONFIG_FILENAME)); } else { return(path); } }
internal static string GetEditorRealPath(string path) { if (string.IsNullOrEmpty(path)) { return(path); } if (!FileSystemUtil.EditorPathExists(path)) { return(path); } if (SystemInfo.operatingSystemFamily != OperatingSystemFamily.Windows) { var realPath = FileSystemUtil.GetFinalPathName(path); // case of snap installation if (SystemInfo.operatingSystemFamily == OperatingSystemFamily.Linux) { if (new FileInfo(path).Name.ToLowerInvariant() == "rider" && new FileInfo(realPath).Name.ToLowerInvariant() == "snap") { var snapInstallPath = "/snap/rider/current/bin/rider.sh"; if (new FileInfo(snapInstallPath).Exists) { return(snapInstallPath); } } } // in case of symlink return(realPath); } return(path); }
public UnityExternalFilesModuleProcessor(Lifetime lifetime, ILogger logger, ISolution solution, ChangeManager changeManager, IShellLocks locks, ISolutionLoadTasksScheduler scheduler, IFileSystemTracker fileSystemTracker, ProjectFilePropertiesFactory projectFilePropertiesFactory, UnityYamlPsiSourceFileFactory psiSourceFileFactory, UnityExternalFilesModuleFactory moduleFactory, UnityYamlDisableStrategy unityYamlDisableStrategy) { myLifetime = lifetime; myLogger = logger; mySolution = solution; myChangeManager = changeManager; myLocks = locks; myFileSystemTracker = fileSystemTracker; myProjectFilePropertiesFactory = projectFilePropertiesFactory; myPsiSourceFileFactory = psiSourceFileFactory; myModuleFactory = moduleFactory; myUnityYamlDisableStrategy = unityYamlDisableStrategy; changeManager.RegisterChangeProvider(lifetime, this); myRootPaths = new JetHashSet <FileSystemPath>(); // SolutionDirectory isn't absolute in tests, and will throw an exception if we use it when we call Exists mySolutionDirectory = solution.SolutionDirectory; if (!mySolutionDirectory.IsAbsolute) { mySolutionDirectory = solution.SolutionDirectory.ToAbsolutePath(FileSystemUtil.GetCurrentDirectory()); } scheduler.EnqueueTask(new SolutionLoadTask(GetType().Name + ".Activate", SolutionLoadTaskKinds.PreparePsiModules, () => myChangeManager.AddDependency(myLifetime, mySolution.PsiModules(), this))); }
public void Upgrade(string projectPath, string userSettingsPath, ref XmlDocument projectDocument, ref XmlDocument userSettingsDocument, ref XmlNamespaceManager nsm) { //Renamed "ParameterOfAPI" to "Parameter." { XmlNodeList nodes = projectDocument.SelectNodes("P:Project/P:TableMappings/P:TableMapping/P:APIs/P:API/P:Parameters/P:ParameterOfAPI", nsm); if (nodes != null) { nodes.Rename("", "Parameter", ProjectSchema.Project.XmlNamespace); } } //Added "hint paths" to Templates. if (userSettingsDocument != null) { XmlNodeList nodes = userSettingsDocument.SelectNodes("P:UserSettings/P:Templates/P:Template", nsm); if (nodes != null) { foreach (XmlElement node in nodes) { XmlAttribute xsltPathAttribute = node.Attributes["XsltPath"]; string xsltHintPath = FileSystemUtil.AbsolutePathToHintPath(projectPath, xsltPathAttribute.Value); XmlAttribute xsltHintPathAttribute = projectDocument.CreateAttribute("XsltHintPath", ProjectSchema.Project.XmlNamespace); XmlAttribute outputPathAttribute = node.Attributes["OutputPath"]; string outputHintPath = FileSystemUtil.AbsolutePathToHintPath(projectPath, outputPathAttribute.Value); XmlAttribute outputHintPathAttribute = projectDocument.CreateAttribute("OutputHintPath", ProjectSchema.Project.XmlNamespace); node.Attributes.InsertBefore(xsltPathAttribute, xsltHintPathAttribute); node.Attributes.Remove(xsltPathAttribute); node.Attributes.InsertBefore(outputPathAttribute, outputHintPathAttribute); node.Attributes.Remove(outputPathAttribute); } } } }
static void GenericBuild(string[] scenes, string target_dir, BuildTarget build_target, BuildOptions build_options, bool override_options) { FileSystemUtil.EnsureParentExists(target_dir); if (EditorUserBuildSettings.activeBuildTarget != build_target) { EditorUserBuildSettings.SwitchActiveBuildTarget(build_target); } if (override_options) { bool FirstRun = !Directory.Exists(target_dir); build_options = OverrideBuildOptionsWithUserSettings(build_options, FirstRun); } Debug.Log("==> BuildOptions: " + build_options); string dir = System.IO.Path.GetDirectoryName(target_dir); PreProcess(dir); string res = BuildPipeline.BuildPlayer(scenes, target_dir, build_target, build_options); if (res.Length > 0) { throw new Exception("BuildPlayer failure: " + res); } PostProcess(dir); }
internal static Upfile LoadTestXml(string path) { StrictXmlDeserializer <Upfile> deserializer = new StrictXmlDeserializer <Upfile>(); using (FileStream fs = new FileStream(path, FileMode.Open)) { Upfile upfile = deserializer.Deserialize(fs); upfile.MakePathConfigurationsOSFriendly(); if (upfile.Repositories != null) { foreach (Repository repo in upfile.Repositories) { if (repo is FileRepository) { (repo as FileRepository).Path = FileSystemUtil.MakePathOSFriendly((repo as FileRepository).Path); } } } return(upfile); } }
public void Save() { Discovery dis = new Discovery(); dis.AddAssembly(Assembly.GetExecutingAssembly()); Stream stream = dis.GetResource("SolutionTemplate.txt"); using (StreamReader reader = new StreamReader(stream)) { string solutionContents = reader.ReadToEnd(); string solutionPath = Path.Combine(Folder, SolutionName + ".sln"); string projectsSection = ""; foreach (Project project in Projects) { project.RelPath = Path.Combine(project.OutputFolder.Replace(Folder + Path.DirectorySeparatorChar, ""), project.Name + ".csproj"); projectsSection += string.Format("Project(\"{{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}}\") = \"{0}\", \"{1}\", \"{2}\"\r\n" + "\tProjectSection(ProjectDependencies) = postProject\r\n" + "\tEndProjectSection\r\n" + "EndProject\r\n", project.Name, project.RelPath, "{" + project.Guid + "}"); } solutionContents = solutionContents.Replace("#Projects#", projectsSection.TrimEnd('\r', '\n')); string configurationTemplate = "\t\t{0}.Debug.ActiveCfg = Debug|.NET\r\n" + "\t\t{0}.Debug.Build.0 = Debug|.NET\r\n" + "\t\t{0}.Release.ActiveCfg = Release|.NET\r\n" + "\t\t{0}.Release.Build.0 = Release|.NET\r\n"; string configuration = ""; foreach (Project project in Projects) { configuration += string.Format(configurationTemplate, "{" + project.Guid + "}"); } solutionContents = solutionContents.Replace("#Configuration#", "\r\n" + configuration + "\t"); FileSystemUtil.WriteFile(solutionPath, solutionContents); } }
/// <summary> /// 扫描数据库,判断是否在mac上存在 /// </summary> /// <param name="config"></param> private void DBSync(Config config) { try { /* * 分页获取SSHPathInfo,找出mac端已经删除文件对应的id,删除对应的本地文件并刷新数据库 * * 待确定的想法:如果发现mac端文件已经更新,则更新本地文件 */ List <string> delIDList = new List <string>(); SSHPathInfoDAL spid = new SSHPathInfoDAL(); #region 主要处理 try { FileSystemUtil fsu = new FileSystemUtil(); //获取所有MonitorServer,以便于数据处理 MonitorServerDAL msd = new MonitorServerDAL(); List <MonitorServer> msList = msd.GetAllMonitorServer(config); foreach (SSHPathInfo spi in spid.GetSSHPathInfo(config)) { if (Signal.IsSystemStoping) { break; } #region 判断Mac端文件是否存在,如果不存在,则删除本地SSH输出目录中对应文件 SFTPProxy sftpProxy = null; string localSSHPath = string.Empty; try { //获取对应mac机的信息 MonitorServer ms = msList.Find(x => x.monitorServerIP.Trim().Equals(spi.MonitorServerIP.Trim()) && spi.MacPath.ToLower().Trim().Contains(x.monitorMacPath.ToLower().Trim())); if (ms != null) { sftpProxy = new SFTPProxy(ms.monitorServerIP, ms.account, ms.password); if (!sftpProxy.IsExist(spi.MacPath)) { delIDList.Add(spi.ID); #region 除SSH输出路径的本地文件 //获取本地路径 localSSHPath = GetLocalSSHPath(ms, spi.MacPath, config.Path.OutputPath); if (spi.typeflag == 0) { fsu.DeleteDir(localSSHPath); } else { //如果是文件 fsu.DeleteFile(localSSHPath); //判断目录是否为空:是否有文件 CleanLocalSSHDirectory(fsu, localSSHPath); } #endregion } } } catch (System.Exception ex) { Common.Util.LogManager.WriteLog(Common.Util.LogFile.DBSync, localSSHPath + Environment.NewLine + MessageUtil.GetExceptionMsg(ex, "")); } finally { if (sftpProxy != null) { sftpProxy.Close(); } } #endregion } } catch (System.Exception ex) { Common.Util.LogManager.WriteLog(Common.Util.LogFile.DBSync, MessageUtil.GetExceptionMsg(ex, "")); } finally { spid.Dispose(); } #endregion #region 更新数据库 spid.DeleteEntrys(config, delIDList); #endregion } catch (System.Exception ex) { Common.Util.LogManager.WriteLog(Common.Util.LogFile.DBSync, MessageUtil.GetExceptionMsg(ex, "")); } }
static RiderScriptEditor() { try { var projectGeneration = new ProjectGeneration(); var editor = new RiderScriptEditor(new Discovery(), projectGeneration); CodeEditor.Register(editor); var path = GetEditorRealPath(CodeEditor.CurrentEditorInstallation); if (IsRiderInstallation(path)) { if (!RiderScriptEditorData.instance.InitializedOnce) { var installations = editor.Installations; // is toolbox and outdated - update if (installations.Any() && RiderPathLocator.IsToolbox(path) && installations.All(a => a.Path != path)) { var toolboxInstallations = installations.Where(a => a.Name.Contains("(JetBrains Toolbox)")).ToArray(); if (toolboxInstallations.Any()) { var newEditor = toolboxInstallations.Last().Path; CodeEditor.SetExternalScriptEditor(newEditor); path = newEditor; } else { var newEditor = installations.Last().Path; CodeEditor.SetExternalScriptEditor(newEditor); path = newEditor; } } // exists, is non toolbox and outdated - notify if (installations.Any() && FileSystemUtil.EditorPathExists(path) && installations.All(a => a.Path != path)) { var newEditorName = installations.Last().Name; Debug.LogWarning($"Consider updating External Editor in Unity to Rider {newEditorName}."); } ShowWarningOnUnexpectedScriptEditor(path); RiderScriptEditorData.instance.InitializedOnce = true; } if (!FileSystemUtil.EditorPathExists(path)) // previously used rider was removed { var installations = editor.Installations; if (installations.Any()) { var newEditor = installations.Last().Path; CodeEditor.SetExternalScriptEditor(newEditor); path = newEditor; } } RiderScriptEditorData.instance.Init(); editor.CreateSolutionIfDoesntExist(); if (RiderScriptEditorData.instance.shouldLoadEditorPlugin) { editor.m_Initiliazer.Initialize(path); } InitProjectFilesWatcher(); } } catch (Exception e) { Debug.LogException(e); } }
internal AppSpec BuildAppSpec(BuildRequest request, ZlpDirectoryInfo workingDirectory) { var os = (from d in this.Options where string.Equals(d.Key, "os", System.StringComparison.Ordinal) select d.Value).SingleOrDefault() ?? "windows"; Assert.IsWhitelistedValue(os, AWSCodeDeployAppSpecGenerator.OSOptions); var destination = (from d in this.Options where string.Equals(d.Key, "destination", System.StringComparison.Ordinal) select d.Value).SingleOrDefault() ?? "c:\\inetpub\\wwwroot"; var applicationStop = (from d in this.Options where string.Equals(d.Key, "applicationstop", System.StringComparison.Ordinal) select d.Value).SingleOrDefault(); var beforeInstall = (from d in this.Options where string.Equals(d.Key, "beforeinstall", System.StringComparison.Ordinal) select d.Value).SingleOrDefault(); var afterInstall = (from d in this.Options where string.Equals(d.Key, "afterinstall", System.StringComparison.Ordinal) select d.Value).SingleOrDefault(); var applicationStart = (from d in this.Options where string.Equals(d.Key, "applicationstart", System.StringComparison.Ordinal) select d.Value).SingleOrDefault(); var validateService = (from d in this.Options where string.Equals(d.Key, "validateservice", System.StringComparison.Ordinal) select d.Value).SingleOrDefault(); if (string.IsNullOrEmpty(applicationStop)) { applicationStop = @"defaultApplicationStop.ps1"; string path = Path.Combine(workingDirectory.FullName, applicationStop); FileSystemUtil.WriteFile(path, Resources.defaultApplicationStop); } if (string.IsNullOrEmpty(beforeInstall)) { beforeInstall = @"defaultBeforeInstall.ps1"; string path = Path.Combine(workingDirectory.FullName, beforeInstall); string commandPath = Path.Combine(destination, "*"); string command = "Remove-Item \"" + commandPath + "\" -Force -Recurse"; FileSystemUtil.WriteFile(path, Resources.defaultBeforeInstall, command); } if (string.IsNullOrEmpty(applicationStart)) { applicationStart = @"defaultApplicationStart.ps1"; string path = Path.Combine(workingDirectory.FullName, applicationStart); FileSystemUtil.WriteFile(path, Resources.defaultApplicationStart); } AppSpec appSpec = new AppSpec() { OS = os }; appSpec.Files.Add("\\", destination); appSpec.Hooks.ApplicationStop.Add(applicationStop); appSpec.Hooks.BeforeInstall.Add(beforeInstall); appSpec.Hooks.ApplicationStart.Add(applicationStart); if (afterInstall != null) { appSpec.Hooks.AfterInstall = new HookEventCollection(); appSpec.Hooks.AfterInstall.Add(afterInstall); } if (validateService != null) { appSpec.Hooks.ValidateService = new HookEventCollection(); appSpec.Hooks.ValidateService.Add(validateService); } return(appSpec); }
private static bool NeedsUpdate(List <AugmentedNote> notes, AppSettings config) { if (!File.Exists(Path.Combine(config.GitMirrorPath, ".git", "HEAD"))) { return(true); } var folder = config.GitMirrorPath; if (config.GitMirrorSubfolders) { folder = Path.Combine(config.GitMirrorPath, config.ActiveAccount.ID.ToString("B")); } if (!Directory.Exists(folder)) { return(true); } var filesGit = FileSystemUtil .EnumerateFilesDeep(folder, 8) .Where(f => f.ToLower().EndsWith(".txt") || f.ToLower().EndsWith(".md")) .Select(Path.GetFileName) .Select(f => f.ToLower()) .ToList(); var filesThis = notes .Select(p => Path.Combine(folder, p.RelativePath)) .Select(f => f.ToLower()) .ToList(); if (filesGit.Count != filesThis.Count) { return(true); } if (filesGit.Except(filesThis).Any()) { return(true); } if (filesThis.Except(filesGit).Any()) { return(true); } foreach (var note in notes) { try { var fn = Path.Combine(folder, note.RelativePath); var txtThis = note.Content; var txtGit = File.ReadAllText(fn, Encoding.UTF8); if (txtGit != txtThis) { return(true); } } catch (IOException) { return(true); } } return(false); }
private static bool SyncNotesToFolder(List <AugmentedNote> reponotes, string targetFolder) { var dataRepo = reponotes.ToList(); var dataSystem = new List <Tuple <string, string> >(); // <rel_path, content> foreach (var file in FileSystemUtil.EnumerateFilesDeep(targetFolder, 16, new[] { ".git" })) { if (!(file.ToLower().EndsWith(".txt") || file.ToLower().EndsWith(".md"))) { continue; } var rpath = FileSystemUtil.MakePathRelative(file, targetFolder); var txt = File.ReadAllText(file, Encoding.UTF8); dataSystem.Add(Tuple.Create(rpath, txt)); } var files_nochange = new List <string>(); for (int i = dataRepo.Count - 1; i >= 0; i--) { var match = dataSystem.FirstOrDefault(ds => ds.Item1 == dataRepo[i].RelativePath && ds.Item2 == dataRepo[i].Content); if (match == null) { continue; } // Note exists in repo and filesystem with same content - everything is ok files_nochange.Add(match.Item1); dataSystem.Remove(match); dataRepo.RemoveAt(i); } if (dataSystem.Count == 0 && dataRepo.Count == 0) { LoggerSingleton.Inst.Debug("LocalGitMirror", "SyncNotesToFolder found 0 differences", string.Join("\n", files_nochange)); return(false); } var files_deleted = new List <string>(); for (int i = dataSystem.Count - 1; i >= 0; i--) { if (dataRepo.Any(ds => ds.RelativePath == dataSystem[i].Item1)) { continue; } // Note exists in filesystem but not in repo - delete it //var noteRepo = null; var noteFSys = dataSystem[i]; files_deleted.Add(noteFSys.Item1); dataSystem.RemoveAt(i); var fpath = Path.Combine(targetFolder, noteFSys.Item1); File.Delete(fpath); LoggerSingleton.Inst.Info("LocalGitMirror", $"File deleted: '{noteFSys.Item1}'", fpath); } var files_modified = new List <string>(); for (int i = dataSystem.Count - 1; i >= 0; i--) { var match = dataRepo.FirstOrDefault(ds => ds.RelativePath == dataSystem[i].Item1 && ds.Content == dataSystem[i].Item2); if (match == null) { continue; } // Note exists in filesystem and in repo but with different content - modify it var noteRepo = match; var noteFSys = dataSystem[i]; files_modified.Add(noteFSys.Item1); dataSystem.RemoveAt(i); dataRepo.Remove(noteRepo); var fpath = Path.Combine(targetFolder, noteRepo.RelativePath); File.WriteAllText(fpath, noteRepo.Content, new UTF8Encoding(false)); LoggerSingleton.Inst.Info("LocalGitMirror", $"File modified: '{noteRepo.RelativePath}'", fpath); } var files_created = new List <string>(); for (int i = dataRepo.Count - 1; i >= 0; i--) { // Note exists in repo but not in filesystem - create it var noteRepo = dataRepo[i]; //var noteFSys = null; files_created.Add(noteRepo.RelativePath); dataRepo.RemoveAt(i); var fpath = Path.Combine(targetFolder, noteRepo.RelativePath); Directory.CreateDirectory(Path.GetDirectoryName(fpath)); File.WriteAllText(fpath, noteRepo.Content, new UTF8Encoding(false)); LoggerSingleton.Inst.Info("LocalGitMirror", $"File created: '{noteRepo.RelativePath}'", fpath); } var dir_deleted = new List <string>(); foreach (var dir in FileSystemUtil.EnumerateEmptyDirectories(targetFolder, 16).ToList()) { dir_deleted.Add(dir); FileSystemUtil.DeleteDirectoryWithRetry(LoggerSingleton.Inst, dir); var rpath = FileSystemUtil.MakePathRelative(dir, targetFolder); LoggerSingleton.Inst.Info("LocalGitMirror", $"Directory dleted: '{rpath}'", dir); } LoggerSingleton.Inst.Debug("LocalGitMirror", "SyncNotesToFolder found multiple differences", "Unchanged:\n{\n" + string.Join("\n", files_nochange.Select(p => " " + p)) + "\n}\n\n" + "Deleted:\n{\n" + string.Join("\n", files_deleted.Select(p => " " + p)) + "\n}\n\n" + "Created:\n{\n" + string.Join("\n", files_created.Select(p => " " + p)) + "\n}\n\n" + "Modified:\n{\n" + string.Join("\n", files_modified.Select(p => " " + p)) + "\n}\n\n" + "Empty-Directories:\n{\n" + string.Join("\n", dir_deleted.Select(p => " " + p)) + "\n}\n\n"); return(true); }
static void CopyDataDirUnderTarget() { FileSystemUtil.copyDirectory("Data", TARGET_DIR + "/Data", COPY_DATA_IGNORE_PATTERNS); }
public override Object Transform(EngineIntrinsics engineIntrinsics, Object input) { List <String> transformedPaths = new List <String>(); bool useResolvedPath = !Literal; if (input is ICollection) { foreach (Object inputPath in (ICollection)input) { transformedPaths.AddRange((ICollection <String>)Transform(engineIntrinsics, inputPath)); } } else { IEnumerable <String> inputPaths = null; ProviderInfo provider = null; PSDriveInfo drive; if (useResolvedPath) { /* Expand wildcards, recurse */ try { inputPaths = engineIntrinsics.SessionState.Path.GetResolvedProviderPathFromPSPath(input.ToString(), out provider); } catch (ItemNotFoundException) { /* * This will occur when a user specifies a path to a file that no longer exists. We should try to * use a literal path here to retry. If the caller does not want to allow nonexistant paths, we * will error below instead. */ useResolvedPath = false; /* retry below */ } } if (!useResolvedPath) { inputPaths = new String[] { engineIntrinsics.SessionState.Path.GetUnresolvedProviderPathFromPSPath(input.ToString(), out provider, out drive) }; } Debug.Assert(provider != null); Debug.Assert(inputPaths != null); if (provider == null || inputPaths == null) { throw new Exception("Invalid path transformation"); } if (provider.ImplementingType != typeof(FileSystemProvider)) { throw new ArgumentException(String.Format("Files must be located on the filesystem, they cannot be provided by {0}", provider.ImplementingType.Name)); } foreach (String inputPath in inputPaths) { if (Directory.Exists(inputPath) && Recursive) { transformedPaths.AddRange(FileSystemUtil.GetFilesRecursive(inputPath)); } else if (!File.Exists(inputPath) && MustExist) { throw new FileNotFoundException(String.Format("The file {0} does not exist", inputPath)); } else { transformedPaths.Add(inputPath); } } } return(transformedPaths); }
static RiderScriptEditor() { try { // todo: make ProjectGeneration lazy var projectGeneration = new ProjectGeneration.ProjectGeneration(); var editor = new RiderScriptEditor(new Discovery(), projectGeneration); CodeEditor.Register(editor); var path = GetEditorRealPath(CurrentEditor); if (IsRiderInstallation(path)) { RiderPathLocator.RiderInfo[] installations = null; if (!RiderScriptEditorData.instance.initializedOnce) { installations = RiderPathLocator.GetAllRiderPaths().OrderBy(a => a.BuildNumber).ToArray(); // is likely outdated if (installations.Any() && installations.All(a => GetEditorRealPath(a.Path) != path)) { if (RiderPathLocator.GetIsToolbox(path)) // is toolbox - update { var toolboxInstallations = installations.Where(a => a.IsToolbox).ToArray(); if (toolboxInstallations.Any()) { var newEditor = toolboxInstallations.Last().Path; CodeEditor.SetExternalScriptEditor(newEditor); path = newEditor; } else { var newEditor = installations.Last().Path; CodeEditor.SetExternalScriptEditor(newEditor); path = newEditor; } } else // is non toolbox - notify { var newEditorName = installations.Last().Presentation; Debug.LogWarning($"Consider updating External Editor in Unity to Rider {newEditorName}."); } } ShowWarningOnUnexpectedScriptEditor(path); RiderScriptEditorData.instance.initializedOnce = true; } if (!FileSystemUtil.EditorPathExists(path)) // previously used rider was removed { if (installations == null) { installations = RiderPathLocator.GetAllRiderPaths().OrderBy(a => a.BuildNumber).ToArray(); } if (installations.Any()) { var newEditor = installations.Last().Path; CodeEditor.SetExternalScriptEditor(newEditor); path = newEditor; } } RiderScriptEditorData.instance.Init(); editor.CreateSolutionIfDoesntExist(); if (RiderScriptEditorData.instance.shouldLoadEditorPlugin) { editor.m_Initiliazer.Initialize(path); } RiderFileSystemWatcher.InitWatcher( Directory.GetCurrentDirectory(), "*.*", (sender, args) => { var extension = Path.GetExtension(args.Name); if (extension == ".sln" || extension == ".csproj") { RiderScriptEditorData.instance.hasChanges = true; } }); RiderFileSystemWatcher.InitWatcher( Path.Combine(Directory.GetCurrentDirectory(), "Library"), "EditorOnlyScriptingUserSettings.json", (sender, args) => { RiderScriptEditorData.instance.hasChanges = true; }); RiderFileSystemWatcher.InitWatcher( Path.Combine(Directory.GetCurrentDirectory(), "Packages"), "manifest.json", (sender, args) => { RiderScriptEditorData.instance.hasChanges = true; }); // can't switch to non-deprecated api, because UnityEditor.Build.BuildPipelineInterfaces.processors is internal #pragma warning disable 618 EditorUserBuildSettings.activeBuildTargetChanged += () => #pragma warning restore 618 { RiderScriptEditorData.instance.hasChanges = true; }; } } catch (Exception e) { Debug.LogException(e); } }
private void aggiornareSpazioLiberoSuDisco() { spazio = FileSystemUtil.FreeSpace(Configurazione.cartellaBaseFoto); }
public override void Execute() { DateTime start = DateTime.Now; if (ExecutableDirectory == null) { ExecutableDirectory = Path.GetFullPath("."); } diagnosticsFile = Path.Combine(ExecutableDirectory, "Exception.txt"); if (DiagnosticsMode && File.Exists(diagnosticsFile)) { Diagnostics.BreakOn(FileSystemUtil.ReadFile(diagnosticsFile)); } InputFolder = Path.GetFullPath(InputFolder); if (!Directory.Exists(InputFolder)) { throw new ApplicationException("Input folder does not exists."); } LoadOptions(); SetDefaultValues(); ValidateParameters(); if (Projects.Count == 0) { Project project = GetDefaultProject(); Projects.Add(project); } Mappings = Path.GetFullPath(Mappings); SetOutputFolder(); Discovery.AddAssembly(Assembly.GetExecutingAssembly()); Discovery.AddAssembly(GetType().Assembly); string folderName = Solution + "-" + Mode; string translatedFolder = "Translated" + Path.DirectorySeparatorChar + folderName; translatedFolder = Path.Combine(ExecutableDirectory, translatedFolder); string patchFile = Path.GetFullPath(Path.Combine(InputFolder, Mode + ".patch")); if (PreserveChanges) { CreateDiff(patchFile, translatedFolder); } Translate(); if (CreateProjects) { CreateSolutionAndProject(); } if (PreserveChanges) { progress.Increment("CopyTranslated"); CopyDirectory(OutputFolder, translatedFolder); } if (File.Exists(patchFile)) { progress.Increment("Patch"); CallProcess("patch.exe", options.GetKey("Preservation", "PatchParameters") + " -d " + OutputFolder + " -i " + patchFile); } if (File.Exists(diagnosticsFile)) { File.Delete(diagnosticsFile); } TimeSpan timespan = DateTime.Now - start; Console.WriteLine("\n\nTranslation took {0} seconds.", (int)timespan.TotalSeconds); }
string ProjectText(Assembly assembly, Dictionary <string, string> allAssetsProjectParts, IEnumerable <ResponseFileData> responseFilesData, List <Assembly> allProjectIslands) { var projectBuilder = new StringBuilder(ProjectHeader(assembly, responseFilesData)); var references = new List <string>(); var projectReferences = new List <Match>(); foreach (string file in assembly.sourceFiles) { if (!ShouldFileBePartOfSolution(file)) { continue; } var extension = Path.GetExtension(file).ToLower(); var fullFile = EscapedRelativePathFor(file); if (".dll" != extension) { projectBuilder.Append(" <Compile Include=\"").Append(fullFile).Append("\" />").Append(k_WindowsNewline); } else { references.Add(fullFile); } } var assemblyName = FileSystemUtil.FileNameWithoutExtension(assembly.outputPath); // Append additional non-script files that should be included in project generation. if (allAssetsProjectParts.TryGetValue(assemblyName, out var additionalAssetsForProject)) { projectBuilder.Append(additionalAssetsForProject); } var islandRefs = references.Union(assembly.allReferences); foreach (string reference in islandRefs) { if (reference.EndsWith("/UnityEditor.dll", StringComparison.Ordinal) || reference.EndsWith("/UnityEngine.dll", StringComparison.Ordinal) || reference.EndsWith("\\UnityEditor.dll", StringComparison.Ordinal) || reference.EndsWith("\\UnityEngine.dll", StringComparison.Ordinal)) { continue; } var match = k_ScriptReferenceExpression.Match(reference); if (match.Success) { // assume csharp language // Add a reference to a project except if it's a reference to a script assembly // that we are not generating a project for. This will be the case for assemblies // coming from .assembly.json files in non-internalized packages. var dllName = match.Groups["dllname"].Value; if (allProjectIslands.Any(i => Path.GetFileName(i.outputPath) == dllName)) { projectReferences.Add(match); continue; } } string fullReference = Path.IsPathRooted(reference) ? reference : Path.Combine(ProjectDirectory, reference); AppendReference(fullReference, projectBuilder); } var responseRefs = responseFilesData.SelectMany(x => x.FullPathReferences.Select(r => r)); foreach (var reference in responseRefs) { AppendReference(reference, projectBuilder); } if (0 < projectReferences.Count) { projectBuilder.AppendLine(" </ItemGroup>"); projectBuilder.AppendLine(" <ItemGroup>"); foreach (Match reference in projectReferences) { var referencedProject = reference.Groups["project"].Value; projectBuilder.Append(" <ProjectReference Include=\"").Append(referencedProject) .Append(GetProjectExtension()).Append("\">").Append(k_WindowsNewline); projectBuilder.Append(" <Project>{") .Append(ProjectGuid(Path.Combine("Temp", reference.Groups["project"].Value + ".dll"))).Append("}</Project>") .Append(k_WindowsNewline); projectBuilder.Append(" <Name>").Append(referencedProject).Append("</Name>").Append(k_WindowsNewline); projectBuilder.AppendLine(" </ProjectReference>"); } } projectBuilder.Append(ProjectFooter()); return(projectBuilder.ToString()); }
/// <summary> /// 处理文件 暂时只考虑Robocopy /// /// 构思:读日志、预处理、解析、存数据库 /// </summary> /// <param name="fpath"></param> public void Analyse(Config config) { lock (_lock) { try { //判断当前时间与配置时间是否匹配 if (TimeCheckHelper.CheckTime("readLogTime", config.ReadLogTime)) { Common.Util.LogManager.WriteLog(Common.Util.LogFile.LogAnalyser, "start"); #region process FileSystemUtil fsu = new FileSystemUtil(); //获取所有日志文件 IEnumerable <FileInfo> copyLogList = GetFileInfos(config.Path.InputLogPath); if (copyLogList == null) { //执行了一个任务 Signal.CompletedTaskCount++; Common.Util.LogManager.WriteLog(Common.Util.LogFile.LogAnalyser, "copyLogList is null"); return; } foreach (FileInfo fileinfo in copyLogList) { Common.Util.LogManager.WriteLog(Common.Util.LogFile.LogAnalyser, fileinfo.FullName); #region 处理日志文件 ILogReader ilr = null; try { //获取出错文件 ilr = new RoboCopyLogReader() { Path = fileinfo.FullName }; ErrorPathInfo epi = ilr.GetErrorList(); if (epi != null && epi.PathList != null && epi.PathList.Count > 0) { //预先过滤不必要文件 ErrorPathFilter.PreFilter(epi); if (epi.PathList.Count > 0) { //获取文件详细信息,然后判断是否更新,若更新则执行copy SSHCopyManager scm = new SSHCopyManager(); scm.SSHCopy(config, epi); } } } catch (System.Exception ex) { Common.Util.LogManager.WriteLog(Common.Util.LogFile.LogAnalyser, MessageUtil.GetExceptionMsg(ex, "")); break; } finally { //释放资源 if (ilr != null) { ilr.Dispose(); } } #endregion //删除日志文件 fsu.DeleteFile(fileinfo); } #endregion Common.Util.LogManager.WriteLog(Common.Util.LogFile.LogAnalyser, "end"); //执行了一个任务 Signal.CompletedTaskCount++; } } catch (System.Exception ex) { Common.Util.LogManager.WriteLog(Common.Util.LogFile.LogAnalyser, MessageUtil.GetExceptionMsg(ex, "")); } } }
public FormMain() { ApplicationService.Init(); ApplicationConfig config = ApplicationService.Config; switch (config.UserInterface_DisplayLanguage.ToLower()) { case "auto": case "": break; case "en-us": case "en": Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); break; case "zh-cn": case "cn": Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("zh-CN"); break; default: break; } _scriptFileDirectoryFullPath1 = FileSystemUtil.GetFullPathBasedOnProgramFile(config.DirPath_ScriptDir1); _scriptFileDirectoryFullPath2 = FileSystemUtil.GetFullPathBasedOnProgramFile(config.DirPath_ScriptDir2); _scriptFileList1 = ScriptUtil.GetScriptFileList(_scriptFileDirectoryFullPath1); _scriptFileList2 = ScriptUtil.GetScriptFileList(_scriptFileDirectoryFullPath2); // this.Font = SystemFonts.MessageBoxFont; InitializeComponent(); UpdateTexts(); string newFontFamily = config.UserInterface_TextareaFontName; float newFontSize; if ((config.UserInterface_TextareaFontSize == string.Empty) || !float.TryParse(config.UserInterface_TextareaFontSize, out newFontSize)) { newFontSize = -1; } if ((newFontFamily != string.Empty) || (newFontSize > 0)) { Font oldFont = textBoxClipboardText.Font; if (newFontFamily == string.Empty) { newFontFamily = oldFont.Name; } if (newFontSize <= 0) { newFontSize = oldFont.Size; } Font newFont = new Font(newFontFamily, newFontSize); textBoxClipboardText.Font = newFont; textBoxProcessedResult1.Font = newFont; textBoxProcessedResult2.Font = newFont; } if (config.UserInterface_TextareaLineEnding.ToLower() == "normalizetocrlf") { _textareaLineEndingNormalizeToCrLf = true; } else { _textareaLineEndingNormalizeToCrLf = false; } _sharpClipboard.ObservableFormats.All = false; _sharpClipboard.ObservableFormats.Texts = true; _sharpClipboard.ClipboardChanged += SharpClipboard_ClipboardChanged; }
public string ProjectFile(Assembly assembly) { return(Path.Combine(ProjectDirectory, $"{FileSystemUtil.FileNameWithoutExtension(assembly.outputPath)}.csproj")); }
public override TemporaryDirectory DownloadPackage(Upset package) { TemporaryDirectory td = new TemporaryDirectory(); string sourcePath = string.Format(formatPattern, Path, System.IO.Path.DirectorySeparatorChar, package.MetaInformation.dirName); if (Directory.Exists(sourcePath)) { FileSystemUtil.CopyDirectoryWithMeta(sourcePath, td.Path); } else if (IsUnityPackage(sourcePath)) { using (MemoryStream TarArchiveMS = new MemoryStream()) { using (FileStream originalFileStream = new FileStream(sourcePath, FileMode.Open)) { using (GZipStream decompressionStream = new GZipStream(originalFileStream, CompressionMode.Decompress)) { decompressionStream.CopyTo(TarArchiveMS); TarArchiveMS.Position = 0; } } TarArchive reader = TarArchive.Open(TarArchiveMS); string assetPath = null; MemoryStream assetMS = null; MemoryStream metaMS = null; foreach (TarArchiveEntry entry in reader.Entries) { if (entry.IsDirectory) { continue; } if (entry.Key.EndsWith("asset")) { if (assetMS != null) { throw new InvalidOperationException("Unexpected state: assetMS not null"); } assetMS = new MemoryStream(); entry.WriteTo(assetMS); assetMS.Position = 0; continue; } if (entry.Key.EndsWith("metaData")) { throw new NotSupportedException("The package has been packed by a Unity version prior to Unity5, and we do not support this. Contact the package maintainer for updated version."); } if (entry.Key.EndsWith("meta")) { metaMS = new MemoryStream(); entry.WriteTo(metaMS); metaMS.Position = 0; continue; } if (entry.Key.EndsWith("pathname")) { MemoryStream MSM = new MemoryStream(); entry.WriteTo(MSM); MSM.Position = 0; using (StreamReader SR = new StreamReader(MSM)) { assetPath = SR.ReadToEnd().Split('\n')[0]; } } if (assetPath != null) { if (assetMS == null) { // these are for directories inside the file Debug.Log("path not null " + assetPath + " but asset not yet read"); assetPath = null; continue; } string AssetPath = td.Path + System.IO.Path.DirectorySeparatorChar + assetPath.Replace('/', System.IO.Path.DirectorySeparatorChar); var AssetPathDir = new FileInfo(AssetPath).Directory.FullName; if (!Directory.Exists(AssetPathDir)) { Directory.CreateDirectory(AssetPathDir); } using (FileStream FS = new FileStream(AssetPath, FileMode.Create)) { assetMS.CopyTo(FS); } assetMS.Dispose(); assetMS = null; if (metaMS != null) { string MetaPath = AssetPath + ".meta"; using (FileStream FS = new FileStream(MetaPath, FileMode.Create)) { metaMS.CopyTo(FS); } metaMS.Dispose(); metaMS = null; } assetPath = null; } } } string commonRoot = ""; string[] directories = Directory.GetDirectories(td.Path); string inspectedPath = td.Path; // Lone directory while (directories.Length == 1) { string[] entries = Directory.GetFiles(inspectedPath); if (entries.Length > 1 || (entries.Length == 1 && !entries[0].EndsWith(".meta"))) { break; } commonRoot = System.IO.Path.Combine(commonRoot, directories[0]); inspectedPath = System.IO.Path.Combine(td.Path, commonRoot); directories = Directory.GetDirectories(inspectedPath); } if (commonRoot != "") { FileSystemUtil.MoveDirectoryContent(inspectedPath, td.Path); Directory.Delete(System.IO.Path.Combine(td.Path, commonRoot.Replace(td.Path, "").Split(System.IO.Path.DirectorySeparatorChar)[1]), true); if (package.Configuration != null) { foreach (InstallSpecPath spec in package.Configuration) { spec.Path.Replace(commonRoot, ""); } } } } else { Debug.LogError(string.Format("Package {0} version {1} has an unexpected format and cannot be downloaded ", package.PackageName, package.PackageVersion)); } return(td); }
string ProjectGuid(string assembly) { return(SolutionGuidGenerator.GuidForProject(m_ProjectName + FileSystemUtil.FileNameWithoutExtension(assembly))); }
//FIXME: This is super unsafe right now, as we can copy down into the FS. // This should be contained using kinds of destinations. public void InstallPackage(Upset package, TemporaryDirectory td, DependencyDefinition dependencyDefinition) { Upbring upbring = Upbring.Instance(); // Note: Full package is ALWAYS copied to the upackages directory right now string localPackagePath = GetRepositoryInstallPath(package); upbring.AddPackage(package); FileSystemUtil.CopyDirectory(td.Path, localPackagePath); upbring.AddLocation(package, InstallSpecType.Root, localPackagePath); InstallSpecPath[] specArray; if (package.Configuration == null) { // If there is no Configuration present we assume // that the whole package is wrapped in "InstallSpecType.Base" InstallSpecPath wrapSpec = new InstallSpecPath { Path = "", Type = InstallSpecType.Base }; specArray = new[] { wrapSpec }; } else { specArray = package.Configuration; } foreach (InstallSpecPath spec in specArray) { if (dependencyDefinition.SkipInstall != null && dependencyDefinition.SkipInstall.Any(skip => skip.Type == spec.Type)) { continue; } var sourcePath = Uplift.Common.FileSystemUtil.JoinPaths(td.Path, spec.Path); PathConfiguration PH = upfile.GetDestinationFor(spec); if (dependencyDefinition.OverrideDestination != null && dependencyDefinition.OverrideDestination.Any(over => over.Type == spec.Type)) { PH.Location = Uplift.Common.FileSystemUtil.MakePathOSFriendly(dependencyDefinition.OverrideDestination.First(over => over.Type == spec.Type).Location); } var packageStructurePrefix = PH.SkipPackageStructure ? "" : GetPackageDirectory(package); var destination = Path.Combine(PH.Location, packageStructurePrefix); // Working with single file if (File.Exists(sourcePath)) { // Working with singular file if (!Directory.Exists(destination)) { Directory.CreateDirectory(destination); } File.Copy(sourcePath, destination); FileSystemUtil.TryCopyMeta(sourcePath, destination); if (destination.StartsWith("Assets")) { TryUpringAddGUID(upbring, sourcePath, package, spec.Type, destination); } else { upbring.AddLocation(package, spec.Type, destination); } } // Working with directory if (Directory.Exists(sourcePath)) { // Working with directory Uplift.Common.FileSystemUtil.CopyDirectoryWithMeta(sourcePath, destination); if (destination.StartsWith("Assets")) { foreach (var file in Uplift.Common.FileSystemUtil.RecursivelyListFiles(sourcePath, true)) { TryUpringAddGUID(upbring, file, package, spec.Type, destination); } } else { foreach (var file in Uplift.Common.FileSystemUtil.RecursivelyListFiles(sourcePath, true)) { upbring.AddLocation(package, spec.Type, Path.Combine(destination, file)); } } } } upbring.SaveFile(); td.Dispose(); }
static RiderScriptEditor() { try { var projectGeneration = new ProjectGeneration.ProjectGeneration(); var editor = new RiderScriptEditor(new Discovery(), projectGeneration); CodeEditor.Register(editor); var path = GetEditorRealPath(CurrentEditor); if (IsRiderInstallation(path)) { RiderPathLocator.RiderInfo[] installations = null; if (!RiderScriptEditorData.instance.initializedOnce) { installations = RiderPathLocator.GetAllRiderPaths().OrderBy(a => a.BuildNumber).ToArray(); // is likely outdated if (installations.Any() && installations.All(a => GetEditorRealPath(a.Path) != path)) { if (RiderPathLocator.GetIsToolbox(path)) // is toolbox - update { var toolboxInstallations = installations.Where(a => a.IsToolbox).ToArray(); if (toolboxInstallations.Any()) { var newEditor = toolboxInstallations.Last().Path; CodeEditor.SetExternalScriptEditor(newEditor); path = newEditor; } else { var newEditor = installations.Last().Path; CodeEditor.SetExternalScriptEditor(newEditor); path = newEditor; } } else // is non toolbox - notify { var newEditorName = installations.Last().Presentation; Debug.LogWarning($"Consider updating External Editor in Unity to Rider {newEditorName}."); } } ShowWarningOnUnexpectedScriptEditor(path); RiderScriptEditorData.instance.initializedOnce = true; } if (!FileSystemUtil.EditorPathExists(path)) // previously used rider was removed { if (installations == null) { installations = RiderPathLocator.GetAllRiderPaths().OrderBy(a => a.BuildNumber).ToArray(); } if (installations.Any()) { var newEditor = installations.Last().Path; CodeEditor.SetExternalScriptEditor(newEditor); path = newEditor; } } RiderScriptEditorData.instance.Init(); editor.CreateSolutionIfDoesntExist(); if (RiderScriptEditorData.instance.shouldLoadEditorPlugin) { editor.m_Initiliazer.Initialize(path); } InitProjectFilesWatcher(); } } catch (Exception e) { Debug.LogException(e); } }
public override RemoteUploadResult UploadNoteToRemote(ref INote inote, out INote conflict, ConflictResolutionStrategy strategy) { FilesystemNote note = (FilesystemNote)inote; var path = note.GetPath(_config); if (File.Exists(note.PathRemote) && path != note.PathRemote && !File.Exists(path)) { _logger.Debug(FilesystemPlugin.Name, "Upload note to changed remote path"); // path changed and new path does not exist WriteNoteToPath(note, path); conflict = null; FileSystemUtil.DeleteFileAndFolderIfEmpty(FilesystemPlugin.Name, _logger, _config.Folder, note.PathRemote); note.PathRemote = path; return(RemoteUploadResult.Uploaded); } else if (File.Exists(note.PathRemote) && path != note.PathRemote && File.Exists(path)) { _logger.Debug(FilesystemPlugin.Name, "Upload note to changed remote path"); // path changed and new path does exist var conf = ReadNoteFromPath(note.PathRemote); if (conf.ModificationDate > note.ModificationDate) { conflict = conf; if (strategy == ConflictResolutionStrategy.UseClientCreateConflictFile || strategy == ConflictResolutionStrategy.UseClientVersion || strategy == ConflictResolutionStrategy.ManualMerge) { WriteNoteToPath(note, path); FileSystemUtil.DeleteFileAndFolderIfEmpty(FilesystemPlugin.Name, _logger, _config.Folder, note.PathRemote); note.PathRemote = path; return(RemoteUploadResult.Conflict); } else { note.PathRemote = path; return(RemoteUploadResult.Conflict); } } else { WriteNoteToPath(note, path); conflict = null; FileSystemUtil.DeleteFileAndFolderIfEmpty(FilesystemPlugin.Name, _logger, _config.Folder, note.PathRemote); note.PathRemote = path; return(RemoteUploadResult.Uploaded); } } else if (File.Exists(path)) // normal update { var conf = ReadNoteFromPath(path); if (conf.ModificationDate > note.ModificationDate) { conflict = conf; if (strategy == ConflictResolutionStrategy.UseClientCreateConflictFile || strategy == ConflictResolutionStrategy.UseClientVersion) { WriteNoteToPath(note, path); if (note.PathRemote != "") { FileSystemUtil.DeleteFileAndFolderIfEmpty(FilesystemPlugin.Name, _logger, _config.Folder, note.PathRemote); } note.PathRemote = path; return(RemoteUploadResult.Conflict); } else { note.PathRemote = path; return(RemoteUploadResult.Conflict); } } else { WriteNoteToPath(note, path); conflict = null; note.PathRemote = path; return(RemoteUploadResult.Uploaded); } } else // new file { WriteNoteToPath(note, path); conflict = null; note.PathRemote = path; return(RemoteUploadResult.Uploaded); } }