/// <exception cref="System.IO.IOException"></exception> internal static void CopyStreamToFile(Stream inStream, FilePath file) { var outStream = new FileStream(file.GetAbsolutePath(), FileMode.OpenOrCreate); var n = 0; var buffer = new byte[16384]; while ((n = inStream.Read(buffer, 0, buffer.Length)) > 0) { outStream.Write(buffer, 0, n); } outStream.Dispose(); inStream.Dispose(); }
public static bool DeleteRecursive (FilePath attachmentsFile) { if(!Directory.Exists(attachmentsFile.GetAbsolutePath())) { return true; } var success = true; try { Directory.Delete (attachmentsFile.GetPath (), true); } catch (Exception ex) { Log.E(Tag, "Error deleting the '{0}' directory.".Fmt(attachmentsFile.GetAbsolutePath()), ex); success = false; } return success; }
/// <summary> /// Deletes the <see cref="Couchbase.Lite.Database" />. /// </summary> /// <exception cref="Couchbase.Lite.CouchbaseLiteException"> /// Thrown if an issue occurs while deleting the <see cref="Couchbase.Lite.Database" /></exception> public void Delete() { if (_isOpen && !Close()) { throw new CouchbaseLiteException("The database was open, and could not be closed", StatusCode.InternalServerError); } Manager.ForgetDatabase(this); if (!Exists()) { return; } var file = new FilePath(Path); var fileJournal = new FilePath(AttachmentStorePath + "-journal"); var deleteStatus = file.Delete(); if (fileJournal.Exists()) { deleteStatus &= fileJournal.Delete(); } //recursively delete attachments path var attachmentsFile = new FilePath(AttachmentStorePath); var deleteAttachmentStatus = FileDirUtils.DeleteRecursive(attachmentsFile); //recursively delete path where attachments stored( see getAttachmentStorePath()) var lastDotPosition = Path.LastIndexOf('.'); if (lastDotPosition > 0) { var attachmentsFileUpFolder = new FilePath(Path.Substring(0, lastDotPosition)); FileDirUtils.DeleteRecursive(attachmentsFileUpFolder); } if (!deleteStatus) { Log.V(Tag, String.Format("Error deleting the SQLite database file at {0}", file.GetAbsolutePath())); } if (!deleteStatus) { throw new CouchbaseLiteException("Was not able to delete the database file", StatusCode.InternalServerError); } if (!deleteAttachmentStatus) { throw new CouchbaseLiteException("Was not able to delete the attachments files", StatusCode.InternalServerError); } }
private string ReadSource(FilePath f) { string absPath = f.GetAbsolutePath(); if (!f.IsFile()) { AddError("msg.jsfile.not.found", absPath); return null; } try { return (string)SourceReader.ReadFileOrUrl(absPath, true, characterEncoding); } catch (FileNotFoundException) { AddError("msg.couldnt.open", absPath); } catch (IOException ioe) { AddFormatedError(ioe.ToString()); } return null; }
public virtual void RepositoryWithRootLevelSubmoduleAbsoluteRef() { ObjectId id = ObjectId.FromString("abcd1234abcd1234abcd1234abcd1234abcd1234"); string path = "sub"; FilePath dotGit = new FilePath(db.WorkTree, path + FilePath.separatorChar + Constants .DOT_GIT); if (!dotGit.GetParentFile().Exists()) { dotGit.GetParentFile().Mkdirs(); } FilePath modulesGitDir = new FilePath(db.Directory, "modules" + FilePath.separatorChar + path); new FileWriter(dotGit).Append("gitdir: " + modulesGitDir.GetAbsolutePath()).Close (); FileRepositoryBuilder builder = new FileRepositoryBuilder(); builder.SetWorkTree(new FilePath(db.WorkTree, path)); builder.Build().Create(); DirCache cache = db.LockDirCache(); DirCacheEditor editor = cache.Editor(); editor.Add(new _PathEdit_153(id, path)); editor.Commit(); SubmoduleWalk gen = SubmoduleWalk.ForIndex(db); NUnit.Framework.Assert.IsTrue(gen.Next()); NUnit.Framework.Assert.AreEqual(path, gen.GetPath()); NUnit.Framework.Assert.AreEqual(id, gen.GetObjectId()); NUnit.Framework.Assert.AreEqual(new FilePath(db.WorkTree, path), gen.GetDirectory ()); NUnit.Framework.Assert.IsNull(gen.GetConfigUpdate()); NUnit.Framework.Assert.IsNull(gen.GetConfigUrl()); NUnit.Framework.Assert.IsNull(gen.GetModulesPath()); NUnit.Framework.Assert.IsNull(gen.GetModulesUpdate()); NUnit.Framework.Assert.IsNull(gen.GetModulesUrl()); Repository subRepo = gen.GetRepository(); AddRepoToClose(subRepo); NUnit.Framework.Assert.IsNotNull(subRepo); NUnit.Framework.Assert.AreEqual(modulesGitDir, subRepo.Directory); NUnit.Framework.Assert.AreEqual(new FilePath(db.WorkTree, path), subRepo.WorkTree ); NUnit.Framework.Assert.IsFalse(gen.Next()); }
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="NGit.Errors.ConfigInvalidException"></exception> private void SetWorkTree(FilePath gitDir, FilePath workTree) { string path = workTree.GetAbsolutePath(); FileBasedConfig cfg = ConfigFor(gitDir); cfg.SetString(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_WORKTREE , path); cfg.Save(); }
/// <summary>Construct a pack invalid error.</summary> /// <remarks>Construct a pack invalid error.</remarks> /// <param name="path">path of the invalid pack file.</param> public PackInvalidException(FilePath path) : base(MessageFormat.Format(JGitText.Get ().packFileInvalid, path.GetAbsolutePath())) { }
/// <exception cref="System.IO.FileNotFoundException"></exception> private void OpenTempFile() { string uuid = Misc.CreateGUID(); string filename = string.Format("{0}.blobtmp", uuid); FilePath tempDir = store.TempDir(); tempFile = new FilePath(tempDir, filename); if (store.EncryptionKey == null) { outStream = new BufferedStream(File.Open (tempFile.GetAbsolutePath(), FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite)); } else { outStream = store.EncryptionKey.CreateStream( new BufferedStream(File.Open(tempFile.GetAbsolutePath(), FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))); } }
/// <summary>Delete file or folder</summary> /// <param name="f"> /// <code>File</code> /// to be deleted /// </param> /// <param name="options"> /// deletion options, /// <code>RECURSIVE</code> /// for recursive deletion of /// a subtree, /// <code>RETRY</code> /// to retry when deletion failed. /// Retrying may help if the underlying file system doesn't allow /// deletion of files being read by another thread. /// </param> /// <exception cref="System.IO.IOException"> /// if deletion of /// <code>f</code> /// fails. This may occur if /// <code>f</code> /// didn't exist when the method was called. This can therefore /// cause IOExceptions during race conditions when multiple /// concurrent threads all try to delete the same file. /// </exception> public static void Delete(FilePath f, int options) { if ((options & SKIP_MISSING) != 0 && !f.Exists()) { return; } if ((options & RECURSIVE) != 0 && f.IsDirectory()) { FilePath[] items = f.ListFiles(); if (items != null) { foreach (FilePath c in items) { Delete(c, options); } } } if (!f.Delete()) { if ((options & RETRY) != 0 && f.Exists()) { for (int i = 1; i < 10; i++) { try { Sharpen.Thread.Sleep(100); } catch (Exception) { } // ignore if (f.Delete()) { return; } } } throw new IOException(MessageFormat.Format(JGitText.Get().deleteFileFailed, f.GetAbsolutePath ())); } }
private static void LoadIdentity(JSch sch, FilePath priv) { if (priv.IsFile()) { try { sch.AddIdentity(priv.GetAbsolutePath()); } catch (JSchException) { } } }
/// <summary> /// Creates the directory named by this abstract pathname, including any /// necessary but nonexistent parent directories. /// </summary> /// <remarks> /// Creates the directory named by this abstract pathname, including any /// necessary but nonexistent parent directories. Note that if this operation /// fails it may have succeeded in creating some of the necessary parent /// directories. /// </remarks> /// <param name="d">directory to be created</param> /// <param name="skipExisting"> /// if /// <code>true</code> /// skip creation of the given directory if it /// already exists in the file system /// </param> /// <exception cref="System.IO.IOException"> /// if creation of /// <code>d</code> /// fails. This may occur if /// <code>d</code> /// did exist when the method was called. This can therefore /// cause IOExceptions during race conditions when multiple /// concurrent threads all try to create the same directory. /// </exception> public static void Mkdirs(FilePath d, bool skipExisting) { if (!d.Mkdirs()) { if (skipExisting && d.IsDirectory()) { return; } throw new IOException(MessageFormat.Format(JGitText.Get().mkDirsFailed, d.GetAbsolutePath ())); } }
/// <exception cref="System.IO.IOException"></exception> private PackLock RenameAndOpenPack(string lockMessage) { if (!keepEmpty && GetObjectCount() == 0) { CleanupTemporaryFiles(); return null; } MessageDigest d = Constants.NewMessageDigest(); byte[] oeBytes = new byte[Constants.OBJECT_ID_LENGTH]; for (int i = 0; i < GetObjectCount(); i++) { PackedObjectInfo oe = GetObject(i); oe.CopyRawTo(oeBytes, 0); d.Update(oeBytes); } string name = ObjectId.FromRaw(d.Digest()).Name; FilePath packDir = new FilePath(db.GetDirectory(), "pack"); FilePath finalPack = new FilePath(packDir, "pack-" + name + ".pack"); FilePath finalIdx = new FilePath(packDir, "pack-" + name + ".idx"); PackLock keep = new PackLock(finalPack, db.GetFS()); if (!packDir.Exists() && !packDir.Mkdir() && !packDir.Exists()) { // The objects/pack directory isn't present, and we are unable // to create it. There is no way to move this pack in. // CleanupTemporaryFiles(); throw new IOException(MessageFormat.Format(JGitText.Get().cannotCreateDirectory, packDir.GetAbsolutePath())); } if (finalPack.Exists()) { // If the pack is already present we should never replace it. // CleanupTemporaryFiles(); return null; } if (lockMessage != null) { // If we have a reason to create a keep file for this pack, do // so, or fail fast and don't put the pack in place. // try { if (!keep.Lock(lockMessage)) { throw new IOException(MessageFormat.Format(JGitText.Get().cannotLockPackIn, finalPack )); } } catch (IOException e) { CleanupTemporaryFiles(); throw; } } if (!tmpPack.RenameTo(finalPack)) { CleanupTemporaryFiles(); keep.Unlock(); throw new IOException(MessageFormat.Format(JGitText.Get().cannotMovePackTo, finalPack )); } if (!tmpIdx.RenameTo(finalIdx)) { CleanupTemporaryFiles(); keep.Unlock(); if (!finalPack.Delete()) { finalPack.DeleteOnExit(); } throw new IOException(MessageFormat.Format(JGitText.Get().cannotMoveIndexTo, finalIdx )); } try { newPack = db.OpenPack(finalPack, finalIdx); } catch (IOException err) { keep.Unlock(); if (finalPack.Exists()) { FileUtils.Delete(finalPack); } if (finalIdx.Exists()) { FileUtils.Delete(finalIdx); } throw; } return lockMessage != null ? keep : null; }
/// <summary>Create a SignatureTokenConnection with the provided password and path to PKCS#12 file. /// </summary> /// <remarks> /// Create a SignatureTokenConnection with the provided password and path to PKCS#12 file. The default constructor /// for Pkcs12SignatureToken. /// </remarks> /// <param name="password"></param> /// <param name="pkcs12FilePath"></param> public RFC3370Pkcs12SignatureToken(char[] password, FilePath pkcs12File) { this.password = password; if (!pkcs12File.Exists()) { throw new RuntimeException("File Not Found " + pkcs12File.GetAbsolutePath()); } this.pkcs12File = pkcs12File; }
public virtual void Test000_openrepo_default_absolute_workdirconfig() { FilePath repo1Parent = new FilePath(trash.GetParentFile(), "r1"); FilePath workdir = new FilePath(trash.GetParentFile(), "rw"); FileUtils.Mkdir(workdir); FileRepository repo1initial = new FileRepository(new FilePath(repo1Parent, Constants .DOT_GIT)); repo1initial.Create(); FileBasedConfig cfg = ((FileBasedConfig)repo1initial.GetConfig()); cfg.SetString("core", null, "worktree", workdir.GetAbsolutePath()); cfg.Save(); repo1initial.Close(); FilePath theDir = new FilePath(repo1Parent, Constants.DOT_GIT); FileRepository r = new FileRepositoryBuilder().SetGitDir(theDir).Build(); AssertEqualsPath(theDir, r.Directory); AssertEqualsPath(workdir, r.WorkTree); AssertEqualsPath(new FilePath(theDir, "index"), r.GetIndexFile()); AssertEqualsPath(new FilePath(theDir, "objects"), ((ObjectDirectory)r.ObjectDatabase ).GetDirectory()); }
/// <summary> /// Deletes the %Database%. /// </summary> /// <exception cref="Couchbase.Lite.CouchbaseLiteException"/> public void Delete() { if (open) { if (!Close()) { throw new CouchbaseLiteException("The database was open, and could not be closed", StatusCode.InternalServerError); } } Manager.ForgetDatabase(this); if (!Exists()) { return; } var file = new FilePath(Path); var attachmentsFile = new FilePath(AttachmentStorePath); var deleteStatus = file.Delete(); if (!deleteStatus) { Log.V(Database.Tag, String.Format("Error deleting the SQLite database file at {0}", file.GetAbsolutePath())); } //recursively delete attachments path var deletedAttachmentsPath = true; try { var dirInfo = new DirectoryInfo(attachmentsFile.GetPath()); dirInfo.Delete(true); //Directory.Delete (attachmentsFile.GetPath (), true); } catch (Exception ex) { Log.V(Database.Tag, "Error deleting the attachments directory.", ex); deletedAttachmentsPath = false; } if (!deleteStatus) { throw new CouchbaseLiteException("Was not able to delete the database file", StatusCode.InternalServerError); } if (!deletedAttachmentsPath) { throw new CouchbaseLiteException("Was not able to delete the attachments files", StatusCode.InternalServerError); } }
public virtual void Test30_stripWorkDir() { FilePath relCwd = new FilePath("."); FilePath absCwd = relCwd.GetAbsoluteFile(); FilePath absBase = new FilePath(new FilePath(absCwd, "repo"), "workdir"); FilePath relBase = new FilePath(new FilePath(relCwd, "repo"), "workdir"); NUnit.Framework.Assert.AreEqual(absBase.GetAbsolutePath(), relBase.GetAbsolutePath ()); FilePath relBaseFile = new FilePath(new FilePath(relBase, "other"), "module.c"); FilePath absBaseFile = new FilePath(new FilePath(absBase, "other"), "module.c"); NUnit.Framework.Assert.AreEqual("other/module.c", Repository.StripWorkDir(relBase , relBaseFile)); NUnit.Framework.Assert.AreEqual("other/module.c", Repository.StripWorkDir(relBase , absBaseFile)); NUnit.Framework.Assert.AreEqual("other/module.c", Repository.StripWorkDir(absBase , relBaseFile)); NUnit.Framework.Assert.AreEqual("other/module.c", Repository.StripWorkDir(absBase , absBaseFile)); FilePath relNonFile = new FilePath(new FilePath(relCwd, "not-repo"), ".gitignore" ); FilePath absNonFile = new FilePath(new FilePath(absCwd, "not-repo"), ".gitignore" ); NUnit.Framework.Assert.AreEqual(string.Empty, Repository.StripWorkDir(relBase, relNonFile )); NUnit.Framework.Assert.AreEqual(string.Empty, Repository.StripWorkDir(absBase, absNonFile )); NUnit.Framework.Assert.AreEqual(string.Empty, Repository.StripWorkDir(db.WorkTree , db.WorkTree)); FilePath file = new FilePath(new FilePath(db.WorkTree, "subdir"), "File.java"); NUnit.Framework.Assert.AreEqual("subdir/File.java", Repository.StripWorkDir(db.WorkTree , file)); }
/// <summary> /// This method implements how to handle conflicts when /// <see cref="failOnConflict">failOnConflict</see> /// is false /// </summary> /// <exception cref="NGit.Errors.CheckoutConflictException">NGit.Errors.CheckoutConflictException /// </exception> private void CleanUpConflicts() { // TODO: couldn't we delete unsaved worktree content here? foreach (string c in conflicts) { FilePath conflict = new FilePath(repo.WorkTree, c); if (!conflict.Delete()) { throw new NGit.Errors.CheckoutConflictException(MessageFormat.Format(JGitText.Get ().cannotDeleteFile, c)); } RemoveEmptyParents(conflict); } foreach (string r in removed) { FilePath file = new FilePath(repo.WorkTree, r); if (!file.Delete()) { throw new NGit.Errors.CheckoutConflictException(MessageFormat.Format(JGitText.Get ().cannotDeleteFile, file.GetAbsolutePath())); } RemoveEmptyParents(file); } }
/// <summary> /// Deletes the <see cref="Couchbase.Lite.Database" />. /// </summary> /// <exception cref="Couchbase.Lite.CouchbaseLiteException"> /// Thrown if an issue occurs while deleting the <see cref="Couchbase.Lite.Database" /></exception> public void Delete() { if (_isOpen && !Close()) { throw new CouchbaseLiteException("The database was open, and could not be closed", StatusCode.InternalServerError); } Manager.ForgetDatabase(this); if (!Exists()) { return; } var file = new FilePath(Path); var fileJournal = new FilePath(Path + "-journal"); var fileWal = new FilePath(Path + "-wal"); var fileShm = new FilePath(Path + "-shm"); var deleteStatus = file.Delete(); if (fileJournal.Exists()){ deleteStatus &= fileJournal.Delete(); } if (fileWal.Exists()) { deleteStatus &= fileWal.Delete(); } if (fileShm.Exists()) { deleteStatus &= fileShm.Delete(); } //recursively delete attachments path var attachmentsFile = new FilePath(AttachmentStorePath); var deleteAttachmentStatus = FileDirUtils.DeleteRecursive(attachmentsFile); if (!deleteStatus) { Log.W(TAG, "Error deleting the SQLite database file at {0}", file.GetAbsolutePath()); throw new CouchbaseLiteException("Was not able to delete the database file", StatusCode.InternalServerError); } if (!deleteAttachmentStatus) { Log.W(TAG, "Error deleting the attachment files file at {0}", attachmentsFile.GetAbsolutePath()); throw new CouchbaseLiteException("Was not able to delete the attachments files", StatusCode.InternalServerError); } }
/// <summary>Construct a pack invalid error.</summary> /// <remarks>Construct a pack invalid error.</remarks> /// <param name="path">path of the invalid pack file.</param> public PackInvalidException(FilePath path) : this(path.GetAbsolutePath()) { }