private static List <IArchiveEntry> PreprocessEntries(SPath outFolder, IArchive zf, Action <string, long> onStart, Func <string, bool> onFilter) { var entries = new List <IArchiveEntry>(); foreach (IArchiveEntry entry in zf) { if (entry.IsLink || entry.IsSymLink) { continue; } if (entry.IsDirectory) { outFolder.Combine(entry.Name).EnsureDirectoryExists(); continue; // Ignore directories } if (!onFilter?.Invoke(entry.Name) ?? false) { continue; } entries.Add(entry); onStart(entry.Name, entry.Size); } return(entries); }
private static SPath MaybeSetPermissions(SPath destDir, string entryFileName, int mode) { var fullZipToPath = destDir.Combine(entryFileName); fullZipToPath.EnsureParentDirectoryExists(); try { if (SPath.IsUnix && MonoPosixShim.HasMonoPosix) { if (mode == -2115174400) { int fd = MonoPosixShim.Open(fullZipToPath, 64 /*Mono.Unix.Native.OpenFlags.O_CREAT */ | 512 /*Mono.Unix.Native.OpenFlags.O_TRUNC*/, 448 /*Mono.Unix.Native.FilePermissions.S_IRWXU*/ | 32 /*Mono.Unix.Native.FilePermissions.S_IRGRP*/ | 8 /*Mono.Unix.Native.FilePermissions.S_IXGRP*/ | 4 /*Mono.Unix.Native.FilePermissions.S_IROTH*/ | 1 /*Mono.Unix.Native.FilePermissions.S_IXOTH*/ ); MonoPosixShim.Close(fd); } } } catch (Exception ex) { LogHelper.GetLogger <ZipHelper>().Error(ex, "Error setting file attributes in " + fullZipToPath); } return(fullZipToPath); }
public static void Copy(SPath fromPath, SPath toPath) { Logger.Trace("Copying from {0} to {1}", fromPath, toPath); try { CopyFolder(fromPath, toPath); } catch (Exception ex1) { Logger.Warning(ex1, "Error copying."); try { CopyFolderContents(fromPath, toPath); } catch (Exception ex2) { Logger.Error(ex2, "Error copying contents."); throw; } } finally { fromPath.DeleteIfExists(); } }
private static bool ExtractArchive(string archive, SPath outFolder, CancellationToken cancellationToken, IArchive zf, List <IArchiveEntry> entries, Action <string, long> onStart, Func <long, long, string, bool> onProgress, Func <string, bool> onFilter = null) { const int chunkSize = 4096; // 4K is optimum foreach (var e in entries) { cancellationToken.ThrowIfCancellationRequested(); var filename = e.Name; var entry = zf.FindEntry(filename); var fullZipToPath = MaybeSetPermissions(outFolder, filename, entry.FileAttributes); var targetFile = new FileInfo(fullZipToPath); var stream = zf.GetInputStream(entry); using (var streamWriter = targetFile.OpenWrite()) { if (!Utils.Copy(stream, streamWriter, entry.Size, chunkSize, progress: (totalRead, timeToFinish) => { return(onProgress?.Invoke(totalRead, entry.Size, filename) ?? true); })) { return(false); } } targetFile.LastWriteTime = entry.LastModifiedTime; } return(true); }
private GitInstallationState ExtractGit(GitInstallationState state) { var tempZipExtractPath = SPath.CreateTempDirectory("ghu_extract_git"); if (state.GitZipExists && !state.GitIsValid) { var gitExtractPath = tempZipExtractPath.Combine("git").CreateDirectory(); var unzipTask = new UnzipTask(TaskManager, state.GitZipPath, gitExtractPath, sharpZipLibHelper) .Progress(progressReporter.UpdateProgress) .Catch(e => { Logger.Trace(e, "Failed to unzip " + state.GitZipPath); return(true); }); unzipTask.RunSynchronously(); var target = state.GitInstallationPath; if (unzipTask.Successful) { Logger.Trace("Moving Git source:{0} target:{1}", gitExtractPath.ToString(), target.ToString()); CopyHelper.Copy(gitExtractPath, target); state.GitIsValid = state.GitLfsIsValid = true; state.IsCustomGitPath = state.GitExecutablePath != installDetails.GitExecutablePath; } } tempZipExtractPath.DeleteIfExists(); return(state); }
public void InitializeRepository(SPath?repositoryPath = null) { SPath expectedRepositoryPath; if (!RepositoryPath.IsInitialized || (repositoryPath != null && RepositoryPath != repositoryPath.Value)) { Guard.NotNull(this, UnityProjectPath, nameof(UnityProjectPath)); expectedRepositoryPath = repositoryPath != null ? repositoryPath.Value : UnityProjectPath.ToSPath(); if (!expectedRepositoryPath.Exists(".git")) { SPath reporoot = UnityProjectPath.ToSPath().RecursiveParents.FirstOrDefault(d => d.Exists(".git")); if (reporoot.IsInitialized) { expectedRepositoryPath = reporoot; } } } else { expectedRepositoryPath = RepositoryPath; } if (expectedRepositoryPath.Exists(".git")) { SPath.FileSystem = new FileSystem(expectedRepositoryPath); RepositoryPath = expectedRepositoryPath; Repository = new Repository(RepositoryPath, CacheContainer); } }
public GitLock(string id, SPath path, GitUser owner, DateTimeOffset locked_at) { this.id = id; this.path = path.IsInitialized ? path.ToString() : null; this.owner = owner; this.lockedAtString = locked_at.ToUniversalTime().ToString(Constants.Iso8601FormatZ, CultureInfo.InvariantCulture); }
private int ProcessEvents(Event[] fileEvents) { var events = new HashSet <EventType>(); foreach (var fileEvent in fileEvents) { if (!running) { break; } if (cancellationToken.IsCancellationRequested) { Stop(); break; } var eventDirectory = new SPath(fileEvent.Directory); var fileA = eventDirectory.Combine(fileEvent.FileA); // handling events in .git/* if (fileA.IsChildOf(paths.DotGitPath) || (paths.WorktreeDotGitPath.IsInitialized && fileA.IsChildOf(paths.WorktreeDotGitPath))) { if (!events.Contains(EventType.ConfigChanged) && fileA.Equals(paths.DotGitConfig)) { events.Add(EventType.ConfigChanged); } else if (!events.Contains(EventType.HeadChanged) && fileA.Equals(paths.DotGitHead)) { events.Add(EventType.HeadChanged); } else if (!events.Contains(EventType.IndexChanged) && fileA.Equals(paths.DotGitIndex)) { events.Add(EventType.IndexChanged); } else if (!events.Contains(EventType.RemoteBranchesChanged) && fileA.IsChildOf(paths.RemotesPath)) { events.Add(EventType.RemoteBranchesChanged); } else if (!events.Contains(EventType.LocalBranchesChanged) && fileA.IsChildOf(paths.BranchesPath)) { events.Add(EventType.LocalBranchesChanged); } else if (!events.Contains(EventType.RepositoryCommitted) && fileA.IsChildOf(paths.DotGitCommitEditMsg)) { events.Add(EventType.RepositoryCommitted); } } else { if (events.Contains(EventType.RepositoryChanged) || ignoredPaths.Any(ignoredPath => fileA.IsChildOf(ignoredPath))) { continue; } events.Add(EventType.RepositoryChanged); } } return(FireEvents(events)); }
private static Stream TryGetStream(ResourceType resourceType, string resource, IEnvironment environment) { /* * This function attempts to get files embedded in the callers assembly. * Unity.VersionControl.Git which tends to contain logos * Git.Api which tends to contain application resources * * Each file's name is their physical path in the project. * * When running tests, we assume the tests are looking for application resources, and default to returning Git.Api * * First check for the resource in the calling assembly. * If the resource cannot be found, fallback to looking in Git.Api's assembly. * If the resource is still not found, it attempts to find it in the file system */ (string type, string os) = ParseResourceType(resourceType, environment); var stream = TryGetResource(resourceType, type, os, resource); if (stream != null) { return(stream); } SPath possiblePath = environment.ExtensionInstallPath.Combine(type, os, resource); if (possiblePath.FileExists()) { return(new MemoryStream(possiblePath.ReadAllBytes())); } return(null); }
private static SPath TryGetFile(ResourceType resourceType, string resource, IEnvironment environment) { /* * This function attempts to get files embedded in the callers assembly. * * Each file's name is their physical path in the project. * * First check for the resource in the calling assembly. * If the resource is still not found, it attempts to find it in the file system */ (string type, string os) = ParseResourceType(resourceType, environment); var stream = TryGetResource(resourceType, type, os, resource); if (stream != null) { var target = SPath.GetTempFilename(); return(target.WriteAllBytes(stream.ToByteArray())); } SPath possiblePath = environment.ExtensionInstallPath.Combine(type, os, resource); if (possiblePath.FileExists()) { return(possiblePath); } return(SPath.Default); }
public ITask UnlockFile(SPath file, bool force) { var task = GitClient.Unlock(file, force) .Then(() => DataNeedsRefreshing?.Invoke(CacheType.GitLocks)); return(HookupHandlers(task, false)); }
private bool ExtractTar(string archive, SPath outFolder, CancellationToken cancellationToken, Action <string, long> onStart, Func <long, long, string, bool> onProgress, Func <string, bool> onFilter = null) { TarArchive zf = null; try { List <IArchiveEntry> entries; using (var read = TarArchive.CreateInputTarArchive(SPath.FileSystem.OpenRead(archive))) { entries = PreprocessEntries(outFolder, read, onStart, onFilter); } zf = TarArchive.CreateInputTarArchive(SPath.FileSystem.OpenRead(archive)); return(ExtractArchive(archive, outFolder, cancellationToken, zf, entries, onStart, onProgress, onFilter)); } catch (Exception ex) { LogHelper.GetLogger <ZipHelper>().Error(ex); throw; } finally { zf?.Close(); // Ensure we release resources } }
private static bool IsObjectUnlocked(Object selected) { if (selected == null) { return(false); } SPath assetPath = AssetDatabase.GetAssetPath(selected.GetInstanceID()).ToSPath(); SPath repositoryPath = assetPath.RelativeToRepository(manager.Environment); var alreadyLocked = locks.Any(x => repositoryPath == x.Path); if (alreadyLocked) { return(false); } GitFileStatus status = GitFileStatus.None; if (entries != null) { status = entries.FirstOrDefault(x => repositoryPath == x.Path.ToSPath()).Status; } return(status != GitFileStatus.Untracked && status != GitFileStatus.Ignored); }
private static void RunWebServer(SPath path, int port) { if (!path.IsInitialized) { path = typeof(Program).Assembly.Location.ToSPath().Parent.Combine("files"); } var evt = new ManualResetEventSlim(false); var server = new HttpServer(path, port); var thread = new Thread(() => { Logger.Error("Press any key to exit"); try { server.Start(); Console.Read(); server.Stop(); } catch (Exception ex) { Logger.Error(ex); } evt.Set(); }); thread.Start(); evt.Wait(); }
public TestData(string testName, ILogging logger, string serverDirectory) { TestName = testName; Logger = logger; Watch = new Stopwatch(); TestPath = SPath.CreateTempDirectory(testName); TaskManager = new TaskManager(); try { TaskManager.Initialize(); } catch { // we're on the nunit sync context, which can't be used to create a task scheduler // so use a different context as the main thread. The test won't run on the main nunit thread ourContext = new MainThreadSynchronizationContext(TaskManager.Token); TaskManager.Initialize(ourContext); } Environment = new UnityEnvironment(testName); InitializeEnvironment(); ProcessManager = new ProcessManager(Environment); Configuration = new ServerConfiguration(serverDirectory); Logger.Trace($"START {testName}"); Watch.Start(); }
public static void CopyFolder(SPath fromPath, SPath toPath) { Logger.Trace("CopyFolder from {0} to {1}", fromPath, toPath); toPath.DeleteIfExists(); toPath.EnsureParentDirectoryExists(); fromPath.Move(toPath); }
public TestData(string testName, ILogging logger, string testRepoName = null, bool withHttpServer = false, ICacheContainer cacheContainer = null, IFileSystem fileSystem = null) { TestName = testName; Logger = logger; Watch = new Stopwatch(); SourceDirectory = TestContext.CurrentContext.TestDirectory.ToSPath(); TestPath = SPath.CreateTempDirectory(testName); SPath.FileSystem = fileSystem ?? new FileSystem(TestPath); if (cacheContainer == null) { var container = new CacheContainer(); container.SetCacheInitializer(CacheType.Branches, () => BranchesCache.Instance); container.SetCacheInitializer(CacheType.GitAheadBehind, () => GitAheadBehindCache.Instance); container.SetCacheInitializer(CacheType.GitLocks, () => GitLocksCache.Instance); container.SetCacheInitializer(CacheType.GitLog, () => GitLogCache.Instance); container.SetCacheInitializer(CacheType.GitStatus, () => GitStatusCache.Instance); container.SetCacheInitializer(CacheType.GitUser, () => GitUserCache.Instance); container.SetCacheInitializer(CacheType.RepositoryInfo, () => RepositoryInfoCache.Instance); cacheContainer = container; } Environment = new IntegrationTestEnvironment(cacheContainer, TestPath, TestPath.Parent, testName); InitializeEnvironment(testRepoName); ApplicationManager = new ApplicationManagerBase(new MainThreadSynchronizationContext(), Environment); if (testRepoName != null) { var testZipFilePath = SourceDirectory.Combine("IOTestsRepo.zip"); ZipHelper.Instance.Extract(testZipFilePath, TestPath, (_, __) => { }, (value, total, name) => true, token: TaskManager.Token); TestRepo = new TestRepoData(this, testRepoName); InstallTestGit(); InitializeRepository(); } #if NUNIT if (withHttpServer) { var filesToServePath = SourceDirectory.Combine("files"); HttpServer = new HttpServer(filesToServePath, 0); var started = new ManualResetEventSlim(); var task = TaskManager.With(HttpServer.Start, TaskAffinity.None); task.OnStart += _ => started.Set(); task.Start(); started.Wait(); } #endif ((ApplicationManagerBase)ApplicationManager).Initialize(); Logger.Trace($"START {testName}"); Watch.Start(); }
public Asset(Asset asset, SPath localPath) { hash = asset.hash; path = asset.path; url = asset.url; needsUnzip = asset.needsUnzip; LocalPath = localPath; NeedsDownload = false; }
private static SPath?GetPath(string left) { var(leftp, lefts) = SPath.TryParse(left); if (lefts) { return(leftp); } return(null); }
public IGitEnvironment Initialize(SPath extensionInstallPath, string projectPath, string unityVersion = null, string EditorApplication_applicationPath = null, string EditorApplication_applicationContentsPath = null) { Initialize(projectPath, unityVersion, EditorApplication_applicationPath, EditorApplication_applicationContentsPath); ExtensionInstallPath = extensionInstallPath; User = new User(CacheContainer); UserSettings = new UserSettings(this); LocalSettings = new LocalSettings(this); SystemSettings = new SystemSettings(this); return(this); }
public static SPath ToFile(ResourceType resourceType, string resource, SPath destinationPath, IGitEnvironment environment) { var source = TryGetFile(resourceType, resource, environment); if (source.IsInitialized) { return(source.Copy(destinationPath)); } return(SPath.Default); }
private static SPath?ComparePath(string left, string right) { var(leftp, lefts) = SPath.TryParse(left); var(rightp, rights) = SPath.TryParse(right); if (lefts == rights && leftp == rightp) { return(leftp); } return(null); }
public IGitEnvironment Initialize(SPath extensionInstallPath, IEnvironment environment) { base.Initialize(environment.UnityProjectPath, environment.UnityVersion, environment.UnityApplication, environment.UnityApplicationContents); ExtensionInstallPath = extensionInstallPath; User = new User(CacheContainer); UserSettings = new UserSettings(this); LocalSettings = new LocalSettings(this); SystemSettings = new SystemSettings(this); return(this); }
private static ITask CreateLockObjectTask(Object selected) { SPath assetPath = AssetDatabase.GetAssetPath(selected.GetInstanceID()).ToSPath(); SPath repositoryPath = assetPath.RelativeToRepository(manager.Environment); var task = Repository.RequestLock(repositoryPath); //task.OnEnd += (_, s, ___) => { if (s) manager.TaskManager.Run(manager.UsageTracker.IncrementUnityProjectViewContextLfsLock, null); }; return(task); }
public GitInstallDetails(SPath baseDataPath, IEnvironment environment) { ZipPath = baseDataPath.Combine("downloads"); ZipPath.EnsureDirectoryExists(); GitInstallationPath = baseDataPath.Combine(GitDirectory); GitExecutablePath = GitInstallationPath.Combine(environment.IsWindows ? "cmd" : "bin", "git" + UnityEnvironment.ExecutableExtension); //GitLfsExecutablePath = GitExecutablePath.Parent.Combine("git-lfs" + UnityEnvironment.ExecutableExtension); GitLfsExecutablePath = SPath.Default; GitPackageFeed = packageFeed; }
static void Main(string[] args) { IPath_Node n1 = new Path_Node(1, 1); IPath_Node n2 = new Path_Node(2, 2); IPath path = new SPath(n1, n2); Console.WriteLine(Directory.GetCurrentDirectory()); Santasearch santasearch = new Santasearch(); Console.WriteLine("Pause"); }
public void WhenEmptyPathShouldBeEmpty() { // Arrange var path = new SPath(); // Act var actual = path.ToString("/"); // Assert Assert.Equal(string.Empty, actual); }
public void WhenEmptyPathSegmentShouldBeIncluded() { // Arrange var path = SPath.Parse(@"C:\Program Files\", @"\"); // Act var actual = path.ToString("/"); // Assert Assert.Equal("C:/Program Files/", actual); }
public void WhenRootShouldBeRoot() { // Arrange var path = SPath.Parse(@"\", @"\"); // Act var actual = path.ToString("/"); // Assert Assert.Equal("/", actual); }
public void When_ShouldBe() { // Arrange var path = new SPath("root", "one", "two"); var expected = new SPath("root", "one"); // Act var actual = path.Parent(); // Assert Assert.Equal(expected, actual); }