public override Task<IEnumerable<FsPath>> FindFiles(FsPath path, string searchPattern)
 {
     if (_next != null)
         return _next.FindFiles(path, searchPattern);
     return Enumerable.Empty<FsPath>()
         .AsImmediateTask();
 }
		public override async Task DeleteDir(FsPath path)
		{
			var randomDirectoryName = (await _undoDataCache)/Guid.NewGuid()
				.ToString("N");
			await Next.MoveDir(path, randomDirectoryName);
			_AddUndoStep(() => Next.MoveDir(randomDirectoryName, path));
		}
		public override async Task<IEnumerable<FsPath>> FindFiles(FsPath path, string searchPattern)
		{
			if (!await DirExists(path))
				return Enumerable.Empty<FsPath>();
			return await Task.Run(()=>Directory.EnumerateFiles(path.Absolute, searchPattern)
				.Select(p => new FsPath(p)));
		}
		public override Task CreateDir(FsPath path)
		{
			_AllMissingDirectoriesInPathFromBottomUp(path)
				.Reverse()
				.Each(dir => { _AddUndoStep(() => Next.DeleteDir(new FsPath(dir))); });
			return base.CreateDir(path);
		}
		public override async Task Overwrite(FsPath path, string newContents)
		{
			using (var writer = File.CreateText(path.Absolute))
			{
				await writer.WriteAsync(newContents);
				await writer.FlushAsync();
			}
		}
		public override async Task Overwrite(FsPath path, byte[] newContents)
		{
			using (var writer = File.OpenWrite(path.Absolute))
			{
				await writer.WriteAsync(newContents, 0, newContents.Length);
				await writer.FlushAsync();
			}
		}
 public void MoveFile(FsPath src, FsPath dest)
 {
     if (_GetStorage(src).Kind != _StorageKind.File)
         throw new ArgumentException("path", string.Format("Attempted to move file {0}, which is not a file.", src.Absolute));
     if (_GetStorage(dest).Kind != _StorageKind.Missing)
         throw new ArgumentException("path", string.Format("Attempted to move file to destination {0}, which already exists.", dest.Absolute));
     _data[dest] = _data[src];
     _data.Remove(src);
 }
 public void CreateDir(FsPath path)
 {
     while (true)
     {
         _data[path] = new _Node(_StorageKind.Directory);
         if (path.IsRoot)
             return;
         path = path.Parent;
     }
 }
 public override Task CreateDir(FsPath path)
 {
     while (true)
     {
         _data[path] = new _Node(_StorageKind.Directory);
         if (path.IsRoot)
             return CompletedTask;
         path = path.Parent;
     }
 }
Beispiel #10
0
 public IEnumerable <FsPathAndFileStatusPair> ListFiles(FsPath path, FileListParameters parameters)
 {
     foreach (var page in ListFilesPaged(path, parameters))
     {
         foreach (var filestatus in page.FileItems)
         {
             var item = new FsPathAndFileStatusPair(page.Path, filestatus);
             yield return(item);
         }
     }
 }
 public override Task DeleteFile(FsPath path)
 {
     var storageKind = _GetStorage(path)
         .Kind;
     if (storageKind == _StorageKind.Missing)
         return CompletedTask;
     if (storageKind == _StorageKind.Directory)
         throw new ArgumentException("path", string.Format("Path {0} was a directory, and you attempted to delete a file.", path.Absolute));
     _data.Remove(path);
     return CompletedTask;
 }
Beispiel #12
0
 public GeneratorRunner(ILog log, IServerLog serverLog, string workDir)
 {
     ServerLog      = serverLog;
     Log            = log;
     _projectLoader = new ProjectLoader(log, workDir);
     _scriptHandler = new CsharpScriptHandler(Log);
     WorkDirectory  = workDir;
     ConfigFile     = new FsPath(WorkDirectory, "bookgen.json");
     _configuration = new Config();
     _toc           = new ToC();
 }
Beispiel #13
0
        public Dictionary <string, string> GetTcgSetBySet()
        {
            FsPath setMapFile = _resourcesDir.Join("tcg.sets.map.txt");

            var tcgSetBySet = setMapFile.ReadAllLines()
                              .Where(l => l != string.Empty)
                              .Select(l => l.Split('\t'))
                              .ToDictionary(p => p[0], p => p[1]);

            return(tcgSetBySet);
        }
