Пример #1
0
        protected override void ExecuteSVNTask(SvnClient client)
        {
            if (Dir == null)
            {
                Dir = new DirectoryInfo(Project.BaseDirectory);
            }

            if (!Dir.Exists)
            {
                throw new BuildException(string.Format(Resources.MissingDirectory, Dir.FullName), Location);
            }

            SVNFunctions svnFunctions = new SVNFunctions(Project, Properties);
            string sourceUri = svnFunctions.GetUriFromPath(Dir.FullName);
            Log(Level.Info, Resources.SVNCopyCopying, sourceUri, SvnUri);

            SvnCopyArgs args = new SvnCopyArgs();
            args.ThrowOnError = true;
            args.LogMessage = Message;

            SvnCommitResult result;
            client.RemoteCopy(SvnTarget.FromString(sourceUri), SvnUri, args, out result);

            if (result != null)
            {
                Log(Level.Info, Resources.SVNCopyResult, Dir.FullName, SvnUri, result.Revision, result.Author);
            }
        }
Пример #2
0
        /// <summary>
        /// Actual method to be executed for the implementing task
        /// </summary>
        /// <param name="client">The instance of the SVN client</param>
        /// <returns></returns>
        public override bool ExecuteCommand(SvnClient client)
        {
            SvnRevertArgs args = new SvnRevertArgs();
            args.Depth = Recursive ? SvnDepth.Infinity : SvnDepth.Children;

            return client.Revert(RepositoryPath, args);
        }
        /// <summary>
        /// Gets the svn log entries from the repository.
        /// </summary>
        /// <returns>An IEnumerable of the QvxDataRows.</returns>
        private IEnumerable<QvxDataRow> GetSvnLogEntries()
        {
            QvxLog.Log(QvxLogFacility.Application, QvxLogSeverity.Notice, "GetSvnLogEntries()");

            string username, password, server;
            this.MParameters.TryGetValue("UserId", out username);
            this.MParameters.TryGetValue("Password", out password);
            this.MParameters.TryGetValue("Server", out server);
            System.Net.NetworkCredential creds = new System.Net.NetworkCredential(username, password);

            SvnClient client = new SvnClient();
            client.Authentication.DefaultCredentials = creds;

            SvnUriTarget target = new SvnUriTarget(server);

            Collection<SvnLogEventArgs> logEntries = new Collection<SvnLogEventArgs>();
            bool result = client.GetLog(target.Uri, out logEntries);

            if(!result)
            {
                throw new SvnClientException("Retrieving Subversion log failed");
            }

            foreach(SvnLogEventArgs entry in logEntries)
            {
                yield return MakeEntry(entry, FindTable("SvnLogEntries", MTables));
            }
        }
Пример #4
0
 protected override void ExecuteTask()
 {
     using(SvnClient svnClient = new SvnClient())
     {
         ExecuteSVNTask(svnClient);
     }
 }
Пример #5
0
        public string Search(string path, bool recurseUp, string propName)
        {
            if (!String.IsNullOrEmpty(_base))
                path = Path.Combine(_base, path);

            if (!Directory.Exists(path))
            {
                if (!File.Exists(path))
                    throw new FileNotFoundException(path);
                path = Path.GetDirectoryName(path);
            }

            using (var client = new SvnClient())
            {
                string result;
                Guid guid;
                do
                {
                    client.TryGetProperty(SvnTarget.FromString(path), propName, out result);
                    Debug.Assert(path != null, "path != null");
                    path = Directory.GetParent(path).FullName;
                } while (result == null && recurseUp && client.TryGetRepositoryId(path, out guid));
                return result ?? string.Empty;
            }
        }
Пример #6
0
        public static void SyncLocalFolderWithO2XRulesDatabase()
        {
            try
            {
                "in SyncLocalFolderWithO2XRulesDatabase".debug();
                //var targetLocalDir = XRules_Config.PathTo_XRulesDatabase_fromO2;
                var targetLocalDir = PublicDI.config.LocalScriptsFolder;
                var o2XRulesSvn = PublicDI.config.SvnO2DatabaseRulesFolder;

                "starting Sync with XRules Database to {0}".info(targetLocalDir);
                using (SvnClient client = new SvnClient())
                {
                    if (targetLocalDir.dirExists().isFalse() || targetLocalDir.pathCombine(".svn").dirExists().isFalse())
                    {
                        "First Sync, so doing an SVN Checkout to: {0}".info(targetLocalDir);
                        Files.deleteFolder(targetLocalDir, true);
                        client.CheckOut(new Uri(o2XRulesSvn), targetLocalDir);
                    }
                    else
                    {
                        "Local XRules folder exists, so doing an SVN Update".info();
                        client.Update(targetLocalDir);
                    }
                    "SVN Sync completed".debug();
                }
            }
            catch (Exception ex)
            {
                ex.log("in SvnApi.SyncLocalFolderWithO2XRulesDatabase");
            }
        }
Пример #7
0
        public override string CheckOut(IPackageTree packageTree, FileSystemInfo destination)
        {
            SvnUpdateResult result = null;

            using (var client = new SvnClient())
            {
                try
                {
                    var svnOptions = new SvnCheckOutArgs();
                    if (UseRevision.HasValue)
                        svnOptions.Revision = new SvnRevision(UseRevision.Value);
                    client.CheckOut(new SvnUriTarget(new Uri(Url)), destination.FullName, svnOptions, out result);
                }
                catch (SvnRepositoryIOException sre)
                {
                    HandleExceptions(sre);
                }
                catch (SvnObstructedUpdateException sue)
                {
                    HandleExceptions(sue);
                }
            }

            return result.Revision.ToString();
        }
Пример #8
0
 /// <summary>
 /// 执行检出操作
 /// </summary>
 /// <param name="repositoryPath">svn服务器路径</param>
 /// <param name="workDirectory">工程本地工作路径</param>
 /// <param name="svnPath">本地svn路径</param>
 /// <param name="checkResult">检出操作的结果</param>
 /// <returns>返回检出操作的日志</returns>
 public string CheckOut(string repositoryPath,string workDirectory,out string checkResult,string xmlConfigPath)
 {
     string err;
     string time;
     XmlDao xmlDao = new XmlDao();
     XmlNodeList xmlNodeList=xmlDao.XmlQuery("config/preferences/SvnPath", xmlConfigPath);
     string svnPath=xmlNodeList[0].InnerText;
     using (SvnClient client = new SvnClient())
     {
         Tools tools = new Tools();
         string checkOutLog = "";
         try
         {
             client.CheckOut(new Uri(repositoryPath), workDirectory);
             string args = "checkout " + repositoryPath + " " + workDirectory;
             checkOutLog = tools.BuildProject(svnPath, args, null, out err, out time);
             checkResult = "successful";
             return checkOutLog;
         }
         catch (Exception ex)
         {
             checkResult = " failed";
             checkOutLog = ex.Message;
             return checkOutLog;
         }
     }
 }
Пример #9
0
        public static FileChanged[] GetChangeSetFromSvn(DateTime startDateTime, DateTime endDateTime, SvnConfig server)
        {
            SvnRevisionRange range = new SvnRevisionRange(new SvnRevision(startDateTime), new SvnRevision(endDateTime));
            Collection<SvnLogEventArgs> logitems;

            var uri = new Uri(server.Url);
            FileChanged[] changed;
            using (SvnClient client = new SvnClient())
            {
                client.Authentication.Clear(); // Disable all use of the authentication area
                client.Authentication.UserNamePasswordHandlers +=
                    delegate(object sender, SvnUserNamePasswordEventArgs e)
                        {
                            e.UserName = server.UserName;
                            e.Password = server.Password;
                            e.Save = true;
                        };
                client.Authentication.SslServerTrustHandlers += delegate(object sender, SvnSslServerTrustEventArgs e)
                    {
                        e.AcceptedFailures = e.Failures;
                        e.Save = true; // Save acceptance to authentication store
                    };
                client.GetLog(uri, new SvnLogArgs(range), out logitems);
                foreach (var svnLogEventArgse in logitems)
                {
                    Console.WriteLine((string) WriteString(svnLogEventArgse));
                }
                changed = logitems.SelectMany<SvnLogEventArgs, FileChanged>(l => GetChangedFiles(l)).ToArray();
            }
            return changed;
        }
 public void RenameProjectFolder(RenameContext context)
 {
     using(SvnClient svnClient = new SvnClient())
     {
         svnClient.Move(context.OldProject.ProjectDirectory, context.NewProject.ProjectDirectory);
     }
 }
Пример #11
0
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override bool ResolveFiles()
        {
            SvnClient client = new SvnClient();
            SvnInfoArgs infoArgs = new SvnInfoArgs();

            infoArgs.ThrowOnError = false;
            infoArgs.Depth = SvnDepth.Files;

            foreach (SourceFile file in State.SourceFiles.Values)
            {
                if (file.IsResolved)
                    continue;

                string dirName = SvnTools.GetTruePath(SvnTools.GetNormalizedDirectoryName(file.FullName), true);

                client.Info(dirName, infoArgs,
                    delegate(object sender, SvnInfoEventArgs e)
                    {
                        SourceFile infoFile;

                        string path = e.FullPath;

                        if (State.SourceFiles.TryGetValue(path, out infoFile)
                            && !infoFile.IsResolved)
                        {
                            infoFile.SourceReference = new SubversionSourceReference(this, infoFile, e.RepositoryRoot,
                                                                                      e.RepositoryRoot.MakeRelativeUri(e.Uri), e.LastChangeRevision, e.Revision);
                        }
                    });
            }

            return true;
        }
Пример #12
0
        public void Resolve_RepeatedEventHookUp_SOC_411()
        {
            SvnSandBox sbox = new SvnSandBox(this);
            Uri projectRoot = new Uri("https://ctf.open.collab.net/svn/repos/sharpsvn/trunk/scripts");

            using (var svnClient = new SvnClient())
            {
                for (int i = 0; i < 3; i++)
                {
                    string workingcopy = sbox.GetTempDir();
                    Directory.CreateDirectory(workingcopy);

                    svnClient.Authentication.UserNamePasswordHandlers += DoNowt;
                    try
                    {
                        SvnUpdateResult svnUpdateResult;
                        SvnCheckOutArgs ca = new SvnCheckOutArgs() { Depth = SvnDepth.Files };
                        Assert.IsTrue(svnClient.CheckOut(projectRoot, workingcopy, ca, out svnUpdateResult));
                        Assert.IsNotNull(svnUpdateResult);
                        Assert.IsTrue(svnUpdateResult.HasRevision);
                    }
                    finally
                    {
                        svnClient.Authentication.UserNamePasswordHandlers -= DoNowt;
                    }
                }
            }
        }
