コード例 #1
0
 public void Delete(string[] files, bool force)
 {
     Debug("SVN: Delete(" + string.Join(",", files) + ", " + force + ")");
     BeforeWriteOperation("delete");
     try {
         client.Delete(
             files,
             new SvnDeleteArgs {
             Force = force
         });
     } catch (SvnException ex) {
         throw new SvnClientException(ex);
     } finally {
         AfterOperation();
     }
 }
コード例 #2
0
ファイル: FsCopy.cs プロジェクト: modulexcite/svn2svn
        public void Sync()
        {
            _svnAdd    = new List <FileSystemInfo>();
            _svnDelete = new List <FileSystemInfo>();

            FolderSync sync = new FolderSync(_args.Source, _args.Destination, FileActions.Ask, FileActions.Ask, FileActions.Ask);

            sync.AskWhatToDo += new AskWhatToDoDelegate(sync_AskWhatToDo);
            sync.ErrorEvent  += new ErrorDelegate(sync_ErrorEvent);
            sync.Sync();

            Console.WriteLine("Applying {0} svn delete changes ...", _svnDelete.Count);
            foreach (FileSystemInfo si in _svnDelete)
            {
                Console.WriteLine(" D {0}", si.FullName);
                if (!_args.simulationOnly)
                {
                    SvnDeleteArgs svnDeleteArgs = new SvnDeleteArgs();
                    svnDeleteArgs.ThrowOnError = true;
                    svnDeleteArgs.Force        = true;
                    _client.Delete(si.FullName, svnDeleteArgs);
                }
            }

            Console.WriteLine("Applying {0} svn add changes ...", _svnAdd.Count);
            foreach (FileSystemInfo si in _svnAdd)
            {
                Console.WriteLine(" A {0}", si.FullName);

                if (!_args.simulationOnly)
                {
                    SvnAddArgs svnAddArgs = new SvnAddArgs();
                    svnAddArgs.ThrowOnError = true;
                    svnAddArgs.Depth        = SvnDepth.Empty;
                    _client.Add(si.FullName, svnAddArgs);
                }
            }
        }
コード例 #3
0
        public void StageAll()
        {
            using (SvnClient client = new SvnClient())
            {
                Collection <SvnStatusEventArgs> changedFiles = new Collection <SvnStatusEventArgs>();

                client.GetStatus(this.repoPath, out changedFiles);

                SvnAddArgs aa = new SvnAddArgs();
                aa.Depth    = SvnDepth.Infinity;
                aa.Force    = true;
                aa.NoIgnore = true;

                aa.Progress += this.OnProgress;
                aa.SvnError += this.OnSvnError;
                aa.Notify   += this.OnNotify;

                SvnDeleteArgs dd = new SvnDeleteArgs();
                dd.Force     = true;
                dd.Progress += this.OnProgress;
                dd.SvnError += this.OnSvnError;
                dd.Notify   += this.OnNotify;

                foreach (SvnStatusEventArgs changedFile in changedFiles)
                {
                    if (changedFile.LocalContentStatus == SvnStatus.Missing)
                    {
                        client.Delete(changedFile.Path, dd);
                    }
                    if (changedFile.LocalContentStatus == SvnStatus.NotVersioned)
                    {
                        client.Add(changedFile.Path, aa);
                    }
                }

                client.Add(this.repoPath, aa);
            }
        }
コード例 #4
0
        //处理有问题的文件
        public void QuestionFile(string path)
        {
            // string path = "D:\\Test";
            //SvnClient client = new SvnClient();
            SvnStatusArgs sa = new SvnStatusArgs();
            Collection <SvnStatusEventArgs> status;

            _client.GetStatus(path, sa, out status);
            foreach (var item in status)
            {
                string fPath = item.FullPath;
                if (item.LocalContentStatus != item.RemoteContentStatus)
                {
                    //被修改了的文件
                }
                if (!item.Versioned)
                {
                    //新增文件
                    _client.Add(fPath);
                }
                else if (item.Conflicted)
                {
                    //将冲突的文件用工作文件解决冲突
                    _client.Resolve(fPath, SvnAccept.Working);
                }
                else if (item.IsRemoteUpdated)
                {
                    //更新来自远程的新文件
                    _client.Update(fPath);
                }
                else if (item.LocalContentStatus == SvnStatus.Missing)
                {
                    //删除丢失的文件
                    _client.Delete(fPath);
                }
            }
        }