Beispiel #14
0
        private static FsPath getTargetPath(ImageFile imageFile, FsPath subdir)
        {
            var fileName = imageFile.FullPath.Basename();

            while (true)
            {
                if (removeExtension(ref fileName, ".jpg"))
                {
                    continue;
                }

                if (removeExtension(ref fileName, ".png"))
                {
                    continue;
                }

                if (removeExtension(ref fileName, ".xlhq"))
                {
                    continue;
                }

                // ReSharper disable once StringLiteralTypo
                if (removeExtension(ref fileName, ".xhlq"))
                {
                    continue;
                }

                if (removeExtension(ref fileName, ".full"))
                {
                    continue;
                }

                break;
            }

            string targetFileName;

            if (imageFile.FullPath.Value.EndsWith(".jpg", Str.Comparison))
            {
                targetFileName = fileName + ".jpg";
            }
            else if (imageFile.FullPath.Value.EndsWith(".png", Str.Comparison))
            {
                targetFileName = fileName + ".png";
            }
            else
            {
                throw new NotSupportedException("only .png .jpg extensions are supported");
            }

            var targetFullPath = subdir.Join(targetFileName);

            return(targetFullPath);
        }
Beispiel #15
0
        public async Task DownloadApp(CancellationToken token)
        {
            var    expectedSignature = AppOnlineSignature;
            FsPath appOnline         = _updateAppDir.Join(expectedSignature.Path);

            ensureFileDeleted(appOnline);
            _updateAppDir.CreateDirectory();
            var    client = new YandexDiskClientWrapper(new YandexDiskClient(), _appSourceConfig.YandexKey);
            string url    = string.Format(_appSourceConfig.ZipUrl, expectedSignature.Path);
            await client.TryDownloadFile(url, appOnline, token);
        }
Beispiel #16
0
        private static bool createApplicationShortcut(FsPath shortcutPath, FsPath exePath, FsPath iconPath)
        {
            if (Runtime.IsLinux)
            {
                Console.WriteLine("Shortcut creation is not supported");
                return(true);
            }

            return(new UtilExe().CreateShortcut(
                       exePath: exePath, iconPath: iconPath, shortcutPath: shortcutPath));
        }
Beispiel #17
0
 public void Download(FsPath src_path, FsLocalPath dest_path, FileDownloadParameters parameters)
 {
     using (var stream = this.RestClients.FileSystemRest.Open(this.Account, src_path))
     {
         var filemode = parameters.Append ? System.IO.FileMode.Append : System.IO.FileMode.Create;
         using (var fileStream = new System.IO.FileStream(dest_path.ToString(), filemode))
         {
             stream.CopyTo(fileStream);
         }
     }
 }
Beispiel #18
0
        private static string GetDescription(ILog log, FsPath file)
        {
            using (var pipeline = new BookGenPipeline(BookGenPipeline.Plain))
            {
                string?content     = file.ReadFile(log).Replace('\n', ' ').Trim();
                string?description = pipeline.RenderMarkdown(content);

                var limit = description.Length < 190 ? description.Length : 190;
                return(description.Substring(0, limit) + "...");
            }
        }
Beispiel #19
0
        private Bitmap tryGetFromCache(FsPath path, RotateFlipType rotations)
        {
            if (!_imagesByPath.TryGetValue(new Tuple <FsPath, RotateFlipType>(path, rotations), out var cacheEntry))
            {
                return(null);
            }

            shiftFromLast(cacheEntry);

            return(cacheEntry.Image);
        }
        public static Result ReadFsPath(out FsPath path, ServiceCtx context, int index = 0)
        {
            long position = context.Request.PtrBuff[index].Position;
            long size     = context.Request.PtrBuff[index].Size;

            byte[] pathBytes = new byte[size];

            context.Memory.Read((ulong)position, pathBytes);

            return(FsPath.FromSpan(out path, pathBytes));
        }