Пример #13
0
        public void Capabilities_Local()
        {
            SvnSandBox sbox = new SvnSandBox(this);
            Uri emptyUri = sbox.CreateRepository(SandBoxRepository.Empty);
            Uri emptyNoMergeUri = sbox.CreateRepository(SandBoxRepository.EmptyNoMerge);

            using (SvnClient client = new SvnClient())
            {
                Collection<SvnCapability> caps;
                SvnGetCapabilitiesArgs aa = new SvnGetCapabilitiesArgs();
                aa.RetrieveAllCapabilities = true;

                IEnumerable<SvnCapability> rCaps = new SvnCapability[] { SvnCapability.MergeInfo };
                Assert.That(client.GetCapabilities(emptyUri, rCaps, out caps));

                Assert.That(caps.Contains(SvnCapability.MergeInfo));

                Assert.That(client.GetCapabilities(emptyNoMergeUri, rCaps, out caps));

                Assert.That(!caps.Contains(SvnCapability.MergeInfo));
                Assert.That(caps.Count, Is.EqualTo(0));

                Assert.That(client.GetCapabilities(emptyNoMergeUri, aa, out caps));
                Assert.That(caps.Count, Is.GreaterThanOrEqualTo(5));

                Assert.That(client.GetCapabilities(emptyUri, aa, out caps));
                Assert.That(caps.Count, Is.GreaterThanOrEqualTo(6));
            }
        }
Пример #14
0
        public override string[] GetAvailableRevisions()
        {
            string url = Url.TrimEnd('/');

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

              List<String> filesFound = new List<String>();
              Collection<SvnListEventArgs> listResults;

              if (client.GetList(folderTarget, out listResults))
              {
              foreach (SvnListEventArgs item in listResults)
                  if (item.Entry.NodeKind == SvnNodeKind.Directory && !string.IsNullOrEmpty(item.Name))
                      filesFound.Add(item.Name);

              return filesFound.ToArray();
              }
              }

             return new string[0];
        }
Пример #15
0
		public void Clear()
		{
			svnStatusCache.Clear();
			svnPathRepoCache.Clear();
			if (svnClient != null)
				svnClient.Dispose();
			svnClient = null;
		}
Пример #16
0
        /// <summary>
        /// Actual method to be executed for the implementing task
        /// </summary>
        /// <param name="client">The instance of the SVN client</param>
        /// <returns></returns>
        public override bool ExecuteCommand(SvnClient client)
        {
            SvnTarget target = new SvnUriTarget(RepositoryPath);
            SvnListArgs args = new SvnListArgs();
            args.Depth = Recursive ? SvnDepth.Infinity : SvnDepth.Children;

            return client.List(target, args, listHandler);
        }
Пример #17
0
 public SvnPort(string name, string server)
 {
     Name = name;
     Server = server;
     // 要发布app.config,否则不能启用混合程序集
     client = new SvnClient();
     log = OperLog.instance;
 }
Пример #18
0
 /// <summary>
 /// Check if the given path is a working copy or not
 /// </summary>
 /// <param name="path">local path to the respository</param>
 /// <returns></returns>
 public static bool IsWorkingCopy(string path)
 {
     using (var client = new SvnClient())
     {
         var uri = client.GetUriFromWorkingCopy(path);
         return uri != null;
     }
 }
        public SvnClientWrapper()
        {
            Debug("SVN: Create SvnClient instance");

            _client = new SvnClient();
            _client.Notify += client_Notify;
            _client.Cancel += client_Cancel;
        }
Пример #20
0
		public void StartRevision()
		{
#if DEBUG
			using (var svn = new SvnClient())
			{
				CheckWcStatus(svn);
			}
#endif
		}
Пример #21
0
		static SvnSharpClient ()
		{
			try {
				client = new SvnClient ();
			} catch (Exception ex) {
				LoggingService.LogError ("SVN client could not be initialized", ex);
				installError = true;
			}
		}
		void Init ( )
		{
			client = new SvnClient ();
			client.Authentication.SslClientCertificateHandlers += new EventHandler<SharpSvn.Security.SvnSslClientCertificateEventArgs> (AuthenticationSslClientCertificateHandlers);
			client.Authentication.SslClientCertificatePasswordHandlers += new EventHandler<SvnSslClientCertificatePasswordEventArgs> (AuthenticationSslClientCertificatePasswordHandlers);
			client.Authentication.SslServerTrustHandlers += new EventHandler<SvnSslServerTrustEventArgs> (AuthenticationSslServerTrustHandlers);
			client.Authentication.UserNameHandlers += new EventHandler<SvnUserNameEventArgs> (AuthenticationUserNameHandlers);
			client.Authentication.UserNamePasswordHandlers += new EventHandler<SvnUserNamePasswordEventArgs> (AuthenticationUserNamePasswordHandlers);
		}
Пример #23
0
 private static byte[] ReadFileVersion(SvnClient svnClient, string uriString, long revision)
 {
     using (var versionStream = new MemoryStream())
     {
         var versionTarget = new SvnUriTarget(uriString, revision);
         svnClient.Write(versionTarget, versionStream);
         return versionStream.ToArray();
     }
 }
Пример #24
0
        static void Main(string[] args)
        {
            using (SvnClient client = new SvnClient())
            {
                SvnUpdateResult result;
                // Checkout the code to the specified directory
                client.CheckOut(new Uri("https://svn01.bauerverlag.de/svn/dev_net/dev/Beispiele/"), @"C:\test\SharpSvnCheckoutTest", out result);

            }
        }
Пример #25
0
 public void ListSshHostCredentials()
 {
     using (SvnClient client = new SvnClient())
     {
         foreach (SvnAuthenticationCacheItem i in client.Authentication.GetCachedItems(SvnAuthenticationCacheType.WindowsSshHostKeys))
         {
             GC.KeepAlive(i);
         }
     }
 }
Пример #26
0
		public void AddFiles(params string[] files)
		{
			using (var svn = new SvnClient())
			{
				foreach (var file in files)
				{
					svn.Add(file);
				}
			}
		}
Пример #27
0
        /// <summary>
        /// Binds the specified client to the user interface defined by args
        /// </summary>
        /// <param name="client">The client to bind.</param>
        /// <param name="parentWindow">The parent window.</param>
        public static void Bind(SvnClient client, IWin32Window parentWindow)
        {
            if (client == null)
                throw new ArgumentNullException("client");

            SvnUIBindArgs args = new SvnUIBindArgs();
            args.ParentWindow = parentWindow;

            Bind(client, args);
        }
Пример #28
0
        public override SvnClient CreateSvnClient()
        {
            var client = new SvnClient();

            if (!string.IsNullOrEmpty(_userName) && !string.IsNullOrEmpty(_password))
            {
                client.Authentication.ForceCredentials(_userName, _password);
            }

            return client;
        }
        public void CheckInChanges(string solutionDirectoryPath, Project oldProject, Project newProject)
        {
            using(SvnClient svnClient = new SvnClient())
            {
                SvnCommitArgs svnCommitArgs = new SvnCommitArgs { LogMessage = string.Format("Renamed project {0} into {1}", oldProject.ProjectName, newProject.ProjectName) };

                // TODO NKO: Do something with the result
                SvnCommitResult result;
                svnClient.Commit(solutionDirectoryPath, svnCommitArgs, out result);
            }
        }
Пример #30
0
        /// <summary>
        /// Binds the specified client to the user interface defined by args
        /// </summary>
        /// <param name="client">The client to bind.</param>
        /// <param name="args">The args.</param>
        public static void Bind(SvnClient client, SvnUIBindArgs args)
        {
            if (client == null)
                throw new ArgumentNullException("client");
            else if (args == null)
                throw new ArgumentNullException("args");

            SvnClientUIHandler handler = new SvnClientUIHandler(args.ParentWindow);

            handler.Bind(client, args);
        }
Пример #31
0
        public void repoStart()
        {
            SvnRevertArgs revertArgs = new SvnRevertArgs()
            {
                Depth = SvnDepth.Infinity
            };

            Stopwatch stopwatch = Stopwatch.StartNew();

            Parallel.ForEach(repoDataSet.Tables["Repo"].Rows.Cast <DataRow>(), row =>
            {
                string repoName = row[0].ToString();
                string repoType = row[1].ToString() + "s";
                string repoUrl  = row[2].ToString();
                string repoPath = $@"{repoType}\{repoName}";

                long currentLap;
                long totalLap;
                currentLap = stopwatch.ElapsedMilliseconds;

                using (SvnClient client = new SvnClient())
                {
                    if (System.IO.Directory.Exists($@"{repoPath}\.svn"))
                    {
                        SvnInfoEventArgs remoteRev;
                        client.GetInfo(repoUrl, out remoteRev);

                        SvnInfoEventArgs localRev;
                        client.GetInfo(repoPath, out localRev);

                        if (localRev.Revision < remoteRev.Revision)
                        {
                            client.Revert(repoPath, revertArgs);
                            client.Update(repoPath);
                            totalLap = stopwatch.ElapsedMilliseconds - currentLap;
                            WriteLog(repoLog, $"[{Name}] updated [{repoType}] {repoName} from {localRev.Revision} to {remoteRev.Revision} in {totalLap} ms.");
                            if (repoType != "Profiles")
                            {
                                restartNeeded = true;
                            }
                        }
                    }
                    else
                    {
                        client.CheckOut(new Uri(repoUrl), repoPath);
                        totalLap = stopwatch.ElapsedMilliseconds - currentLap;
                        WriteLog(repoLog, $"[{Name}] {repoName} checkout complete in {totalLap} ms.");
                        if (repoType != "Profiles")
                        {
                            restartNeeded = true;
                        }
                    }
                }
            });
            stopwatch.Stop();
            Logging.Write(LogColor, $"[{Name}] processes complete in {stopwatch.ElapsedMilliseconds} ms.");

            if (repoLog.Count > 0)
            {
                using (StreamWriter file = File.CreateText(@"Plugins\repoBuddy\repoLog.json"))
                {
                    JsonSerializer serializer = new JsonSerializer();
                    serializer.Serialize(file, repoLog);
                }
            }
            if (restartNeeded)
            {
                Logging.Write(LogColor, $"[{Name}] Restarting to reload assemblies.");
                RestartRebornBuddy();
            }
        }
