Beispiel #1
0
    public void Dispose_DeletesDirectoryWithContent()
    {
        TemporaryDirectory.ExecuteIn(_dirPath, dir => {
            File.WriteAllText(dir.GetUniquePath(), "a");
        });

        Assert.IsFalse(Directory.Exists(_dirPath));
    }
Beispiel #2
0
    public void Dispose_KeepDirectoryOnException()
    {
        System.Environment.SetEnvironmentVariable(EnvironmentVariables.KeepFilesOnErrorEnvironmentVariable, "yes");

        try
        {
            TemporaryDirectory.ExecuteIn(_dirPath, dir => {
                throw new System.Exception();
            });
        }
        catch (System.Exception)
        {}

        Assert.IsTrue(Directory.Exists(_dirPath));

        Directory.Delete(_dirPath, true);
        System.Environment.SetEnvironmentVariable(EnvironmentVariables.KeepFilesOnErrorEnvironmentVariable, null);
    }
Beispiel #3
0
        public override void Execute(CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogDebug("Installing diff...");

                base.Execute(cancellationToken);

                _logger.LogTrace("diffSummary.compressionMethod = " + _diffSummary.CompressionMethod);

                if (_diffSummary.CompressionMethod == "pack1")
                {
                    ReadPack1MetaFile();
                }

                TemporaryDirectory.ExecuteIn(_packagePath + ".temp_unpack_" + Path.GetRandomFileName(), (packageDir) =>
                {
                    _logger.LogTrace("packageDir = " + packageDir.Path);

                    string usedSuffix;

                    UnarchivePackage(packageDir.Path, out usedSuffix, cancellationToken);

                    ProcessAddedFiles(packageDir.Path, usedSuffix, cancellationToken);
                    ProcessRemovedFiles(cancellationToken);

                    TemporaryDirectory.ExecuteIn(_packagePath + ".temp_diff_" + Path.GetRandomFileName(), (tempDiffDir) =>
                    {
                        _logger.LogTrace("tempDiffDir = " + tempDiffDir.Path);

                        ProcessModifiedFiles(packageDir.Path, usedSuffix, tempDiffDir, cancellationToken);
                    });

                    DeleteEmptyMacAppDirectories(cancellationToken);
                });

                _logger.LogDebug("Diff installed.");
            }
            catch (Exception e)
            {
                _logger.LogError("Diff installation failed", e);
                throw;
            }
        }
Beispiel #4
0
    public void GetUniquePath_ReturnsUniquePaths()
    {
        TemporaryDirectory.ExecuteIn(_dirPath, temporaryData => {
            for (int i = 0; i < 100; i++)
            {
                string path = temporaryData.GetUniquePath();

                Assert.IsFalse(File.Exists(path));
                Assert.IsFalse(Directory.Exists(path));

                if (i % 2 == 0)
                {
                    File.WriteAllText(temporaryData.GetUniquePath(), "a");
                }
                else
                {
                    Directory.CreateDirectory(path);
                }
            }
        });
    }
Beispiel #5
0
        public override void Execute(CancellationToken cancellationToken)
        {
            base.Execute(cancellationToken);

            foreach (var entry in _entries)
            {
                var tempDirName = _packagePath + string.Format("{0}_{1}_{2}", entry.Name, entry.Offset, entry.Size);
                TemporaryDirectory.ExecuteIn(tempDirName, (tempDir) =>
                {
                    _logger.LogDebug(string.Format("Repairing the file {0}", entry.Name));
                    string packagePath   = Path.Combine(tempDir.Path, ".pack" + Path.GetRandomFileName());
                    string unarchivePath = Path.Combine(tempDir.Path, Path.GetRandomFileName());

                    if (!Directory.Exists(unarchivePath))
                    {
                        DirectoryOperations.CreateDirectory(unarchivePath, cancellationToken);
                    }

                    var downloader = new ChunkedHttpDownloader(packagePath, _resource.ResourceUrls, _resource.ChunksData, _resource.Size);

                    long start = entry.Offset.GetValueOrDefault();
                    long end   = (start + entry.Size.GetValueOrDefault()) - 1; // Offset by 1 to denote a byte index

                    var range = new BytesRange(start, end);

                    downloader.SetRange(range);
                    var effectiveRange = downloader.CalculateContainingChunksRange(range);

                    long totalData = effectiveRange.End == -1 ? _resource.Size - effectiveRange.Start : effectiveRange.End - effectiveRange.Start;

                    var downloadStatus = _entryStatus[entry].DownloadStatus;
                    var repairStatus   = _entryStatus[entry].RepairStatus;

                    downloadStatus.IsActive.Value    = true;
                    downloadStatus.TotalBytes.Value  = totalData;
                    downloadStatus.Description.Value = "Downloading broken file...";
                    downloadStatus.Bytes.Value       = 0;

                    downloader.DownloadProgressChanged += downloadedBytes =>
                    {
                        downloadStatus.Bytes.Value = downloadedBytes;
                    };

                    _logger.LogDebug(string.Format("Downloading the partial package with range {0}-{1}", start, end));
                    downloader.Download(cancellationToken);

                    downloadStatus.IsActive.Value = false;

                    repairStatus.IsActive.Value    = true;
                    repairStatus.Description.Value = "Reparing broken file...";
                    repairStatus.Progress.Value    = 0.0;

                    _logger.LogDebug("Unarchiving the package.");
                    var unarchiver = new Pack1Unarchiver(packagePath, _meta, unarchivePath, _packagePassword, _unpackingSuffix, effectiveRange);
                    unarchiver.UnarchiveProgressChanged += (name, isFile, unarchiveEntry, amount, entryProgress) =>
                    {
                        repairStatus.Progress.Value = entryProgress;
                    };

                    unarchiver.UnarchiveSingleFile(entry, cancellationToken);

                    EmplaceFile(Path.Combine(unarchivePath, entry.Name + _unpackingSuffix), Path.Combine(_localData.Path, entry.Name), cancellationToken);

                    repairStatus.IsActive.Value = false;
                });
            }
        }