Beispiel #21
0
        public static bool FallbackTemplateRequired(FsPath workingDirectory, BuildConfig buildConfig)
        {
            if (string.IsNullOrEmpty(buildConfig.TemplateFile))
            {
                return(true);
            }

            FsPath templatePath = workingDirectory.Combine(buildConfig.TemplateFile);

            return(!templatePath.IsExisting);
        }
Beispiel #22
0
 private static void scale(FsPath smallImg, FsPath zoomImg)
 {
     if (isZoomed(smallImg))
     {
         File.Copy(smallImg.Value, zoomImg.Value);
     }
     else
     {
         WaifuScaler.Scale(smallImg, zoomImg);
     }
 }
Beispiel #23
0
        public void Document(FsPath assembly, FsPath xmlFile, FsPath outputDir)
        {
            IEnumerable <Type> documentableTypes = GetDocumentableTypes(assembly);
            XElement           documentation     = XElement.Load(xmlFile.ToString());

            foreach (var type in documentableTypes)
            {
                _log.Info("Documenting type: {0}", type.FullName);
                DocumentType(type, documentation, outputDir);
            }
        }
Beispiel #24
0
 private void InlineOrSave(FsPath file, FsPath targetdir, ILog log, RuntimeSettings settings, SKData data, string?extensionOverride = null)
 {
     if (data.Size < settings.CurrentBuildConfig.ImageOptions.InlineImageSizeLimit)
     {
         log.Detail("Inlining: {0}", file);
         InlineImage(file, settings, data, extensionOverride);
     }
     else
     {
         SaveImage(file, targetdir, log, data, extensionOverride);
     }
 }
Beispiel #25
0
        internal async Task SetCustomColumnsDataAsync(IEnumerable <FileSystemItemPropertyData> customColumnsData)
        {
            List <StorageProviderItemProperty> customColumns = new List <StorageProviderItemProperty>();

            if (customColumnsData != null)
            {
                foreach (FileSystemItemPropertyData column in customColumnsData)
                {
                    customColumns.Add(new StorageProviderItemProperty()
                    {
                        Id = column.Id,
                        // If value is empty Windows File Manager crushes.
                        Value = string.IsNullOrEmpty(column.Value) ? "-" : column.Value,
                        // If icon is not set Windows File Manager crushes.
                        IconResource = column.IconResource ?? Path.Combine(virtualDrive.Settings.IconsFolderPath, "Blank.ico")
                    });
                }
            }

            // This method may be called on temp files, typically created by MS Office, that exist for a short period of time.
            IStorageItem storageItem = await FsPath.GetStorageItemAsync(userFileSystemPath);

            if (storageItem == null)
            {
                // This method may be called on temp files, typically created by MS Office, that exist for a short period of time.
                // StorageProviderItemProperties.SetAsync(null,) causes AccessViolationException
                // which is not handled by .NET (or handled by HandleProcessCorruptedStateExceptions) and causes a fatal crush.
                return;
            }

            FileInfo file = new FileInfo(userFileSystemPath);

            // Can not set provider properties on read-only files.
            // Changing read-only attribute on folders triggers folders listing. Changing it on files only.
            bool readOnly = file.IsReadOnly;

            // Remove read-only attribute.
            if (readOnly && ((file.Attributes & System.IO.FileAttributes.Directory) == 0))
            {
                file.IsReadOnly = false;
                //new FileInfo(userFileSystemPath).Attributes &= ~System.IO.FileAttributes.ReadOnly;
            }

            // Update columns data.
            await StorageProviderItemProperties.SetAsync(storageItem, customColumns);

            // Set read-only attribute.
            if (readOnly && ((file.Attributes & System.IO.FileAttributes.Directory) == 0))
            {
                file.IsReadOnly = true;
                //new FileInfo(userFileSystemPath).Attributes |= System.IO.FileAttributes.ReadOnly;
            }
        }
Beispiel #26
0
        public void FSPath_Constructor_Root()
        {
            var p0 = new FsPath("/");

            Assert.AreEqual("/", p0.ToString());

            var p1 = FsPath.Root;

            Assert.AreEqual("/", p1.ToString());

            Assert.AreEqual(p1.ToString(), p1.ToString());
        }