Пример #32
0
        /// <summary>
        /// 从SVN检出并自动更新项目
        /// </summary>
        public List <string> CheckOutPrograme()
        {
            using (SvnClient client = new SvnClient())
            {
                SvnInfoEventArgs serverInfo;
                SvnInfoEventArgs clientInfo;
                SvnUriTarget     repos = new SvnUriTarget(SVNAdress);
                //SvnPathTarget local = new SvnPathTarget(@"C:\demo");

                client.Authentication.UserNamePasswordHandlers +=
                    new EventHandler <SvnUserNamePasswordEventArgs>(
                        delegate(object s, SvnUserNamePasswordEventArgs e)
                {
                    e.UserName = SVNUserName;
                    e.Password = SVNUserPwd;
                });
                client.Authentication.SslServerTrustHandlers += new EventHandler <SharpSvn.Security.SvnSslServerTrustEventArgs>(
                    delegate(Object ssender, SharpSvn.Security.SvnSslServerTrustEventArgs se)
                {
                    // Look at the rest of the arguments of E whether you wish to accept

                    // If accept:
                    se.AcceptedFailures = se.Failures;
                    se.Save             = true; // Save acceptance to authentication store
                });

                //string path = @"C:\Demo";
                //client.CleanUp(path);
                //client.Revert(path);

                if (!Directory.Exists(SVNPath))
                {
                    Directory.CreateDirectory(SVNPath);
                }

                client.CheckOut(repos, SVNPath);
                client.Update(SVNPath);

                client.GetInfo(repos, out serverInfo);
                client.GetInfo(SVNPath, out clientInfo);

                List <string> listMsg = new List <string>();
                SvnLogArgs    logArgs = new SvnLogArgs();

                logArgs.Range = new SvnRevisionRange(clientInfo.LastChangeRevision, serverInfo.LastChangeRevision);
                logArgs.RetrieveAllProperties = true;
                EventHandler <SvnLogEventArgs> logHandler = new EventHandler <SvnLogEventArgs>(delegate(object lo, SvnLogEventArgs le)
                {
                    foreach (SvnChangeItem changeItem in le.ChangedPaths)
                    {
                        string str = string.Format(
                            "[操作]:{0}   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[路径]:{1}   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[作者]:{2}   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[日志]:{3}   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[版本]:{4} ",
                            changeItem.Action,
                            changeItem.Path,
                            //changeItem.CopyFromRevision,
                            //changeItem.CopyFromPath,
                            le.Author,
                            le.LogMessage,
                            le.Revision);
                        listMsg.Add(str);
                    }
                });

                client.Log(new Uri(SVNAdress), logArgs, logHandler);
                return(listMsg);
                //  this.txtLog.Text += DateTime.Now.ToLongTimeString() + "\r\n";

                //Console.WriteLine(string.Format("serverInfo revision of {0} is {1}", repos, serverInfo.Revision));
                //Console.WriteLine(string.Format("clientInfo revision of {0} is {1}", local, clientInfo.Revision));
            }

            //using (SvnClient client = new SvnClient())
            //{
            //    client.
            //    client.Authentication.UserNamePasswordHandlers +=
            //        new EventHandler<SvnUserNamePasswordEventArgs>(
            //            delegate (object s, SvnUserNamePasswordEventArgs e)
            //            {
            //                e.UserName = "******";
            //                e.Password = "******";
            //            });
            //}
            //using (SvnClient client = new SvnClient())
            //{
            //    SharpSvn.UI.SvnUIBindArgs uiBindArgs = new SharpSvn.UI.SvnUIBindArgs();
            //    SharpSvn.UI.SvnUI.Bind(client, uiBindArgs);
            //}
        }
Пример #33
0
        internal void BrowseItem(Uri uri)
        {
            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }

            if (DesignMode)
            {
                return;
            }

            Uri nUri = SvnTools.GetNormalizedUri(uri);

            if (_running.Contains(nUri))
            {
                return;
            }

            _running.Add(nUri);

            if (_running.Count == 1)
            {
                OnRetrievingChanged(EventArgs.Empty);
            }

            AnkhAction d = delegate()
            {
                bool ok = false;
                try
                {
                    SvnListArgs la = new SvnListArgs();
                    la.RetrieveEntries = RetrieveItems;
                    la.RetrieveLocks   = RetrieveLocks;
                    la.Depth           = SvnDepth.Children;
                    la.ThrowOnError    = false;

                    Collection <SvnListEventArgs> items;
                    using (SvnClient client = Context.GetService <ISvnClientPool>().GetClient())
                    {
                        client.GetList(uri, la, out items);
                    }

                    AnkhAction addItems = (AnkhAction) delegate()
                    {
                        if (items != null && items.Count > 0)
                        {
                            bool first = true;
                            foreach (SvnListEventArgs a in items)
                            {
                                if (first)
                                {
                                    if (a.RepositoryRoot != null)
                                    {
                                        EnsureRoot(a.RepositoryRoot);
                                    }
                                }

                                AddItem(a, a.RepositoryRoot);
                                first = false;
                            }

                            MaybeExpand(uri);
                        }

                        _running.Remove(nUri);

                        if (_running.Count == 0)
                        {
                            OnRetrievingChanged(EventArgs.Empty);
                        }
                    };

                    if (IsHandleCreated)
                    {
                        BeginInvoke(addItems);
                    }
                    else
                    {
                        addItems();
                    }

                    ok = true;
                }
                finally
                {
                    if (!ok)
                    {
                        BeginInvoke((AnkhAction) delegate()
                        {
                            _running.Remove(nUri);

                            if (_running.Count == 0)
                            {
                                OnRetrievingChanged(EventArgs.Empty);
                            }
                        });
                    }
                }
            };

            d.BeginInvoke(null, null);
        }
Пример #34
0
 private IDisposable BindOutputPane(SvnClient client)
 {
     return(new OutputPaneReporter(this, client));
 }
Пример #35
0
        private void GatherSvnInformation(SvnInformation svn)
        {
            Log.LogMessage("Gathering SVN details from " + WorkingCopy);
            using (var client = new SvnClient())
            {
                var arg = new SvnStatusArgs()
                {
                    Revision = new SvnRevision(SvnRevisionType.Working),
                    Depth    = SvnDepth.Empty
                };
                client.Info(WorkingCopy, (sender, e) =>
                {
                    svn.Now = DateTime.Now;
                    if (String.IsNullOrEmpty(svn.Url))
                    {
                        svn.Url = e.Uri.AbsoluteUri;
                    }
                    svn.CommitRevision = e.Revision;
                });
                Collection <SvnStatusEventArgs> statuses;
                arg.Depth = SvnDepth.Infinity;
                arg.RetrieveAllEntries = true;
                client.GetStatus(WorkingCopy, arg, out statuses);
                foreach (var item in statuses)
                {
                    if (string.IsNullOrEmpty(svn.RootUrl))
                    {
                        svn.RootUrl = item.RepositoryRoot.AbsoluteUri;
                    }
                    svn.MinRevision = item.Revision > 0 && (item.Revision < svn.MinRevision || svn.MinRevision == 0) ? item.Revision : svn.MinRevision;
                    svn.MaxRevision = item.Revision > 0 && (item.Revision > svn.MaxRevision || svn.MaxRevision == 0) ? item.Revision : svn.MaxRevision;
                    svn.IsSvnItem   = false;
                    switch (item.LocalNodeStatus)
                    {
                    case SvnStatus.None:
                    case SvnStatus.NotVersioned:
                    case SvnStatus.Ignored:
                        break;

                    case SvnStatus.External:
                    case SvnStatus.Incomplete:
                    case SvnStatus.Normal:
                        svn.IsSvnItem = true;
                        break;

                    default:
                        svn.IsSvnItem        = true;
                        svn.HasModifications = true;
                        break;
                    }
                    switch (item.LocalPropertyStatus)
                    {
                    case SvnStatus.None:
                    case SvnStatus.NotVersioned:
                    case SvnStatus.Ignored:
                        break;

                    case SvnStatus.External:
                    case SvnStatus.Incomplete:
                    case SvnStatus.Normal:
                        svn.IsSvnItem = true;
                        break;

                    default:
                        svn.IsSvnItem        = true;
                        svn.HasModifications = true;
                        break;
                    }
                }

                svn.MixedRevisions = svn.MinRevision != svn.MaxRevision;
                svn.RevisionRange  = String.Format("{0}:{1}", svn.MinRevision, svn.MaxRevision);
            }
        }
Пример #36
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");
            }
        }
Пример #37
0
        public static bool CheckIsSvnDir(string path)
        {
            SvnClient client = new SvnClient();

            return(false);
        }
Пример #38
0
        private static void GetLogs(bool console_mode, string application_path, string repository_location, long last_revision, Output_Type output_type)
        {
            SvnTarget repository;

            SvnClient client = new SvnClient();

            long current_revision = -1;

            if (SvnTarget.TryParse(repository_location, out repository) == true)
            {
                try
                {
                    SvnInfoEventArgs info;
                    client.GetInfo(new Uri(repository_location), out info);
                    current_revision = info.Revision;
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);

                    if (console_mode == true)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }

                if (last_revision < current_revision)
                {
                    DataTable datatable = new DataTable("log");
                    datatable.Columns.Add("Revision", typeof(long));
                    datatable.Columns.Add("Author", typeof(string));
                    datatable.Columns.Add("Time", typeof(DateTime));
                    datatable.Columns.Add("ChangedPaths", typeof(string));
                    datatable.Columns.Add("LogMessage", typeof(string));

                    try
                    {
                        System.Collections.ObjectModel.Collection <SvnLogEventArgs> logitems = new System.Collections.ObjectModel.Collection <SvnLogEventArgs>();

                        SvnLogArgs logargs = new SvnLogArgs(new SvnRevisionRange(current_revision, last_revision + 1));

                        client.GetLog(new Uri(repository_location), logargs, out logitems);

                        datatable.BeginLoadData();

                        foreach (SvnLogEventArgs logitem in logitems)
                        {
                            StringBuilder ChangedPaths = new StringBuilder();

                            if (logitem.ChangedPaths != null)
                            {
                                foreach (SvnChangeItem path in logitem.ChangedPaths)
                                {
                                    ChangedPaths.AppendFormat("{1} {2}{0}", Environment.NewLine, path.Action, path.Path);

                                    if (path.CopyFromRevision != -1)
                                    {
                                        ChangedPaths.AppendFormat("{1} -> {2}{0}", Environment.NewLine, path.CopyFromPath, path.CopyFromRevision);
                                    }
                                }
                            }

                            DataRow datarow = datatable.NewRow();
                            datarow["Revision"]     = logitem.Revision;
                            datarow["Author"]       = logitem.Author;
                            datarow["Time"]         = logitem.Time.ToLocalTime();
                            datarow["ChangedPaths"] = ChangedPaths.ToString();
                            datarow["LogMessage"]   = logitem.LogMessage;

                            datatable.Rows.Add(datarow);
                        }

                        datatable.EndLoadData();

                        datatable.AcceptChanges();

                        switch (output_type)
                        {
                        case Output_Type.Console:
                            OutputToConsole(console_mode, application_path, datatable);

                            break;

                        case Output_Type.Txt:
                            OutputToTxt(console_mode, application_path, datatable);

                            break;

                        case Output_Type.XML:
                            OutputToXML(console_mode, application_path, datatable);

                            break;

                        case Output_Type.XMLTransform:
                            OutputToXMLTransform(console_mode, application_path, datatable);

                            break;

                        case Output_Type.RSS:
                            OutputToRSS(console_mode, application_path, datatable);

                            break;

                        default:
                            break;
                        }

                        last_revision = Convert.ToInt32(datatable.Compute("max(Revision)", string.Empty));

                        System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                        config.AppSettings.Settings.Remove("last_revision");
                        config.AppSettings.Settings.Add("last_revision", last_revision.ToString());
                        config.Save();
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.Message);

                        if (console_mode == true)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }
                }

                client.Dispose();
            }
            else
            {
                Debug.WriteLine("Unable to connect to repository");

                if (console_mode == true)
                {
                    Console.WriteLine("Unable to connect to repository");
                }
            }
        }