Beispiel #6
0
        public override void Execute(CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogDebug("Installing diff...");

                base.Execute(cancellationToken);

                _logger.LogTrace("diffSummary.compressionMethod = " + _diffSummary.CompressionMethod);

                if (_diffSummary.CompressionMethod == "pack1")
                {
                    ReadPack1MetaFile();
                }

                TemporaryDirectory.ExecuteIn(_packagePath + ".temp_unpack_" + Path.GetRandomFileName(), (packageDir) =>
                {
                    _logger.LogTrace("packageDir = " + packageDir.Path);

                    string usedSuffix;

                    UnarchivePackage(packageDir.Path, out usedSuffix, cancellationToken);

                    // To correctly install diff, we need to first remove the
                    // files & dirs, and later add a new ones.
                    //
                    // Otherwise we could encounter a situation when we try to
                    // add a file/dir, which is already present in the data
                    // (but should be removed becuase it's in the removed_files)
                    //
                    // But only with diff summary 2.6 we can be sure that
                    // removed_files field contains directories as well.
                    //
                    // That's why we're keeping the "wrong" behaviour for diffs
                    // with version lower than 2.6.

                    if (IsDiffSummaryVersionAtLeast2_6())
                    {
                        ProcessRemovedFiles(cancellationToken);
                        ProcessAddedFiles(packageDir.Path, usedSuffix, cancellationToken);
                    }
                    else
                    {
                        ProcessAddedFiles(packageDir.Path, usedSuffix, cancellationToken);
                        ProcessRemovedFiles(cancellationToken);
                    }

                    TemporaryDirectory.ExecuteIn(_packagePath + ".temp_diff_" + Path.GetRandomFileName(), (tempDiffDir) =>
                    {
                        _logger.LogTrace("tempDiffDir = " + tempDiffDir.Path);

                        ProcessModifiedFiles(packageDir.Path, usedSuffix, tempDiffDir, cancellationToken);
                    });

                    DeleteEmptyMacAppDirectories(cancellationToken);
                });

                _logger.LogDebug("Diff installed.");
            }
            catch (Exception e)
            {
                _logger.LogError("Diff installation failed", e);
                throw;
            }
        }
Beispiel #7
0
    public void Dispose_DeletesDirectory()
    {
        TemporaryDirectory.ExecuteIn(_dirPath, dir => {});

        Assert.IsFalse(Directory.Exists(_dirPath));
    }