Beispiel #27
0
        public void EnsureThat_FsUtils_WriteFile_CreatesFile()
        {
            var file = new FsPath(_testDir, "test.txt");

            file.WriteFile(TestEnvironment.GetMockedLog(), "test");

            Assert.IsTrue(file.IsExisting);

            var content = File.ReadAllText(Path.Combine(_testDir, "test.txt"));

            Assert.AreEqual("test", content);
        }
Beispiel #28
0
        public async Task <bool> DownloadAndExtract(string remotePath, FsPath targetDirectory, FsPath fileName, CancellationToken token)
        {
            if (!Str.Equals(".7z", fileName.Extension()))
            {
                throw new ArgumentException();
            }

            FsPath archiveFileName = targetDirectory.Join(fileName);

            if (archiveFileName.IsFile())
            {
                try
                {
                    archiveFileName.DeleteFile();
                }
                catch (Exception ex)
                {
                    lock (_syncOutput)
                        Console.WriteLine($"Failed to remove {archiveFileName}: {ex.Message}");
                    return(false);
                }
            }

            bool downloaded = await TryDownloadFile(remotePath, archiveFileName, token);

            if (!downloaded)
            {
                return(false);
            }

            if (!archiveFileName.IsFile())
            {
                lock (_syncOutput)
                    Console.WriteLine($"Failed to download {archiveFileName} from {remotePath}");
                return(false);
            }

            var sevenZip = new SevenZip(silent: true);

            sevenZip.Extract(archiveFileName, targetDirectory, Enumerable.Empty <FsPath>());

            try
            {
                archiveFileName.DeleteFile();
            }
            catch (Exception ex)
            {
                lock (_syncOutput)
                    Console.WriteLine($"Failed to remove {archiveFileName}: {ex.Message}");
            }

            return(true);
        }
 public override Task DeleteDir(FsPath path)
 {
     var storageKind = _GetStorage(path)
         .Kind;
     if (storageKind == _StorageKind.Missing)
         return CompletedTask;
     if (storageKind == _StorageKind.File)
         throw new ArgumentException("path", string.Format("Path {0} was a file, and you attempted to delete a directory.", path.Absolute));
     var toDelete = _ItemsInScopeOfDirectory(path);
     toDelete.Each(p => _data.Remove(p.Key));
     return CompletedTask;
 }
Beispiel #30
0
        public void Set_images_are_from_expected_directory(string setCode, params FsPath[] expectedDirsSet)
        {
            setCode = setCode.Trim();
            var set = Repo.SetsByCode[setCode];

            foreach (var card in set.ActualCards)
            {
                var    imageModel = Ui.GetSmallImage(card);
                FsPath dir = imageModel.ImageFile.FullPath.Parent();
                new[] { dir.Value }.Should().BeSubsetOf(expectedDirsSet.Select(_ => _.Value));
            }
        }
Beispiel #31
0
        public static void CreateApplicationShortcut(FsPath exePath, FsPath iconPath, FsPath shortcutPath)
        {
            if (shortcutPath.IsFile())
            {
                shortcutPath.DeleteFile();
            }

            var          wsh = new WshShell();
            IWshShortcut shortcut;

            try
            {
                shortcut = wsh.CreateShortcut(shortcutPath.Value) as IWshShortcut;
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(
                    "Failed to create shortcut object {0} at {1}: {2}",
                    exePath, shortcutPath, ex);
                return;
            }

            FsPath bin = exePath.Parent();

            if (shortcut == null)
            {
                Console.Error.WriteLine("Failed to create shortcut {0} at {1}: {2}.{3} returned null",
                                        exePath, shortcutPath, nameof(WshShell), nameof(wsh.CreateShortcut));
                return;
            }

            shortcut.Arguments   = "";
            shortcut.TargetPath  = exePath.Value;
            shortcut.WindowStyle = 1;

            shortcut.Description      = "Application to search MTG cards and build decks";
            shortcut.WorkingDirectory = bin.Value;

            if (iconPath.HasValue())
            {
                shortcut.IconLocation = iconPath.Value;
            }

            try
            {
                shortcut.Save();
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("Failed to create shortcut {0} at {1}: {2}", exePath, shortcutPath, ex);
            }
        }