Пример #39
0
        public void List_ListDetails()
        {
            SvnSandBox sbox = new SvnSandBox(this);

            sbox.Create(SandBoxRepository.Default);

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

            using (SvnClient client = NewSvnClient(true, false))
            {
                string oneFile = Path.Combine(WcPath, "LocalFileForTestList");
                TouchFile(oneFile);
                client.Add(oneFile);

                SvnCommitResult ci;
                client.Commit(WcPath, out ci);
                SvnUpdateResult r;
                client.Update(WcPath, out r);

                Assert.That(r, Is.Not.Null);
                Assert.That(r.HasRevision);
                Assert.That(r.HasResultMap);
                Assert.That(r.Revision, Is.EqualTo(ci.Revision));

                bool        visited = false;
                SvnListArgs a       = new SvnListArgs();
                a.RetrieveEntries = SvnDirEntryItems.AllFieldsV15;

                client.List(new SvnPathTarget(WcPath), a, delegate(object sender, SvnListEventArgs e)
                {
                    Assert.That(e.Entry, Is.Not.Null, "Entry set");
                    Assert.That(e.RepositoryRoot, Is.Null, "Only valid when listing a Uri");

                    if (e.Path == "LocalFileForTestList")
                    {
                        Assert.That(e.BasePath, Is.EqualTo("/trunk"), "Basepath");
                        Assert.That(e.Lock, Is.Null);
                        Assert.That(e.Entry.Author, Is.EqualTo(Environment.UserName));
                        Assert.That(e.Entry.FileSize, Is.EqualTo(0));
                        Assert.That(e.Entry.NodeKind, Is.EqualTo(SvnNodeKind.File));
                        Assert.That(e.Entry.Revision, Is.EqualTo(ci.Revision));
                        Assert.That(e.Entry.Time, Is.GreaterThan(DateTime.UtcNow - new TimeSpan(0, 5, 0)));
                        visited = true;
                    }
                });
                Assert.That(visited, Is.True, "Visited is true");


                visited = false;
                client.List(WcUri, a, delegate(object sender, SvnListEventArgs e)
                {
                    Assert.That(e.Entry, Is.Not.Null, "Entry set");

                    if (e.Path == "LocalFileForTestList")
                    {
                        Assert.That(e.BasePath, Is.EqualTo("/trunk"), "Basepath");
                        Assert.That(e.Lock, Is.Null);
                        Assert.That(e.Entry.Author, Is.EqualTo(Environment.UserName));
                        Assert.That(e.Entry.FileSize, Is.EqualTo(0));
                        Assert.That(e.Entry.NodeKind, Is.EqualTo(SvnNodeKind.File));
                        Assert.That(e.Entry.Revision, Is.EqualTo(ci.Revision));
                        Assert.That(e.Entry.Time, Is.GreaterThan(DateTime.UtcNow - new TimeSpan(0, 5, 0)));
                        visited = true;
                    }
                });
                Assert.That(visited, Is.True, "Visited is true");

                SvnWorkingCopyClient wcC = new SvnWorkingCopyClient();
                SvnWorkingCopyState  state;
                Assert.That(wcC.GetState(oneFile, out state));

                Assert.That(state, Is.Not.Null);
                Assert.That(state.IsTextFile, Is.True);

                client.SetProperty(oneFile, "svn:mime-type", "application/binary");

                Assert.That(wcC.GetState(oneFile, out state));

                Assert.That(state, Is.Not.Null);
                Assert.That(state.IsTextFile, Is.False);
            }
        }
