Exemplo n.º 1
0
        static void Test10()
        {
            var homeUri = new Uri("http://192.168.1.105/svn/BIST/release");
            var tgtUri  = SvnTools.GetNormalizedUri(new Uri("http://192.168.1.105/svn/BIST/../modelsBinaries/missiontrModels/trunk"));

            var client = new SvnClient();

            SvnInfoEventArgs homeInfo;

            if (!client.GetInfo(homeUri, out homeInfo))
            {
                return;
            }

            string homeRepoUrl = homeInfo.RepositoryRoot.AbsoluteUri;

            SvnInfoEventArgs tgtInfo;

            if (!client.GetInfo(tgtUri, out tgtInfo))
            {
                return;
            }

            string tgtRepoUrl = tgtInfo.RepositoryRoot.AbsoluteUri;

            string relativizedUrl;

            Exter.TryMakeRelativeReference(client, tgtUri.AbsoluteUri, homeRepoUrl, out relativizedUrl);
        }
Exemplo n.º 2
0
        public bool Updata(string SvnPathTarget)
        {
            ShowState(String.Format("{0} start updata", SvnPathTarget));
            //SvnInfoEventArgs serverInfo;
            SvnInfoEventArgs clientInfo;
            //SvnUpdateResult svnUpdateResult;
            //System.Collections.ObjectModel.Collection<SvnLogEventArgs> logSvnArgs;
            //SvnUriTarget repos = new SvnUriTarget(svnUriTarget);
            SvnPathTarget local = new SvnPathTarget(SvnPathTarget);

            //client.GetInfo(repos, out serverInfo);
            //client.GetLog(SvnPathTarget, out logSvnArgs);
            if (!client.Update(SvnPathTarget))
            {
                ShowState(String.Format("[updata errer] {0}", SvnPathTarget));
                return(false);
            }
            try
            {
                client.GetInfo(local, out clientInfo);
            }
            catch (Exception ex)
            {
                ShowState(String.Format("[updata errer] {0}", ex.Message));
                return(false);
            }
            ShowState(string.Format("Svn remote path is :{0} \r\nLocal path is :{1} \r\nLast change revision is :{2} \r\nLast change time is :{3} \r\nLast change author is :{4} \r\n",
                                    clientInfo.Uri, clientInfo.Path, clientInfo.LastChangeRevision, clientInfo.LastChangeTime, clientInfo.LastChangeAuthor, clientInfo.Revision));
            return(true);
        }
        /// <summary>
        /// Checks, if the item at <paramref name="svnUrl"/> in specific revision exists
        /// </summary>
        /// <param name="svnUrl">URL of item inside the SVN Repository</param>
        /// <param name="versionSpec">Version specification ("H" for latest or "Rxxx" for specific revision)</param>
        /// <returns>true, item exists in expected revision, otherwise false.</returns>
        public bool ItemExists(string svnUrl, string versionSpec)
        {
            if (!IsUrlValid(svnUrl))
            {
                return(false);
            }

            SvnInfoArgs args = new SvnInfoArgs();

            args.Revision = ConvertToRevsion(versionSpec);

            try
            {
                Collection <SvnInfoEventArgs> contents;

                _svn.GetInfo(new Uri(svnUrl), args, out contents);

                return(true);
            }
            catch (SvnAuthenticationException)
            {
                throw new SvnAuthenticationException();
            }
            catch
            {
                return(false);
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="fileName">文件夹名称</param>
        /// <returns></returns>
        public JsonResult UpdateSvn(string fileName, string user, string pwd, string type)
        {
            string result = string.Empty;

            using (SvnClient client = new SvnClient())
            {
                try
                {
                    GetPermission(client, user, pwd);
                    SvnInfoEventArgs serverInfo;
                    SvnInfoEventArgs clientInfo;
                    SvnUriTarget     repos = new SvnUriTarget("https://" + (type == "local" ? localSVN : onlineSVN) + fileName);
                    SvnPathTarget    local = new SvnPathTarget(localPath + "\\" + fileName);

                    client.GetInfo(repos, out serverInfo);

                    client.Update(localPath + "\\" + fileName);

                    client.GetInfo(local, out clientInfo);
                    if (serverInfo.Revision > 0 && clientInfo.Revision > 0)
                    {
                        result = serverInfo.Revision.ToString() + "-" + clientInfo.Revision.ToString();
                    }
                    return(Json(new { result = true }));
                }
                catch (Exception ex)
                {
                    return(Json(new { result = false, msg = ex.Message.ToString() }));
                }
            }
        }
Exemplo n.º 5
0
        private void checkout(string alias)
        {
            string projectUrl = Url.TrimEnd('/') + "/" + alias;
            string tempFolder = TempFolderPath(alias);

            bool workingCopy = false;

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

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

                if (!workingCopy)
                {
                    if (Directory.Exists(Path.Combine(TempFolderPath(string.Empty), ".svn")))
                    {
                        SvnUriTarget target = new SvnUriTarget(projectUrl);

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

                        Collection <SvnInfoEventArgs> info;
                        bool res = client.GetInfo(target, new SvnInfoArgs {
                            ThrowOnError = false
                        }, out info);
                        if (res)
                        {
                            client.CheckOut(target, tempFolder);
                        }
                    }
                    else
                    {
                        SvnUriTarget target = new SvnUriTarget(Url);
                        Collection <SvnInfoEventArgs> info;
                        bool res = client.GetInfo(target, new SvnInfoArgs {
                            ThrowOnError = false
                        }, out info);

                        if (res)
                        {
                            client.CheckOut(target, TempFolderPath(string.Empty));
                        }
                    }
                }
                else
                {
                    client.Update(tempFolder);
                }
            }
        }
Exemplo n.º 6
0
        public override string GetRepositoryURL(ref string error)
        {
            if (client == null)
            {
                Init();
            }


            SvnInfoEventArgs info;

            client.GetInfo(SolutionFolder, out info);
            string RemoteURL = info.Uri.ToString();

            return(RemoteURL);
        }
Exemplo n.º 7
0
        public bool TryGetSvnRoot([NotNull] string path, out string rootPath)
        {
            Guard.NotNull(path, nameof(path));

            try
            {
                using (var client = new SvnClient())
                {
                    var result = client.GetInfo(path, out var info);
                    rootPath = result ? info.WorkingCopyRoot : null;
                    return(result);
                }
            }
            catch (SvnInvalidNodeKindException)
            {
                // expected when root does not exists.
                // do nothing specific
            }
            catch (Exception)
            {
                // not expected.
                // log exception (todo)
            }

            rootPath = null;
            return(false);
        }
        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)
            });
        }
        public TestSourceResult TestConnection(SourceControlVersion sourceControlVersion)
        {
            NetworkCredential credentials = new NetworkCredential(
                sourceControlVersion.SourceControl.GetStringProperty("Login"),
                sourceControlVersion.SourceControl.GetStringProperty("Password"));

            using (SvnClient client = new SvnClient())
            {
                client.LoadConfiguration(Path.Combine(Path.GetTempPath(), "Svn"), true);

                client.Authentication.DefaultCredentials = credentials;

                try
                {
                    SvnInfoEventArgs info;
                    client.GetInfo(new Uri(this.GetVersionURI(sourceControlVersion)), out info);
                }
                catch (SvnException e)
                {
                    return(new TestSourceResult()
                    {
                        IsSuccess = false,
                        ErrorMessage = e.Message
                    });
                }

                return(new TestSourceResult()
                {
                    IsSuccess = true,
                });
            }
        }