Beispiel #32
0
        /// <summary>
        /// Moves a file or folder placeholder in user file system.
        /// </summary>
        /// <param name="userFileSystemNewPath">New path in user file system.</param>
        /// <remarks>
        /// This method failes if the file or folder in user file system is modified (not in sync with the remote storage)
        /// or if the target file exists.
        /// </remarks>
        public async Task MoveToAsync(string userFileSystemNewPath)
        {
            // Cloud Filter API does not provide a function to move a placeholder file only if it is not modified.
            // The file may be modified between InSync call, Move() call and SetInSync() in this method.

            try
            {
                // Because of the on-demand population the file or folder placeholder may not exist in the user file system.
                if (FsPath.Exists(userFileSystemPath))
                {
                    bool inSync = PlaceholderItem.GetItem(userFileSystemPath).GetInSync();
                    if (inSync)
                    {
                        string eTag = await ETag.GetETagAsync(userFileSystemPath);

                        ETag.DeleteETag(userFileSystemPath);
                        try
                        {
                            Directory.Move(userFileSystemPath, userFileSystemNewPath);
                        }
                        catch
                        {
                            await ETag.SetETagAsync(userFileSystemPath, eTag);

                            throw;
                        }

                        await ETag.SetETagAsync(userFileSystemNewPath, eTag);

                        // The file is marked as not in sync after move/rename. Marking it as in-sync.
                        PlaceholderItem placeholderItem = PlaceholderItem.GetItem(userFileSystemNewPath);
                        placeholderItem.SetInSync(true);
                        placeholderItem.SetOriginalPath(userFileSystemNewPath);

                        await new UserFileSystemRawItem(userFileSystemNewPath).ClearStateAsync();
                    }

                    if (!inSync)
                    {
                        throw new ConflictException(Modified.Client, "The item is not in-sync with the cloud.");
                    }
                }
            }
            catch (Exception ex)
            {
                string path = FsPath.Exists(userFileSystemNewPath) ? userFileSystemNewPath : userFileSystemPath;
                await new UserFileSystemRawItem(userFileSystemPath).SetDownloadErrorStateAsync(ex);

                // Rethrow the exception preserving stack trace of the original exception.
                System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(ex).Throw();
            }
        }
Beispiel #33
0
        public void FSPath_Constructor_Combine_Unrooted()
        {
            var p0 = new FsPath("test");
            var p1 = p0.Append("foo");
            var p2 = p0.Append("foo/bar");

            Assert.AreEqual("test", p0.ToString());
            Assert.AreEqual("test/foo", p1.ToString());
            Assert.AreEqual("test/foo/bar", p2.ToString());
            Assert.IsFalse(p0.IsRooted);
            Assert.IsFalse(p1.IsRooted);
            Assert.IsFalse(p2.IsRooted);
        }
Beispiel #34
0
        private async Task downloadImage(string url, FsPath targetPath, CancellationToken token)
        {
            try
            {
                var stream = await DownloadStream(url, token);

                convertToPng(stream, targetPath);
            }
            catch (HttpRequestException ex)
            {
                _log.Info(ex, "Failed request to {0} {1}", url);
            }
        }
Beispiel #35
0
        public void EnsureThat_FsUtils_CopyDirectory_Works()
        {
            var source = new FsPath(TestEnvironment.GetTestFolder());
            var target = new FsPath(_testDir, "copydir");

            var result = source.CopyDirectory(target, TestEnvironment.GetMockedLog());

            Assert.IsTrue(result);

            var files = Directory.GetFiles(Path.Combine(_testDir, "copydir"));

            Assert.AreEqual(6, files.Length);
        }
        /// <summary>
        /// Deletes file or folder in the remote storage.
        /// </summary>
        internal async Task <bool> DeleteAsync()
        {
            if (!FsPath.AvoidSync(userFileSystemPath))
            {
                await new VirtualFileSystem.UserFileSystemItem(userFileSystemPath).DeleteAsync();

                ETag.DeleteETag(userFileSystemPath);

                return(true);
            }

            return(false);
        }