Пример #40
0
        public override ObservableList <SolutionInfo> GetProjectsList()
        {
            ObservableList <SolutionInfo> SourceControlSolutions = new ObservableList <SolutionInfo>();

            if (SourceControlURL.ToUpper().Trim().StartsWith("HTTP"))
            {
                WebRequest request = WebRequest.Create(SourceControlURL);
                request.Timeout     = 60000;
                request.Credentials = new System.Net.NetworkCredential(SourceControlUser, SourceControlPass);
                SourceControlSolutions.Clear();
                Stream objStream;

                objStream = request.GetResponse().GetResponseStream();
                StreamReader objReader = new StreamReader(objStream);

                //quick and dirty way to get the folder instead of messing with XML
                string sLine = "";
                while (!objReader.EndOfStream)
                {
                    sLine = objReader.ReadLine();
                    if (sLine.Contains("dir name"))
                    {
                        int    i1           = sLine.IndexOf("dir name=");
                        int    len          = sLine.IndexOf(" href") - i1 - 11;
                        string SolutionName = sLine.Substring(i1 + 10, len);

                        AddSolution(SourceControlSolutions, SourceControlLocalFolder + @"\" + SolutionName, SolutionName);
                    }
                    else if (sLine.StartsWith("  <li><a href=\""))
                    {
                        int start = sLine.IndexOf("\"");
                        sLine = sLine.Substring(start + 1);
                        int    end          = sLine.IndexOf("\"");
                        string SolutionName = sLine.Substring(0, end - 1);

                        if (!SolutionName.Contains("."))
                        {
                            AddSolution(SourceControlSolutions, SourceControlLocalFolder + @"\" + SolutionName, SolutionName);
                        }
                    }
                }
            }
            else if (SourceControlURL.ToUpper().Trim().StartsWith("SVN"))
            {
                using (SvnClient sc = new SvnClient())
                {
                    sc.Authentication.DefaultCredentials = new System.Net.NetworkCredential(SourceControlUser, SourceControlPass);
                    Uri targetUri = new Uri(SourceControlURL);
                    var target    = SvnTarget.FromUri(targetUri);
                    Collection <SvnInfoEventArgs> info;
                    bool result = sc.GetInfo(target, new SvnInfoArgs {
                        ThrowOnError = false
                    }, out info);
                    SourceControlSolutions.Clear();
                    if (result)
                    {
                        foreach (var f in info)
                        {
                            AddSolution(SourceControlSolutions, SourceControlLocalFolder + @"\" + f.Path, f.Uri.OriginalString);
                        }
                    }
                }
            }
            return(SourceControlSolutions);
        }
Пример #41
0
        private void dlModWorker(object sender, DoWorkEventArgs e)
        {
            List <Mod> checkedMods = new List <Mod>();

            foreach (Mod listedMod in downloadableModsList.Items)
            {
                if (listedMod.IsChecked == true)
                {
                    checkedMods.Add(listedMod);
                }
            }
            if (checkedMods.Count == 0)
            {
                return;
            }

            Dispatcher.Invoke(new Action(() =>
            {
                modsTabs.IsEnabled    = false;
                menu.IsEnabled        = false;
                everythingGrid.Effect = new BlurEffect {
                    Radius = 10
                };
                installLogGrid.Visibility = Visibility.Visible;
                closeLogButton.Visibility = Visibility.Collapsed;
                closeLogButton.Focus();
                installLogBox.Text  = "";
                installLogBox.Text += "-- " + downloadingmods.ToUpper() + " --" + Environment.NewLine + Environment.NewLine;
            }));

            int i = 0;

            foreach (Mod checkedMod in checkedMods)
            {
                i++;
                Dispatcher.Invoke(new Action(() =>
                {
                    installLogBox.Text += downloadingmods + " (" + i + "/" + checkedMods.Count + ") : " + checkedMod.Name + " " + checkedMod.Version + Environment.NewLine;
                }));

                SvnClient svnClient = new SvnClient();
                svnClient.Progress += new EventHandler <SvnProgressEventArgs>(svnProgress);
                string remoteLocation = repository + Path.GetDirectoryName(checkedMod.Location);
                string localLocation  = Path.GetDirectoryName(Path.Combine(System.IO.Directory.GetCurrentDirectory(), "mods", "tagmods", checkedMod.Location.Replace("/", "\\")));

                try
                {
                    deleteDirectory(localLocation);
                } catch
                {
                    // mod doesn't already exist - all fine
                }

                if (!Directory.Exists(localLocation))
                {
                    Directory.CreateDirectory(localLocation);
                }

                if (Directory.Exists(Path.Combine(localLocation, ".svn")))
                {
                    svnClient.CleanUp(localLocation);
                }

                try
                {
                    svnClient.CheckOut(new Uri(remoteLocation), localLocation);
                    Dispatcher.Invoke(new Action(() =>
                    {
                        installLogBox.Text += "| " + moddlsuccess + Environment.NewLine;
                    }));
                }
                catch
                {
                    Dispatcher.Invoke(new Action(() =>
                    {
                        installLogBox.Text += "| " + moddlfailed + Environment.NewLine;
                    }));
                }
            }

            Dispatcher.Invoke(new Action(() =>
            {
                MessageBox.Show(Application.Current.MainWindow, modsdownloaded, this.Title, MessageBoxButton.OK, MessageBoxImage.Information);
                closeLogButton.Visibility = Visibility.Visible;

                foreach (Mod listedMod in downloadableModsList.Items)
                {
                    if (listedMod.IsChecked == true)
                    {
                        listedMod.IsChecked = false;
                    }
                }

                mMods.Clear();
                infobarScroll.Visibility = Visibility.Collapsed;
                workerPopulateMyMods.RunWorkerAsync();
            }));
        }
        private LoadSourcesResult LoadSourcesFromScratch(SourceControlVersion sourceControlVersion, string path, SvnClient client)
        {
            SvnUpdateResult result;

            Directory.CreateDirectory(path);

            string uriString = this.GetVersionURI(sourceControlVersion);

            client.CheckOut(new Uri(uriString), path, out result);

            SvnInfoEventArgs info;

            client.GetInfo(path, out info);

            return(new LoadSourcesResult
            {
                RevisionId = info.LastChangeRevision.ToString(CultureInfo.InvariantCulture)
            });
        }
Пример #43
0
        public static bool TraerObjeto(string origen, string destino, string usuario, string clave, out string respuesta, int revision = -1)
        {
            try
            {
                destino = destino.ToUpper();
                // Obtener la ruta del repositorio
                int    index       = Cadena.EncontrarEnesimaCoincidencia('/', origen, 4);
                string repositorio = origen.Substring(0, index);
                string instancia   = repositorio.Substring(repositorio.LastIndexOf('/') + 1);

                // Verificar si existen subcarpetas
                if (origen.Substring(index + 1).IndexOf('/') > 0)
                {
                    // Existe una subcarpeta
                    // Obtener lista de subcarpetas
                    string[] subCarpetas         = ListarCarpetas(repositorio, usuario, clave);
                    string   subCarpeta          = origen.Substring(index + 1, Cadena.EncontrarEnesimaCoincidencia('/', origen, 5) - index - 1);
                    string   subCarpetaCorregida = Cadena.EncontrarTextoEnArreglo(subCarpeta, subCarpetas);
                    if (String.IsNullOrEmpty(subCarpetaCorregida))
                    {
                        respuesta = String.Format("No se encuentra la carpeta {0} en el versionador", subCarpeta);
                        return(false);
                    }
                    string urlCorregidaBase = String.Concat(repositorio, "/", subCarpetaCorregida);

                    // Obtener lista de objetos
                    string[] objetos         = ListarArchivos(urlCorregidaBase, usuario, clave);
                    string   objeto          = origen.Substring(Cadena.EncontrarEnesimaCoincidencia('/', origen, 5) + 1);
                    string   objetoCorregido = Cadena.EncontrarTextoEnArreglo(objeto, objetos);
                    if (String.IsNullOrEmpty(objetoCorregido))
                    {
                        respuesta = String.Format("No se encuentra el objeto {0} en el versionador", objeto);
                        return(false);
                    }
                    string urlCorregido = String.Concat(urlCorregidaBase, "/", objetoCorregido);

                    // Verificar si la carpeta del repositorio=instancia existe
                    if (!Directory.Exists(destino))
                    {
                        // No existe la carpeta, crearla
                        Directory.CreateDirectory(destino);
                    }

                    // Verificar si el archivo existe
                    string rutaArchivoLocal = String.Concat(destino, "\\", objetoCorregido);
                    if (File.Exists(rutaArchivoLocal))
                    {
                        // Si existe el archivo, eliminarlo
                        File.Delete(rutaArchivoLocal);
                    }

                    // Traer el objeto a la carpeta destino
                    SvnClient svnClient = new SvnClient();
                    svnClient.Authentication.ForceCredentials(usuario, clave);
                    //svnClient.Authentication.Clear();
                    //svnClient.Authentication.DefaultCredentials =  //new NetworkCredential(usuario, clave);
                    if (revision == -1)
                    {
                        svnClient.Export(urlCorregido, rutaArchivoLocal);
                    }
                    else
                    {
                        SvnRevision rev = new SvnRevision(revision);
                        svnClient.Export(urlCorregido, rutaArchivoLocal, new SvnExportArgs()
                        {
                            Revision = rev
                        });
                    }
                }
                else
                {
                    // El archivo se encuentra en la raíz del repositorio.
                    string[] objetos         = ListarArchivos(repositorio, usuario, clave);
                    string   objeto          = origen.Substring(Cadena.EncontrarEnesimaCoincidencia('/', origen, 4) + 1);
                    string   objetoCorregido = Cadena.EncontrarTextoEnArreglo(objeto, objetos);
                    if (String.IsNullOrEmpty(objetoCorregido))
                    {
                        respuesta = String.Format("No se encuentra el objeto {0} en el versionador", objeto);
                        return(false);
                    }
                    string urlCorregido = String.Concat(instancia, "\\", objetoCorregido);

                    // Verificar si el archivo existe
                    string rutaArchivoLocal = String.Concat(instancia, "\\", repositorio, "\\", objetoCorregido);
                    if (File.Exists(rutaArchivoLocal))
                    {
                        // Si existe el archivo, eliminarlo
                        File.Delete(rutaArchivoLocal);
                    }

                    // Traer el objeto a la carpeta destino
                    SvnClient svnClient = new SvnClient();
                    svnClient.Authentication.DefaultCredentials = new NetworkCredential(usuario, clave);
                    svnClient.Export(urlCorregido, destino);
                }
                respuesta = String.Format("{0} Copiado satisfactoriamente", origen);
                return(true);
            }
            catch (SvnRepositoryIOException ex)
            {
                respuesta = ex.Message;
                return(false);
            }
        }
Пример #44
0
        public static bool SvnUpdate(string path)
        {
            SvnClient client = new SvnClient();

            return(client.Update(path));
        }
Пример #45
0
        public void TestChangeLists()
        {
            SvnSandBox sbox = new SvnSandBox(this);

            sbox.Create(SandBoxRepository.Default);

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

            string file1 = Path.Combine(WcPath, "ChangeListFile1");
            string file2 = Path.Combine(WcPath, "ChangeListFile2");
            string file3 = Path.Combine(WcPath, "ChangeListFile3");
            string file4 = Path.Combine(WcPath, "ChangeListFile4");

            using (SvnClient client = NewSvnClient(true, false))
            {
                SvnInfoArgs ia = new SvnInfoArgs();
                ia.ThrowOnError = false;
                SvnInfoEventArgs iea;
                Collection <SvnInfoEventArgs> ee;
                Assert.That(client.GetInfo(new Uri(WcUri, "ChangeListFile1"), ia, out ee), Is.False);
                Assert.That(client.GetInfo(new Uri(WcUri, "ChangeListFile2"), ia, out ee), Is.False);
                Assert.That(client.GetInfo(new Uri(WcUri, "ChangeListFile3"), ia, out ee), Is.False);
                Assert.That(client.GetInfo(new Uri(WcUri, "ChangeListFile4"), ia, out ee), Is.False);

                TouchFile(file1);
                TouchFile(file2);
                TouchFile(file3);
                TouchFile(file4);

                client.Add(file1);
                client.Commit(WcPath);

                client.GetInfo(new Uri(WcUri, "ChangeListFile1"), out iea);
                Assert.That(iea, Is.Not.Null);

                client.Add(file2);
                client.Add(file3);
                client.Add(file4);

                client.AddToChangeList(file2, "ChangeListTest-2");
                client.AddToChangeList(file3, "ChangeListTest-3");

                Collection <SvnListChangeListEventArgs> paths;
                SvnListChangeListArgs a = new SvnListChangeListArgs();
                a.ChangeLists.Add("ChangeListTest-2");

                client.GetChangeList(WcPath, a, out paths);

                Assert.That(paths, Is.Not.Null);
                Assert.That(paths.Count, Is.EqualTo(1));
                Assert.That(paths[0].Path, Is.EqualTo(SvnTools.GetNormalizedFullPath(file2)));

                a = new SvnListChangeListArgs();
                a.ChangeLists.Add("ChangeListTest-4");
                client.GetChangeList(WcPath, a, out paths);

                Assert.That(paths, Is.Not.Null);
                Assert.That(paths.Count, Is.EqualTo(0));

                SvnCommitArgs ca = new SvnCommitArgs();
                ca.ChangeLists.Add("ChangeListTest-2");

                client.Commit(WcPath, ca);

                Assert.That(client.GetInfo(new Uri(WcUri, "ChangeListFile2"), ia, out ee), Is.True);
                Assert.That(client.GetInfo(new Uri(WcUri, "ChangeListFile3"), ia, out ee), Is.False);
                Assert.That(client.GetInfo(new Uri(WcUri, "ChangeListFile4"), ia, out ee), Is.False);

                bool visited = false;
                a = new SvnListChangeListArgs();
                a.ChangeLists.Add("ChangeListTest-3");
                client.ListChangeList(WcPath, a, delegate(object sender, SvnListChangeListEventArgs e)
                {
                    Assert.That(e.Path, Is.EqualTo(file3));
                    visited = true;
                });
                Assert.That(visited, Is.True);

                visited = false;
                client.Status(file4, delegate(object sender, SvnStatusEventArgs e)
                {
                    Assert.That(e.FullPath, Is.EqualTo(file4));
                    Assert.That(e.LocalNodeStatus, Is.EqualTo(SvnStatus.Added));
                    Assert.That(e.IsRemoteUpdated, Is.False);
                    Assert.That(e.Path, Is.EqualTo(file4));
                    visited = true;
                });
                Assert.That(visited, Is.True);

                client.Commit(WcPath);

                Assert.That(client.GetInfo(new Uri(WcUri, "ChangeListFile3"), ia, out ee), Is.True);
                Assert.That(client.GetInfo(new Uri(WcUri, "ChangeListFile4"), ia, out ee), Is.True);
            }
        }
Пример #46
0
        public static bool SvnCleanup(string path)
        {
            SvnClient client = new SvnClient();

            return(client.CleanUp(path));
        }
        protected override IEnumerable <string> GetCommitMessages()
        {
            SvnWorkingCopyVersion svnWorkingCopyVersion;

            using (var svnWorkingCopyClient = new SvnWorkingCopyClient())
            {
                if (!svnWorkingCopyClient.GetVersion(this.RepositoryPath,
                                                     out svnWorkingCopyVersion) ||
                    svnWorkingCopyVersion == null)
                {
                    this.LogError?.Invoke($"Could not get working copy version for {this.RepositoryPath}");
                    return(Enumerable.Empty <string>());
                }
            }

            if (svnWorkingCopyVersion.Modified)
            {
                this.LogError?.Invoke($"Could not calculate version for {this.RepositoryPath} due to local uncomitted changes");
                return(Enumerable.Empty <string>());
            }

            Collection <SvnLogEventArgs> logItems;

            using (var svnClient = new SvnClient())
            {
                SvnRevision start;
                if (this.BaseRevision == null)
                {
                    start = SvnRevision.Zero;
                }
                else
                {
                    int startRevision;
                    if (!int.TryParse(this.BaseRevision,
                                      out startRevision))
                    {
                        this.LogError?.Invoke($"could not parse {nameof(this.BaseRevision)} to {typeof (int).FullName}: {this.BaseRevision}");
                        return(Enumerable.Empty <string>());
                    }
                    start = startRevision;
                }

                this.LogInfo?.Invoke($"retrieving commits from {this.RepositoryPath} since {start}");

                var svnLogArgs = new SvnLogArgs
                {
                    StrictNodeHistory = false,
                    Range             = new SvnRevisionRange(start,
                                                             SvnRevision.Head)
                };
                if (!svnClient.GetLog(this.RepositoryPath,
                                      svnLogArgs,
                                      out logItems) ||
                    logItems == null)
                {
                    this.LogError?.Invoke($"Could not get log for repository in {this.RepositoryPath}");
                    return(null);
                }
            }

            var commitMessages = logItems.OrderBy(arg => arg.Revision)
                                 .Select(arg => arg.LogMessage);

            return(commitMessages);
        }
Пример #48
0
        public static bool SvnCommit(string path)
        {
            SvnClient client = new SvnClient();

            return(client.Commit(path));
        }
Пример #49
0
        static void Main(string[] args)
        {
            Console.WriteLine("Добро пожаловать в установщик продуктов компании \"Правильные измерения\"!");

            string userName = "******";

            string gitPublicApiUrl = "https://api.github.com/orgs/" + userName + "/repos?per_page=1000";

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

LBL_START:
            Console.WriteLine("Список продуктов загружается...\n");
            using (WebClient webClient = new WebClient())
            {
                webClient.Headers["User-Agent"] = "Mozilla/5.0";
                var json = webClient.DownloadString(gitPublicApiUrl);

                var repositoryList = RepositoryList.FromJson(json);
                int i = 0;
                foreach (var repository in repositoryList)
                {
                    Console.WriteLine(i.ToString() + ": " + repository.Name);
                    i++;
                }
                Console.WriteLine();

INPUT_IDX:

                Console.Write("Введите индекс репозитория для копирования: ");
                string inpStr      = Console.ReadLine().Trim();
                int    selectedIdx = 0;
                bool   res         = int.TryParse(inpStr, out selectedIdx);
                if (!res || selectedIdx < 0 || selectedIdx > repositoryList.Count)
                {
                    goto INPUT_IDX;
                }

                string repositoryName = repositoryList[selectedIdx].Name;
                string projectName    = repositoryList[selectedIdx].Description;

                string remoteURL    = "https://github.com/" + userName + "/" + repositoryName + "/trunk/";
                bool   bFullProject = false;
                if (projectName != null && projectName.Length > 0)
                {
                    Console.Write("Введите [1] для копирования всего проекта, если нужен лишь исполнимый файл, нажмите ввод: ");
                    inpStr = Console.ReadLine().Trim();
                    if (inpStr.Length == 0)
                    {
                        remoteURL = $"https://github.com/{userName}/{repositoryName}/trunk/{projectName}/bin/Debug/";
                    }
                    else
                    {
                        bFullProject = true;
                    }
                }

LBL_REPEAT:

                string targetDirectory = @"C:\" + userName + @"\" + repositoryName;

                Console.WriteLine("\nURL: " + remoteURL);
                Console.WriteLine("Дирректория установки: " + targetDirectory);
                Console.WriteLine("Копировать весь проект: " + bFullProject);


                if (Directory.Exists(targetDirectory))
                {
                    Console.Write("\nУдаляем старые файлы...");
                    Directory.Delete(targetDirectory, true);
                    Console.Write("Готово!\n");
                }
                else
                {
                    Console.WriteLine("");
                }

                Console.Write("Ожидайте...");

                SvnClient     svnClient  = new SvnClient();
                SvnUriTarget  target     = new SvnUriTarget(remoteURL);
                SvnExportArgs svnExpArgs = new SvnExportArgs();
                try
                {
                    svnClient.Export(target, targetDirectory, svnExpArgs, out SvnUpdateResult svnUpdRes);
                    Console.Write("Завершено!\n");

                    if (Directory.Exists(targetDirectory))
                    {
                        Process.Start(targetDirectory);
                    }
                }
                catch (Exception ex)
                {
                    Console.Write("ОШИБКА:\n" + ex.Message + "\n");
                }


                Console.WriteLine("Выход - ESC, Повтор - SPACE, начать заново - любая клавиша");
                ConsoleKeyInfo cki = Console.ReadKey();
                if (cki.Key == ConsoleKey.Escape)
                {
                    Environment.Exit(-1);
                }
                else if (cki.Key == ConsoleKey.Spacebar)
                {
                    Console.Clear();
                    goto LBL_REPEAT;
                }
                else
                {
                    Console.Clear();
                    goto LBL_START;
                }
            }
        }
Пример #50
0
        /// <summary>
        /// Initialize the Subversion adapter based on the TestEnvironment and the test EndPoint data
        /// </summary>
        /// <param name="endPoint"></param>
        public void Initialize(MigrationTestLibrary.EndPoint endPoint)
        {
            Trace.TraceInformation("SubversionTCAdapter: Initialize BEGIN");
            m_serverUri = new Uri(endPoint.ServerUrl, UriKind.Absolute);

            foreach (Setting s in endPoint.CustomSettingsList)
            {
                if (String.Equals(s.Key, "Username", StringComparison.OrdinalIgnoreCase))
                {
                    m_userName = s.Value;
                }
                if (String.Equals(s.Key, "Password", StringComparison.OrdinalIgnoreCase))
                {
                    m_password = s.Value;
                }
            }

            if (String.IsNullOrEmpty(m_userName))
            {
                m_userName = Environment.UserName;
                endPoint.CustomSettingsList.Add(new Setting()
                {
                    Key = "Username", Value = m_userName
                });
            }
            Trace.TraceInformation("Using SVN username '{0}'", m_userName);

            if (String.IsNullOrEmpty(m_password))
            {
                m_password = m_userName;
                endPoint.CustomSettingsList.Add(new Setting()
                {
                    Key = "Password", Value = m_password
                });
            }

            // set these values to something so the product code doesn't complain later
            endPoint.TeamProject = "unusedSVNProjectName";

            //Create a new instance of the svn client
            m_client = new SvnClient();

            Trace.TraceInformation("Setting SVN credentials");
            //Use the credentials if we have any
            if (!string.IsNullOrEmpty(m_userName))
            {
                m_client.Authentication.DefaultCredentials = new NetworkCredential(m_userName, m_password);
            }

            //Ensure that we can access the repository. The easist way is to query any information. We will receive an exception if a connection cannot be established
            //Trace.TraceInformation("Testing SVN access");
            //m_client.GetRepositoryRoot(m_serverUri);

            // endPoint.ServerUrl includes the repository
            string serverRoot = endPoint.ServerUrl;
            string localRoot  = endPoint.LocalStorageLocation;

            if (String.IsNullOrEmpty(localRoot))
            {
                localRoot = Environment.ExpandEnvironmentVariables(@"%systemdrive%\SvnTest");
            }

            Directory.CreateDirectory(localRoot);

            // now map the 'mt' test folder, adding it if it does not exist
            string serverTestRootFolder = String.Format("{0}/{1}", serverRoot, "tests");
            string localTestRootFolder  = String.Format(@"{0}\{1}", localRoot, "tests");

            // assume that the test root folder is already in SVN
            try
            {
                Trace.TraceInformation("Checking out SVN test root folder");
                m_client.CheckOut(new SvnUriTarget(serverTestRootFolder), localTestRootFolder);
            }
            catch (SharpSvn.SvnRepositoryIOException)
            {
                Trace.TraceInformation("Adding base test folder to SVN: {0} -> {1}", localRoot, serverRoot);

                // backup and map just the root
                Trace.TraceInformation("Checking out SVN root folder");
                m_client.CheckOut(new SvnUriTarget(serverRoot), localRoot);

                // create and map the main test folder
                Directory.CreateDirectory(localTestRootFolder);
                m_client.Add(localTestRootFolder);
                m_client.Commit(localTestRootFolder, new SvnCommitArgs()
                {
                    LogMessage = "Adding automated tests root folder"
                });
                Trace.TraceInformation("Committed SVN root folder");
            }

            // create the new folder specific for this test
            string testFolder = String.Format(@"{0}.{1}", DateTime.Now.ToString("yyyyMMdd.HHmmss"), endPoint.TestName);

            m_filterPath = String.Format(@"/{0}/{1}", "tests", testFolder);
            m_localPath  = String.Format(@"{0}\{1}", localTestRootFolder, testFolder);
            string serverTestFolder = String.Format("{0}/{1}", serverTestRootFolder, testFolder);

            //m_filterPath = serverTestFolder;

            Directory.CreateDirectory(m_localPath);
            Trace.TraceInformation("Adding test folder to SVN: {0} -> {1}", m_localPath, serverTestFolder);
            m_client.Add(m_localPath);
            m_client.Commit(m_localPath, new SvnCommitArgs()
            {
                LogMessage = "Adding test folder"
            });
            Trace.TraceInformation("Committed test folder for this test");

            Trace.TraceInformation("m_workspaceLocalPath: {0}", m_localPath);
            Trace.TraceInformation("m_filterPath: {0}", m_filterPath);

            Trace.TraceInformation("SubversionTCAdapter: Initialize END");
        }
Пример #51
0
 public static void Update(string target, string SVNUser, string SVNPassword)
 {
     SvnClient client  = InitializeSvnClient(SVNUser, SVNPassword);
     bool      success = client.Update(target);
 }
Пример #52
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="client"></param>
        /// <param name="ei"></param>
        /// <param name="hostUrl">url of directory where the svn external is defined</param>
        /// <returns></returns>
        public static bool GetFullReferenceUrl(SvnClient client, SvnExternalItem ei, string hostUrl, out string result)
        {
            var url = ei.Reference;

            result = url;

            if (url.StartsWith("^/../"))
            {
                var relativeUrl = url.Substring(1);

                // get repo root
                SvnInfoEventArgs info;
                if (!client.GetInfo(new Uri(hostUrl), out info))
                {
                    return(false);
                }

                // normalize <server>/repo1/../repo2/xxx to <server>/repo2/xxx
                string combinedUrl           = CombineUrls(info.RepositoryRoot.AbsoluteUri, relativeUrl);
                var    combinedNormalizedUri = SvnTools.GetNormalizedUri(new Uri(combinedUrl));
                result = combinedNormalizedUri.AbsoluteUri;

                return(true);
            }
            else
            if (url.StartsWith("^/"))
            {
                var relativeUrl = url.Substring(1);

                // get repo root
                SvnInfoEventArgs info;
                if (!client.GetInfo(new Uri(hostUrl), out info))
                {
                    return(false);
                }

                result = CombineUrls(info.RepositoryRoot.AbsoluteUri, relativeUrl);
                return(true);
            }
            else
            if (url.StartsWith("//"))
            {
                // FIXME: add support
                Logger.Error($"Unsupported relative external '{url}'");
                throw new Exception($"Unsupported relative external '{url}'");
                //return false;
            }
            else
            if (url.StartsWith(".."))
            {
                // FIXME: add support
                Logger.Error($"Unsupported relative external '{url}'");
                throw new Exception($"Unsupported relative external '{url}'");
                //return false;
            }
            else
            if (url.StartsWith("/"))
            {
                // FIXME: add support
                Logger.Error($"Unsupported relative external '{url}'");
                throw new Exception($"Unsupported relative external '{url}'");
                //return false;
            }
            else
            {
                // leave the result same as url
                return(true);
            }


            //return false;
        }
Пример #53
0
        public void Merge_MinimalMergeTest()
        {
            SvnSandBox sbox = new SvnSandBox(this);

            sbox.Create(SandBoxRepository.Empty);

            using (SvnClient client = NewSvnClient(true, false))
            {
                string merge1 = Path.Combine(sbox.Wc, "mmerge-1");
                string merge2 = Path.Combine(sbox.Wc, "mmerge-2");
                client.CreateDirectory(merge1);

                string f1 = Path.Combine(merge1, "myfile.txt");

                using (StreamWriter fs = File.CreateText(f1))
                {
                    fs.WriteLine("First line");
                    fs.WriteLine("Second line");
                    fs.WriteLine("Third line");
                    fs.WriteLine("Fourth line");
                }

                client.Add(f1);

                SvnCommitResult ci;
                client.Commit(sbox.Wc, out ci);
                client.Copy(new SvnPathTarget(merge1), merge2);
                client.Commit(sbox.Wc);
                client.Update(sbox.Wc);

                SvnMergeSourcesCollection sources;
                client.GetSuggestedMergeSources(new SvnPathTarget(merge1), out sources);

                Assert.That(sources.Count, Is.EqualTo(0));

                client.GetSuggestedMergeSources(new SvnPathTarget(merge2), out sources);

                Assert.That(sources.Count, Is.EqualTo(1));

                Uri fromUri = new Uri(sbox.RepositoryUri, new Uri("mmerge-1", UriKind.Relative));
                Assert.That(sources[0].Uri, Is.EqualTo(fromUri));

                SvnAppliedMergeInfo applied;
                client.GetAppliedMergeInfo(new SvnPathTarget(merge2), out applied);

                Assert.That(applied, Is.Null);
                //Assert.That(applied.AppliedMerges.Count, Is.EqualTo(0));
                //Assert.That(applied.Target, Is.Not.Null);

                Collection <SvnMergesEligibleEventArgs> available;
                client.GetMergesEligible(new SvnPathTarget(merge2), fromUri, out available);
                Assert.That(available, Is.Not.Null);
                Assert.That(available.Count, Is.EqualTo(0));

                /*Assert.That(available[0].Revision, Is.EqualTo(ci.Revision));
                 * //Assert.That(available.MergeRanges[0].End, Is.EqualTo(ci.Revision + 1));
                 * //Assert.That(available.MergeRanges[0].Inheritable, Is.True);
                 * Assert.That(available[0].SourceUri, Is.Not.Null);*/

                using (StreamWriter fs = File.AppendText(f1))
                {
                    fs.WriteLine("Fifth line");
                }
                client.Commit(merge1);

                client.GetMergesEligible(new SvnPathTarget(merge2), fromUri, out available);
                Assert.That(available, Is.Not.Null);
                Assert.That(available.Count, Is.EqualTo(1));
                Assert.That(available[0].Revision, Is.EqualTo(3));
                Assert.That(available[0].SourceUri, Is.Not.Null);

                client.Merge(merge2, fromUri, available[0].AsRange());

                client.GetMergesEligible(new SvnPathTarget(merge2), fromUri, out available);
                Assert.That(available, Is.Not.Null);
                Assert.That(available.Count, Is.EqualTo(0));

                client.Commit(sbox.Wc);

                client.GetMergesEligible(new SvnPathTarget(merge2), fromUri, out available);
                Assert.That(available, Is.Not.Null);
                Assert.That(available.Count, Is.EqualTo(0));

                client.GetAppliedMergeInfo(new SvnPathTarget(merge2), out applied);

                Assert.That(applied, Is.Not.Null);
                Assert.That(applied.AppliedMerges.Count, Is.EqualTo(1));
                Assert.That(applied.AppliedMerges[0].Uri, Is.EqualTo(fromUri));
                Assert.That(applied.AppliedMerges[0].MergeRanges, Is.Not.Null);
                Assert.That(applied.AppliedMerges[0].MergeRanges.Count, Is.EqualTo(1));
                Assert.That(applied.AppliedMerges[0].MergeRanges[0].Start, Is.EqualTo(ci.Revision + 1));
                Assert.That(applied.AppliedMerges[0].MergeRanges[0].End, Is.EqualTo(ci.Revision + 2));
                Assert.That(applied.AppliedMerges[0].MergeRanges[0].Inheritable, Is.True);
                Assert.That(applied.Target, Is.Not.Null);
            }
        }
Пример #54
0
        private void BuildAnkhCases(Uri uri)
        {
            using (SvnClient client = new SvnClient())
            {
                client.UseDefaultConfiguration();
                client.Configuration.LogMessageRequired = false;

                client.RepositoryOperation(uri,
                                           delegate(SvnMultiCommandClient mucc)
                {
                    mucc.CreateDirectory("trunk");
                    mucc.CreateFile("trunk/App.ico", StringToFile("icon\n"));
                    mucc.CreateFile("trunk/AssemblyInfo.cs", StringToFile("AssemblyInfo.cs"));
                    mucc.CreateFile("trunk/Form.cs", StringToFile("Form.cs\r\n"));
                    mucc.CreateFile("trunk/Form.resx", StringToFile("Form.resx\n"));
                    mucc.CreateFile("trunk/GoogleOne.csproj", StringToFile("GoogleOne.csproj\n"));
                    mucc.CreateFile("trunk/GoogleOne.csproj.user", StringToFile("GoogleOne.csproj.user\n"));
                    mucc.CreateFile("trunk/GoogleOne.sln", StringToFile("GoogleOne.sln\n"));
                    mucc.CreateFile("trunk/GoogleOne.suo", StringToFile("GoogleOne.suo\n"));
                    mucc.CreateFile("trunk/GoogleSearch.wsdl", StringToFile("GoogleSearch.wsdl\n"));
                    mucc.CreateFile("trunk/GoogleSearchService.cs", StringToFile("GoogleSearchService.cs\n"));
                    mucc.CreateDirectory("trunk/bin");
                    mucc.CreateDirectory("trunk/bin/Debug");
                    mucc.CreateFile("trunk/bin/Debug/GoogleOne.exe", StringToFile("GoogleOne.exe\n"));
                    mucc.CreateFile("trunk/bin/Debug/GoogleOne.pdb", StringToFile("GoogleOne.pdb\n"));
                    mucc.CreateDirectory("trunk/obj");
                    mucc.CreateDirectory("trunk/obj/Debug");
                    mucc.CreateFile("trunk/obj/Debug/GoogleOne.exe", StringToFile("GoogleOne.exe\n"));
                    mucc.CreateFile("trunk/obj/Debug/GoogleOne.exe.incr", StringToFile("GoogleOne.exe.incr\n"));
                    mucc.CreateFile("trunk/obj/Debug/GoogleOne.Form.resources", StringToFile("GoogleOne.Form.resources\n"));
                    mucc.CreateFile("trunk/obj/Debug/GoogleOne.pdb", StringToFile("GoogleOne.pdb\n"));
                    mucc.CreateFile("trunk/obj/Debug/GoogleOne.projdata", StringToFile("GoogleOne.projdata\n"));

                    mucc.SetProperty("trunk/App.ico", SvnPropertyNames.SvnMimeType, "application/octet-stream");
                    mucc.SetProperty("trunk/GoogleOne.suo", SvnPropertyNames.SvnMimeType, "application/octet-stream");
                    mucc.SetProperty("trunk/bin/Debug/GoogleOne.exe", SvnPropertyNames.SvnMimeType, "application/octet-stream");
                    mucc.SetProperty("trunk/bin/Debug/GoogleOne.pdb", SvnPropertyNames.SvnMimeType, "application/octet-stream");
                    mucc.SetProperty("trunk/obj/Debug/GoogleOne.exe", SvnPropertyNames.SvnMimeType, "application/octet-stream");
                    mucc.SetProperty("trunk/obj/Debug/GoogleOne.exe.incr", SvnPropertyNames.SvnMimeType, "application/octet-stream");
                    mucc.SetProperty("trunk/obj/Debug/GoogleOne.Form.resources", SvnPropertyNames.SvnMimeType, "application/octet-stream");
                    mucc.SetProperty("trunk/obj/Debug/GoogleOne.pdb", SvnPropertyNames.SvnMimeType, "application/octet-stream");
                    mucc.SetProperty("trunk/obj/Debug/GoogleOne.projdata", SvnPropertyNames.SvnMimeType, "application/octet-stream");
                });

                client.RepositoryOperation(uri,
                                           delegate(SvnMultiCommandClient mucc)
                {
                    mucc.CreateDirectory("trunk/doc");
                    mucc.CreateFile("trunk/doc/text.txt", StringToFile("Hello\r\n"));
                });

                client.RepositoryOperation(uri,
                                           delegate(SvnMultiCommandClient mucc)
                {
                    mucc.CreateFile("trunk/doc/text_r3.txt", StringToFile("Hei\r\n"));
                });

                client.RepositoryOperation(uri,
                                           delegate(SvnMultiCommandClient mucc)
                {
                    mucc.CreateFile("trunk/doc/text_r4.txt", StringToFile("Hay\r\n"));
                });

                client.RepositoryOperation(uri,
                                           delegate(SvnMultiCommandClient mucc)
                {
                    mucc.CreateFile("trunk/doc/text_r5.txt", StringToFile("Bye\r\n"));
                });

                client.RepositoryOperation(uri,
                                           delegate(SvnMultiCommandClient mucc)
                {
                    mucc.Delete("trunk/obj");
                });
            }
        }
Пример #55
0
        public bool CopyAndClassification(SvnClient client, string s, string d, string dir, bool fromSvn, bool move = false)
        {
            var log = Log.GetInstance();

            try
            {
                if (fromSvn)
                {
                    MemoryStream stream = new MemoryStream();
                    client.Write(SvnTarget.FromUri(new Uri(s)), stream);
                    string dest = Path.Combine(dir, d);
                    Directory.CreateDirectory(dest);
                    dest = Path.Combine(dest, Path.GetFileName(s));
                    if (File.Exists(dest))
                    {
                        DialogResult dialogResult = Temp.SummaryMessageBox("the file" + dest + " is exist Do you want to overwrite it", "Info", MessageBoxIcon.Question, MessageBoxButtons.YesNo);
                        if (dialogResult == DialogResult.Yes)
                        {
                            using (FileStream outputFileStream = new FileStream(Path.Combine(dest), FileMode.OpenOrCreate, FileAccess.Write))
                            {
                                stream.WriteTo(outputFileStream);
                            }
                            log.LogToFile("Move File, " + s + " ,to " + dest + " ,at " + DateTime.Now);
                            //log.LogToDataBase("Move", "Move File " + s + " to " + dest);
                            return(true);
                        }
                        else if (dialogResult == DialogResult.No)
                        {
                            return(false);
                        }
                        else
                        {
                            return(false);
                        }
                    }
                    else
                    {
                        using (FileStream outputFileStream = new FileStream(Path.Combine(dest), FileMode.OpenOrCreate, FileAccess.Write))
                        {
                            stream.WriteTo(outputFileStream);
                        }
                        log.LogToFile("Move File, " + s + " ,to " + dest + " ,at " + DateTime.Now);
                        //log.LogToDataBase("Move", "Move File " + s + " to " + dest);
                        return(true);
                    }
                }
                else
                {
                    string dest = Path.Combine(dir, d);
                    Directory.CreateDirectory(dest);
                    dest = Path.Combine(dest, Path.GetFileName(s));
                    if (File.Exists(dest))
                    {
                        DialogResult dialogResult = Temp.SummaryMessageBox("the file" + dest + " is exist Do you want to overwrite it", "Info", MessageBoxIcon.Question, MessageBoxButtons.YesNo);
                        if (dialogResult == DialogResult.Yes)
                        {
                            File.Copy(s, dest, true);
                            return(true);
                        }
                        else if (dialogResult == DialogResult.No)
                        {
                            return(false);
                        }
                        else
                        {
                            return(false);
                        }
                    }
                    else
                    {
                        if (move == true)
                        {
                            File.Move(s, dest);
                        }
                        else
                        {
                            File.Copy(s, dest);
                        }
                        return(true);
                    }
                    //using (var db = new DatabaseContext())
                    //{
                    //    ProjectFile projectFile = new ProjectFile()
                    //    {
                    //        ProjectId = Session.CurrentProjectId,
                    //        Properties ="{test:test}",
                    //        File = d
                    //    };
                    //    db.ProjectFiles.Add(projectFile);
                    //    db.SaveChanges();
                    //}
                    //projectFile.
                    log.LogToFile("Move File, " + s + " ,to " + dest + " ,at " + DateTime.Now);
                    //log.LogToDataBase("Move", "Move File " + s + " to " + dest);
                    //}
                    return(true);
                }
            }
            catch (Exception ex)
            {
                log.LogToFile(ex.Message);
                return(false);
            }
        }
Пример #56
0
        public override bool TestConnection(ref string error)
        {
            WebResponse response = null;

            try
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(
                    delegate
                {
                    return(true);
                }
                    );

                bool result = false;
                if (SourceControlURL.ToUpper().Trim().StartsWith("HTTP"))
                {
                    if (!SourceControlURL.EndsWith("/"))
                    {
                        SourceControlURL = SourceControlURL + "/";
                    }
                    WebRequest request = WebRequest.Create(SourceControlURL);

                    request.Timeout     = SourceControlTimeout * 1000;
                    request.Credentials = new System.Net.NetworkCredential(SourceControlUser, SourceControlPass);
                    response            = (WebResponse)request.GetResponse();
                }
                else if (SourceControlURL.ToUpper().Trim().StartsWith("SVN"))
                {
                    using (SvnClient sc = new SvnClient())
                    {
                        sc.Authentication.DefaultCredentials = new System.Net.NetworkCredential(SourceControlUser, SourceControlPass);
                        Uri targetUri = new Uri(SourceControlURL);
                        var target    = SvnTarget.FromUri(targetUri);
                        Collection <SvnInfoEventArgs> info;
                        result = sc.GetInfo(target, new SvnInfoArgs {
                            ThrowOnError = false
                        }, out info);
                    }
                }

                if (response != null || result)
                {
                    return(true);
                }
                else
                {
                    error = "No Details";
                    return(false);
                }
            }
            catch (Exception ex)
            {
                error = ex.Message;
                if (response != null)
                {
                    response.Close();
                }
                return(false);
            }
            finally
            {
                //Close Response
                if (response != null)
                {
                    response.Close();
                }
            }
        }
Пример #57
0
 		private static SvnClient GetSvnClient()
 		{
 			SvnClient client = new SvnClient();
 
 			return client;
 		}
Пример #58
0
        static int Main(string[] args)
        {
            try
            {
                Console.WriteLine("Svn2: {0}", Assembly.GetExecutingAssembly().GetName().Version);

                if (args.Length < 1)
                {
                    Usage();
                    return(-2);
                }

                string command = args[0];
                if (command == "/?" || command == "-?" || command == "--help")
                {
                    Usage();
                    return(-2);
                }

                string path = (args.Length == 2)
                    ? Path.GetFullPath(args[1])
                    : Path.GetFullPath(Environment.CurrentDirectory);

                SvnClient client = new SvnClient();

                switch (command)
                {
                case "sync":
                {
                    SvnStatusArgs statusArgs = new SvnStatusArgs();
                    statusArgs.Depth        = SvnDepth.Infinity;
                    statusArgs.ThrowOnError = true;
                    client.Status(path, statusArgs, new EventHandler <SvnStatusEventArgs>(delegate(object sender, SvnStatusEventArgs e)
                        {
                            switch (e.LocalContentStatus)
                            {
                            case SvnStatus.NotVersioned:
                                Console.WriteLine(" {0} {1}", StatusToChar(e.LocalContentStatus), e.FullPath);
                                if (File.Exists(e.FullPath))
                                {
                                    FileSystem.DeleteFile(e.FullPath, UIOption.OnlyErrorDialogs,
                                                          RecycleOption.SendToRecycleBin);
                                }
                                else if (Directory.Exists(e.FullPath))
                                {
                                    FileSystem.DeleteDirectory(e.FullPath, UIOption.OnlyErrorDialogs,
                                                               RecycleOption.SendToRecycleBin);
                                }
                                break;
                            }
                        }));
                }
                break;

                case "cleanup":
                {
                    Console.WriteLine("Cleaning up {0}", path);
                    SvnCleanUpArgs cleanupArgs = new SvnCleanUpArgs();
                    cleanupArgs.ThrowOnError = true;
                    cleanupArgs.Notify      += new EventHandler <SvnNotifyEventArgs>(delegate(object sender, SvnNotifyEventArgs e)
                        {
                            Console.WriteLine(" L {0}", e.FullPath);
                        });
                    client.CleanUp(path, cleanupArgs);
                }
                break;

                case "revert":
                {
                    Console.WriteLine("Reverting {0}", path);
                    SvnRevertArgs revertArgs = new SvnRevertArgs();
                    revertArgs.Depth        = SvnDepth.Infinity;
                    revertArgs.ThrowOnError = true;
                    revertArgs.Notify      += new EventHandler <SvnNotifyEventArgs>(delegate(object sender, SvnNotifyEventArgs e)
                        {
                            Console.WriteLine(" R {0}", e.FullPath);
                        });
                    client.Revert(path, revertArgs);
                }
                break;

                case "status":
                {
                    SvnStatusArgs statusArgs = new SvnStatusArgs();
                    statusArgs.Depth        = SvnDepth.Infinity;
                    statusArgs.ThrowOnError = true;
                    client.Status(path, statusArgs, new EventHandler <SvnStatusEventArgs>(delegate(object sender, SvnStatusEventArgs e)
                        {
                            Console.WriteLine(" {0} {1}", StatusToChar(e.LocalContentStatus), e.FullPath);
                        }));
                }
                break;

                default:
                    throw new Exception(string.Format("Unsupported '{0}' command", command));
                }

                return(0);
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.Message);
#if DEBUG
                Console.Error.WriteLine(ex.StackTrace);
#endif
                return(-1);
            }
        }
        private LoadSourcesResult LoadSourcesWithUpdate(SourceControlVersion sourceControlVersion, string path, SvnClient client)
        {
            SvnUpdateResult result;

            try
            {
                client.Update(path, out result);
            }
            catch (SvnInvalidNodeKindException e)
            {
                Directory.Delete(path, true);
                return(this.LoadSourcesFromScratch(sourceControlVersion, path, client));
            }
            catch (SvnWorkingCopyException e)
            {
                client.CleanUp(path);
                client.Update(path, out result);
            }

            SvnInfoEventArgs info;

            client.GetInfo(path, out info);

            return(new LoadSourcesResult
            {
                RevisionId = info.LastChangeRevision.ToString(CultureInfo.InvariantCulture)
            });
        }
Пример #60
0
        public void Copy_CopyTest()
        {
            SvnSandBox sbox = new SvnSandBox(this);

            sbox.Create(SandBoxRepository.Default);

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

            using (SvnClient client = NewSvnClient(true, false))
            {
                string file = Path.Combine(WcPath, "CopyBase");

                TouchFile(file);
                client.Add(file);

                client.Commit(WcPath);

                client.RemoteCopy(new Uri(WcUri, "CopyBase"), new Uri(WcUri, "RemoteCopyBase"));
                bool visited = false;
                bool first   = true;
                client.Log(new Uri(WcUri, "RemoteCopyBase"), delegate(object sender, SvnLogEventArgs e)
                {
                    if (first)
                    {
                        first = false;
                        foreach (SvnChangeItem i in e.ChangedPaths)
                        {
                            Assert.That(i.Path, Is.StringEnding("trunk/RemoteCopyBase"), "Path ends with folder/RemoteCopyBase");
                            Assert.That(i.Action, Is.EqualTo(SvnChangeAction.Add));
                            Assert.That(i.CopyFromPath, Is.StringEnding("trunk/CopyBase"), "CopyFromPath ends with folder/CopyBase");
                            Assert.That(i.CopyFromRevision, Is.GreaterThan(0L));
                            Assert.That(i.NodeKind, Is.EqualTo(SvnNodeKind.File));
                        }
                    }
                    else
                    {
                        foreach (SvnChangeItem i in e.ChangedPaths)
                        {
                            Assert.That(i.Action, Is.EqualTo(SvnChangeAction.Add));
                            Assert.That(i.Path, Is.StringEnding("trunk/CopyBase"), "Path ends with folder/CopyBase");
                            Assert.That(i.NodeKind, Is.EqualTo(SvnNodeKind.File));
                            visited = true;
                        }
                    }
                });
                Assert.That(visited, "Visited log item");

                client.Copy(new SvnPathTarget(file), Path.Combine(WcPath, "LocalCopy"));
                client.Commit(WcPath);
                visited = false;
                first   = true;
                client.Log(new Uri(WcUri, "LocalCopy"), delegate(object sender, SvnLogEventArgs e)
                {
                    if (first)
                    {
                        foreach (SvnChangeItem i in e.ChangedPaths)
                        {
                            Assert.That(i.Path, Is.StringEnding("trunk/LocalCopy"), "Path ends with folder/LocalCopy");
                            Assert.That(i.Action, Is.EqualTo(SvnChangeAction.Add));
                            Assert.That(i.CopyFromPath, Is.StringEnding("trunk/CopyBase"), "CopyFromPath ensd with folder/CopyBase");
                            Assert.That(i.CopyFromRevision, Is.GreaterThan(0L));
                        }
                        first = false;
                    }
                    else
                    {
                        foreach (SvnChangeItem i in e.ChangedPaths)
                        {
                            Assert.That(i.Action, Is.EqualTo(SvnChangeAction.Add));
                            Assert.That(i.Path, Is.StringEnding("trunk/CopyBase"), "Path ends with folder/CopyBase");
                            visited = true;
                        }
                    }
                });
                Assert.That(visited, "Visited local log item");
            }
        }