Beispiel #8
0
 public void Constructor_CreatesDirectory()
 {
     TemporaryDirectory.ExecuteIn(_dirPath, dir => {
         Assert.IsTrue(Directory.Exists(_dirPath));
     });
 }
        public override void Execute(CancellationToken cancellationToken)
        {
            base.Execute(cancellationToken);

            Checks.FileExists(_packagePath);
            Assert.IsTrue(_localMetaData.GetRegisteredEntries().Length == 0,
                          "Cannot install content if previous version is still present.");

            if (_versionContentSummary.CompressionMethod == "pack1")
            {
                Assert.IsTrue(File.Exists(_packageMetaPath),
                              "Compression method is pack1, but meta file does not exist");

                DebugLogger.Log("Parsing package meta file");
                _pack1Meta = Pack1Meta.ParseFromFile(_packageMetaPath);
                DebugLogger.Log("Package meta file parsed succesfully");
            }

            DebugLogger.Log("Installing content.");

            TemporaryDirectory.ExecuteIn(_packagePath + ".temp_unpack_" + Path.GetRandomFileName(), (packageDir) => {
                DebugLogger.LogVariable(packageDir.Path, "packageDirPath");

                DebugLogger.Log("Unarchiving package.");

                string usedSuffix;
                IUnarchiver unarchiver = CreateUnrachiver(packageDir.Path, out usedSuffix);

                _unarchivePackageStatus.IsActive.Value    = true;
                _unarchivePackageStatus.Description.Value = "Unarchiving package...";
                _unarchivePackageStatus.Progress.Value    = 0.0;

                unarchiver.UnarchiveProgressChanged += (name, isFile, entry, amount, entryProgress) =>
                {
                    var entryMinProgress = (entry - 1) / (double)amount;
                    var entryMaxProgress = entry / (double)amount;

                    _unarchivePackageStatus.Progress.Value = entryMinProgress + (entryMaxProgress - entryMinProgress) * entryProgress;

                    _unarchivePackageStatus.Description.Value = string.Format("Unarchiving package ({0}/{1})...", entry, amount);
                };

                unarchiver.Unarchive(cancellationToken);

                _unarchivePackageStatus.Progress.Value = 1.0;
                _unarchivePackageStatus.IsActive.Value = false;

                DebugLogger.Log("Copying files.");

                _copyFilesStatus.IsActive.Value    = true;
                _copyFilesStatus.Description.Value = "Installing...";
                _copyFilesStatus.Progress.Value    = 0.0;

                for (int i = 0; i < _versionContentSummary.Files.Length; i++)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    InstallFile(_versionContentSummary.Files[i].Path, packageDir.Path, usedSuffix, cancellationToken);

                    _copyFilesStatus.Progress.Value    = (i + 1) / (double)_versionContentSummary.Files.Length;
                    _copyFilesStatus.Description.Value = string.Format("Installing ({0}/{1})...", i + 1, _versionContentSummary.Files.Length);
                }

                _copyFilesStatus.Progress.Value = 1.0;
                _copyFilesStatus.IsActive.Value = false;
            });
        }
        public override void Execute(CancellationToken cancellationToken)
        {
            base.Execute(cancellationToken);

            Checks.FileExists(_packagePath);
            Assert.IsTrue(_localMetaData.GetRegisteredEntries().Length == 0,
                          "Cannot install content if previous version is still present.");

            if (_versionContentSummary.CompressionMethod == "pack1")
            {
                Assert.IsTrue(File.Exists(_packageMetaPath),
                              "Compression method is pack1, but meta file does not exist");

                DebugLogger.Log("Parsing package meta file");
                _pack1Meta = Pack1Meta.ParseFromFile(_packageMetaPath);
                DebugLogger.Log("Package meta file parsed succesfully");
            }

            DebugLogger.Log("Installing content.");

            TemporaryDirectory.ExecuteIn(_packagePath + ".temp_unpack_" + Path.GetRandomFileName(), (packageDir) => {
                DebugLogger.LogVariable(packageDir.Path, "packageDirPath");

                DebugLogger.Log("Unarchiving package.");

                string usedSuffix;
                IUnarchiver unarchiver = CreateUnrachiver(packageDir.Path, out usedSuffix);

                _unarchivePackageStatus.IsActive.Value    = true;
                _unarchivePackageStatus.Description.Value = "Unarchiving package...";
                _unarchivePackageStatus.Progress.Value    = 0.0;

                unarchiver.UnarchiveProgressChanged += (name, isFile, entry, amount, entryProgress) =>
                {
                    var entryMinProgress = (entry - 1) / (double)amount;
                    var entryMaxProgress = entry / (double)amount;

                    _unarchivePackageStatus.Progress.Value = entryMinProgress + (entryMaxProgress - entryMinProgress) * entryProgress;

                    _unarchivePackageStatus.Description.Value = string.Format("Unarchiving package ({0}/{1})...", entry, amount);
                };

                // Allow to unpack with errors. This allows to install content even on corrupted hard drives, and attempt to fix these later
                unarchiver.ContinueOnError = true;

                unarchiver.Unarchive(cancellationToken);
                NeedRepair = unarchiver.HasErrors;

                _unarchivePackageStatus.Progress.Value = 1.0;
                _unarchivePackageStatus.IsActive.Value = false;

                DebugLogger.Log("Moving files.");

                _copyFilesStatus.IsActive.Value    = true;
                _copyFilesStatus.Description.Value = "Installing...";
                _copyFilesStatus.Progress.Value    = 0.0;

                for (int i = 0; i < _versionContentSummary.Files.Length; i++)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    var sourceFile = new SourceFile(_versionContentSummary.Files[i].Path, packageDir.Path, usedSuffix);

                    if (unarchiver.HasErrors && !sourceFile.Exists()) // allow unexistent file only if does not have errors
                    {
                        DebugLogger.LogWarning("Skipping unexisting file because I've been expecting unpacking errors: " + sourceFile.Name);
                    }
                    else
                    {
                        InstallFile(sourceFile, cancellationToken);
                    }

                    _copyFilesStatus.Progress.Value    = (i + 1) / (double)_versionContentSummary.Files.Length;
                    _copyFilesStatus.Description.Value = string.Format("Installing ({0}/{1})...", i + 1, _versionContentSummary.Files.Length);
                }

                _copyFilesStatus.Progress.Value = 1.0;
                _copyFilesStatus.IsActive.Value = false;
            });
        }