Beispiel #37
0
        /// <summary>
        /// Sets or removes icon.
        /// </summary>
        /// <param name="set">True to display the icon. False - to remove the icon.</param>
        private async Task SetIconAsync(bool set, int?id = null, string iconFile = null, string description = null)
        {
            IStorageItem storageItem = await FsPath.GetStorageItemAsync(userFileSystemPath);

            if (storageItem == null)
            {
                // This method may be called on temp files, typically created by MS Office, that exist for a short period of time.
                // StorageProviderItemProperties.SetAsync(null,) causes AccessViolationException
                // which is not handled by .NET (or handled by HandleProcessCorruptedStateExceptions) and causes a fatal crush.
                return;
            }

            try
            {
                if (set)
                {
                    StorageProviderItemProperty propState = new StorageProviderItemProperty()
                    {
                        Id           = id.Value,
                        Value        = description,
                        IconResource = Path.Combine(virtualDrive.Settings.IconsFolderPath, iconFile)
                    };
                    await StorageProviderItemProperties.SetAsync(storageItem, new StorageProviderItemProperty[] { propState });
                }
                else
                {
                    await StorageProviderItemProperties.SetAsync(storageItem, new StorageProviderItemProperty[] { });
                }
            }

            // Setting status icon failes for blocked files.
            catch (FileNotFoundException)
            {
            }
            catch (COMException)
            {
                // "Error HRESULT E_FAIL has been returned from a call to a COM component."
            }
            catch (Exception ex)
            {
                if (ex.HResult == -2147024499)
                {
                    // "The operation failed due to a conflicting cloud file property lock. (0x8007018D)"
                }
                else
                {
                    // Rethrow the exception preserving stack trace of the original exception.
                    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(ex).Throw();
                }
            }
        }
Beispiel #38
0
        public void CreateApplicationShortcut(FsPath shortcutLocation)
        {
            string appVersionInstalled = GetAppVersionInstalled();
            // Mtgdb.Gui.v1.3.5.10.zip
            var prefix     = "Mtgdb.Gui.";
            var postfix    = ".zip";
            var versionDir = appVersionInstalled.Substring(prefix.Length, appVersionInstalled.Length - prefix.Length - postfix.Length);

            FsPath currentBin = AppDir.BinVersion.Parent().Join(versionDir);
            // may be different from currently running executable because of just installed upgrade
            FsPath execPath = currentBin.Join(ExecutableFileName);
            FsPath iconPath = currentBin.Join("mtg64.ico");

            FsPath shortcutPath = shortcutLocation.Join(ShortcutFileName);

            if (createApplicationShortcut(shortcutPath, execPath, iconPath))
            {
                return;
            }

            // workaround a problem with WshShell unable to create the link within desktop directory
            // due to a mismatch between physical and localized directory names
            var    tempLocation = new FsPath(Path.GetTempPath());
            FsPath tempPath     = tempLocation.Join(ShortcutFileName);

            if (!createApplicationShortcut(tempPath, execPath, iconPath))
            {
                return;
            }
            try
            {
                tempPath.MoveFileTo(shortcutPath);
                Console.WriteLine("Moved application shortcut from {0} to {1}",
                                  tempLocation, shortcutLocation);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed to move application shortcut from {0} to {1}: {2}",
                                  tempLocation, shortcutLocation, ex);

                try
                {
                    tempPath.DeleteFile();
                }
                catch (Exception cleanupEx)
                {
                    Console.WriteLine("Failed to remove application shortcut from {0}: {1}",
                                      tempLocation, cleanupEx);
                }
            }
        }
Beispiel #39
0
 internal async Task SetUploadErrorStateAsync(Exception ex)
 {
     if (FsPath.Exists(userFileSystemPath))
     {
         if (ex is ConflictException)
         {
             await SetConflictIconAsync(true);
         }
         else
         {
             await SetUploadPendingIconAsync(true);
         }
     }
 }
Beispiel #40
0
        private bool addFirst(FsPath path, RotateFlipType rotations, Bitmap image)
        {
            var key = new Tuple <FsPath, RotateFlipType>(path, rotations);

            if (_imagesByPath.ContainsKey(key))
            {
                return(false);
            }

            _ratings.AddFirst(key);
            _imagesByPath[key] = new ImageCacheEntry(image, _ratings.First);

            return(true);
        }