Exemplo n.º 10
0
        protected virtual void ValidateAdd(object sender, CancelEventArgs e)
        {
            ISvnClientPool clientPool = Context.GetService <ISvnClientPool>();

            if (localFolder.SelectedItem == null)
            {
                errorProvider1.SetError(localFolder, "Please select a working copy path");
                e.Cancel = true;
                return;
            }

            if (RepositoryAddUrl == null)
            {
                errorProvider1.SetError(repositoryTree, "Please select a location in the repository to add to");
                e.Cancel = true;
                return;
            }

            using (SvnClient sc = clientPool.GetClient())
            {
                SvnInfoArgs ia = new SvnInfoArgs();
                ia.ThrowOnError = false;
                Collection <SvnInfoEventArgs> info;
                bool result = sc.GetInfo(RepositoryUri, ia, out info);
                if (!result)
                {
                    errorProvider1.SetError(repositoryTree, "Please select a valid location in the repository to add to");
                    e.Cancel = true;
                    return;
                }
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// 执行获取本地项目svn信息的操作
        /// </summary>
        /// <param name="projectInfo">传入想要获取信息的projectInfo实例对象</param>
        /// <returns>获取完信息的projectInfo的实例对象</returns>
        public ProjectInfo GetLocalInfo(ProjectInfo projectInfo)
        {
            using (SvnClient svnClient = new SvnClient())
            {
                try
                {
                    SvnInfoEventArgs clientInfo;
                    SvnPathTarget    local = new SvnPathTarget(projectInfo.WorkDirectory);
                    svnClient.GetInfo(local, out clientInfo);
                    string author   = clientInfo.LastChangeAuthor;
                    string revision = clientInfo.LastChangeRevision.ToString();
                    projectInfo.Author = author;

                    SvnLogArgs getLogMessage = new SvnLogArgs();
                    Collection <SvnLogEventArgs> col;
                    getLogMessage.Start = int.Parse(revision);
                    getLogMessage.End   = int.Parse(revision);
                    bool gotLog = svnClient.GetLog(new Uri(projectInfo.RepositoryPath), getLogMessage, out col);
                    if (gotLog)
                    {
                        projectInfo.LogMessage = col[0].LogMessage;
                    }
                    return(projectInfo);
                }
                catch (Exception ex)
                {
                    return(projectInfo);
                }
            }
        }
Exemplo n.º 12
0
        public PathInfo GetPathInfo(string path, int revision)
        {
            SvnClient client = AllocSvnClient();

            try
            {
                SvnInfoEventArgs info;
                client.GetInfo(MakeTarget(path, revision), out info);

                PathInfo result = new PathInfo();
                result.Size      = (int)info.RepositorySize;
                result.Author    = info.LastChangeAuthor ?? "";
                result.Timestamp = info.LastChangeTime;
                //result.Revision = (int) info.LastChangeRevision; // wrong if data is directory
                result.IsDirectory = info.NodeKind == SvnNodeKind.Directory;
                return(result);
            }
            catch (SvnException x)
            {
                if (x.SvnErrorCode == SvnErrorCode.SVN_ERR_RA_ILLEGAL_URL)
                {
                    return(null);
                }
                if (path.IndexOfAny(InvalidPathChars) >= 0) // this condition exists only because of a bug in the svn client for local repositoreis
                {
                    Console.WriteLine("WARNING: path with invalid charactes could not be indexed: " + path + "@" + revision);
                    return(null);
                }
                throw;
            }
            finally
            {
                FreeSvnClient(client);
            }
        }
Exemplo n.º 13
0
        public void Diff(long revision, long revisionto)
        {
            using (SvnClient client = new SvnClient()) {
                string           file = SrcFile;
                SvnInfoEventArgs info;
                client.GetInfo(file, out info);
                var uri = info.Uri;

                var tempDir  = System.IO.Path.GetTempPath();
                var filename = System.IO.Path.GetFileName(SrcFile);

                var file1        = tempDir + revision + "_" + filename;
                var checkoutArgs = new SvnWriteArgs()
                {
                    Revision = revision
                };
                using (var fs = System.IO.File.Create(file1)) {
                    client.Write(uri, fs, checkoutArgs);
                }
                var file2         = tempDir + revisionto + "_" + filename;
                var checkoutArgs2 = new SvnWriteArgs()
                {
                    Revision = revisionto
                };
                using (var fs = System.IO.File.Create(file2)) {
                    client.Write(uri, fs, checkoutArgs2);
                }

                _tempFiles.Add(file1);
                _tempFiles.Add(file2);
                Diff(file1, file2, false);
            }
        }
Exemplo n.º 14
0
 private void GetSVNRevision()
 {
     using (SvnClient client = new SvnClient())
     {
         SvnInfoEventArgs info;
         SVNVersion = client.GetInfo(SvnPathTarget.FromString(Path), out info) ? info.Revision : 0;
     }
 }
Exemplo n.º 15
0
        private SvnInfoEventArgs GetSourceInfo(long revision)
        {
            SvnInfoEventArgs info;
            var sourceTarget = new SvnUriTarget(_source, revision == -1 ? SvnRevision.Head : revision);

            using (var svn = new SvnClient()) svn.GetInfo(sourceTarget, out info);
            return(info);
        }
Exemplo n.º 16
0
        private bool CheckUrlValide(SvnClient client, SvnUriTarget uri)
        {
            Collection <SvnInfoEventArgs> info = new Collection <SvnInfoEventArgs>();

            return(client.GetInfo(uri, new SvnInfoArgs {
                ThrowOnError = false
            }, out info));
        }
Exemplo n.º 17
0
    /// <summary>
    /// 获取本地Working Copy中某个文件的信息
    /// </summary>
    public static SvnInfoEventArgs GetLocalFileInfo(string localPath, out SvnException svnException)
    {
        SvnInfoEventArgs localFileInfo;
        SvnPathTarget    localPathTarget = new SvnPathTarget(localPath);

        try
        {
            _svnClient.GetInfo(localPathTarget, out localFileInfo);
            svnException = null;
            return(localFileInfo);
        }
        catch (SvnException exception)
        {
            svnException = exception;
            return(null);
        }
    }
Exemplo n.º 18
0
        public static SvnInfoEventArgs GetLatestRevisionInfo(SvnClient client, string svnSourceURL)
        {
            SvnInfoEventArgs svnInfo;
            Uri repos = new Uri(svnSourceURL);

            client.GetInfo(repos, out svnInfo);

            return(svnInfo);
        }
Exemplo n.º 19
0
 public bool InitFromWCDir(string wcDir)
 {
     try
     {
         SvnInfoEventArgs info;
         if (svnClient.GetInfo(new SvnPathTarget(wcDir), out info))
         {
             RepoRootUrl = info.RepositoryRoot.AbsoluteUri;
             IsRepoValid = true;
             return(true);
         }
     }
     catch (SvnException)
     {
     }
     IsRepoValid = false;
     return(false);
 }
Exemplo n.º 20
0
 public void Ping(string path)
 {
     using (SvnClient client = new SvnClient()) {
         client.Authentication.ForceCredentials(SvnUserName, SvnUserPassword);
         if (!client.GetInfo(new Uri(path), out SvnInfoEventArgs info))
         {
             throw new Exception("Cann't reach svn server.");
         }
     }
 }
Exemplo n.º 21
0
             /// <summary>
             /// 检查版本号,如果版本号不符, 则更新
             /// </summary>
             /// <returns></returns>
            public bool CheckVer()
            
    {
                    bool result = true;
                    var  repos  = new SvnUriTarget(svnurl);
                    var  local  = new SvnPathTarget(GetAppLoc());
                    try
                     {
                            notiny = "正在检查服务器版本...";
                            ShowInfo();

                            SvnInfoEventArgs serverInfo;
                            bool             oks = SC.GetInfo(repos, out serverInfo);
                            notiny = "正在检查本地版本...";
                            ShowInfo();

                            SvnInfoEventArgs clientInfo;
                            bool             okc = SC.GetInfo(local, out clientInfo);
                            if (oks && okc) //如果客户端服务端都会成功, 则对比服务器版本, 否则返回true 执行更新命令
            {
                                {
                                        result = (serverInfo.Revision > clientInfo.Revision);
                                      
                }
            }
                            ShowInfo(string.Format("检查完毕,服务器版本{0}客户端版本{1}",
                                                                                          (serverInfo != null ? serverInfo.Revision.ToString() : "(未知)"),
                                                                                          (clientInfo != null ? clientInfo.Revision.ToString() : "(未知)")
                                                                                ));

                        
        }
                    catch(Exception)
                    
        {
                            ShowInfo("检查文件是出现错误...");

                        
        }

                    return result;
                
    }
Exemplo n.º 22
0
        static void Test6()
        {
            var client = new SvnClient();
            var url    = "file:///D:/Work/svn/BIST/repo/releases/IG/Head/Config";
            SvnInfoEventArgs info;

            if (!client.GetInfo(new Uri(url), out info))
            {
                return;
            }
        }
Exemplo n.º 23
0
        static bool MakePeg(SvnClient client, ref SvnExternalItem ei, string hostUrl)
        {
            Exter.EPinType oldType;
            if (!Exter.GetExternalType(ei, out oldType))
            {
                return(false);
            }

            switch (oldType)
            {
            case Exter.EPinType.Head:
            case Exter.EPinType.Branch:
            {
                // resolve relative url references
                string fullRefUrl;
                if (!Exter.GetFullReferenceUrl(client, ei, hostUrl, out fullRefUrl))
                {
                    return(false);
                }

                // find the revision of the external
                SvnInfoEventArgs info;
                if (!client.GetInfo(new SvnUriTarget(fullRefUrl, SvnRevision.Head), out info))
                {
                    return(false);
                }

                // change to peg revision
                ei = new SvnExternalItem(ei.Target, ei.Reference, info.Revision);

                return(true);
            }

            case Exter.EPinType.Peg:
            {
                // no change needed, already a peg external
                return(true);
            }

            case Exter.EPinType.Tag:
            {
                // no change needed, tag is considered unchangeable, keep it as it is
                return(true);
            }

            default:
            {
                // unknown Pin type
                return(false);
            }
            }

            //return true;
        }
Exemplo n.º 24
0
 public static bool IsSVNFolder(SvnClient client, string path)
 {
     return(client.GetInfo(
                new SvnPathTarget(path),
                new SvnInfoArgs()
     {
         ThrowOnError = false
     },
                out _
                ));
 }
        public void EventWorker_CommittsNewFileToSvn_WhenFileIsAdded()
        {
            _manager.Monitor(_testFolders);
            _manager.StartProcessing();

            var folder   = _testFolders[0];
            var fileName = TestFileSystemHelper.MakeUniqueFileName("css");

            using (var client = new SvnClient()) {
                SvnInfoEventArgs info;
                client.GetInfo(folder.RepositoryUrl, out info);
                var revisionBeforeAdd = info.Revision;

                DoAndWaitForWorker(() => TestFileSystemHelper.CreateFile(fileName, folder.Path));

                client.GetInfo(folder.RepositoryUrl, out info);
                var revisionAfterAdd = info.Revision;

                Assert.That(revisionAfterAdd, Is.EqualTo(revisionBeforeAdd + 1));
            }
        }
Exemplo n.º 26
0
        //
        // 编写测试时,可以使用以下附加特性:
        //
        // 在运行类中的第一个测试之前使用 ClassInitialize 运行代码
        // [ClassInitialize()]
        // public static void MyClassInitialize(TestContext testContext) { }
        //
        // 在类中的所有测试都已运行之后使用 ClassCleanup 运行代码
        // [ClassCleanup()]
        // public static void MyClassCleanup() { }
        //
        // 在运行每个测试之前,使用 TestInitialize 来运行代码
        // [TestInitialize()]
        // public void MyTestInitialize() { }
        //
        // 在每个测试运行完之后,使用 TestCleanup 来运行代码
        // [TestCleanup()]
        // public void MyTestCleanup() { }
        //
        #endregion


        public void TestMethod1()
        {
            //http://docs.sharpsvn.net/current/

            using (SvnClient client = new SvnClient())
            {
                // Checkout the code to the specified directory
                client.Authentication.Clear(); // Clear a previous authentication
                client.Authentication.DefaultCredentials = new System.Net.NetworkCredential("", "");
                // client.CheckOut(new Uri("http://ip:9001/svn/CCMS/trunk/CCMS_V6/DOCUMENT/"),  "d:\\sharpsvn");


                Uri targetUri = new Uri("http://ip:9001/svn/CCMS/trunk/CCMS_V6/DOCUMENT");
                var target    = SvnTarget.FromUri(targetUri);
                Collection <SvnInfoEventArgs> info;//System.Collections.ObjectModel
                bool result2 = client.GetInfo(target, new SvnInfoArgs {
                    ThrowOnError = false
                }, out info);
                //Assert.AreEqual(result2, false);
                // Assert.Equals(info, "");


                SvnUpdateArgs ua    = new SvnUpdateArgs();
                SvnLogArgs    args2 = new SvnLogArgs(new SvnRevisionRange(500, new SvnRevision(SvnRevisionType.Head)));
                Collection <SvnLogEventArgs> logitems;
                ua.Notify += delegate(object sender, SvnNotifyEventArgs e)
                {
                    Console.WriteLine(e.Action);
                    Console.WriteLine(e.FullPath);
                };
                // Update the specified working copy path to the head revision
                client.Update("d:\\sharpsvn", ua);
                SvnUpdateResult result;

                client.Update("d:\\sharpsvn", out result);

                client.GetLog(targetUri, out logitems);
                foreach (var logentry in logitems)
                {
                    string   author      = logentry.Author;
                    string   message     = logentry.LogMessage;
                    DateTime checkindate = logentry.Time;
                }


                //  client.Move("c:\\sharpsvn\\from.txt", "c:\\sharpsvn\\new.txt");

                // Commit the changes with the specified logmessage
                //SvnCommitArgs ca = new SvnCommitArgs();
                // ca.LogMessage = "Moved from.txt to new.txt";
                // client.Commit("c:\\sharpsvn", ca);
            }
        }
Exemplo n.º 27
0
        public void Diff(long revision, long revisionto)
        {
            Uri uri;

            using (SvnClient client = new SvnClient()) {
                string           file = SrcFile;
                SvnInfoEventArgs info;
                client.GetInfo(file, out info);
                uri = info.Uri;
            }
            DiffUri(revision, revisionto, uri);
        }
Exemplo n.º 28
0
        public override bool TestConnection(ref string error)
        {
            try
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(
                    delegate
                {
                    return(true);
                }
                    );
                WebResponse response = null;
                bool        result   = false;
                if (SourceControlURL.ToUpper().Trim().StartsWith("HTTP"))
                {
                    if (!SourceControlURL.EndsWith("/"))
                    {
                        SourceControlURL = SourceControlURL + "/";
                    }
                    WebRequest request = WebRequest.Create(SourceControlURL);
                    request.Timeout     = 15000;
                    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;
                return(false);
            }
        }
Exemplo n.º 29
0
        // tries to find relative external reference
        // it true is returned, relativeRef contains relativized path
        // if false is returned, relativeRef contains original absUrl
        public static bool TryMakeRelativeReference(SvnClient client, string absUrl, string repoRootUrl, out string relativeRef)
        {
            relativeRef = absUrl;

            if (!repoRootUrl.EndsWith("/"))
            {
                repoRootUrl += "/";
            }


            // same server & repository?
            if (absUrl.StartsWith(repoRootUrl))
            {
                var relativePart = absUrl.Substring(repoRootUrl.Length);
                relativeRef = $"^/{relativePart}";
                return(true);
            }

            string homeServerRootUrl;
            string homeRepoName;

            Exter.ParseRepoRootUrlToServerAndRepo(repoRootUrl, out homeServerRootUrl, out homeRepoName);


            SvnInfoEventArgs tgtInfo;

            if (!client.GetInfo(new SvnUriTarget(absUrl), out tgtInfo))
            {
                return(false);
            }

            string tgtRepoRootUrl = tgtInfo.RepositoryRoot.AbsoluteUri;
            string tgtServerRootUrl;
            string tgtRepoName;

            Exter.ParseRepoRootUrlToServerAndRepo(tgtRepoRootUrl, out tgtServerRootUrl, out tgtRepoName);

            if (!absUrl.StartsWith(tgtRepoRootUrl))
            {
                return(false);                        // this should not happen!
            }
            string inRepoPath = absUrl.Substring(tgtRepoRootUrl.Length);

            // same server? (different repo name then...)
            if (homeServerRootUrl == tgtServerRootUrl)
            {
                relativeRef = $"^/../{tgtRepoName}/{inRepoPath}";
                return(true);
            }

            return(false);
        }
Exemplo n.º 30
0
        public void TestChangeListAndLog()
        {
            var svnService = new Utry.Core.Services.SvnService();

            //http://docs.sharpsvn.net/current/

            using (SvnClient client = new SvnClient())
            {
                // Checkout the code to the specified directory
                client.Authentication.Clear(); // Clear a previous authentication
                client.Authentication.DefaultCredentials = new System.Net.NetworkCredential("", "");
                //client.CheckOut(new Uri("http://ip:9001/svn/CCMS/trunk/CCMS_V6/DOCUMENT/"), "d:\\sharpsvn");

                Uri targetUri = new Uri("http://ip:9001/svn/CCMS/trunk/CCMS_V6/DOCUMENT");
                var target    = SvnTarget.FromUri(targetUri);
                Collection <SvnInfoEventArgs> info;//System.Collections.ObjectModel
                bool result2 = client.GetInfo(target, new SvnInfoArgs {
                    ThrowOnError = false
                }, out info);


                SvnUpdateArgs ua    = new SvnUpdateArgs();
                SvnLogArgs    args2 = new SvnLogArgs(new SvnRevisionRange(500, new SvnRevision(SvnRevisionType.Head)));
                var           sua   = new SvnUpdateArgs {
                    Revision = new SvnRevision(0)
                };

                Collection <SvnLogEventArgs> logitems;

                long version = 0;
                ua.Notify += delegate(object sender, SvnNotifyEventArgs e)
                {
                    Console.WriteLine(string.Format("{0}:{1}.", svnService.GetNotifyAction(e.Action), e.FullPath));
                    Console.WriteLine(e.Revision);
                    version = e.Revision;
                };

                client.Update("d:\\sharpsvn", ua);

                if (version > 0)
                {
                    client.GetLog(targetUri, new SvnLogArgs(new SvnRevisionRange(version, version)), out logitems);
                    foreach (var logentry in logitems)
                    {
                        string   author      = logentry.Author;
                        string   message     = logentry.LogMessage;
                        DateTime checkindate = logentry.Time;
                        Console.WriteLine(string.Format("{0}  :  {1  }:  {2}", author, message, checkindate));
                    }
                }
            }
        }
        public string ComposeForUrl(string branchUrl, long revision)
        {
            // get props
            using (_client = new SvnClient())
            {
                SvnInfoEventArgs info;
                _client.GetInfo(new SvnUriTarget(branchUrl, new SvnRevision(revision)), out info);
                _cancellationToken.ThrowIfCancellationRequested();
                _repoRoot = info.RepositoryRoot;
                _requestedMergeMessageForBranch = "/" + info.Path.Trim('/') + "/";

                var mergedRevisions = GetMergedRevisions(branchUrl, revision);

                LoadLogEntries(mergedRevisions);

                return BuildMessage(mergedRevisions);
            }
        }
Exemplo n.º 32
0
        public static void getDiff(int lastVersion)
        {
            using (SvnClient client = new SvnClient())
            {
                client.Authentication.UserNamePasswordHandlers +=
                    new EventHandler<SvnUserNamePasswordEventArgs>(
                        delegate (object s, SvnUserNamePasswordEventArgs e)
                        {
                            e.UserName = "******";
                            e.Password = "******";
                        });
                SvnInfoEventArgs clientInfo;
                string path = @"http://test10.svn.7road-inc.com/svn/Mobilephone_SRC/Mobilephone_DDT/trunk/Client/Develop/Resource";

                client.GetInfo(path, out clientInfo);

                int i = 0;
            }
        }
Exemplo n.º 33
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 SvnPathTarget(RepositoryPath);
            SvnInfoArgs args = new SvnInfoArgs();
            Collection<SvnInfoEventArgs> infoResult = new Collection<SvnInfoEventArgs>();

            bool result = client.GetInfo(target, args, out infoResult);

            SvnInfoEventArgs info = infoResult[0];

            Revision = info.Revision;
            RepositoryId = info.RepositoryId;
            NodeKind = info.NodeKind.ToString();
            Schedule = info.Schedule.ToString();
            LastChangedRevision = info.LastChangeRevision;
            LastChangedAuthor = info.LastChangeAuthor;
            LastChangeDate = info.LastChangeTime;

            return result;
        }
        public string ComposeForPath(string wc)
        {
            // find root (where .svn reside)
            var wcRoot = SvnUtils.FindSvnWC(wc);
            if (wcRoot == null)
                throw new ApplicationException("Can't find working copy root for " + wc);

            using (_client = new SvnClient())
            {
                var wcTarg = new SvnPathTarget(wcRoot);

                SvnInfoEventArgs info;
                _client.GetInfo(wcTarg, out info);
                _cancellationToken.ThrowIfCancellationRequested();
                _repoRoot = info.RepositoryRoot;
                _requestedMergeMessageForBranch = "/" + info.Path.Trim('/') + "/";

                SvnTargetPropertyCollection mergeInfoPre;
                if (!_client.GetProperty(wcTarg, "svn:mergeinfo", new SvnGetPropertyArgs { Revision = SvnRevision.Base }, out mergeInfoPre))
                    throw new ApplicationException("Error in GetProperty");

                string mergeInfoNew;
                if (!_client.GetProperty(wcTarg, "svn:mergeinfo", out mergeInfoNew))
                    throw new ApplicationException("Error in GetProperty");

                var baseMergeInfo = new Dictionary<string, RevRangeSet>();

                if (mergeInfoPre != null && mergeInfoPre.Count != 0)
                {
                    baseMergeInfo = ParseMegeinfoLines(mergeInfoPre[0].StringValue);
                }

                var currentMergeInfo = ParseMegeinfoLines(mergeInfoNew);

                var newRevs = Subtract(currentMergeInfo, baseMergeInfo);

                LoadLogEntries(newRevs);

                return BuildMessage(newRevs);
            }
        }
Exemplo n.º 35
0
		public SvnDriver(string workingCopy, TextWriter log)
		{
			_log = log;
			_wc = workingCopy;

			if(!Directory.Exists(_wc))
				throw new ApplicationException("Working copy does not exists: " + _wc);

			if (!Directory.Exists(Path.Combine(_wc, ".svn")))
				throw new ApplicationException("Working copy has no .svn: " + _wc);

			using (var svn = new SvnClient())
			{
				SvnInfoEventArgs info;
				svn.GetInfo(new SvnPathTarget(_wc), out info);

				_svnUri = info.Uri;

				CheckWcStatus(svn);
			}
		}
Exemplo n.º 36
0
        void LoadRevisions()
        {
            int limit;

            Int32.TryParse(textBoxLoadBunch.Text, out limit);

            var cts = new CancellationTokenSource();

            Task.Factory
                .StartNew(() => {
                    using (var client = new SvnClient())
                    {
                        client.Authentication.SslServerTrustHandlers += (sender, e) => { e.AcceptedFailures = SvnCertificateTrustFailures.MaskAllFailures; };
                        client.Authentication.DefaultCredentials = CredentialCache.DefaultNetworkCredentials;

                        SvnInfoEventArgs info;
                        client.GetInfo(_url != null ? (SvnTarget)new SvnUriTarget(_url) : new SvnPathTarget(_path), out info);
                        _repoUri = info.RepositoryRoot;

                        var args = new SvnLogArgs { Limit = limit };

                        var url = _url;

                        if (_lastLoaded != null)
                        {
                            args.OperationalRevision = _lastLoaded.Revision - 1;
                        }

                        Collection<SvnLogEventArgs> entries;
                        if (url != null)
                            client.GetLog(url, args, out entries);
                        else
                            client.GetLog(_path, args, out entries);

                        return entries;
                    }
                }, cts.Token)
                .TrackProgress(loadingOperation, cts)
                .LockControls(textBoxUrl, buttonLoad, buttonLoadNext, textBoxLoadBunch)
                .ContinueWith(t => {

                    if (t.IsFaulted || t.IsCanceled)
                    {
                        // if error occured - strat from scratch: can be load first N entries, can't continue
                        _lastLoaded = null;
                        buttonLoad.Enabled = true;
                        buttonLoadNext.Enabled = false;
                    }

                    cts.Token.ThrowIfCancellationRequested();

                    var entries = t.Result;

                    if (entries.Count < limit)
                    {
                        // nothing to load next - all revisions loaded
                        buttonLoadNext.Enabled = false;
                        _lastLoaded = null;
                    }
                    else
                    {
                        _lastLoaded = entries.Last();
                    }

                    try
                    {
                        listViewLog.BeginUpdate();

                        foreach (var entry in entries)
                        {
                            var lvi = new ListViewItem(new[] { entry.Revision.ToString(CultureInfo.InvariantCulture), entry.Author, entry.LogMessage })
                            {
                                Tag = entry
                            };
                            listViewLog.Items.Add(lvi);
                        }
                    }
                    finally
                    {
                        listViewLog.EndUpdate();
                    }

                }, TaskScheduler.FromCurrentSynchronizationContext())
                //.TrackProgress(loadingOperation)
                .WithDisposeWeak(cts)
            ;
        }
Exemplo n.º 37
0
 private long GetLastRevision(SvnClient client, string repoUrl)
 {
     SvnInfoEventArgs info;
     client.GetInfo(repoUrl, out info);
     return info.Revision;
 }
Exemplo n.º 38
0
        public static string Update(string url, Log log, string directory)
        {
            if (string.IsNullOrWhiteSpace(url))
            {
                Utility.Log(LogStatus.Skipped, "Updater", string.Format("No Url specified - {0}", url), log);
            }
            else
            {
                try
                {
                    var dir = Path.Combine(directory, url.GetHashCode().ToString("X"));
                    using (var client = new SvnClient())
                    {
                        var cleanUp = false;
                        client.Conflict +=
                            delegate(object sender, SvnConflictEventArgs eventArgs)
                            {
                                eventArgs.Choice = SvnAccept.TheirsFull;
                            };
                        client.Status(
                            dir, new SvnStatusArgs { ThrowOnError = false },
                            delegate(object sender, SvnStatusEventArgs args)
                            {
                                if (args.Wedged)
                                {
                                    cleanUp = true;
                                }
                            });

                        if (cleanUp)
                        {
                            client.CleanUp(dir);
                        }

                        try
                        {
                            if (Directory.Exists(dir))
                            {
                                SvnInfoEventArgs remoteVersion;
                                var b1 = client.GetInfo(new Uri(url), out remoteVersion);

                                SvnInfoEventArgs localVersion;
                                var b2 = client.GetInfo(dir, out localVersion);

                                if (b1 && b2 && remoteVersion.Revision == localVersion.Revision)
                                {
                                    Utility.Log(
                                        LogStatus.Ok, "Updater", string.Format("Update not needed - {0}", url), log);
                                    return dir;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Utility.Log(LogStatus.Error, "Updater", string.Format("{0} - {1}", ex, url), log);
                        }

                        client.CheckOut(new Uri(url), dir);
                        client.Update(dir);
                        Utility.Log(LogStatus.Ok, "Updater", string.Format("Updated - {0}", url), log);
                    }
                    return dir;
                }
                catch (SvnException ex)
                {
                    Utility.Log(LogStatus.Error, "Updater", string.Format("{0} - {1}", ex.RootCause, url), log);
                }
                catch (Exception ex)
                {
                    Utility.Log(LogStatus.Error, "Updater", string.Format("{0} - {1}", ex.Message, url), log);
                }
            }

            return string.Empty;
        }
Exemplo n.º 39
0
 /// <summary>
 /// Checks the SVN.
 /// </summary>
 private void checkSVN()
 {
     SvnClient __svnClient = new SvnClient();
     SvnInfoEventArgs __sieaInfo;
     bool __getInfo;
     //MessageBox.Show(__versionFilePath);
     if (__versionFilePath != "")
     {
         try
         {
            __getInfo = __svnClient.GetInfo(SvnPathTarget.FromString(GetSourcePath() + __versionFilePath + settingObject.ClassName + ".as"), out __sieaInfo);
             //MessageBox.Show(__sieaInfo.ToString());
             pluginUI.Revision.Text = __sieaInfo.LastChangeRevision.ToString();
             __vRevision = (int)__sieaInfo.LastChangeRevision;
         }
         catch (SvnException e)
         {
             try
             {
                 //MessageBox.Show(">" + e.Message);
                 __getInfo = __svnClient.GetInfo(SvnPathTarget.FromString(GetSourcePath() + __versionFilePath), out __sieaInfo);
                 pluginUI.Revision.Text = __sieaInfo.LastChangeRevision.ToString();
                 __vRevision = (int)__sieaInfo.LastChangeRevision;
             }
             catch (SvnException ex)
             {
                 __vRevision = 0;
                 pluginUI.Revision.Text = "";
             }
         }
     }
     else
     {
         __vRevision = 0;
         pluginUI.Revision.Text = "";
     }
 }
Exemplo n.º 40
0
        private void ProcessChangedPaths(SvnLoggingEventArgs svnLogEntry, long revision, LogEntryDto logEntry)
        {
            svnLogEntry.ChangedPaths.AsParallel().WithDegreeOfParallelism(1).ForAll(changedPath =>
            {
                Logger.Write(new LogEntry { Message = "Processing path " + changedPath.Path, Categories = { "Plugin.Subversion" } });
                using (var parallelSvnClient = new SvnClient())
                {
                    var changedFile = new ChangedFileDto { FileName = changedPath.Path };

                    var nodeKind = changedPath.NodeKind;
                    if (nodeKind == SvnNodeKind.Unknown)
                    {
                        // Use GetInfo to get the NodeKind
                        SvnInfoEventArgs svnInfo;
                        try
                        {
                            parallelSvnClient.GetInfo(
                                new SvnUriTarget(
                                    SettingsXml + changedPath.Path,
                                // If the file is deleted then using revision causes an exception
                                    (changedPath.Action == SvnChangeAction.Delete ? revision - 1 : revision)
                                ),
                                out svnInfo);
                            nodeKind = svnInfo.NodeKind;
                        }
                        catch (SvnRepositoryIOException svnRepositoryIoException)
                        {
                            Logger.Write(new LogEntry
                                {
                                    Message = svnRepositoryIoException.ToString(),
                                    Categories = { "Plugin.Subversion" },
                                    Severity = TraceEventType.Warning
                                });
                        }

                    }

                    if (nodeKind != SvnNodeKind.File)
                    {
                        changedFile.OldVersion = new byte[0];
                        changedFile.NewVersion = new byte[0];
                    }
                    else
                    {
                        if (changedPath.Action == SvnChangeAction.Modify || changedPath.Action == SvnChangeAction.Delete)
                        {
                            // Use GetInfo to get the last change revision
                            var previousRevisionUri = new SvnUriTarget(SettingsXml + changedPath.Path, revision - 1);
                            try
                            {
                                // For some reason we seem to get an exception with a message stating that
                                // a previous version doesn't exist for a Modify action.  I'm not sure how
                                // you can have a modify without a previous version (surely everything
                                // starts with an add..?
                                SvnInfoEventArgs previousRevisionInfo;
                                parallelSvnClient.GetInfo(previousRevisionUri, out previousRevisionInfo);
                                changedFile.OldVersion = ReadFileVersion(
                                    parallelSvnClient, SettingsXml + changedPath.Path,
                                    previousRevisionInfo.LastChangeRevision);
                            }
                            catch (SvnRepositoryIOException e)
                            {
                                Logger.Write(new LogEntry { Message = "SvnRepositoryIOException: " + e, Categories = { "Plugin.Subversion" }, Severity = TraceEventType.Error });
                                changedFile.OldVersion = new byte[0];
                            }
                            catch (SvnFileSystemException ex)
                            {
                                // http://stackoverflow.com/questions/12939642/sharpsvn-getinfo-lastchangerevision-is-wrong
                                Logger.Write(new LogEntry { Message = "SvnFileSystemException: " + ex, Categories = { "Plugin.Subversion" }, Severity = TraceEventType.Warning });
                                changedFile.OldVersion = new byte[0];
                            }
                        }
                        else
                        {
                            changedFile.OldVersion = new byte[0];
                        }

                        if (changedPath.Action == SvnChangeAction.Modify || changedPath.Action == SvnChangeAction.Add)
                        {
                            changedFile.NewVersion = ReadFileVersion(parallelSvnClient, SettingsXml + changedPath.Path, revision);
                        }
                        else
                        {
                            changedFile.NewVersion = new byte[0];
                        }
                    }

                    switch (changedPath.Action)
                    {
                        case SvnChangeAction.Add:
                            changedFile.ChangeType = ChangeType.Added;
                            break;
                        case SvnChangeAction.Delete:
                            changedFile.ChangeType = ChangeType.Deleted;
                            break;
                        default:
                            changedFile.ChangeType = ChangeType.Modified;
                            break;
                    }

                    logEntry.ChangedFiles.Add(changedFile);
                }
            });
        }
Exemplo n.º 41
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");
                }
            }
        }
