Dispose() public method

Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
public Dispose ( ) : void
return void
示例#1
0
        public void TearDown()
        {
            var workDir = repo.Info.WorkingDirectory;

            repo.Dispose();
            DeleteDirectory(workDir);
        }
 void Dispose(bool disposing)
 {
     if (repository != null)
     {
         repository.Dispose();
     }
 }
示例#3
0
 public void Dispose()
 {
     if (_repo != null)
     {
         _repo.Dispose();
     }
 }
示例#4
0
        public void CleanupTestRepo()
        {
            string repoPath = repo.Info.WorkingDirectory;

            if (repo != null)
            {
                repo.Dispose();
            }
            FileSystemHelper.DeleteDirectory(repoPath);
        }
示例#5
0
        private static void Main(string[] args)
        {
            var result = CommandLine.Parser.Default.ParseArguments<Options>(args);
              if (!result.Errors.Any())
              {
            string url = result.Value.Repository;

            var brancOption = result.Value.Branch;
            var branchSepIndex = brancOption.IndexOf('/');
            if (branchSepIndex > 0)
            {
              var credentials = new UsernamePasswordCredentials
            {
              Username = result.Value.UserName,
              Password = result.Value.Password
            };
              CredentialsHandler credHandler = (s, fromUrl, types) => credentials;

              var remote = brancOption.Substring(0, branchSepIndex);
              var branch = brancOption.Substring(branchSepIndex+1, brancOption.Length - branchSepIndex-1);

              var workingDirectory = result.Value.LocalRepoPath;

              var isLocalRepoExist = Repository.Discover(workingDirectory);
              if (isLocalRepoExist == null)
              {
            var cloneOptions = new CloneOptions {CredentialsProvider = credHandler};
            Repository.Clone(url, workingDirectory, cloneOptions);
              }

              Repository repo = null;
              try
              {
            var tagName = result.Value.TagName;
            repo = new Repository(workingDirectory);
            //repo.Fetch(remote, new FetchOptions(){CredentialsProvider = credHandler});
            repo.Network.Pull(new Signature(result.Value.UserName,result.Value.Email, new DateTimeOffset()),
              new PullOptions() { FetchOptions = new FetchOptions() { CredentialsProvider = credHandler } });
            repo.ApplyTag(tagName);
            PushChanges(repo, credHandler, remote, branch, tagName);
            Console.WriteLine("Tagged :{0}", result.Value.TagName);
              }
              catch (Exception ex)
              {
            Console.WriteLine("Error happened {0}", ex.Message);
              }
              finally
              {
            if (repo != null) repo.Dispose();
              }
            }
              }
              Console.ReadLine();
        }