Beispiel #41
0
 public MiddlewareContext(string sourcePath, string outputPath = "", string pluginPath = "")
 {
     SourcePath = new FsPath(sourcePath);
     if (string.IsNullOrWhiteSpace(outputPath))
     {
         outputPath = "_output";
     }
     OutputPath = SourcePath.Combine(outputPath);
     if (string.IsNullOrWhiteSpace(pluginPath))
     {
         pluginPath = "plugins";
     }
     PluginPath = SourcePath.Combine(pluginPath);
 }
 public override void Overwrote(FsPath path)
 {
     if (!_fileSystem._Disk.FileExists(path))
     {
         _undoActions.Add(() => _fileSystem._Disk.DeleteFile(path));
         return;
     }
     var randomFileName = FsPath.TempFolder/Guid.NewGuid().ToString("N");
     _fileSystem._Disk.MoveFile(path, randomFileName);
     _undoActions.Add(() =>
     {
         _fileSystem._Disk.DeleteFile(path);
         _fileSystem._Disk.MoveFile(randomFileName, path);
     });
 }
 public bool FileExists(FsPath path)
 {
     return _GetStorage(path).Kind == _StorageKind.File;
 }
 public void DeleteFile(FsPath path)
 {
     if (_GetStorage(path).Kind == _StorageKind.Directory)
         throw new ArgumentException("path", string.Format("Path {0} was a directory, and you attempted to delete a file.", path.Absolute));
     _data.Remove(path);
 }
 public bool DirExists(FsPath path)
 {
     return _GetStorage(path).Kind == _StorageKind.Directory;
 }
Beispiel #46
0
		public override Task CreateDir(FsPath path)
		{
			return Task.Run(() => Directory.CreateDirectory(path.Absolute));
		}
Beispiel #47
0
 public void CreateDir(FsPath path)
 {
     Directory.CreateDirectory(path.Absolute);
 }
Beispiel #48
0
		public override Task MoveDir(FsPath src, FsPath dest)
		{
			return Task.Run(() => Directory.Move(src.Absolute, dest.Absolute));
		}
 public byte[] RawContents(FsPath path)
 {
     _Node storage = _GetStorage(path);
     _ValidateStorage(path, storage);
     return storage.RawContents;
 }
Beispiel #50
0
		public override Task DeleteFile(FsPath path)
		{
			return Task.Run(() => File.Delete(path.Absolute));
		}
Beispiel #51
0
		public override Task MoveFile(FsPath src, FsPath dest)
		{
			return Task.Run(() => File.Move(src.Absolute, dest.Absolute));
		}
Beispiel #52
0
		public override Task DeleteDir(FsPath path)
		{
			return Task.Run(() => Directory.Delete(path.Absolute, true));
		}
Beispiel #53
0
		public override Task<bool> FileExists(FsPath path)
		{
			return File.Exists(path.Absolute)
				.AsImmediateTask();
		}
Beispiel #54
0
		public override Task<string> TextContents(FsPath path)
		{
			return Task.Run(() => File.ReadAllText(path.Absolute));
		}
 public void Overwrite(FsPath path, string newContents)
 {
     _data[path] = new _Node(_StorageKind.File) {
         RawContents= DefaultEncoding.GetBytes(newContents)
     };
 }
Beispiel #56
0
		public override Task<bool> DirExists(FsPath path)
		{
			return Directory.Exists(path.Absolute)
				.AsImmediateTask();
		}
 public void Overwrite(FsPath path, byte[] newContents)
 {
     _data[path] = new _Node(_StorageKind.File) {
         RawContents = newContents
     };
 }
 private void _ValidateStorage(FsPath path, _Node storage)
 {
     if (storage.Kind == _StorageKind.Missing)
         throw new FileNotFoundException(string.Format("Could not find file '{0}'.", path.Absolute), path.Absolute);
     if (storage.Kind == _StorageKind.Directory)
         throw new UnauthorizedAccessException(string.Format("Access to the path '{0}' is denied.", path.Absolute));
 }
 public string TextContents(FsPath path)
 {
     _Node storage = _GetStorage(path);
     _ValidateStorage(path, storage);
     return DefaultEncoding.GetString(storage.RawContents);
 }
Beispiel #60
0
		public override Task<byte[]> RawContents(FsPath path)
		{
			return Task.Run(() => File.ReadAllBytes(path.Absolute));
		}