コード例 #5
0
ファイル: SvnCopy.cs プロジェクト: modulexcite/svn2svn
        public void Copy()
        {
            long lastSyncRevision = 0;

            if (_args.Incremental)
            {
                SvnLogParser logParser = new SvnLogParser(_args.Destination);
                lastSyncRevision = logParser.GetLastSyncedRevisionFromDestination();
                Console.WriteLine("Last revision synched: {0}", lastSyncRevision);
            }

            Console.Write("Collecting svn log: ");

            if (_args.RevisionRange != null)
            {
                Console.Write("{0}:{1} ",
                              _args.RevisionRange.StartRevision,
                              _args.RevisionRange.EndRevision);
            }

            // fetch the source svn respository and
            SvnInfo sourceInfo = new SvnInfo(_args.Source);

            Console.WriteLine("Source SVN root: {0}", sourceInfo.Info.RepositoryRoot);
            Console.WriteLine("Source SVN uri: {0}", sourceInfo.Info.Uri);

            string sourceRelativePath = sourceInfo.Info.Uri.ToString().Remove(
                0, sourceInfo.Info.RepositoryRoot.ToString().Length - 1);

            Console.WriteLine("Relative path: {0}", sourceRelativePath);

            if (!string.IsNullOrEmpty(_args.Root))
            {
                sourceRelativePath = _args.Root;
                Console.WriteLine("Substituting relative path: {0}", sourceRelativePath);
            }

            SvnLogArgs logArgs = new SvnLogArgs();

            logArgs.StrictNodeHistory = _args.StopOnCopy;
            logArgs.ThrowOnError      = true;
            logArgs.Range             = _args.RevisionRange;

            logArgs.RetrieveChangedPaths = true;

            _client.Log(_args.Source, logArgs, new EventHandler <SvnLogEventArgs>(OnLog));
            Console.WriteLine();
            Console.WriteLine("Collected {0} revisions.", _revisions.Count);

            SvnTarget fromSvnTarget = SvnTarget.FromString(_args.Source);

            foreach (KeyValuePair <long, SvnLogEventArgs> revisionPair in _revisions)
            {
                SvnLogEventArgs revision = revisionPair.Value;

                if (_args.Incremental && lastSyncRevision != 0 && lastSyncRevision >= revision.Revision)
                {
                    Console.WriteLine("Skipping revision {0} ({1})", revision.Revision, revision.Time);
                    continue;
                }

                Console.WriteLine("Revision {0} ({1})", revision.Revision, revision.Time);

                if (_args.SimulationOnly)
                {
                    continue;
                }

                SvnExportArgs exportArgs = new SvnExportArgs();
                exportArgs.Overwrite    = true;
                exportArgs.ThrowOnError = true;
                exportArgs.Revision     = revision.Revision;

                SvnUpdateResult exportResult = null;
                _client.Export(fromSvnTarget, _args.Destination, exportArgs, out exportResult);

                if (revision.ChangedPaths == null)
                {
                    throw new Exception(string.Format("No changed paths in rev. {0}",
                                                      revision.Revision));
                }

                SortedList <string, SvnChangeItem> changeItems = new SortedList <string, SvnChangeItem>();

                foreach (SvnChangeItem changeItem in revision.ChangedPaths)
                {
                    changeItems.Add(changeItem.Path, changeItem);
                }

                List <string> filesAdd    = new List <string>();
                List <string> filesDelete = new List <string>();
                List <string> filesModify = new List <string>();

                // add files in forward order (add directories first)
                // delete files in reverse order (delete files first)
                foreach (SvnChangeItem changeItem in changeItems.Values)
                {
                    // anything above (outside) of the source path is ignored, we didn't export that
                    if (!changeItem.Path.StartsWith(sourceRelativePath))
                    {
                        Console.WriteLine("Skipping {0}. Did you need to specify /root:<path>?)", changeItem.Path);
                        continue;
                    }

                    string targetSvnPath = changeItem.Path.Remove(0, sourceRelativePath.Length);
                    string targetOSPath  = targetSvnPath.Replace("/", @"\");
                    string targetPath    = Path.Combine(_args.Destination, targetOSPath);
                    Console.WriteLine(" {0} {1}", changeItem.Action, changeItem.Path);
                    switch (changeItem.Action)
                    {
                    case SvnChangeAction.Add:
                    case SvnChangeAction.Replace:
                        filesAdd.Add(targetPath);
                        break;

                    case SvnChangeAction.Delete:
                        filesDelete.Insert(0, targetPath);
                        break;

                    case SvnChangeAction.Modify:
                        filesModify.Add(targetPath);
                        break;
                    }
                }

                Console.WriteLine("Applying changes @ rev. {0} ...", revision.Revision);

                foreach (string targetPath in filesModify)
                {
                    Console.WriteLine(" M {0}", targetPath);
                }

                foreach (string targetPath in filesAdd)
                {
                    if (!File.Exists(targetPath))
                    {
                        throw new Exception(string.Format("Added file '{0}' doesn't exist. Did you need to specify /root:<path>?",
                                                          targetPath));
                    }

                    Console.WriteLine(" A {0}", targetPath);
                    SvnAddArgs svnAddArgs = new SvnAddArgs();
                    svnAddArgs.ThrowOnError = true;
                    svnAddArgs.Depth        = SvnDepth.Empty;
                    _client.Add(targetPath, svnAddArgs);
                }

                foreach (string targetPath in filesDelete)
                {
                    Console.WriteLine(" D {0}", targetPath);
                    SvnDeleteArgs svnDeleteArgs = new SvnDeleteArgs();
                    svnDeleteArgs.ThrowOnError = true;
                    svnDeleteArgs.Force        = true;
                    _client.Delete(targetPath, svnDeleteArgs);
                }


                SvnCommitArgs commitArgs = new SvnCommitArgs();
                commitArgs.LogMessage  = revision.LogMessage;
                commitArgs.LogMessage += string.Format("\nCopied from {0}, rev. {1} by {2} @ {3} {4}",
                                                       sourceInfo.Info.Uri, revision.Revision, revision.Author, revision.Time.ToShortDateString(), revision.Time.ToShortTimeString());
                commitArgs.ThrowOnError = true;

                Console.WriteLine("Committing changes @ rev. {0} in {1}", revision.Revision, _args.Destination);
                Console.WriteLine("----------------------------------------------------------------------------");
                Console.WriteLine(commitArgs.LogMessage);
                Console.WriteLine("----------------------------------------------------------------------------");

                if (_args.Prompt)
                {
                    while (true)
                    {
                        Console.Write("Commit? [Y/N] ");
                        char k = Char.ToLower(Console.ReadKey().KeyChar);
                        Console.WriteLine();
                        if (k == 'y')
                        {
                            break;
                        }
                        if (k == 'n')
                        {
                            throw new Exception("Aborted by user.");
                        }
                    }
                }

                SvnCommitResult commitResult = null;
                _client.Commit(_args.Destination, commitArgs, out commitResult);
                if (commitResult != null)
                {
                    Console.WriteLine("Commited revision {0}.", commitResult.Revision);
                }
                else
                {
                    Console.WriteLine("There were no committable changes.");
                    Console.WriteLine("Subversion property changes are not supported.");
                }
            }
        }
コード例 #6
0
        public void DeleteTest()
        {
            SvnSandBox sbox = new SvnSandBox(this);

            sbox.Create(SandBoxRepository.Default);

            string WcPath = sbox.Wc;
            Uri    WcUri  = sbox.Uri;

            using (SvnClient client = NewSvnClient(true, false))
            {
                string local  = Path.Combine(WcPath, "LocalDeleteBase");
                string remote = Path.Combine(WcPath, "RemoteDeleteBase");

                TouchFile(local);
                client.Add(local);
                TouchFile(remote);
                client.Add(remote);

                SvnCommitResult ci;
                client.Commit(WcPath, out ci);

                Assert.That(ItemExists(new Uri(WcUri, "LocalDeleteBase")), Is.True, "Remote base does exist");
                Assert.That(ItemExists(new Uri(WcUri, "RemoteDeleteBase")), Is.True, "Local base does exist");

                client.Delete(local);
                client.RemoteDelete(new Uri(WcUri, "RemoteDeleteBase"));

                bool visited = false;
                int  n       = 0;
                client.Status(local, delegate(object sender, SvnStatusEventArgs e)
                {
                    Assert.That(n++, Is.EqualTo(0));
                    Assert.That(e.FullPath, Is.EqualTo(local));
                    Assert.That(e.LocalNodeStatus, Is.EqualTo(SvnStatus.Deleted));
                    Assert.That(e.Switched, Is.False);
                    Assert.That(e.NodeKind, Is.EqualTo(SvnNodeKind.File));
                    Assert.That(e.Uri, Is.EqualTo(new Uri(WcUri, "LocalDeleteBase")));
                    Assert.That(e.IsRemoteUpdated, Is.EqualTo(false));
                    Assert.That(e.LocalNodeStatus, Is.EqualTo(SvnStatus.Deleted));
                    Assert.That(e.LocalCopied, Is.EqualTo(false));
                    Assert.That(e.Wedged, Is.EqualTo(false));
                    Assert.That(e.LocalPropertyStatus, Is.EqualTo(SvnStatus.None));
                    Assert.That(e.Path, Is.EqualTo(local));
                    Assert.That(e.RemoteNodeStatus, Is.EqualTo(SvnStatus.None));
                    Assert.That(e.RemoteLock, Is.Null);
                    Assert.That(e.RemotePropertyStatus, Is.EqualTo(SvnStatus.None));
                    Assert.That(e.RemoteUpdateCommitAuthor, Is.Null);
                    Assert.That(e.RemoteUpdateCommitTime, Is.EqualTo(DateTime.MinValue));
                    Assert.That(e.RemoteUpdateNodeKind, Is.EqualTo(SvnNodeKind.None));
                    Assert.That(e.RemoteUpdateRevision, Is.EqualTo(-1L));
                    Assert.That(e.Switched, Is.EqualTo(false));

#pragma warning disable 0618
                    Assert.That(e.WorkingCopyInfo, Is.Not.Null);
                    Assert.That(e.WorkingCopyInfo.ChangeList, Is.Null);
                    Assert.That(e.WorkingCopyInfo.Checksum, Is.Not.Null);
                    Assert.That(e.WorkingCopyInfo.ConflictNewFile, Is.Null);
                    Assert.That(e.WorkingCopyInfo.ConflictOldFile, Is.Null);
                    Assert.That(e.WorkingCopyInfo.ConflictWorkFile, Is.Null);
                    Assert.That(e.WorkingCopyInfo.CopiedFrom, Is.Null);
                    Assert.That(e.WorkingCopyInfo.CopiedFromRevision, Is.EqualTo(-1L));
                    Assert.That(e.WorkingCopyInfo.Depth, Is.EqualTo(SvnDepth.Infinity));
                    Assert.That(e.WorkingCopyInfo.HasProperties, Is.False);
                    Assert.That(e.WorkingCopyInfo.HasPropertyChanges, Is.False);
                    Assert.That(e.WorkingCopyInfo.IsAbsent, Is.False);
                    Assert.That(e.WorkingCopyInfo.IsCopy, Is.False);
                    Assert.That(e.WorkingCopyInfo.IsDeleted, Is.False);
                    Assert.That(e.WorkingCopyInfo.IsIncomplete, Is.False);
                    Assert.That(e.WorkingCopyInfo.KeepLocal, Is.False);
                    Assert.That(e.WorkingCopyInfo.LastChangeAuthor, Is.EqualTo(Environment.UserName));
                    Assert.That(e.WorkingCopyInfo.LastChangeRevision, Is.EqualTo(ci.Revision));
                    Assert.That(e.WorkingCopyInfo.LastChangeTime, Is.GreaterThan(DateTime.UtcNow - new TimeSpan(0, 0, 45)));
                    Assert.That(e.WorkingCopyInfo.LockComment, Is.Null);
                    Assert.That(e.WorkingCopyInfo.LockOwner, Is.Null);
                    Assert.That(e.WorkingCopyInfo.LockTime, Is.EqualTo(DateTime.MinValue));
                    Assert.That(e.WorkingCopyInfo.LockToken, Is.Null);
                    Assert.That(e.WorkingCopyInfo.Name, Is.EqualTo("LocalDeleteBase"));
                    Assert.That(e.WorkingCopyInfo.NodeKind, Is.EqualTo(SvnNodeKind.File));
                    Assert.That(e.WorkingCopyInfo.PropertyRejectFile, Is.Null);
                    Assert.That(e.WorkingCopyInfo.RepositoryId, Is.Not.Null);
                    Assert.That(e.WorkingCopyInfo.RepositoryId, Is.Not.EqualTo(Guid.Empty));
                    Assert.That(e.WorkingCopyInfo.RepositoryUri, Is.EqualTo(sbox.RepositoryUri));
                    Assert.That(e.WorkingCopyInfo.Revision, Is.EqualTo(ci.Revision));
                    Assert.That(e.WorkingCopyInfo.Schedule, Is.EqualTo(SvnSchedule.Delete));
                    Assert.That(e.WorkingCopyInfo.Uri, Is.EqualTo(new Uri(WcUri, "LocalDeleteBase")));
#pragma warning restore 0618
                    visited = true;
                });
                Assert.That(visited, "Visited handler");

                client.Commit(WcPath);

                Assert.That(ItemExists(new Uri(WcUri, "LocalDeleteBase")), Is.False, "Remote base does not exist");
                Assert.That(ItemExists(new Uri(WcUri, "RemoteDeleteBase")), Is.False, "Local base does not exist");
            }
        }
コード例 #7
0
        public override void OnExecute(CommandEventArgs e)
        {
            List <SvnItem> toDelete = new List <SvnItem>(e.Selection.GetSelectedSvnItems(true));

            AnkhMessageBox mb = new AnkhMessageBox(e.Context);

            string body;

            // We do as if we are Visual Studio here: Same texts, same behavior (same chance on data loss)
            if (toDelete.Count == 1)
            {
                body = string.Format(CommandStrings.XWillBeDeletedPermanently, toDelete[0].Name);
            }
            else
            {
                body = CommandStrings.TheSelectedItemsWillBeDeletedPermanently;
            }

            if (DialogResult.OK != mb.Show(body, "", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation))
            {
                return; // No delete
            }
            int hr = VSErr.S_OK;

            foreach (SvnItem item in toDelete)
            {
                {
                    IVsUIHierarchy hier;
                    uint           id;
                    IVsWindowFrame frame;

                    if (VsShellUtilities.IsDocumentOpen(e.Context, item.FullPath, Guid.Empty, out hier, out id, out frame))
                    {
                        hr = frame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave);
                        if (!VSErr.Succeeded(hr))
                        {
                            break; // Show error and cancel further actions
                        }
                    }
                }

                try
                {
                    if (item.IsVersioned)
                    {
                        using (SvnClient cl = e.GetService <ISvnClientPool>().GetNoUIClient())
                        {
                            SvnDeleteArgs da = new SvnDeleteArgs();
                            da.Force = true;
                            cl.Delete(item.FullPath, da);
                        }
                    }
                    else
                    {
                        SvnItem.DeleteNode(item.FullPath);
                    }
                }
                finally
                {
                    // TODO: Notify the working copy explorer here!
                    // (Maybe via one of these methods below)

                    e.GetService <ISvnStatusCache>().MarkDirtyRecursive(item.FullPath);
                    e.GetService <IFileStatusMonitor>().ScheduleGlyphUpdate(item.FullPath);
                }

                // Ok, now remove the file from projects

                IProjectFileMapper pfm = e.GetService <IProjectFileMapper>();

                List <SccProject> projects = new List <SccProject>(pfm.GetAllProjectsContaining(item.FullPath));

                foreach (SccProject p in projects)
                {
                    IVsProject2 p2 = p.RawHandle as IVsProject2;

                    if (p2 == null)
                    {
                        continue;
                    }

                    VSDOCUMENTPRIORITY[] prio = new VSDOCUMENTPRIORITY[1];
                    int  found;
                    uint id;
                    if (!VSErr.Succeeded(p2.IsDocumentInProject(item.FullPath, out found, prio, out id)) || found == 0)
                    {
                        continue; // Probably already removed (mapping out of synch?)
                    }
                    hr = p2.RemoveItem(0, id, out found);

                    if (!VSErr.Succeeded(hr))
                    {
                        break;
                    }
                }
            }

            if (!VSErr.Succeeded(hr))
            {
                mb.Show(Marshal.GetExceptionForHR(hr).Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
コード例 #8
0
            public bool Commit()
            
    {
                    Console.WriteLine("开始检查是否需要提交新参数表...");

                    SvnCommitArgs ca = new SvnCommitArgs();
                    SvnStatusArgs sa = new SvnStatusArgs();
                    Collection <SvnStatusEventArgs> statuses;
                    SC.GetStatus(GetAppLoc(), sa, out statuses);

                    int i = 0;

                    foreach(var item in statuses)
                    
        {
                            if (item.LocalContentStatus != item.RemoteContentStatus)
            {
                                {
                                        i++;
                                      
                }
            }
                            if (!item.Versioned)
            {
                                {
                                        SC.Add(item.FullPath);

                                        Console.WriteLine("新增加文件" + item.FullPath);

                                        i++;
                                      
                }
            }
                            else if (item.Conflicted)
            {
                                {
                                        SC.Resolve(item.FullPath, SvnAccept.Working);

                                        Console.WriteLine("处理冲突文件" + item.FullPath);

                                   
                }
            }
                            else if (item.IsRemoteUpdated)
            {
                                {
                                        SC.Update(item.FullPath);

                                        Console.WriteLine("处理冲突文件" + item.FullPath);

                                   
                }
            }
                            else if (item.LocalContentStatus == SvnStatus.Missing)
            {
                                {
                                        SC.Delete(item.FullPath);

                                        Console.WriteLine("处理丢失文件" + item.FullPath);

                                        i++;
                                      
                }
            }
                        
        }

                    if(i > 0)
                    
        {
                            ca.LogMessage = "";
                            SvnCommitResult scr;
                            if (SC.Commit(GetAppLoc(), ca, out scr))
            {
                                {
                                        Console.WriteLine("提交完成");

                                   
                }
            }
                            else
            {
                                {
                                        Console.WriteLine("提交失败");

                                   
                }
            }
                        
        }

                    else
                     {
                            Console.WriteLine("无变化,无需检查");

                        
        }


                    return true;
                
    }
コード例 #9
0
ファイル: SvnUtils.cs プロジェクト: alzuabi/WindowsFormsApp1
        public static void CompleteSync(Parameters parameters)
        {
            using (var client = new SvnClient())
            {
                client.Progress += new EventHandler <SvnProgressEventArgs>(Client_Progress);
                SetUpClient(parameters, client);

                if (parameters.UpdateBeforeCompleteSync)
                {
                    DebugMessage(parameters, "Updating");
                    client.Update(parameters.Path);
                    DebugMessage(parameters, "Done");
                }

                Collection <SvnStatusEventArgs> changedFiles;
                DebugMessage(parameters, "Getting status");
                client.GetStatus(parameters.Path, out changedFiles);
                DebugMessage(parameters, "Done");
                if (changedFiles.Count == 0)
                {
                    Console.WriteLine("No changes to commit.");
                    return;
                }

                //delete files from subversion that are not in filesystem
                //add files to subversion that are new in filesystem
                //modified files are automatically included as part of the commit

                //TODO: check remoteStatus
                DebugMessage(parameters, "Recording changes");
                foreach (var changedFile in changedFiles)
                {
                    if (changedFile.LocalContentStatus == SvnStatus.Missing)
                    {
                        // SVN thinks file is missing but it still exists hence
                        // a change in the case of the filename.
                        if (File.Exists(changedFile.Path))
                        {
                            var changedArgs = new SvnDeleteArgs {
                                KeepLocal = true
                            };
                            client.Delete(changedFile.Path, changedArgs);
                        }
                        else
                        {
                            client.Delete(changedFile.Path);
                        }
                    }
                    if (changedFile.LocalContentStatus == SvnStatus.NotVersioned)
                    {
                        client.Add(changedFile.Path);
                    }
                }
                DebugMessage(parameters, "Done");

                var ca = new SvnCommitArgs {
                    LogMessage = parameters.Message
                };
                SvnCommitResult result;
                DebugMessage(parameters, "Committing");
                if (client.Commit(parameters.Path, ca, out result))
                {
                    DebugMessage(parameters, "Done");
                    if (result == null)
                    {
                        Console.WriteLine("No result returned from commit.");
                        return;
                    }
                    if (!string.IsNullOrEmpty(result.PostCommitError))
                    {
                        Console.WriteLine("Post-commit hook error: " + result.PostCommitError);
                        return;
                    }
                    Console.WriteLine("Committed r" + result.Revision);
                }
                else
                {
                    if (result != null && !string.IsNullOrEmpty(result.PostCommitError))
                    {
                        Console.WriteLine("Post-commit hook error after failed commit: " + result.PostCommitError);
                        return;
                    }
                    Console.WriteLine("Commit failed.");
                }
            }
        }
コード例 #10
0
ファイル: Program.cs プロジェクト: tapika/RepositorySync
    void Main2(String[] args)
    {
        //  from where                                      to where
        urls    = new[] { "https://svn.code.sf.net/p/syncproj/code/", "https://github.com/tapika/syncProj.git/trunk" };
        workDir = new[] { @"d:\Prototyping\svnSource", @"d:\Prototyping\svnTarget" };
        Uri[] uris = new Uri[2];

        for (int i = 0; i < urls.Length; i++)
        {
            uris[i] = new Uri(urls[i]);

            if (!Directory.Exists(workDir[i]))
            {
                if (i == 0)
                {
                    svn.CheckOut(uris[i], workDir[i], new SvnCheckOutArgs()
                    {
                        Revision = new SvnRevision(i)
                    });
                }
                else
                {
                    svn.CheckOut(uris[i], workDir[i]);
                }
            }
        }

        SvnInfoEventArgs info;

        svn.GetInfo(uris[0], out info);

        SvnLogArgs svnArgs = new SvnLogArgs {
            Start = 1 /*change next svn revision number*/, End = info.Revision, RetrieveAllProperties = true
        };
        Collection <SvnLogEventArgs> list;

        svn.GetLog(uris[0], svnArgs, out list);


        foreach (SvnLogEventArgs log in list)
        {
            long   rev = log.Revision;
            String msg = log.LogMessage;
            Console.WriteLine("Commit " + rev + ": " + msg);

            svn.Update(workDir[0], new SvnUpdateArgs()
            {
                Revision = new SvnRevision(rev)
            });

            foreach (SvnChangeItem chItem in log.ChangedPaths)
            {
                String path = chItem.Path;

                switch (chItem.Action)
                {
                case SvnChangeAction.Add:
                    if (chItem.NodeKind == SvnNodeKind.Directory)
                    {
                        try { svn.CreateDirectory(workDir[1] + path); } catch { }
                    }
                    else
                    {
                        File.Copy(workDir[0] + path, workDir[1] + path, true);
                        try { svn.Add(workDir[1] + path); } catch { }
                    }
                    break;

                case SvnChangeAction.Replace:
                case SvnChangeAction.Delete:
                    if (chItem.NodeKind == SvnNodeKind.Directory)
                    {
                        svn.Delete(workDir[1] + path);
                    }
                    else
                    {
                        File.Delete(workDir[1] + path);
                        svn.Delete(workDir[1] + path);
                    }
                    break;

                case SvnChangeAction.Modify:
                    if (chItem.NodeKind == SvnNodeKind.Directory)
                    {
                        Collection <SvnPropertyListEventArgs> propList = null;
                        svn.GetPropertyList(new SvnPathTarget(workDir[0] + path), out propList);

                        foreach (SvnPropertyListEventArgs p in propList)
                        {
                            foreach (SvnPropertyValue pv in p.Properties)
                            {
                                svn.SetProperty(workDir[1] + path, pv.Key, pv.StringValue);
                            }
                        }
                    }
                    else
                    {
                        File.Copy(workDir[0] + path, workDir[1] + path, true);
                    }
                    break;
                }
            }
            svn.Commit(workDir[1], new SvnCommitArgs()
            {
                LogMessage = msg
            });
        }
    }
コード例 #11
0
        private static void GetAndAddRevision(VssRevProps properties, Dictionary <string, VssFileVersion> files,
                                              SvnClient svnClient)
        {
            string dir      = Path.Combine(repoDIR, vssPROJ.Substring(2).Replace("/", "\\"));
            string filePath = string.Empty;
            var    delkeys  = new List <string>();

            foreach (string key in files.Keys)
            {
                try
                {
                    //take care of the rare case of an item both file and label
                    if (!String.IsNullOrEmpty(files[key].Version.Label))
                    {
                        if (files[key].Version.VSSItem.Type != 0)
                        {
                            GetFileVersion(files[key].Version.VSSItem, files[key].Version, svnClient);
                            var commitArgs = new SvnCommitArgs {
                                LogMessage = properties.Comment
                            };
                            svnClient.Commit(dir, commitArgs);

                            filePath =
                                Path.Combine(
                                    Path.GetDirectoryName(
                                        string.Format("{0}{1}", repoDIR, files[key].Spec.Substring(1)).Replace("/", "\\")),
                                    files[key].Version.VSSItem.Name);

                            var uri = new Uri(string.Format("{0}{1}", svnURL, svnPROJ));
                            //svnClient.GetInfo(SvnTarget.FromString(filePath), out infoEventArgs);
                            CounterfeitRevProps(svnClient, SvnTarget.FromUri(uri), files[key].Version);
                        }

                        TagSourceUrl = String.Empty;
                        var tag = new Tag
                        {
                            fromUrlString = GenerateSourceUrl(files[key].Version.VSSItem),
                            tagString     = String.Format("{0}/{1}/{2}_{3}",
                                                          svnURL,
                                                          svnTAG,
                                                          files[key].Version.VSSItem.Name,
                                                          sanitizeLabel(files[key].Version.Label)),
                            label = files[key].Version.Label
                        };
                        ApplyTag(files[key].Version.VSSItem, svnClient, files[key].Version, tag);

                        return;
                    } //rare case end

                    GetFileVersion(files[key].Version.VSSItem, files[key].Version, svnClient);
                    //Only need one file to get the revision information from
                    if (string.IsNullOrEmpty(filePath))
                    {
                        filePath =
                            Path.Combine(
                                Path.GetDirectoryName(
                                    string.Format("{0}{1}", repoDIR, files[key].Spec.Substring(1)).Replace("/", "\\")),
                                files[key].Version.VSSItem.Name);
                    }

                    if (files[key].Deleted)
                    {
                        delkeys.Add(filePath);
                    }
                }
                catch (COMException ex)
                {
                    switch ((uint)ex.ErrorCode)
                    {
                    case 0x8004D838:     //version is corrupted and unavailable
                        migrateLog.WarnFormat("Skipping version due to corruption in file {1}:{0}",
                                              files[key].VersionNumber, files[key].Spec);
                        continue;

                    default:
                        if (IgnoreExceptions)
                        {
                            migrateLog.ErrorFormat("Error processing file {1}:{0}",
                                                   files[key].VersionNumber, files[key].Spec);
                            migrateLog.ErrorFormat(ex.ToString());
                            continue;
                        }
                        throw;
                    }
                }
            }
            //Only commit if we actually have a file that has been updated as a result of the get
            if (!string.IsNullOrEmpty(filePath))
            {
                var commitArgs = new SvnCommitArgs {
                    LogMessage = properties.Comment
                };
                migrateLog.DebugFormat("Committing revision ...");
                //SLOW!!!, change to ICollection of FilePaths (only verify updated files!)
                svnClient.Commit(dir, commitArgs);

                //delete files which are marked as deleted in vss
                foreach (string delFilePath in delkeys)
                {
                    svnClient.Delete(delFilePath);
                    migrateLog.Info(String.Format("Deleted: {0}", delFilePath));
                }
                delkeys.Clear();

                SvnInfoEventArgs infoEventArgs;
                //Use one of the committed files to determine the revision we just committed
                var uri = new Uri(string.Format("{0}{1}", svnURL, svnPROJ));
                //svnClient.GetInfo(SvnTarget.FromString(filePath), out infoEventArgs);
                svnClient.GetInfo(SvnTarget.FromUri(uri), out infoEventArgs);

                svnClient.SetRevisionProperty(new Uri(svnURL), infoEventArgs.Revision,
                                              SvnPropertyNames.SvnAuthor,
                                              properties.Author);

                string   strCfgTime;
                string[] strSplit, strSplit2;

                strSplit  = properties.Time.ToString().Split(' ');
                strSplit2 = strSplit[0].Split('/');

                strCfgTime = strSplit2[2] + '-' + strSplit2[1] + '-' + strSplit2[0] + 'T' + strSplit[1] + ".000000Z";

                svnClient.SetRevisionProperty(new Uri(svnURL), infoEventArgs.Revision,
                                              SvnPropertyNames.SvnDate,
                                              strCfgTime);
            }
        }
コード例 #12
0
ファイル: SvnWrapper.cs プロジェクト: mathewng/vss2svn
 public void Remove(string path, bool recursive)
 {
     /*
     SvnExec("rm " + (recursive ? "-r " : "") + "-- " + Quote(path));
     */
     using (var client = new SvnClient())
     {
         SvnUI.Bind(client, parentWindow);
         var result = client.Delete(path, new SvnDeleteArgs { Force = true, KeepLocal = false });
     }
 }
コード例 #13
0
ファイル: SvnWrapper.cs プロジェクト: mathewng/vss2svn
        /*
         * This adds, modifies, and removes index entries to match the working tree.
         */
        public bool AddAll()
        {
            /*
            var startInfo = GetStartInfo("add -A");

            // add fails if there are no files (directories don't count)
            return ExecuteUnless(startInfo, "did not match any files");
            */
            var overallStatus = true;

            using (var client = new SvnClient())
            {
                SvnUI.Bind(client, parentWindow);

                var statusList = (Collection<SvnStatusEventArgs>)null;
                var svnStatusArgs = new SvnStatusArgs { Depth = SvnDepth.Infinity, IgnoreExternals = false, KeepDepth = false, RetrieveIgnoredEntries = false };

                if (client.GetStatus(useSvnStandardDirStructure ? trunkPath : workingCopyPath, svnStatusArgs, out statusList))
                {
                    overallStatus = statusList.Select(svnStatusEventArg =>
                    {
                        switch (svnStatusEventArg.LocalNodeStatus)
                        {
                            case SvnStatus.Missing:
                                logger.WriteLine("Commit: Deleting file {0} due to status = {1}", svnStatusEventArg.FullPath, svnStatusEventArg.LocalNodeStatus);
                                return client.Delete(svnStatusEventArg.FullPath, new SvnDeleteArgs { KeepLocal = false, Force = false });
                            case SvnStatus.NotVersioned:
                                logger.WriteLine("Commit: Adding file {0} due to status = {1}", svnStatusEventArg.FullPath, svnStatusEventArg.LocalNodeStatus);
                                return client.Add(svnStatusEventArg.FullPath, new SvnAddArgs { AddParents = false, Depth = SvnDepth.Infinity, Force = false });
                            default:
                                return true;
                        }
                    })
                    .Aggregate(true, (state, val) => state &= val);
                }
                else
                    overallStatus = false;
            }

            return overallStatus;
        }
コード例 #14
0
        private void Commit(string alias, string svnFolder, string revFolder)
        {
            var reviFiles = System.IO.Directory.GetFiles(revFolder, "*.*", System.IO.SearchOption.AllDirectories);
            var svnFiles  = System.IO.Directory.GetFiles(svnFolder, "*.*", System.IO.SearchOption.AllDirectories);

            Dictionary <string, string> reviFileIndex = new Dictionary <string, string>();
            Dictionary <string, string> svnFileIndex  = new Dictionary <string, string>();

            string url         = Url.TrimEnd('/') + "/" + alias;
            string tempFolder  = TempFolderPath(alias);
            bool   workingCopy = false;


            if (Directory.Exists(Path.Combine(tempFolder, ".svn")))
            {
                workingCopy = true;
            }
            else if (!Directory.Exists(tempFolder))
            {
                Directory.CreateDirectory(tempFolder);
            }


            foreach (string s in reviFiles)
            {
                DirectoryInfo parent = Directory.GetParent(s);
                if (!parent.Name.StartsWith("."))
                {
                    reviFileIndex.Add(s.Substring(revFolder.Length).Trim('\\'), s);
                }
            }


            foreach (string s in svnFiles)
            {
                if (!s.ToLower().Contains(".svn"))
                {
                    svnFileIndex.Add(s.Substring(svnFolder.Length).Trim('\\'), s);
                }
            }

            using (SvnClient client = new SvnClient())
            {
                client.LoadConfiguration("path");
                client.Authentication.DefaultCredentials = new NetworkCredential(Login, Password);

                if (!workingCopy)
                {
                    client.Add(tempFolder);
                }

                SvnUriTarget target = new SvnUriTarget(url);

                //remove not needed files
                foreach (var key in svnFileIndex.Keys)
                {
                    if (!reviFileIndex.ContainsKey(key))
                    {
                        client.Delete(svnFileIndex[key]);
                    }
                }


                //add missing files
                foreach (var file in reviFileIndex)
                {
                    string newPath = Path.Combine(svnFolder, file.Key);
                    bool   add     = false;

                    if (!File.Exists(newPath))
                    {
                        add = true;
                        ensureDirectory(Directory.GetParent(newPath).FullName, false);
                    }

                    System.IO.File.Copy(file.Value, Path.Combine(svnFolder, file.Key), true);
                }

                SvnAddArgs saa = new SvnAddArgs();
                saa.Force = true;
                saa.Depth = SvnDepth.Infinity;


                foreach (var dir in Directory.GetDirectories(svnFolder))
                {
                    if (!dir.Contains(".svn"))
                    {
                        client.Add(dir, saa);
                    }
                }

                SvnCommitArgs args = new SvnCommitArgs();
                args.LogMessage    = "Comitted from Courier 2";
                args.ThrowOnError  = true;
                args.ThrowOnCancel = true;

                client.Commit(tempFolder, args);
            }
        }
コード例 #15
0
        public void Copy()
        {
            Console.Write("Collecting svn log: ");

            if (_args.RevisionRange != null)
            {
                Console.Write("{0}:{1} ",
                              _args.RevisionRange.StartRevision,
                              _args.RevisionRange.EndRevision);
            }

            // fetch the source svn respository and
            SvnInfo sourceInfo = new SvnInfo(_args.Source);

            Console.WriteLine("Source SVN root: {0}", sourceInfo.Info.RepositoryRoot);
            Console.WriteLine("Source SVN uri: {0}", sourceInfo.Info.Uri);

            string sourceRelativePath = sourceInfo.Info.Uri.ToString().Remove(
                0, sourceInfo.Info.RepositoryRoot.ToString().Length - 1);

            Console.WriteLine("Relative path: {0}", sourceRelativePath);

            SvnLogArgs logArgs = new SvnLogArgs();

            logArgs.StrictNodeHistory    = true;
            logArgs.ThrowOnError         = true;
            logArgs.Range                = _args.RevisionRange;
            logArgs.RetrieveChangedPaths = true;

            _client.Log(_args.Source, logArgs, new EventHandler <SvnLogEventArgs>(OnLog));
            Console.WriteLine();
            Console.WriteLine("Collected {0} revisions.", _revisions.Count);

            SvnTarget fromSvnTarget = SvnTarget.FromString(_args.Source);

            foreach (KeyValuePair <long, SvnLogEventArgs> revisionPair in _revisions)
            {
                SvnLogEventArgs revision = revisionPair.Value;
                Console.WriteLine("Revision {0} ({1})", revision.Revision, revision.Time);

                if (_args.simulationOnly)
                {
                    continue;
                }

                SvnExportArgs exportArgs = new SvnExportArgs();
                exportArgs.Overwrite    = true;
                exportArgs.ThrowOnError = true;
                exportArgs.Revision     = revision.Revision;

                SvnUpdateResult exportResult = null;
                _client.Export(fromSvnTarget, _args.Destination, exportArgs, out exportResult);

                if (revision.ChangedPaths == null)
                {
                    throw new Exception(string.Format("No changed paths in rev. {0}",
                                                      revision.Revision));
                }

                SortedList <string, SvnChangeItem> changeItems = new SortedList <string, SvnChangeItem>();

                foreach (SvnChangeItem changeItem in revision.ChangedPaths)
                {
                    changeItems.Add(changeItem.Path, changeItem);
                }

                foreach (SvnChangeItem changeItem in changeItems.Values)
                {
                    string targetSvnPath = changeItem.Path.Remove(0, sourceRelativePath.Length);
                    string targetOSPath  = targetSvnPath.Replace("/", @"\");
                    string targetPath    = Path.Combine(_args.Destination, targetOSPath);
                    Console.WriteLine("{0} {1}", changeItem.Action, changeItem.Path);
                    switch (changeItem.Action)
                    {
                    case SvnChangeAction.Add:
                    {
                        Console.WriteLine(" A {0}", targetPath);
                        SvnAddArgs svnAddArgs = new SvnAddArgs();
                        svnAddArgs.ThrowOnError = true;
                        svnAddArgs.Depth        = SvnDepth.Empty;
                        _client.Add(targetPath, svnAddArgs);
                    }
                    break;

                    case SvnChangeAction.Delete:
                    {
                        Console.WriteLine(" D {0}", targetPath);
                        SvnDeleteArgs svnDeleteArgs = new SvnDeleteArgs();
                        svnDeleteArgs.ThrowOnError = true;
                        _client.Delete(targetPath, svnDeleteArgs);
                    }
                    break;
                    }
                }

                SvnCommitArgs commitArgs = new SvnCommitArgs();
                commitArgs.LogMessage  = revision.LogMessage;
                commitArgs.LogMessage += string.Format("\nCopied from {0}, rev. {1} by {2} @ {3} {4}",
                                                       sourceInfo.Info.Uri, revision.Revision, revision.Author, revision.Time.ToShortDateString(), revision.Time.ToShortTimeString());
                commitArgs.ThrowOnError = true;

                Console.WriteLine("Commiting {0}", _args.Destination);
                Console.WriteLine("----------------------------------------------------------------------------");
                Console.WriteLine(commitArgs.LogMessage);
                Console.WriteLine("----------------------------------------------------------------------------");

                if (_args.prompt)
                {
                    while (true)
                    {
                        Console.Write("Commit? [Y/N] ");
                        char k = Char.ToLower(Console.ReadKey().KeyChar);
                        Console.WriteLine();
                        if (k == 'y')
                        {
                            break;
                        }
                        if (k == 'n')
                        {
                            throw new Exception("Aborted by user.");
                        }
                    }
                }

                _client.Commit(_args.Destination, commitArgs);
            }
        }