示例#6
0
        public void Remove(string path, string fileName, string folderName)
        {
            string delimiter = Path.Combine(@"\");


            var repo = new LibGit2Sharp.Repository(path + delimiter + folderName);

            repo.Dispose();

            DeleteDirectory(path + delimiter + folderName);
        }
        /// <inheritdoc />
        public LibGit2Sharp.IRepository CreateInMemory()
        {
            logger.LogTrace("Creating in-memory libgit2 repository...");
            var repo = new LibGit2Sharp.Repository();

            try
            {
                logger.LogTrace("Successfully created in-memory libgit2 repository.");
                return(repo);
            }
            catch
            {
                repo.Dispose();
                throw;
            }
        }
 public RepositoryWrapper(Repository repo)
 {
     this.repo = repo;
     Head = async (i) => { return new BranchWrapper(repo, repo.Head); };
     Config = async (i) => { return repo.Config; };
     Index = async (i) => { return repo.Index; };
     Ignore = async (i) => { return repo.Ignore; };
     Network = async (i) => { return new NetworkWrapper(repo.Network); };
     ObjectDatabase = async (i) => { return repo.ObjectDatabase; };
     Refs = async (i) => { return repo.Refs; };
     Commits = async (i) => { return repo.Commits.Select(c => new CommitWrapper(c)); };
     Tags = async (i) => { return repo.Tags; };
     Stashes = async (i) => { return repo.Stashes; };
     Info = async (i) => { return repo.Info; };
     Diff = async (i) => { return repo.Diff; };
     Notes = async (i) => { return repo.Notes; };
     Submodules = async (i) => { return repo.Submodules; };
     Dispose = async (i) => { repo.Dispose(); return null; };
     Lookup = async (id) => {
         var found = repo.Lookup(id.ToString());
         if (found.GetType() == typeof(Commit)) {
             return new CommitWrapper((Commit)found);
         } else {
             return found;
         }
     };
     Branches = async (i) => repo.Branches.Select(b => new BranchWrapper(repo, b)).ToDictionary(b => b.Name);
     Reset = async (dynamic i) => {
         var modeName = ((string)i.mode).ToLower();
         ResetMode mode;
         if (modeName == "soft") {
             mode = ResetMode.Soft;
         } else if (modeName == "mixed") {
             mode = ResetMode.Mixed;
         } else {
             mode = ResetMode.Hard;
         }
         var committish = (string)i.committish;
         repo.Reset(mode, committish, null, null);
         return null;
     };
     Checkout = async (i) => {
         var branch = repo.Branches.First(b => b.Name == i.ToString());
         repo.Checkout(branch);
         return branch;
     };
 }
示例#9
0
        public IObservable<DateTimeOffset> LastCommitTime(string repoPath)
        {
            return Observable.Start(() => {
                var repo = default(Repository);
                try {
                    repo = new Repository(repoPath);
                    if (repo.Head == null || repo.Head.Tip == null) {
                        throw new Exception("Couldn't find commit");
                    }

                    this.Log().Debug("Last Commit Time: {0}", repo.Head.Tip.Author.When);
                    return repo.Head.Tip.Author.When;
                } catch (Exception ex) {
                    this.Log().WarnException("Couldn't read commit time on repo: " + repoPath, ex);
                    throw;
                } finally {
                    if (repo != null) repo.Dispose();
                }
            }, RxApp.TaskpoolScheduler);
        }
示例#10
0
 public IObservable<RepositoryStatus> GetStatus(string repoPath)
 {
     return Observable.Start(() => {
         var repo = default(Repository);
         try {
             repo = new Repository(repoPath);
             return repo.Index.RetrieveStatus();
         } catch (Exception ex) {
             this.Log().WarnException("Couldn't read status for repo: " + repoPath, ex);
             throw;
         } finally {
             if (repo != null) repo.Dispose();
         }
     }, RxApp.TaskpoolScheduler);
 }
示例#11
0
        public string ProtocolUrlForRepoPath(string repoPath)
        {
            if (!isGitHubForWindowsInstalled()) return null;

            var remoteUrl = default(string);
            var repo = default(Repository);

            try {
                repo = new Repository(repoPath);
                var remote = repo.Network.Remotes.FirstOrDefault(x => x.Name.Equals("origin", StringComparison.OrdinalIgnoreCase));
                if (remote == null) return null;

                this.Log().Info("Using remote {0} for repo {1}", remote.Url, repoPath);
                remoteUrl = remote.Url.ToLowerInvariant();
            } catch (Exception ex) {
                this.Log().WarnException("Failed to open repo: " + repoPath, ex);
                return null;
            } finally {
                if (repo != null) repo.Dispose();
            }

            var ret = protocolUrlForRemoteUrl(remoteUrl);
            this.Log().Info("Protocol URL for {0} is {1}", repoPath, ret);
            return ret;
        }
		protected override Repository OnPublish (string serverPath, FilePath localPath, FilePath[] files, string message, ProgressMonitor monitor)
		{
			// Initialize the repository
			RootRepository = new LibGit2Sharp.Repository (LibGit2Sharp.Repository.Init (localPath));
			RootPath = localPath;
			RootRepository.Network.Remotes.Add ("origin", Url);

			// Add the project files
			ChangeSet cs = CreateChangeSet (localPath);
			foreach (FilePath fp in files) {
				RootRepository.Stage (RootRepository.ToGitPath (fp));
				cs.AddFile (fp);
			}

			// Create the initial commit
			cs.GlobalComment = message;
			Commit (cs, monitor);

			RootRepository.Branches.Update (RootRepository.Branches ["master"], branch => branch.TrackedBranch = "refs/remotes/origin/master");

			RetryUntilSuccess (monitor, credType => RootRepository.Network.Push (RootRepository.Head, new PushOptions {
				OnPushStatusError = delegate (PushStatusError e) {
					RootRepository.Dispose ();
					RootRepository = null;
					if (RootPath.Combine (".git").IsDirectory)
						Directory.Delete (RootPath.Combine (".git"), true);
					throw new VersionControlException (e.Message);
				},
				CredentialsProvider = (url, userFromUrl, types) => GitCredentials.TryGet (url, userFromUrl, types, credType)
			}));

			return this;
		}
示例#13
0
        /// <inheritdoc />
        public Task Initialize(CancellationToken cancellationToken)
        {
            return(Task.Factory.StartNew(async() =>
            {
                using (logger.BeginScope("Initializing repository..."))
                {
                    var repoPath = ioManager.ResolvePath(ioManager.ConcatPath(gitHubConfiguration.RepoOwner, gitHubConfiguration.RepoName));

                    logger.LogTrace("Repo path evaluated to be: {0}", repoPath);

                    try
                    {
                        logger.LogTrace("Creating repository object.");
                        cancellationToken.ThrowIfCancellationRequested();
                        repositoryObject = new LibGit2Sharp.Repository(repoPath);

                        repositoryObject.RemoveUntrackedFiles();

                        cancellationToken.ThrowIfCancellationRequested();

                        repositoryObject.RetrieveStatus();
                    }
                    catch (OperationCanceledException e)
                    {
                        logger.LogDebug(e, "Repository setup cancelled!");
                        repositoryObject?.Dispose();
                        throw;
                    }
                    catch (Exception e)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        using (logger.BeginScope("Repository fallback initializing..."))
                        {
                            repositoryObject?.Dispose();
                            try
                            {
                                logger.LogTrace("Checking repository directory exists.");
                                if (await ioManager.DirectoryExists(repoPath, cancellationToken).ConfigureAwait(false))
                                {
                                    logger.LogWarning(e, "Failed to load repository! Deleting and cloning...");
                                    await ioManager.DeleteDirectory(repoPath, cancellationToken).ConfigureAwait(false);
                                }
                                else
                                {
                                    logger.LogInformation(e, "Cloning repository...");
                                }

                                LibGit2Sharp.Repository.Clone(String.Format(CultureInfo.InvariantCulture, "https://github.com/{0}/{1}", gitHubConfiguration.RepoOwner, gitHubConfiguration.RepoName), repoPath, new CloneOptions
                                {
                                    Checkout = false,
                                    RecurseSubmodules = true,
                                    OnProgress = (a) => !cancellationToken.IsCancellationRequested,
                                    OnUpdateTips = (a, b, c) => !cancellationToken.IsCancellationRequested,
                                    OnTransferProgress = (a) => !cancellationToken.IsCancellationRequested
                                });

                                logger.LogInformation("Repo clone completed.");

                                repositoryObject = new LibGit2Sharp.Repository(repoPath);
                            }
                            catch (UserCancelledException e2)
                            {
                                logger.LogDebug(e2, "Repository setup cancelled!");
                                cancellationToken.ThrowIfCancellationRequested();
                            }
                            catch (Exception e2)
                            {
                                logger.LogCritical(e2, "Unable to clone repository!");
                                throw;
                            }
                        }
                    }
                }
            }, cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Current));
        }