Exemplo n.º 42
0
        static int Main(string[] args)
        {
#if DEBUG
            Console.Write("ProjectBuildInfo command line: ");
            foreach (var arg in args) Console.Write(arg + " ");
#endif
            Console.WriteLine();
            string namespaceName = null;
            string className = null;
            string outputFilename = null;
            string versionFile = null;
            string versionNumber = null;
            string assemblyVersionFile = null;
            string wixVersionFile = null;
            string webVersionFile = null;
            string installer32 = null;
            string installer64 = null;
            string productName = null;
            for (var i = 0; i < args.Length; i++)
            {
                switch (args[i])
                {
                    case "-namespace":
                        namespaceName = args[++i];
                        break;
                    case "-class":
                        className = args[++i];
                        break;
                    case "-output":
                        outputFilename = args[++i];
                        break;
                    case "-version":
                        versionFile = args[++i].Trim();
                        break;
                    case "-assemblyversion":
                        assemblyVersionFile = args[++i].Trim();
                        break;
                    case "-wixversion":
                        wixVersionFile = args[++i].Trim();
                        break;
                    case "-webversion":
                        webVersionFile = args[++i].Trim();
                        break;
                    case "-installer32bit":
                        installer32 = args[++i].Trim();
                        break;
                    case "-installer64bit":
                        installer64 = args[++i].Trim();
                        break;
                    case "-productName":
                        productName = args[++i].Trim();
                        break;
                    default:
                        Usage();
                        return -1;
                }
            }
            try
            {
                var gitUrl = Repository.FindRepository(outputFilename);
                if (gitUrl == null || !Repository.IsValid(gitUrl))
                    throw new ApplicationException("Given path doesn't seem to refer to a git repository: " + outputFilename);
                var repo = new Repository(gitUrl);
                var target = repo.Head.Target;

                if (versionFile != null)
                {
                    foreach (var versionFields in from curLine in File.ReadAllLines(versionFile)
                                                  select curLine.Trim()
                                                  into trimmedLine
                                                  where !string.IsNullOrEmpty(trimmedLine) && !trimmedLine.StartsWith("//")
                                                  select trimmedLine.Split('.'))
                    {
                        switch (versionFields.Length)
                        {
                            case 4:
                            case 3:
                                int major, minor, build;
                                if (!int.TryParse(versionFields[0], out major) || !int.TryParse(versionFields[1], out minor) || !int.TryParse(versionFields[2], out build) || major < 0 || minor < 0 ||
                                    build < 0)
                                    throw new FormatException(
                                        string.Format(
                                            "Version file not in expected format. There should be only one line that does not begin with a comment mark ('//') and that line should contain a version number template in the form 1.2.3 where 1 is the Major version number of this application, 2 is the Minor version number and 3 is the Build number.  A fourth field, taken from the Subversion revision number of the output directory, will be appended to this and used for assembly and installer version numbers later in the build process."));
                                versionNumber = string.Format("{0}.{1}.{2}", versionFields[0], versionFields[1], versionFields[2]);
                                break;
                            default:
                                throw new FormatException(
                                    string.Format(
                                        "Version file not in expected format. There should be only one line that does not begin with a comment mark ('//') and that line should contain a version number template in the form 1.2.3 where 1 is the Major version number of this application, 2 is the Minor version number and 3 is the Build number.  A fourth field, taken from the git hash of the output directory, will be appended to this and used for assembly and installer version numbers later in the build process."));
                        }
                    }
                }
                if (assemblyVersionFile != null)
                {
                    if (versionNumber == null) throw new ApplicationException("if -assemblyversion is specified, -version must also be specified");
                    using (var writer = new StreamWriter(assemblyVersionFile))
                    {
                        writer.WriteLine("using System.Reflection;");
                        writer.WriteLine();
                        writer.WriteLine("[assembly: AssemblyVersion(\"{0}\")]", versionNumber);
                        writer.WriteLine("[assembly: AssemblyFileVersion(\"{0}\")]", versionNumber);
                    }
                }

                if (wixVersionFile != null)
                {
                    if (versionNumber == null) throw new ApplicationException("if -wixversion is specified, -version must also be specified");
                    using (var writer = new StreamWriter(wixVersionFile))
                    {
                        writer.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
                        writer.WriteLine("<Include>");
                        writer.WriteLine("  <?define ProductFullVersion = \"{0}\" ?>", versionNumber);
                        writer.WriteLine("</Include>");
                    }
                }
                if (namespaceName != null && className != null) GenerateCode(namespaceName, className, target.Hash, outputFilename);
                if (webVersionFile != null)
                {
                    using (var writer = new StreamWriter(webVersionFile))
                    {
                        writer.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
                        writer.WriteLine("<product>");
                        if (productName != null)
                        {
                            writer.WriteLine("  <name>{0}</name>", productName);
                        }
                        if (installer32 != null)
                        {
                            writer.WriteLine("  <x86>");
                            writer.WriteLine(GenerateWebVersionXml(installer32));
                            writer.WriteLine("  </x86>");
                        }
                        if (installer64 != null)
                        {
                            writer.WriteLine("  <x64>");
                            writer.WriteLine(GenerateWebVersionXml(installer64));
                            writer.WriteLine("  </x64>");
                        }
                        writer.WriteLine("</product>");
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Usage();
                return -1;
            }
#if false
            try
            {
                string svnVersionString;
                using (var client = new SvnClient())
                {
                    if (string.IsNullOrEmpty(outputFilename)) outputFilename = assemblyVersionFile;
                    SvnInfoEventArgs svnInfo;
                    client.GetInfo(new SvnUriTarget(client.GetUriFromWorkingCopy(Path.GetDirectoryName(outputFilename))), out svnInfo);
                    svnVersionString = svnInfo.Revision.ToString(CultureInfo.InvariantCulture);
                }
                if (versionFile != null)
                {
                    var inputLines = File.ReadAllLines(versionFile);
                    foreach (var inputLine in inputLines)
                    {
                        var curLine = inputLine.Trim();
                        if (string.IsNullOrEmpty(curLine) || curLine.StartsWith("//")) continue;
                        var versionFields = curLine.Split('.');
                        switch (versionFields.Length)
                        {
                            case 4:
                            case 3:
                                int major, minor, build;
                                if (!int.TryParse(versionFields[0], out major) || !int.TryParse(versionFields[1], out minor) || !int.TryParse(versionFields[2], out build) || major < 0 || minor < 0 || build < 0) throw new FormatException(string.Format("Version file not in expected format. There should be only one line that does not begin with a comment mark ('//') and that line should contain a version number template in the form 1.2.3 where 1 is the Major version number of this application, 2 is the Minor version number and 3 is the Build number.  A fourth field, taken from the Subversion revision number of the output directory, will be appended to this and used for assembly and installer version numbers later in the build process."));
                                versionNumber = string.Format("{0}.{1}.{2}.{3}", versionFields[0], versionFields[1], versionFields[2], svnVersionString);
                                break;
                            default:
                                throw new FormatException(string.Format("Version file not in expected format. There should be only one line that does not begin with a comment mark ('//') and that line should contain a version number template in the form 1.2.3 where 1 is the Major version number of this application, 2 is the Minor version number and 3 is the Build number.  A fourth field, taken from the Subversion revision number of the output directory, will be appended to this and used for assembly and installer version numbers later in the build process."));
                        }
                    }
                }
                if (assemblyVersionFile != null)
                {
                    if (versionNumber == null) throw new ApplicationException("if -assemblyversion is specified, -version must also be specified");
                    using (var writer = new StreamWriter(assemblyVersionFile))
                    {
                        writer.WriteLine("using System.Reflection;");
                        writer.WriteLine();
                        writer.WriteLine("[assembly: AssemblyVersion(\"{0}\")]", versionNumber);
                        writer.WriteLine("[assembly: AssemblyFileVersion(\"{0}\")]", versionNumber);
                    }
                }

                if (wixVersionFile != null)
                {
                    if (versionNumber == null) throw new ApplicationException("if -wixversion is specified, -version must also be specified");
                    using (var writer = new StreamWriter(wixVersionFile))
                    {
                        writer.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
                        writer.WriteLine("<Include>");
                        writer.WriteLine("  <?define ProductFullVersion = \"{0}\" ?>", versionNumber);
                        writer.WriteLine("</Include>");
                    }
                }
                if (namespaceName != null && className != null) GenerateCode(namespaceName, className, svnVersionString, outputFilename);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Usage();
                return -1;
            }
#endif
            return 0;
        }
Exemplo n.º 43
0
        private static long getSVNVersion(SvnClient client, SvnUriTarget source)
        {
            ConsoleLogStartAction(Resources.UILogging.GetSvnVersion);

            SvnInfoEventArgs infos;
            client.GetInfo(source, out infos);

            Console.WriteLine(string.Format(Resources.UILogging.FoundSVNVersion, infos.Revision));

            ConsoleEndAction();

            return infos.Revision;
        }
Exemplo n.º 44
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            lbInfo.Content = "一切正常";

            String curDir = Directory.GetCurrentDirectory();
            String curExe = System.Reflection.Assembly.GetExecutingAssembly().Location;


            SvnClient = new SvnClient();

            SvnTarget svnTargetCurDir = SvnTarget.FromString(curDir);
            SvnTarget snvTargetCurExe = SvnTarget.FromString(curExe);

            // 未使用 - 获取目录下的文件状态
            Collection<SvnStatusEventArgs> svnStatusEventArgsCollection;
            SvnClient.GetStatus(Directory.GetCurrentDirectory(), out svnStatusEventArgsCollection);

            // 未使用 - 空的
            Collection<SvnPropertyListEventArgs> svnPropertyListEventArgsCollection;
            SvnClient.GetPropertyList(Directory.GetCurrentDirectory(), out svnPropertyListEventArgsCollection);

            // 未使用 - 获取一个文件的状态
            Collection<SvnFileVersionEventArgs> svnFileVersionEventArgsCollection;
            try
            {
                SvnClient.GetFileVersions(snvTargetCurExe, out svnFileVersionEventArgsCollection);
            }
            catch(SvnWorkingCopyPathNotFoundException ex)
            {
                // 如果查询的文件未加入Repo,会抛此异常
            }

            // 未使用 - 一个好像没什么用的信息列表,目录是第一个项,没有版本号
            Collection<SvnListEventArgs> svnListEventArgsCollection;
            SvnClient.GetList(svnTargetCurDir, out svnListEventArgsCollection);

            // 未使用 - 工作目录全路径
            String workingCopyRoot = SvnClient.GetWorkingCopyRoot(Directory.GetCurrentDirectory());
            
            // 未使用 - 整个仓库的最新版本
            long revision = 0;
            SvnClient.Youngest(Directory.GetCurrentDirectory(), out revision);

            // 此目录的相关变更 和 GUI中的ShowLog一样 是此目录的相关变更           
            Collection<SvnLogEventArgs> logList;
            try
            {
                SvnClient.GetLog(Directory.GetCurrentDirectory(), out logList);
            }
            catch(SvnInvalidNodeKindException ex)
            {
                lbInfo.Content = "当前目录不是SVN目录,停用更新检查功能";
                btnUpdateAndLaunch.Visibility = Visibility.Hidden;
                return;
            }

            // 获取本地目录信息,当前版本和修改版本都是本地的
            SvnInfoEventArgs svnInfoEventArgs;
            SvnClient.GetInfo(svnTargetCurDir, out svnInfoEventArgs);

            long curRevision = svnInfoEventArgs.Revision;       // 当前的SVN版本
            long changeRevision = logList[0].Revision;          // 当前目录的最新远程变更版本

            lbVersionChange.Content = changeRevision;
            lbVersionCur.Content = svnInfoEventArgs.Revision;

            if (curRevision < changeRevision)
            {
                btnUpdateAndLaunch.Visibility = Visibility.Visible;
                lbInfo.Content = "发现新版本";
            }
            else
            {
                btnUpdateAndLaunch.Visibility = Visibility.Hidden;
                lbInfo.Content = "已经是最新版";
            }

            // --------------------------------------------------------
            // SvnWorkingCopyClient
            // --------------------------------------------------------
            SvnWorkingCopyClient svnWorkingCopyClient = new SvnWorkingCopyClient();

            // 未使用 只有一个值IsText 没看出有什么用处
            SvnWorkingCopyState svnWorkingCopyState;
            svnWorkingCopyClient.GetState(Directory.GetCurrentDirectory(), out svnWorkingCopyState);

            // 未使用 返回仅本地存在的所有修改版本 
            SvnWorkingCopyVersion svnWorkingCopyVersion;
            svnWorkingCopyClient.GetVersion(curDir, out svnWorkingCopyVersion);

            // --------------------------------------------------------
            // SvnTools
            // --------------------------------------------------------
            // 未使用 传入正确的目录却返回false????
            bool isCurDirInWorkingCopy = SvnTools.IsManagedPath(curDir);

        }
Exemplo n.º 45
0
 /// <summary>
 /// 执行获取本地项目svn信息的操作
 /// </summary>
 /// <param name="projectInfo">传入想要获取信息的projectInfo实例对象</param>
 /// <returns>获取完信息的projectInfo的实例对象</returns>
 public ProjectInfo GetLocalInfo(ProjectInfo projectInfo)
 {
     using (SvnClient svnClient = new SvnClient())
     {
         try
         {
             SvnInfoEventArgs clientInfo;
             SvnPathTarget local = new SvnPathTarget(projectInfo.Workdirectory);
             svnClient.GetInfo(local, out clientInfo);
             //string revision =
             //    Regex.Match(string.Format("clientInfo revision of {0} is {1}", local, clientInfo.Revision),
             //        @"\d+").Value;
             string author = clientInfo.LastChangeAuthor;
             string changeTime = clientInfo.LastChangeTime.ToLocalTime().ToString();
             projectInfo.Author = author;
             //projectInfo.Revision = revision;
             //projectInfo.Changetime = changeTime;
             return projectInfo;
         }
         catch (Exception exception)
         {
             return projectInfo;
         }
     }
 }
Exemplo n.º 46
-1
        public static void ShowCommitedIssueTools(IntPtr hParentWnd, string commonRoot, string[] pathList, string logMessage, int revision)
        {
            if (!Settings.Default.EnablePostCommitTools)
                return;

            var gitRepos = false;
            var repoUrl = "";
            var repoRelPathList = pathList;
            try
            {
                // ensure it is not git repository
                var wc = commonRoot;
                while(wc != null)
                {
                    if (Directory.Exists(Path.Combine(wc, ".svn")))
                        break;

                    if (Directory.Exists(Path.Combine(wc, ".git")))
                    {
                        gitRepos = true;
                        break;
                    }

                    wc = Path.GetDirectoryName(wc);
                }

                if(!gitRepos)
                {
                    SvnInfoEventArgs info;
                    using (var client = new SvnClient())
                    {
                        client.GetInfo(new SvnPathTarget(commonRoot), out info);
                        repoUrl = info.RepositoryRoot.OriginalString;
                    }

                    // calculate paths relative to repository:
                    var commonRootRepoRelPath = info.Uri.OriginalString.Substring(repoUrl.Length).Trim('/');
                    repoRelPathList = pathList
                        .Select(p => {
                            var relToCommon = p.Substring(commonRoot.Length).Replace('\\', '/').TrimStart('/');
                            return commonRootRepoRelPath + "/" + relToCommon;
                        })
                        .ToArray()
                    ;
                }
            }
            catch (Exception ex)
            {
                MessageBoxEx.ShowWarning("Error while detecting repository url: " + ex.Message);
            }

            new CommitedIssueTools(repoRelPathList, logMessage, revision, repoUrl) {
                Parent = Control.FromHandle(hParentWnd),
                StartPosition = FormStartPosition.CenterParent
            }.ShowDialog();
        }