public bool Commit(string message, string authorName, string emailAddress) { using (var repo = new LibGit2Sharp.Repository(RepositoryPath)) { var changes = repo.RetrieveStatus(new StatusOptions { DetectRenamesInIndex = false, DetectRenamesInWorkDir = false }).Select(c => c.FilePath); if (!changes.Any()) { return(false); } repo.Stage(changes); if (string.IsNullOrWhiteSpace(authorName) || string.IsNullOrWhiteSpace(emailAddress)) { repo.Commit(message); } else { repo.Commit(message, new Signature(authorName, emailAddress, DateTimeOffset.UtcNow)); } return(true); } }
private static void UpdateHomePageContent(Repository repo, string homePath, Signature sig) { File.AppendAllText(homePath, "\nThis will be a bare bone user experience.\n"); repo.Index.Stage(homePath); repo.Commit(sig, sig, "Add warning to the Home page\n\nA very informational explicit message preventing the user from expecting too much."); }
/// <summary> /// Exports files from VBProject to the file system, initalizes the repository, and creates an inital commit of those files to the repo. /// </summary> /// <param name="directory">Local file path of the directory where the new repository will be created.</param> /// <returns>Newly initialized repository.</returns> public override IRepository InitVBAProject(string directory) { var repository = base.InitVBAProject(directory); Init(repository.LocalLocation); //add a master branch to newly created repo using (var repo = new LibGit2Sharp.Repository(repository.LocalLocation)) { var status = repo.RetrieveStatus(new StatusOptions { DetectRenamesInWorkDir = true }); foreach (var stat in status.Untracked) { repo.Stage(stat.FilePath); } try { //The default behavior of LibGit2Sharp.Repo.Commit is to throw an exception if no signature is found, // but BuildSignature() does not throw if a signature is not found, it returns "unknown" instead. // so we pass a signature that won't throw along to the commit. repo.Commit("Initial Commit", GetSignature(repo)); } catch (LibGit2SharpException ex) { throw new SourceControlException(SourceControlText.GitNoInitialCommit, ex); } } return(repository); }
private static void RenameMyWishListPage(Repository repo, string myWishListPath, Signature sig) { repo.Index.Unstage(myWishListPath); File.Move(myWishListPath, myWishListPath + "List"); repo.Index.Stage(myWishListPath + "List"); repo.Commit(sig, sig, "Fix MyWishList page name"); }
private void btnCommit_Click(object sender, RibbonControlEventArgs e) { //Get Active Project var pj = Globals.ThisAddIn.Application.ActiveProject; //Get Project Filename. var projectFile = pj.FullName; //Get Directory from File Name var directory = Path.GetDirectoryName(projectFile); //Create a new Git Repository Repository.Init(directory); //Open the git repository in a using context so its automatically disposed of. using (var repo = new Repository(directory)) { // Stage the file repo.Index.Stage(projectFile); // Create the committer's signature and commit var author = new Signature("Richard", "@ARM", DateTime.Now); var committer = author; // Commit to the repository var commit = repo.Commit("Initial commit", author, committer); } }
/// <summary> /// Delete an entry /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void deleteToolStripMenuItem_Click(object sender, EventArgs e) { // remove from git using (var repo = new LibGit2Sharp.Repository(cfg["PassDirectory"])) { // remove the file repo.Remove(dataPass.Rows[dataPass.CurrentCell.RowIndex].Cells[0].Value.ToString()); // Commit repo.Commit("password removed", new LibGit2Sharp.Signature("pass4win", "pass4win", System.DateTimeOffset.Now), new LibGit2Sharp.Signature("pass4win", "pass4win", System.DateTimeOffset.Now)); if (cfg["UseGitRemote"] == true && GITRepoOffline == false) { // push toolStripOffline.Visible = false; var remote = repo.Network.Remotes["origin"]; var options = new PushOptions(); options.CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials { Username = cfg["GitUser"], Password = DecryptConfig(cfg["GitPass"], "pass4win") }; var pushRefSpec = @"refs/heads/master"; repo.Network.Push(remote, pushRefSpec, options); } } ResetDatagrid(); }
/// <summary> /// Commit changes for repository /// </summary> /// <param name="commitInfo">Information about the commit</param> public void Commit(CommitInfo commitInfo) { string localServiceRepoFolder = _settings.GetServicePath(commitInfo.Org, commitInfo.Repository, AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext)); using (LibGit2Sharp.Repository repo = new LibGit2Sharp.Repository(localServiceRepoFolder)) { string remoteUrl = FindRemoteRepoLocation(commitInfo.Org, commitInfo.Repository); Remote remote = repo.Network.Remotes["origin"]; if (!remote.PushUrl.Equals(remoteUrl)) { // This is relevant when we switch beteen running designer in local or in docker. The remote URL changes. // Requires adminstrator access to update files. repo.Network.Remotes.Update("origin", r => r.Url = remoteUrl); } Commands.Stage(repo, "*"); // Create the committer's signature and commit LibGit2Sharp.Signature author = new LibGit2Sharp.Signature(AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext), "@jugglingnutcase", DateTime.Now); LibGit2Sharp.Signature committer = author; // Commit to the repository LibGit2Sharp.Commit commit = repo.Commit(commitInfo.Message, author, committer); } }
/// <summary> /// Callback for the encrypt thread /// </summary> /// <param name="result"></param> /// <param name="tmpFile"></param> /// <param name="tmpFile2"></param> /// <param name="path"></param> public void Encrypt_Callback(GpgInterfaceResult result, string tmpFile, string tmpFile2, string path) { if (result.Status == GpgInterfaceStatus.Success) { File.Delete(tmpFile); File.Delete(path); File.Move(tmpFile2, path); // add to git using (var repo = new LibGit2Sharp.Repository(cfg["PassDirectory"])) { // Stage the file repo.Stage(path); // Commit repo.Commit("password changes", new LibGit2Sharp.Signature("pass4win", "pass4win", System.DateTimeOffset.Now), new LibGit2Sharp.Signature("pass4win", "pass4win", System.DateTimeOffset.Now)); if (cfg["UseGitRemote"] == true && GITRepoOffline == false) { toolStripOffline.Visible = false; var remote = repo.Network.Remotes["origin"]; var options = new PushOptions(); options.CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials { Username = cfg["GitUser"], Password = DecryptConfig(cfg["GitPass"], "pass4win") }; var pushRefSpec = @"refs/heads/master"; repo.Network.Push(remote, pushRefSpec, options); } } } else { MessageBox.Show(Strings.Error_weird_shit_happened_encryption, Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public void CloneRepo() { var scd = BuildSelfCleaningDirectory(); CloneOptions options = new CloneOptions(); var credentials = new UsernamePasswordCredentials(); credentials.Username = Constants.Identity.Name; credentials.Password = "******"; options.CredentialsProvider += (url, fromUrl, types) => credentials; string clonedRepoPath = Repository.Clone(testUrl, scd.DirectoryPath, options); string file = Path.Combine(scd.DirectoryPath, "testpush.txt"); var rbg = new RandomBufferGenerator(30000); using (var repo = new Repository(clonedRepoPath)) { for (int i = 0; i < 1; i++) { var network = repo.Network.Remotes.First(); FetchOptions fetchOptions = new FetchOptions(); fetchOptions.CredentialsProvider += (url, fromUrl, types) => credentials; repo.Fetch(network.Name, fetchOptions); File.WriteAllBytes(file, rbg.GenerateBufferFromSeed(30000)); repo.Stage(file); Signature author = Constants.Signature; Commit commit = repo.Commit($"Here's a commit {i + 1} i made!", author, author); PushOptions pushOptions = new PushOptions(); pushOptions.CredentialsProvider += (url, fromUrl, types) => credentials; repo.Network.Push(repo.Branches["master"], pushOptions); } } }
/// <summary> /// Commit changes to local repo. Use Github.Add first. /// TODO: Possibly add ability for users to specify msg? /// </summary> public void Commit() { using (var repo = new Repository(_LocalRepo)) { repo.Commit("Update via Chuck interface."); } }
private void CommitCore(string message) { using var repo = new Git.Repository(Location); var statusOptions = new Git.StatusOptions { DetectRenamesInIndex = true, DetectRenamesInWorkDir = true, IncludeIgnored = false, IncludeUntracked = true, RecurseUntrackedDirs = true, RecurseIgnoredDirs = false }; if (!repo.RetrieveStatus(statusOptions).IsDirty) { return; } Git.Commands.Stage(repo, "*"); var author = new Git.Signature("JournalCli", "@journalCli", DateTime.Now); var committer = author; var options = new Git.CommitOptions { PrettifyMessage = true }; var commit = repo.Commit(message, author, committer, options); }
public void SaveFile(string fileName, string content, string username, string email) { using (var repo = new Repository(_basePath)) { File.WriteAllText(Path.Combine(repo.Info.WorkingDirectory, fileName), content); // stage the file repo.Stage(fileName); // Create the committer's signature and commit //var user = repo.Config.Get<string>("user", "name", null); //var email = repo.Config.Get<string>("user", "email", null); var author = new Signature(username, email, DateTime.Now); var committer = author; // Commit to the repo var commitMessage = string.Format("Revision: {0}", GetRevisionCount(repo, fileName)); try { var commit = repo.Commit(commitMessage, author, committer); foreach (var parent in commit.Parents) { Console.WriteLine("Id: {0}, Sha: {1}", parent.Id, parent.Sha); } } catch (EmptyCommitException) { } // I don't care if the user didn't change anything at this time } }
// difference to other Save method: no content, but a commit_key as an OUT parameter public string Save(string pathLocalRepo, string fileName, string author, string email, DateTime commitTime, string commitMessage, string userName, string passWord, bool calcChanged, out string commit_key) { commit_key = string.Empty; using (var repo = new LibGit2Sharp.Repository(pathLocalRepo)) { // Commit Commands.Stage(repo, "*"); // added jede Änderung // Create the committer's signature and commit Signature authorHelp = new Signature(author, email, commitTime); Signature committer = authorHelp; // Commit to the repository try { if (calcChanged == true) // CalcChanged Flag nach dem später gefiltert wird { Commit commit = repo.Commit("CalcChanged: " + commitMessage, authorHelp, committer); // Bei keinen Änderungen im Commit hängt es Ihn hier auf, exceptionhandling einbauen commit_key = (commit == null) ? string.Empty : Convert.ToString(commit.Id).Substring(0, 7); } else { Commit commit = repo.Commit(commitMessage, authorHelp, committer); // Bei keinen Änderungen im Commit hängt es Ihn hier auf, exceptionhandling einbauen commit_key = (commit == null) ? string.Empty : Convert.ToString(commit.Id).Substring(0, 7); } // Pushen in RemoteRepository Remote remote = repo.Network.Remotes["origin"]; // hier gehts auf die Server-Adresse var options = new PushOptions(); options.CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials { Username = userName, Password = passWord }; repo.Network.Push(remote, @"refs/heads/master", options); } catch (Exception e) { return(e.ToString()); } } return("ok"); }
public static void CommitChanges(string Message, string RepoPath) { using (var repo = new Repository(RepoPath)) { logger.Debug("Git commit to " + RepoPath); Signature sig = new Signature("SantiagoDevelopment", "*****@*****.**", DateTimeOffset.Now ); repo.Commit(Message, sig, sig); } }
void CreateData() { int index = 0; foreach (var commit in commits) { foreach (var data in commit.Datas) { var path = GetPath(data.File); File.WriteAllText(path, data.AsText()); } LibGit2Sharp.Commands.Stage(repo, "*"); var gitCommit = repo.Commit($"commit - {index}", signature, signature); commit.Commit = gitCommit; } }
void CommitCore(CommonRepository repository) { string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name.Split('\\').Last(); using (var repo = new Repository(repository.Path)) { Signature author = new Signature("DXVisualTestsBot", "*****@*****.**", DateTime.Now); Signature committer = author; Commit commit = repo.Commit($"Update tests ({userName})", author, committer); } }
/// <summary> /// rename the entry with all the hassle that accompanies it. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void renameToolStripMenuItem_Click(object sender, EventArgs e) { // rename the entry InputBoxValidation validation = delegate(string val) { if (val == "") { return(Strings.Error_not_empty); } if (new Regex(@"[a-zA-Z0-9-\\_]+/g").IsMatch(val)) { return(Strings.Error_valid_filename); } if (File.Exists(cfg["PassDirectory"] + "\\" + @val + ".gpg")) { return(Strings.Error_already_exists); } return(""); }; string value = dataPass.Rows[dataPass.CurrentCell.RowIndex].Cells[1].Value.ToString(); if (InputBox.Show(Strings.Input_new_name, Strings.Input_new_name_label, ref value, validation) == DialogResult.OK) { // parse path string tmpPath = cfg["PassDirectory"] + "\\" + @value + ".gpg"; Directory.CreateDirectory(Path.GetDirectoryName(tmpPath)); File.Copy(dataPass.Rows[dataPass.CurrentCell.RowIndex].Cells[0].Value.ToString(), tmpPath); using (var repo = new LibGit2Sharp.Repository(cfg["PassDirectory"])) { // add the file repo.Remove(dataPass.Rows[dataPass.CurrentCell.RowIndex].Cells[0].Value.ToString()); repo.Stage(tmpPath); // Commit repo.Commit("password moved", new LibGit2Sharp.Signature("pass4win", "pass4win", System.DateTimeOffset.Now), new LibGit2Sharp.Signature("pass4win", "pass4win", System.DateTimeOffset.Now)); if (cfg["UseGitRemote"] == true && GITRepoOffline == false) { //push toolStripOffline.Visible = false; var remote = repo.Network.Remotes["origin"]; var options = new PushOptions(); options.CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials { Username = cfg["GitUser"], Password = DecryptConfig(cfg["GitPass"], "pass4win") }; var pushRefSpec = @"refs/heads/master"; repo.Network.Push(remote, pushRefSpec, options); } } ResetDatagrid(); } }
public override void Commit(string message) { try { _repo.Commit(message); } catch (LibGit2SharpException ex) { throw new SourceControlException("Commit Failed.", ex); } }
public void GitVersionConfig(string[] lines, string prerelease) { string filePath = Path.Combine(repo.Info.WorkingDirectory, ".gitversion"); File.WriteAllLines(filePath, lines); Commands.Stage(repo, filePath); repo.Commit("Test", me, me); repo.ApplyTag("v2.0.0", me, "Annotation"); repo.CreateBranch("test"); verifyVersion(repo, 2, 0, 0, prerelease, (prerelease ?? "").StartsWith("alpha") ? "master": ""); }
private Commit Commit(string Comments) { CheckinComment = Comments; using (var repo = new LibGit2Sharp.Repository(RepositoryRootFolder)) { // Create the committer's signature and commit Signature author = new LibGit2Sharp.Signature(SolutionSourceControlAuthorName, SolutionSourceControlAuthorEmail, DateTime.Now); Signature committer = author; // Commit to the repository return(repo.Commit(Comments, author, committer)); } }
public string Commit() { if( string.IsNullOrEmpty( RepoPath ) ) throw new ArgumentException("Must open first"); using( Repository repo = new Repository(RepoPath) ) { var author = new Signature(UserName, "nulltoken", DateTimeOffset.Now); var commit = repo.Commit("Ganji commit\n", author, author); return commit.Id.Sha; } }
void commitChangesToGitVersionFile(LibGit2Sharp.Repository repo, string version, string commitMessage) { string filePath = Path.Combine(repo.Info.WorkingDirectory, ".gitversion"); using (StreamWriter file = new StreamWriter(filePath)) { file.WriteLine("version = " + version); file.WriteLine("beta branch = master"); } Commands.Stage(repo, filePath); repo.Commit(commitMessage, me, me); }
public bool Commit(string message, string authorName, string emailAddress) { using (var repo = new LibGit2Sharp.Repository(RepositoryPath)) { var changes = repo.RetrieveStatus(new StatusOptions { DetectRenamesInIndex = false, DetectRenamesInWorkDir = false }) .Where(c => c.State != FileStatus.Ignored) .Select(c => c.FilePath); if (!changes.Any()) { return(false); } foreach (var change in changes) { repo.Index.Add(change); } if (string.IsNullOrWhiteSpace(authorName) || string.IsNullOrWhiteSpace(emailAddress)) { var author = repo.Config.BuildSignature(DateTimeOffset.Now); //var author = new Signature(authorName, emailAddress, DateTimeOffset.UtcNow); var committer = author; repo.Commit(message, author, committer); } else { var author = new Signature(authorName, emailAddress, DateTimeOffset.UtcNow); var committer = author; repo.Commit(message, author, committer); } return(true); } }
public void PushInitialCommit(string fullname, string email, string username, string password, string url, string gitignore, string license) { var path = GetTemporaryDirectory(); Directory.CreateDirectory(path); FillAccessories(fullname, email, path, gitignore, license); if (!LibGit2Sharp.Repository.IsValid(path)) { LibGit2Sharp.Repository.Init(path); } using (var repo = new LibGit2Sharp.Repository(path)) { if (File.Exists(Path.Combine(path, ".gitignore"))) { LibGit2Sharp.Commands.Stage(repo, ".gitignore"); } if (File.Exists(Path.Combine(path, "LICENSE"))) { LibGit2Sharp.Commands.Stage(repo, "LICENSE"); } // Create the committer's signature and commit Signature author = new Signature(fullname, email, DateTime.Now); Signature committer = author; // Commit to the repository Commit commit = repo.Commit("Initial commit", author, committer); //var options = new LibGit2Sharp.PushOptions() //{ // CredentialsProvider = (url, usernameFromUrl, types) => // new UsernamePasswordCredentials() // { // Username = email, // Password = password // } //}; //repo.Network.Push(repo.Branches["master"], options); repo.Network.Remotes.Add("origin", url); var remote = repo.Network.Remotes["origin"]; var options = new PushOptions(); options.CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials { Username = (string.IsNullOrEmpty(username) ? email : username), Password = password }; repo.Network.Push(remote, @"refs/heads/master", options); } DeleteDirectory(path); }
public void PushWithLicense(string fullname, string email, string username, string password, string url, string path, string license) { if (!LibGit2Sharp.Repository.IsValid(path)) { LibGit2Sharp.Repository.Init(path); } using (var repo = new LibGit2Sharp.Repository(path)) { if (!string.IsNullOrEmpty(license)) { try { FillAccessories(fullname, email, path, null, license); LibGit2Sharp.Commands.Stage(repo, "LICENSE"); // Create the committer's signature and commit Signature author = new Signature(fullname, email, DateTime.Now); Signature committer = author; // Commit to the repository Commit commit = repo.Commit($"Use {license}", author, committer); } catch (Exception ex) { Debug.WriteLine(ex.Message); } } if (repo.Network.Remotes.Any(r => r.Name == "origin")) { repo.Network.Remotes.Remove("origin"); } repo.Network.Remotes.Add("origin", url); var remote = repo.Network.Remotes["origin"]; var options = new PushOptions(); options.CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials { Username = (string.IsNullOrEmpty(username) ? email : username), Password = password }; Branch current = repo.Branches.Where(b => b.IsCurrentRepositoryHead).FirstOrDefault(); repo.Network.Push(remote, current.CanonicalName, options); //@"refs/heads/master", options); Branch remoteBranch = repo.Branches.Where(b => b.FriendlyName.EndsWith(current.FriendlyName) && b.IsRemote).FirstOrDefault(); repo.Branches.Update(current, bu => { bu.Remote = remoteBranch.RemoteName; bu.TrackedBranch = remoteBranch.CanonicalName; bu.UpstreamBranch = remoteBranch.UpstreamBranchCanonicalName; }); } }
public static async Task CommitAllChanges(string message, string filePath, string cloneUrl) { try { Console.WriteLine("Commit all changes to GitHub."); var _folder = new DirectoryInfo(filePath); string path = LibGit2Sharp.Repository.Init(_folder.FullName); using (var repo = new LibGit2Sharp.Repository(path)) { var files = _folder.GetFiles("*", SearchOption.AllDirectories).Select(f => f.FullName); Commands.Stage(repo, "*"); repo.Commit(message, new LibGit2Sharp.Signature("sormita", "*****@*****.**", DateTimeOffset.Now), new LibGit2Sharp.Signature("sormita", "*****@*****.**", DateTimeOffset.Now)); //push files string name = "origin"; repo.Network.Remotes.Add(name, cloneUrl); var remote = repo.Network.Remotes.FirstOrDefault(r => r.Name == name); var options = new PushOptions { CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials { Username = "******", Password = "******" } }; var fetchOptions = new FetchOptions { CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials { Username = "******", Password = "******" } }; string pushRefSpec = @"+refs/heads/master"; List <string> fetchString = new List <string>(); fetchString.Add(pushRefSpec); repo.Network.Fetch("origin", fetchString, fetchOptions); repo.Network.Push(remote, pushRefSpec, options); } } catch (Exception ex) { throw; } }
public void Commit(string commitMessage) { var numberOfChanges = _repository.RetrieveStatus(new LibGit2Sharp.StatusOptions()).Count(); Console.WriteLine($"Committing {numberOfChanges} changed files."); Commands.Stage(_repository, "*"); // equivalent of "git add ." // We need to specify the author for the commit, grab it from config Configuration config = _repository.Config; Signature author = config.BuildSignature(DateTimeOffset.Now); _repository.Commit(commitMessage, author, author); }
/** * Save the locally modified files into the local repository */ private static void GitCommit(LibGit2Sharp.Repository repo) { Commands.Stage(repo, "*"); LibGit2Sharp.Signature author = new LibGit2Sharp.Signature("GitSheller", "@cornerpirate", DateTime.Now); LibGit2Sharp.Signature committer = author; // This line throws a LibGit2Sharp.EmptyCommitException when the file has not been altered. try { LibGit2Sharp.Commit commit = repo.Commit("Committed", author, committer); } catch (LibGit2Sharp.EmptyCommitException ece) { // No changes detected. } }
public override void Commit(string message) { try { //The default behavior of LibGit2Sharp.Repo.Commit is to throw an exception if no signature is found, // but BuildSignature() does not throw if a signature is not found, it returns "unknown" instead. // so we pass a signature that won't throw along to the commit. _repo.Commit(message, GetSignature()); } catch (LibGit2SharpException ex) { throw new SourceControlException(SourceControlText.GitCommitFailed, ex); } }
private void CommitFileToRepo(string fileName, Models.Repository repo, string personalAccessKey) { using (var gitRepo = new Repository(GetLocalFolder(repo))) { gitRepo.Index.Add(fileName); gitRepo.Index.Write(); // Create the committer's signature and commit Signature author = new Signature("Webservice", "*****@*****.**", DateTime.Now); Signature committer = author; Commit commit = gitRepo.Commit("Modified " + fileName + " by webservice", author, committer); foreach (var gitRepoBranch in gitRepo.Branches) { gitRepo.Network.Push(gitRepoBranch, getPushOptions(personalAccessKey)); } } }
public void Commit(Signature p_Signature) { RepositoryStatus status = m_Repository.RetrieveStatus(); if (!status.IsDirty) { return; } string commitMessage = $"{m_CommitMessagePrefix} - Dependency Update"; s_Logger.Info($"Commit message. {commitMessage}"); s_Logger.Info("Commiting the changes."); m_Repository.Commit(commitMessage, p_Signature, p_Signature, null); }
public override void Commit(string message) { try { base.Commit(message); RepositoryStatus status = _repo.RetrieveStatus(); List <string> filePaths = status.Modified.Select(mods => mods.FilePath).ToList(); _repo.Stage(filePaths); _repo.Commit(message); } catch (LibGit2SharpException ex) { throw new SourceControlException("Commit Failed.", ex); } }
public ReferenceRepository(GitModuleTestHelper moduleTestHelper) { _moduleTestHelper = moduleTestHelper; using (var repository = new LibGit2Sharp.Repository(_moduleTestHelper.Module.WorkingDir)) { _moduleTestHelper.CreateRepoFile("A.txt", "A"); repository.Index.Add("A.txt"); var message = "A commit message"; var author = new LibGit2Sharp.Signature("GitUITests", "*****@*****.**", DateTimeOffset.Now); var committer = author; var options = new LibGit2Sharp.CommitOptions(); var commit = repository.Commit(message, author, committer, options); CommitHash = commit.Id.Sha; } }
public void PushWithLicense(string fullname, string email, string username, string password, string url, string path, string license) { if (!LibGit2Sharp.Repository.IsValid(path)) { LibGit2Sharp.Repository.Init(path); } using (var repo = new LibGit2Sharp.Repository(path)) { if (!string.IsNullOrEmpty(license)) { try { FillAccessories(fullname, email, path, null, license); LibGit2Sharp.Commands.Stage(repo, "LICENSE"); // Create the committer's signature and commit Signature author = new Signature(fullname, email, DateTime.Now); Signature committer = author; // Commit to the repository Commit commit = repo.Commit($"Use {license}", author, committer); } catch (Exception ex) { Debug.WriteLine(ex.Message); } } if (repo.Network.Remotes.Any(r => r.Name == "origin")) { repo.Network.Remotes.Remove("origin"); } repo.Network.Remotes.Add("origin", url); var remote = repo.Network.Remotes["origin"]; //https://stackoverflow.com/questions/22596367/pushing-to-bitbucket-with-libgit2sharp repo.Branches.Update(repo.Head, b => b.Remote = remote.Name, b => b.UpstreamBranch = repo.Head.CanonicalName); var options = new PushOptions(); options.CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials { Username = (string.IsNullOrEmpty(username) ? email : username), Password = password }; repo.Network.Push(remote, @"refs/heads/master", options); } }
public static void Commit(FileInfo file) { using (var repository = new LibGit2Sharp.Repository(file.DirectoryName)) { try { var status = repository.RetrieveStatus(file.FullName); switch (status) { case FileStatus.Unaltered: Log.Add($"Commit, FileStatus: {status}"); return; case FileStatus.Nonexistent: case FileStatus.Added: case FileStatus.Staged: case FileStatus.Removed: case FileStatus.RenamedInIndex: case FileStatus.StagedTypeChange: case FileStatus.Untracked: case FileStatus.Modified: case FileStatus.Missing: case FileStatus.TypeChanged: case FileStatus.RenamedInWorkDir: { var commit = repository.Commit("Update", CommitOptions); Log.Add($"Commit: {commit.Message}"); break; } case FileStatus.Unreadable: case FileStatus.Ignored: throw new InvalidOperationException($"FileStatus: {status}"); default: throw new ArgumentOutOfRangeException(); } } catch (Exception e) { Log.Add(e.Message); } } }
public void AddModifiedFilesToVersioning(string commitMessage) { Repository.Init(repositoryPath, false); using (var repository = new Repository(repositoryPath)) { var filesToAddToCommit = FilesToCommit(repository); if (!filesToAddToCommit.Any()) { return; } repository.Index.Stage(filesToAddToCommit); repository.Commit(commitMessage); } }
internal static bool StageAndCommit(FileInfo file) { if (!File.Exists(file.FullName)) { return(false); } using (var repository = new LibGit2Sharp.Repository(file.DirectoryName)) { repository.Stage(file.FullName, new StageOptions { IncludeIgnored = true }); var status = repository.RetrieveStatus(file.FullName); switch (status) { case FileStatus.Nonexistent: case FileStatus.Unaltered: return(false); case FileStatus.Added: case FileStatus.Staged: case FileStatus.Removed: case FileStatus.RenamedInIndex: case FileStatus.StagedTypeChange: case FileStatus.Untracked: case FileStatus.Modified: case FileStatus.Missing: case FileStatus.TypeChanged: case FileStatus.RenamedInWorkdir: { var commit = repository.Commit(status.ToString(), CommitOptions); return(true); } case FileStatus.Unreadable: case FileStatus.Ignored: throw new InvalidOperationException($"FileStatus: {status}"); default: throw new ArgumentOutOfRangeException(); } } }
private void ValidateGitRepo() { if (Git.Repository.IsValid(Location)) { return; } Git.Repository.Init(Location); using var repo = new Git.Repository(Location); Git.Commands.Stage(repo, "*"); var author = new Git.Signature("JournalCli", "@journalCli", DateTime.Now); var committer = author; var options = new Git.CommitOptions { PrettifyMessage = true }; var commit = repo.Commit("Initial commit", author, committer, options); }
public static void Commit(FileInfo file) { using (var repository = new LibGit2Sharp.Repository(file.DirectoryName)) { try { var status = repository.RetrieveStatus(file.FullName); switch (status) { case FileStatus.Unaltered: Log.Add($"Commit, FileStatus: {status}"); return; case FileStatus.Nonexistent: case FileStatus.Added: case FileStatus.Staged: case FileStatus.Removed: case FileStatus.RenamedInIndex: case FileStatus.StagedTypeChange: case FileStatus.Untracked: case FileStatus.Modified: case FileStatus.Missing: case FileStatus.TypeChanged: case FileStatus.RenamedInWorkDir: { var commit = repository.Commit("Update", CommitOptions); Log.Add($"Commit: {commit.Message}"); break; } case FileStatus.Unreadable: case FileStatus.Ignored: throw new InvalidOperationException($"FileStatus: {status}"); default: throw new ArgumentOutOfRangeException(); } } catch (Exception e) { Log.Add(e.Message); } } }
/// <summary> /// Exports files from VBProject to the file system, initalizes the repository, and creates an inital commit of those files to the repo. /// </summary> /// <param name="directory">Local file path of the directory where the new repository will be created.</param> /// <returns>Newly initialized repository.</returns> public override IRepository InitVBAProject(string directory) { var repository = base.InitVBAProject(directory); Init(repository.LocalLocation); //add a master branch to newly created repo using (var repo = new LibGit2Sharp.Repository(repository.LocalLocation)) { var status = repo.RetrieveStatus(new StatusOptions()); foreach (var stat in status.Untracked) { repo.Stage(stat.FilePath); } repo.Commit("Intial Commit"); } return(repository); }
/// <summary> /// Initializes a new bare repository at the specified location, adds a repository info file to the root directory /// and tags the initial commit with he value of <see cref="InitialCommitTagName"/> /// </summary> public static void InitializeRepository(string location) { // initialize a bare repository Repository.Init(location, true); var directoryCreator = new LocalItemCreator(); // clone the repository, add initial commit and push the changes back to the actual repository using (var tempDirectory = directoryCreator.CreateTemporaryDirectory()) { var clonedRepoPath = Repository.Clone(location, tempDirectory.Directory.Location); var repositoryInfoFile = new RepositoryInfoFile(tempDirectory.Directory); // add a empty file to the repository directoryCreator.CreateFile(repositoryInfoFile, tempDirectory.Directory.Location); // commit and push the file to the bare repository we created using (var clonedRepo = new Repository(clonedRepoPath)) { var signature = SignatureHelper.NewSignature(); clonedRepo.Stage(repositoryInfoFile.Name); clonedRepo.Commit("Initial Commit", signature, signature, new CommitOptions()); clonedRepo.Network.Push(clonedRepo.Network.Remotes["origin"], @"refs/heads/master"); } } //create the configuration branch pointing to the initial commit using (var repository = new Repository(location)) { repository.CreateBranch(ConfigurationBranchName.ToString(), repository.GetAllCommits().Single()); repository.Tags.Add(InitialCommitTagName, repository.GetAllCommits().Single()); } }
/// <summary> /// Exports files from VBProject to the file system, initalizes the repository, and creates an inital commit of those files to the repo. /// </summary> /// <param name="directory">Local file path of the directory where the new repository will be created.</param> /// <returns>Newly initialized repository.</returns> public override IRepository InitVBAProject(string directory) { var repository = base.InitVBAProject(directory); Init(repository.LocalLocation); //add a master branch to newly created repo using (var repo = new LibGit2Sharp.Repository(repository.LocalLocation)) { var status = repo.RetrieveStatus(new StatusOptions()); foreach (var stat in status.Untracked) { repo.Stage(stat.FilePath); } try { //The default behavior of LibGit2Sharp.Repo.Commit is to throw an exception if no signature is found, // but BuildSignature() does not throw if a signature is not found, it returns "unknown" instead. // so we pass a signature that won't throw along to the commit. repo.Commit("Intial Commit", GetSignature(repo)); } catch(LibGit2SharpException ex) { throw new SourceControlException(SourceControlText.GitNoInitialCommit, ex); } } return repository; }
void Start() { if (IsRepoDir()) { _repo = new Repository(_scriptdir); } else { Repository.Init(_scriptdir); _repo = new Repository(_scriptdir); _repo.Index.Stage("*"); _repo.Commit("initial commit"); } if (_branchNameList == null) { GetBranches(); } if (_inusebranch != _repo.Head.Name) { _repo.Checkout(_inusebranch); } if (ToolbarManager.ToolbarAvailable) { _button = ToolbarManager.Instance.add("kos_ma", "toggle"); _button.TexturePath = BtextureOff; _button.ToolTip = Tooltipoff; _button.OnClick += (e => { Toggle(); }); } }
/// <summary> /// Exports files from VBProject to the file system, initalizes the repository, and creates an inital commit of those files to the repo. /// </summary> /// <param name="directory">Local file path of the directory where the new repository will be created.</param> /// <returns>Newly initialized repository.</returns> public override IRepository InitVBAProject(string directory) { var repository = base.InitVBAProject(directory); Init(repository.LocalLocation); //add a master branch to newly created repo using (var repo = new LibGit2Sharp.Repository(repository.LocalLocation)) { var status = repo.RetrieveStatus(new StatusOptions()); foreach (var stat in status.Untracked) { repo.Stage(stat.FilePath); } repo.Commit("Intial Commit"); } return repository; }
private static bool TryCommit(string gitRepoPath, string message) { try { using (var r = new Repository(gitRepoPath)) { var status = r.RetrieveStatus(); var toStage = status.Where(s => (s.State & FileStatus.Untracked) != 0 || (s.State & FileStatus.Modified) != 0 || (s.State & FileStatus.RenamedInWorkDir) != 0); var toRemove = status.Where(s => (s.State & FileStatus.Missing) != 0); foreach (var item in toStage) { r.Stage(item.FilePath); } foreach (var item in toRemove) { r.Remove(item.FilePath); } r.Commit(message); } return true; } catch (Exception ex) { Console.WriteLine(ex); return false; } }
/// <summary> /// rename the entry with all the hassle that accompanies it. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void RenameToolStripMenuItemClick(object sender, EventArgs e) { SaveFileDialog newFileDialog = new SaveFileDialog { AddExtension = true, AutoUpgradeEnabled = true, CreatePrompt = false, DefaultExt = "gpg", InitialDirectory = Cfg["PassDirectory"], Title = Strings.FrmMain_RenameToolStripMenuItemClick_Rename }; if (newFileDialog.ShowDialog() == DialogResult.Cancel) { return; } string tmpFileName = newFileDialog.FileName; newFileDialog.Dispose(); // ReSharper disable once AssignNullToNotNullAttribute Directory.CreateDirectory(path: Path.GetDirectoryName(tmpFileName)); File.Copy(dirTreeView.SelectedNode.Tag + "\\" + listFileView.SelectedItem + ".gpg", tmpFileName); using (var repo = new Repository(Cfg["PassDirectory"])) { // add the file repo.Remove(listFileView.SelectedItem.ToString()); repo.Stage(tmpFileName); // Commit repo.Commit("password moved", new Signature("pass4win", "pass4win", DateTimeOffset.Now), new Signature("pass4win", "pass4win", DateTimeOffset.Now)); if (Cfg["UseGitRemote"] == true && this.gitRepoOffline == false) { //push toolStripOffline.Visible = false; var remote = repo.Network.Remotes["origin"]; var options = new PushOptions { CredentialsProvider = (url, user, cred) => new UsernamePasswordCredentials { Username = Cfg["GitUser"], Password = DecryptConfig(Cfg["GitPass"], "pass4win") } }; var pushRefSpec = @"refs/heads/master"; repo.Network.Push(remote, pushRefSpec, options); } } this.CreateNodes(); }
/// <summary> /// Remove a GPG key from a directory /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void RemoveToolStripMenuItemClick(object sender, EventArgs e) { if (listBox1.Items[0].ToString() != Strings.Error_keys_set) if (listBox1.Items.Count > 1) { listBox1.Items.Remove(listBox1.SelectedItem); listBox1.Refresh(); string tmpFile = Path.GetDirectoryName(_config["PassDirectory"]) + "\\" + treeView1.SelectedNode.FullPath + "\\.gpg-id"; File.Delete(tmpFile); using (StreamWriter w = new StreamWriter(tmpFile)) { foreach (var line in listBox1.Items) { w.WriteLine(line.ToString()); } } using (var repo = new Repository(_config["PassDirectory"])) { repo.Stage(tmpFile); repo.Commit("gpgid changed", new Signature("pass4win", "pass4win", DateTimeOffset.Now), new Signature("pass4win", "pass4win", DateTimeOffset.Now)); } } DirectoryInfo path = new DirectoryInfo(Path.GetDirectoryName(_config["PassDirectory"]) + "\\" + treeView1.SelectedNode.FullPath); foreach (var ffile in path.GetFiles().Where(ffile => !ffile.Name.StartsWith("."))) { this.Recrypt(ffile.FullName); } ScanDirectory(path); }
public ObjectId ProcessContent(String content, String loc, String fileName, String comments) { StringBuilder objectPath = new StringBuilder(); objectPath.Append(String.Format(@"{0}{1}{2}", dir, loc, fileName)); //GitHub GUID ObjectId blobId = null; //Save the data to the github repo. FileInfo fi = new FileInfo(objectPath.ToString()); if (fi.Exists) { using (var repo = new Repository(dir)) { // CREATE a new file string docPath = Path.Combine(repo.Info.WorkingDirectory, loc, fileName); File.WriteAllText(docPath, content.ToString(), Encoding.ASCII); repo.Index.Stage(docPath); Signature who = new Signature("James Davis", "*****@*****.**", new DateTimeOffset(System.DateTime.Now)); //This is a test helper that returns a dummy signature Commit commit = repo.Commit(comments, who, who, false); blobId = commit.Tree[loc + fileName].Target.Id; //For future usage below } } else { using (var repo = new Repository(dir)) { // CREATE a new file string docPath = Path.Combine(repo.Info.WorkingDirectory, loc, fileName); File.WriteAllText(docPath, content.ToString(), Encoding.ASCII); repo.Index.Stage(docPath); Signature who = new Signature("James Davis", "*****@*****.**", new DateTimeOffset(System.DateTime.Now)); //This is a test helper that returns a dummy signature Commit commit = repo.Commit(comments, who, who, false); blobId = commit.Tree[loc + fileName].Target.Id; //For future usage below } } return blobId; }
private void deleteToolStripMenuItem_Click(object sender, EventArgs e) { // remove from git using (var repo = new Repository(Properties.Settings.Default.PassDirectory)) { // remove the file repo.Remove(dataPass.Rows[dataPass.CurrentCell.RowIndex].Cells[0].Value.ToString()); // Commit repo.Commit("password removed", new Signature("pass4win", "pass4win", System.DateTimeOffset.Now), new Signature("pass4win", "pass4win", System.DateTimeOffset.Now)); // push var remote = repo.Network.Remotes["origin"]; var options = new PushOptions(); options.CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials { Username = GitUsername, Password = GitPassword }; var pushRefSpec = @"refs/heads/master"; repo.Network.Push(remote, pushRefSpec, options, new Signature("pass4win", "*****@*****.**", DateTimeOffset.Now), "pushed changes"); } ResetDatagrid(); }
public frmMain() { InitializeComponent(); // Checking for appsettings // Do we have a valid password store if (Properties.Settings.Default.PassDirectory == "firstrun") { if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) { Properties.Settings.Default.PassDirectory = folderBrowserDialog1.SelectedPath; } else { MessageBox.Show("We need a place to store stuff. Restart the program and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); System.Environment.Exit(1); } } // GPG exe location if (Properties.Settings.Default.GPGEXE == "firstrun") { if (openFileDialog1.ShowDialog() == DialogResult.OK) { Properties.Settings.Default.GPGEXE = openFileDialog1.FileName; } else { MessageBox.Show("We really need GPG2.exe. Restart the program and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); System.Environment.Exit(1); } } //checking git status if (!Repository.IsValid(Properties.Settings.Default.PassDirectory)) { string value = ""; // Do we have a remote if (InputBox.Show("Enter the remote git repo or blank for no remote", "Remote Git (HTTPS):", ref value) == DialogResult.OK) { Properties.Settings.Default.GitRemote = value; if (Properties.Settings.Default.GitRemote != "") { // Get username and password value = ""; if (InputBox.Show("Username", "Remote Username:"******""; if (InputBox.Show("Password", "Remote Password:"******"Couldn't connect to remote git repository. Restart the program and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); System.Environment.Exit(1); } // save encrypted version of user and pass for git Properties.Settings.Default.GitUser = EncryptConfig(GitUsername, "pass4win"); Properties.Settings.Default.GitPass = EncryptConfig(GitPassword, "pass4win"); } } } } // Checking if the remote is cloned succesfull if (!Repository.IsValid(Properties.Settings.Default.PassDirectory)) { // creating new Git Repository.Init(Properties.Settings.Default.PassDirectory); Properties.Settings.Default.GitUser = EncryptConfig("RandomGarbage", "pass4win"); Properties.Settings.Default.GitPass = EncryptConfig("RandomGarbage", "pass4win"); } } else { // so we have a repository let's load the user/pass if (Properties.Settings.Default.GitUser != "") { GitUsername = DecryptConfig(Properties.Settings.Default.GitUser, "pass4win"); GitPassword = DecryptConfig(Properties.Settings.Default.GitPass, "pass4win"); } else { string value = ""; if (InputBox.Show("Username", "Remote Username:"******""; if (InputBox.Show("Password", "Remote Password:"******"We really need a username. Restart the program and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); System.Environment.Exit(1); } if (GitPassword == null) { MessageBox.Show("We really need a password. Restart the program and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); System.Environment.Exit(1); } Properties.Settings.Default.GitUser = EncryptConfig(GitUsername, "pass4win"); Properties.Settings.Default.GitPass = EncryptConfig(GitPassword, "pass4win"); } // Check if we have the latest using (var repo = new Repository(Properties.Settings.Default.PassDirectory)) { Signature Signature = new Signature("pass4win","*****@*****.**", new DateTimeOffset(2011, 06, 16, 10, 58, 27, TimeSpan.FromHours(2))); FetchOptions fetchOptions = new FetchOptions(); fetchOptions.CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials { Username = GitUsername, Password = GitPassword }; MergeOptions mergeOptions = new MergeOptions(); PullOptions pullOptions = new PullOptions(); pullOptions.FetchOptions = fetchOptions; pullOptions.MergeOptions = mergeOptions; MergeResult mergeResult = repo.Network.Pull(Signature, pullOptions); } } // Init GPG if needed string gpgfile = Properties.Settings.Default.PassDirectory; gpgfile += "\\.gpg-id"; // Check if we need to init the directory if (!File.Exists(gpgfile)) { Directory.CreateDirectory(Path.GetDirectoryName(gpgfile)); KeySelect newKeySelect = new KeySelect(); if (newKeySelect.ShowDialog() == DialogResult.OK) { using (StreamWriter w = new StreamWriter(gpgfile)) { w.Write(newKeySelect.gpgkey); } using (var repo = new Repository(Properties.Settings.Default.PassDirectory)) { repo.Stage(gpgfile); repo.Commit("gpgid added", new Signature("pass4win", "pass4win", System.DateTimeOffset.Now), new Signature("pass4win", "pass4win", System.DateTimeOffset.Now)); } } else { MessageBox.Show("Need key...... Restart the program and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); System.Environment.Exit(1); } } // Setting the exe location for the GPG Dll GpgInterface.ExePath = Properties.Settings.Default.GPGEXE; // saving settings Properties.Settings.Default.Save(); // Setting up datagrid dt.Columns.Add("colPath", typeof(string)); dt.Columns.Add("colText", typeof(string)); ListDirectory(new DirectoryInfo(Properties.Settings.Default.PassDirectory), ""); dataPass.DataSource = dt.DefaultView; dataPass.Columns[0].Visible=false; }
private void renameToolStripMenuItem_Click(object sender, EventArgs e) { // rename the entry InputBoxValidation validation = delegate(string val) { if (val == "") return "Value cannot be empty."; if (new Regex(@"[a-zA-Z0-9-\\_]+/g").IsMatch(val)) return "Not a valid name, can only use characters or numbers and - \\."; if (File.Exists(Properties.Settings.Default.PassDirectory + "\\" + @val + ".gpg")) return "Entry already exists."; return ""; }; string value = dataPass.Rows[dataPass.CurrentCell.RowIndex].Cells[1].Value.ToString(); if (InputBox.Show("Enter a new name", "Name:", ref value, validation) == DialogResult.OK) { // parse path string tmpPath = Properties.Settings.Default.PassDirectory + "\\" + @value + ".gpg"; Directory.CreateDirectory(Path.GetDirectoryName(tmpPath)); File.Copy(dataPass.Rows[dataPass.CurrentCell.RowIndex].Cells[0].Value.ToString(), tmpPath); using (var repo = new Repository(Properties.Settings.Default.PassDirectory)) { // add the file repo.Remove(dataPass.Rows[dataPass.CurrentCell.RowIndex].Cells[0].Value.ToString()); repo.Stage(tmpPath); // Commit repo.Commit("password moved", new Signature("pass4win", "pass4win", System.DateTimeOffset.Now), new Signature("pass4win", "pass4win", System.DateTimeOffset.Now)); //push var remote = repo.Network.Remotes["origin"]; var options = new PushOptions(); options.CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials { Username = GitUsername, Password = GitPassword }; var pushRefSpec = @"refs/heads/master"; repo.Network.Push(remote, pushRefSpec, options, new Signature("pass4win", "*****@*****.**", DateTimeOffset.Now), "pushed changes"); } ResetDatagrid(); } }
public IActionResult GetAQuoteViaGit(QuoteViewModel model) { var watch = Stopwatch.StartNew(); string rootedPath = Repository.Init("C:\\temp\\rooted\\path"); string jsondata = new JavaScriptSerializer().Serialize(model); using (var repo = new Repository("C:\\temp\\rooted\\path")) { // Write content to file system System.IO.File.WriteAllText(System.IO.Path.Combine(repo.Info.WorkingDirectory, "output.json"), jsondata); // Stage the file repo.Stage("output.json"); // Create the committer's signature and commit Signature author = new Signature(model.FirstName, model.Email, DateTime.Now); Signature committer = author; // Commit to the repository try { Commit commit = repo.Commit("Quote committed", author, committer); watch.Stop(); var elapsedMs = watch.ElapsedMilliseconds; if (ModelState.IsValid) { ViewBag.Message = "Quote number is: " + commit.Id + " Time taken: " + elapsedMs + "ms"; } } catch(Exception ex) { ViewBag.Message = "Nothing to commit"; } } return View(); }
/// <summary> /// Inits the repo, gpg etc /// </summary> public FrmMain() { InitializeComponent(); toolStripStatusLabel1.Text = ""; // ReSharper disable once UnusedVariable var bugsnag = new BaseClient("23814316a6ecfe8ff344b6a467f07171"); this.enableTray = false; // Getting actual version var assembly = Assembly.GetExecutingAssembly(); var fvi = FileVersionInfo.GetVersionInfo(assembly.Location); var version = fvi.FileVersion; Cfg["version"] = version.Remove(5, 2); Text = @"Pass4Win " + Strings.Version + @" " + Cfg["version"]; // checking for update this an async operation #pragma warning disable 4014 LatestPass4WinRelease(); #pragma warning restore 4014 // Do we have a valid password store and settings try { if (Cfg["PassDirectory"] == "") { // this will fail, I know ugly hack } } catch (Exception) { Cfg["FirstRun"] = true; var config = new FrmConfig(); config.ShowDialog(); } //checking git status if (!IsValid(Cfg["PassDirectory"])) { // Remote or generate a new one if (Cfg["UseGitRemote"] == true) { // check if server is alive if (IsGitAlive(Cfg["UseGitRemote"]) || IsHttpsAlive(Cfg["UseGitRemote"])) { // clone the repo and catch any error try { Clone(Cfg["GitRemote"], Cfg["PassDirectory"], new CloneOptions { CredentialsProvider = (url, user, cred) => new UsernamePasswordCredentials { Username = Cfg["GitUser"], Password = DecryptConfig(Cfg["GitPass"], "pass4win") } }); } catch (Exception) { MessageBox.Show(Strings.Error_connection, Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Error); this.toolStripOffline.Visible = true; } } else { MessageBox.Show(Strings.Error_git_unreachable, Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Error); toolStripOffline.Visible = true; } } else { // creating new Git Repository.Init(Cfg["PassDirectory"], false); toolStripOffline.Visible = true; } } else { // Do we do remote or not CheckOnline(true); } // Making sure core.autocrlf = true using (var repo = new Repository(Cfg["PassDirectory"])) { repo.Config.Set("core.autocrlf", true); } // Init GPG if needed string gpgfile = Cfg["PassDirectory"]; gpgfile += "\\.gpg-id"; // Check if we need to init the directory if (!File.Exists(gpgfile)) { // ReSharper disable once AssignNullToNotNullAttribute Directory.CreateDirectory(Path.GetDirectoryName(gpgfile)); var newKeySelect = new KeySelect(); if (newKeySelect.ShowDialog() == DialogResult.OK) { using (var w = new StreamWriter(gpgfile)) { w.Write(newKeySelect.Gpgkey); } using (var repo = new Repository(Cfg["PassDirectory"])) { repo.Stage(gpgfile); repo.Commit("gpgid added", new Signature("pass4win", "pass4win", DateTimeOffset.Now), new Signature("pass4win", "pass4win", DateTimeOffset.Now)); } } else { newKeySelect.Close(); MessageBox.Show(Strings.Error_nokey, Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Error); Environment.Exit(1); } } // Setting the exe location for the GPG Dll GpgInterface.ExePath = Cfg["GPGEXE"]; // init FileSystemInterface class fsi = new FileSystemInterface(Cfg["PassDirectory"]); // Fill tree CreateNodes(); this.enableTray = true; }
/// <summary> /// Delete an entry /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void DeleteToolStripMenuItemClick(object sender, EventArgs e) { // remove from git using (var repo = new Repository(Cfg["PassDirectory"])) { // remove the file repo.Remove(dirTreeView.SelectedNode.Tag + "\\" + listFileView.SelectedItem + ".gpg"); // Commit repo.Commit("password removed", new Signature("pass4win", "pass4win", DateTimeOffset.Now), new Signature("pass4win", "pass4win", DateTimeOffset.Now)); if (Cfg["UseGitRemote"] == true && this.gitRepoOffline == false) { // push toolStripOffline.Visible = false; var remote = repo.Network.Remotes["origin"]; var options = new PushOptions { CredentialsProvider = (url, user, cred) => new UsernamePasswordCredentials { Username = Cfg["GitUser"], Password = DecryptConfig(Cfg["GitPass"], "pass4win") } }; var pushRefSpec = @"refs/heads/master"; repo.Network.Push(remote, pushRefSpec, options); } } this.CreateNodes(); }
public void RepoManager() { using (var repo = new Repository(dir)) { // CREATE a new file const string oldName = "polite.txt"; string oldPath = Path.Combine(repo.Info.WorkingDirectory, oldName); File.WriteAllText(oldPath, "hello test file\n", Encoding.ASCII); repo.Index.Stage(oldName); Signature who = new Signature("James Davis", "*****@*****.**", new DateTimeOffset(System.DateTime.Now)); //This is a test helper that returns a dummy signature repo.Commit("Initial Commit", who, who, false); // RENAME a file const string newName = "being.frakking.polite.txt"; string newPath = Path.Combine(repo.Info.WorkingDirectory, newName); repo.Index.Unstage(oldName); File.Move(oldPath, newPath); repo.Index.Stage(newName); //who = who.TimeShift(TimeSpan.FromMinutes(1)); //Also a test helper extension method Commit commit = repo.Commit("Fix file name", who, who); ObjectId blobId = commit.Tree[newName].Target.Id; //For future usage below // UPDATE a file File.AppendAllText(newPath, "Hey! I said 'hello'. Why don't you answer me\n", Encoding.ASCII); repo.Index.Stage(newName); //who = who.TimeShift(TimeSpan.FromMinutes(1)); repo.Commit("Update the content", who, who); // DELETE a file repo.Index.Unstage(newName); //who = who.TimeShift(TimeSpan.FromMinutes(2)); repo.Commit("Remove the file as it's not that polite", who, who); // RETRIEVE a specific version of a file Blob file = repo.Lookup<Blob>(blobId); } }
private static object PushReleasesToGithub(Options options, Version newVersion) { using (Repository repo = new Repository(options.LocalRepo)) { RepositoryStatus st = repo.RetrieveStatus(); List<string> toCommit = st.Untracked.Concat(st.Modified).Select(x => x.FilePath).Where(f => f.Contains("Releases")).ToList(); if (toCommit.Any()) { repo.Stage(toCommit); RepositoryStatus st2 = repo.RetrieveStatus(); Commit commit = repo.Commit("Release v." + newVersion); } } bool pushed = RunProcess("git", "push origin master", options.LocalRepo); return null; }
// Callback for the encrypt thread public void Encrypt_Callback(GpgInterfaceResult result, string tmpFile, string tmpFile2, string path) { if (result.Status == GpgInterfaceStatus.Success) { File.Delete(tmpFile); File.Delete(path); File.Move(tmpFile2, path); // add to git using (var repo = new Repository(Properties.Settings.Default.PassDirectory)) { // Stage the file repo.Stage(path); // Commit repo.Commit("password changes", new Signature("pass4win", "pass4win", System.DateTimeOffset.Now), new Signature("pass4win", "pass4win", System.DateTimeOffset.Now)); var remote = repo.Network.Remotes["origin"]; var options = new PushOptions(); options.CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials { Username = GitUsername, Password = GitPassword }; var pushRefSpec = @"refs/heads/master"; repo.Network.Push(remote, pushRefSpec, options, new Signature("pass4win", "*****@*****.**", DateTimeOffset.Now), "pushed changes"); } } else { MessageBox.Show("You shouldn't see this.... Awkward right... Encryption failed", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public bool Commit(string message, string authorName, string emailAddress) { using (var repo = new LibGit2Sharp.Repository(RepositoryPath)) { var changes = repo.RetrieveStatus(new StatusOptions { DetectRenamesInIndex = false, DetectRenamesInWorkDir = false }).Select(c => c.FilePath); if (!changes.Any()) { return false; } repo.Stage(changes); if (string.IsNullOrWhiteSpace(authorName) || string.IsNullOrWhiteSpace(emailAddress)) { repo.Commit(message); } else { repo.Commit(message, new Signature(authorName, emailAddress, DateTimeOffset.UtcNow)); } return true; } }
/// <summary> /// Callback for the encrypt thread /// </summary> /// <param name="result"></param> /// <param name="tmpFile"></param> /// <param name="tmpFile2"></param> /// <param name="path"></param> public void EncryptCallback(GpgInterfaceResult result, string tmpFile, string tmpFile2, string path) { if (result.Status == GpgInterfaceStatus.Success) { File.Delete(tmpFile); File.Delete(path); File.Move(tmpFile2, path); // add to git using (var repo = new Repository(Cfg["PassDirectory"])) { // Stage the file repo.Stage(path); // Commit repo.Commit("password changes", new Signature("pass4win", "pass4win", DateTimeOffset.Now), new Signature("pass4win", "pass4win", DateTimeOffset.Now)); if (Cfg["UseGitRemote"] == true && this.gitRepoOffline == false) { toolStripOffline.Visible = false; var remote = repo.Network.Remotes["origin"]; var options = new PushOptions { CredentialsProvider = (url, user, cred) => new UsernamePasswordCredentials { Username = Cfg["GitUser"], Password = DecryptConfig(Cfg["GitPass"], "pass4win") } }; var pushRefSpec = @"refs/heads/master"; repo.Network.Push(remote, pushRefSpec, options); } } } else { MessageBox.Show(Strings.Error_weird_shit_happened_encryption, Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public GitBackupStatus InPlaceGitBackup(string repositoryFolder) { var isValidGitRepository = LibGit2Sharp.Repository.IsValid(repositoryFolder); var createdRepository = false; if (!isValidGitRepository) { _logger.InfoFormat("Initializing git repository in folder '{0}'...", repositoryFolder); repositoryFolder = LibGit2Sharp.Repository.Init(repositoryFolder, false); createdRepository = true; } var numberOfFilesAdded = 0; var numberOfFilesChanged = 0; var numberOfFilesRemoved = 0; using (var repository = new LibGit2Sharp.Repository(repositoryFolder)) { var options = new StatusOptions(); var status = repository.RetrieveStatus(options); _logger.Debug("Repository Status: " + JsonConvert.SerializeObject(status)); if (status.IsDirty) { var untractedFiles = status.Untracked; foreach (var untrackedFile in untractedFiles) { _logger.Info("Added: " + untrackedFile.FilePath); var stageOptions = new StageOptions(); repository.Stage(untrackedFile.FilePath, stageOptions); numberOfFilesAdded++; } var modifiedFiles = status.Modified; foreach (var modifiedFile in modifiedFiles) { _logger.Info("Modified: " + modifiedFile.FilePath); var stageOptions = new StageOptions(); repository.Stage(modifiedFile.FilePath, stageOptions); numberOfFilesChanged++; } var removedFiles = status.Missing; foreach (var removedFile in removedFiles) { _logger.Info("Removed: " + removedFile.FilePath); var stageOptions = new StageOptions(); repository.Stage(removedFile.FilePath, stageOptions); numberOfFilesRemoved++; } var author = new Signature(Environment.UserName, "*****@*****.**", System.DateTimeOffset.Now); var committer = new Signature(Environment.UserName, "*****@*****.**", System.DateTimeOffset.Now); var commitOptions = new CommitOptions(); _logger.Info("Commiting..."); repository.Commit(DateTime.Now.ToString(CultureInfo.InvariantCulture), author, committer, commitOptions); } } var gitBackupStatus = new GitBackupStatus(createdRepository, numberOfFilesAdded, numberOfFilesChanged, numberOfFilesRemoved); return gitBackupStatus; }