示例#14
0
 /// <summary>
 /// Disposes the <see cref="repositoryObject"/>
 /// </summary>
 public void Dispose()
 {
     repositoryObject?.Dispose();
     semaphore.Dispose();
 }
示例#15
0
        private static void StartDeploying(Repository repository, FileManager fileManager)
        {
            Commit commitOlder = null;
            Commit commitNewer = null;
            string olderVersion = "UNK";
            string newerVersion = "UNK";

            bool wrongInput = true;
            while (wrongInput)
            {
                Console.Out.Write("Older version: ");
                olderVersion = Console.In.ReadLine();
                Console.Out.Write("Newer version: ");
                newerVersion = Console.In.ReadLine();

                Tag tagOlder = repository.Tags.FirstOrDefault(x => x.Name == olderVersion);
                Tag tagNewer = repository.Tags.FirstOrDefault(x => x.Name == newerVersion);

                if (tagOlder == null || tagNewer == null)
                {
                    if (tagOlder == null)
                    {
                        Printf("Invalid older tag");
                    }
                    if (tagNewer == null)
                    {
                        Printf("Invalid newer tag");
                    }
                }
                else
                {
                    commitOlder = tagOlder.Target as Commit;
                    commitNewer = tagNewer.Target as Commit;

                    if (commitOlder == null || commitNewer == null)
                    {
                        if (commitOlder == null)
                        {
                            Printf("Older tag does not point to commit");
                        }
                        if (commitNewer == null)
                        {
                            Printf("Newer tag does not point to commit");
                        }
                    }
                    else
                    {
                        if (commitOlder.Author.When >= commitNewer.Author.When)
                        {
                            Printf("Wrong timing");
                        }
                        else
                        {
                            wrongInput = false;
                        }
                    }
                }
            }

            TreeChanges changes = repository.Diff.Compare<TreeChanges>(commitOlder.Tree, commitNewer.Tree);

            PrintChanges(changes);
            LogChanges(changes);

            List<TreeEntryChanges> filesToBeBackedUp = new List<TreeEntryChanges>();
            filesToBeBackedUp.AddRange(changes.Modified);
            filesToBeBackedUp.AddRange(changes.Deleted);
            filesToBeBackedUp.AddRange(changes.Renamed);

            List<TreeEntryChanges> filesToBeDeployed = new List<TreeEntryChanges>();
            filesToBeDeployed.AddRange(changes.Added);
            filesToBeDeployed.AddRange(changes.Modified);
            filesToBeDeployed.AddRange(changes.Renamed);

            string backUpPath = string.Format("{0}{1}", TmpPath, "backup\\");
            string deployPath = string.Format("{0}{1}", TmpPath, "deploy\\");
            fileManager.CreateTmpFolder(TmpPath);

            BundleCreationResult backupResult;
            BundleCreationResult deployResult;
            BundleCreationResult rollBackResult;
            BundleCreationResult deployPackResult;

            Printf("Creating backup");
            backupResult = fileManager.CreateBackUp(ServerPath, backUpPath, filesToBeBackedUp);
            PrintResult("Creating backup", backupResult);

            if (backupResult == BundleCreationResult.Succes)
            {
                Printf("Creating deploy pack");
                deployPackResult = fileManager.CreateDeployPack(BaseRepositoryPath, deployPath, filesToBeDeployed);
                PrintResult("Creating deploy pack", deployPackResult);

                if (deployPackResult == BundleCreationResult.Succes)
                {
                    Printf("Deploying files");
                    deployResult = fileManager.DeployFiles(deployPath, ServerPath, changes, BaseRepositoryPath);
                    PrintResult("Deploying files", deployResult);

                    if (deployResult == BundleCreationResult.Fail)
                    {
                        Printf("Rolling back");
                        rollBackResult = fileManager.RollBack(backUpPath, ServerPath, changes);
                        PrintResult("Rolling back", rollBackResult);
                    }
                }
            }

            Printf("Generating Zip");
            fileManager.GenerateZip(ZipFilePath, TmpPath, filesToBeBackedUp, filesToBeDeployed, olderVersion.Replace(".", "_"), newerVersion.Replace(".", "_"));

            fileManager.DeleteTmpFolder(TmpPath);
            repository.Dispose();
        }
示例#16
0
        Commit fetchLatestCommitForHead(string repositoryRoot)
        {
            if (String.IsNullOrEmpty(repositoryRoot)) {
                return null;
            }

            var repo = default(Repository);
            try {
                repo = new Repository(repositoryRoot);
                return repo.Commits.FirstOrDefault();
            } catch (Exception ex) {
                this.Log().ErrorException("Couldn't open repo", ex);
                return null;
            } finally {
                if (repo != null) {
                    repo.Dispose();
                }
            }
        }