Esempio n. 1
0
        public static string GetInfo(string[] args, string revision)
        {
            Parameters parameters;

            if (!Parameters.TryParse(args, out parameters))
            {
                return("False");
            }

            using (var client = new SharpSvn.SvnClient())
            {
                SetUpClient(parameters, client);

                var target = SvnTarget.FromString(parameters.Path);
                SvnInfoEventArgs svnInfoEventArgs;
                SvnUpdateResult  svnUpdateResult;

                if (!client.GetInfo(target, out svnInfoEventArgs))
                {
                    throw new Exception("SVN info failed");
                }
                Uri svnUrl = svnInfoEventArgs.Uri;
                return(svnInfoEventArgs.Revision.ToString());

                throw new Exception("SVN update failed");
            }
            return("jhgjg");
        }
Esempio n. 2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="strFileName"></param>
        /// <param name="strError"></param>
        /// <returns></returns>
        public SvnInfoEventArgs GetTargetInformation(string strFileName, ref string strError)
        {
            try
            {
                // Create Target Information
                SvnTarget target = SvnTarget.FromString(strFileName);

                SvnInfoEventArgs args;

                // Get Target Information
                bool boolRetrievedInfo = this.Connection.GetInfo(target, out args);

                // Validation
                if (boolRetrievedInfo == false || args == null)
                {
                    return(null);
                }

                return(args);
            }
            catch (Exception ex)
            {
                strError = ex.ToString();
                Console.WriteLine(strError);

                return(null);
            }
        }
Esempio n. 3
0
        public void TestGetOnCwd()
        {
            SvnSandBox sbox           = new SvnSandBox(this);
            Uri        CollabReposUri = sbox.CreateRepository(SandBoxRepository.MergeScenario);

            string wc = sbox.Wc;

            Client.CheckOut(new Uri(CollabReposUri, "trunk"), wc);

            string dir = Directory.GetCurrentDirectory();

            Directory.SetCurrentDirectory(wc);
            try
            {
                string v;
                Assert.That(Client.TryGetProperty(".", SvnPropertyNames.SvnMergeInfo, out v));
                Assert.That(v, Is.Not.Null);

                Assert.That(Client.TryGetProperty(SvnTarget.FromString("."), SvnPropertyNames.SvnMergeInfo, out v));
                Assert.That(v, Is.Not.Null);
            }
            finally
            {
                Directory.SetCurrentDirectory(wc);
            }
        }
Esempio n. 4
0
        private string Diff(string pSourcePath, Uri u)
        {
            if (client == null)
            {
                Init();
            }
            try
            {
                MemoryStream objMemoryStream = new MemoryStream();
                SvnDiffArgs  da = new SvnDiffArgs();
                da.IgnoreAncestry = true;
                da.DiffArguments.Add("-b");
                da.DiffArguments.Add("-w");

                bool b = client.Diff(SvnTarget.FromString(pSourcePath), new SvnUriTarget(u, SvnRevision.Head), da, objMemoryStream);
                objMemoryStream.Position = 0;
                StreamReader strReader = new StreamReader(objMemoryStream);
                string       str       = strReader.ReadToEnd();
                return(str);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Esempio n. 5
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]);
        }
Esempio n. 6
0
        public override Revision GetRevision(string alias)
        {
            string url        = Url.TrimEnd('/');
            string tempFolder = Context.Current.MapPath(Core.Settings.rootPath + "/svnRepoTemp/");

            if (System.IO.Directory.Exists(tempFolder))
            {
                System.IO.Directory.Delete(tempFolder);
            }

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

                RevisionStorage rs = new RevisionStorage();
                var             r  = rs.GetFromDirectory(alias, tempFolder + alias);

                rs.Save(r, alias);

                rs.Dispose();

                return(r);
            }

            return(null);
        }
Esempio n. 7
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);
            }
        }
Esempio n. 8
0
        private bool ConexaoOK(string p_URL_SVN, string p_Usuario_SVN, string p_Senha_SVN)
        {
            bool Resp = false;

            SvnClient _SvnClient = new SvnClient();
            SvnTarget _SvnTarget = SvnTarget.FromString(p_URL_SVN);

            _SvnClient.Authentication.DefaultCredentials = new NetworkCredential(p_Usuario_SVN, p_Senha_SVN);
            System.Collections.ObjectModel.Collection <SvnListEventArgs> _Lista;

            for (int i = 0; i < 5; i++)
            {
                try
                {
                    if (_SvnClient.GetList(_SvnTarget, out _Lista))
                    {
                        Resp = true;
                    }
                }
                catch (Exception)
                {
                }
            }
            return(Resp);
        }
Esempio n. 9
0
        public void DeleteClosedFeature()
        {
            string featureRootUrl = string.Empty;

            Info(SvnTarget.FromString(WorkingCopyPath), (sender, args) => featureRootUrl = args.Uri.ToString());
            var svnDeleteArgs = new SvnDeleteArgs {
                LogMessage = "Remove closed feature branch"
            };

            RemoteDelete(new Uri(featureRootUrl), svnDeleteArgs);
        }
Esempio n. 10
0
        public static string GetLogText(string[] args, string revision, out Collection <SvnLogEventArgs> logItemsColl)
        {
            Parameters parameters;

            if (!Parameters.TryParse(args, out parameters))
            {
                throw new Exception("TryParse failed");
            }

            using (var client = new SharpSvn.SvnClient())
            {
                SetUpClient(parameters, client);

                var target = SvnTarget.FromString(parameters.Path);
                SvnInfoEventArgs svnInfoEventArgs;
                SvnUpdateResult  svnUpdateResult;

                if (!client.GetInfo(target, out svnInfoEventArgs))
                {
                    throw new Exception("SVN info failed");
                }

                Uri  svnUrl       = svnInfoEventArgs.Uri;
                long revisionLong = long.Parse(revision);

                long revisionLongTo = svnInfoEventArgs.Revision;


                SvnLogArgs Logargs = new SvnLogArgs
                {
                    Range = new SvnRevisionRange(revisionLong, revisionLongTo)
                };
                Collection <SvnLogEventArgs> logItems;
                //  client.GetLog(svnUrl, Logargs, out logItems);
                client.GetLog(svnUrl, out logItemsColl);

                string AlllogText = "";
                for (int i = logItemsColl.Count - 1; i > 0; i--)
                {
                    AlllogText = AlllogText + (Char)13 + (Char)10 +
                                 logItemsColl[i].Revision.ToString() + " " + logItemsColl[i].Time.ToString() + " " + logItemsColl[i].LogMessage;
                }



                return(AlllogText);

                throw new Exception("SVN update failed");
            }



            return("jhgjg");
        }
Esempio n. 11
0
        /// <summary>
        ///     Получить URL ветки из которой была выделена фитча
        /// </summary>
        /// <param name="revision">Номер ревизии в которой выделена ветка</param>
        /// <param name="workingCopyPath">Путь к рабочей копии</param>
        /// <returns>Строка с URL</returns>
        private string GetBaseBranchPath(long revision, string workingCopyPath)
        {
            string basePath    = string.Empty;
            var    svnInfoArgs = new SvnInfoArgs {
                Revision = new SvnRevision(revision)
            };

            Info(SvnTarget.FromString(workingCopyPath), svnInfoArgs, (sender, args) => {
                basePath = args.Uri.ToString();
                Logger.LogInfo(args.Uri.ToString());
            });
            return(basePath);
        }
Esempio n. 12
0
        private int BranchItem(string source, string target)
        {
            Trace.TraceInformation("SVNTCAdapter BranchItem {0} {1}", source, target);
            SvnTarget sourceTarget = SvnTarget.FromString(source);

            m_client.Copy(sourceTarget, target);
            m_client.Commit(target, new SvnCommitArgs()
            {
                LogMessage = BranchComment
            });

            return(GetLatestRevisionNumber());
        }
Esempio n. 13
0
        public void Run()
        {
            var svnParams = new Dictionary <string, string> {
                { SvnUtilsBase.SvnUserOptionName, Parameter.SvnLogin },
                { SvnUtilsBase.SvnPasswordOptionName, Parameter.SvnPassword }
            };

            using (var svnClient = new SvnUtils(svnParams, Logger)) {
                if (svnClient.GetList(SvnTarget.FromString(Parameter.UrlPath), out var repositoryPackages))
                {
                    ChangePackages(svnClient, repositoryPackages.Where(args => !string.IsNullOrWhiteSpace(args.Path)));
                }
            }
        }
Esempio n. 14
0
        public override void CommitRevision(Revision revision)
        {
            string localPath = PackagingManager.Instance.OutputDirectory;
            string url       = Url.TrimEnd('/') + "/" + revision.Directory;

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

                //client.Export(folderTarget, tempFolder);
            }
        }
Esempio n. 15
0
        public int MergeItem(MigrationItemStrings mergeItem, int mergeFrom, int mergeTo)
        {
            Trace.TraceInformation("SVNTCAdapter MergeItem {0} {1}", mergeItem.LocalPath, mergeItem.NewLocalPath);
            SvnTarget        sourceTarget = SvnTarget.FromString(mergeItem.LocalPath);
            SvnRevisionRange range        = new SvnRevisionRange(mergeFrom, mergeTo);

            m_client.Merge(mergeItem.NewLocalPath, sourceTarget, range);
            m_client.Commit(mergeItem.NewLocalPath, new SvnCommitArgs()
            {
                LogMessage = MergeComment
            });

            return(GetLatestRevisionNumber());
        }
Esempio n. 16
0
        private void btnGetProp_Click(object sender, EventArgs e)
        {
            if (tbFileURI.Text.Length == 0)
            {
                MessageBox.Show("geçerli bir URI girin");
                return;
            }

            lvProps.Items.Clear();                                //liste görüntüsünü temizliyor

            SvnTarget tgt = SvnTarget.FromString(tbFileURI.Text); // Bu, özellikleri aldığımız hedef dosya olacak

            System.Collections.ObjectModel.Collection <SvnPropertyListEventArgs> proplist;
            SvnPropertyListArgs args = new SvnPropertyListArgs();//argmanlar koyabilecegimiz yer

            if (cbRecurse.Checked == true)
            {
                args.Depth = SvnDepth.Infinity;
            }
            using (SharpSvn.SvnClient client = new SharpSvn.SvnClient())
            {
                try
                {
                    client.GetPropertyList(tgt, args, out proplist);
                    foreach (SvnPropertyListEventArgs node in proplist)
                    {
                        foreach (SvnPropertyValue propVal in node.Properties)
                        {
                            ListViewItem entry = new ListViewItem(node.Path);
                            entry.SubItems.Add(propVal.Key);
                            entry.SubItems.Add(propVal.StringValue);
                            lvProps.Items.Add(entry);
                        }
                    }
                    for (int i = 0; i < 3; i++)
                    {
                        lvProps.Columns[i].Width = -2;
                    }
                }
                catch (SvnException se)
                {
                    MessageBox.Show(se.Message + Environment.NewLine +
                                    "Error:" + se.SvnErrorCode,
                                    "svn proplist error",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
                }
            }
        }
Esempio n. 17
0
 public static string GetRepositoryPathWithFolder(string folderPath)
 {
     try {
         using (var svnClient = new SvnClient()) {
             svnClient.GetInfo(SvnTarget.FromString(folderPath), out var args);
             return(args?.Uri?.AbsoluteUri);
         }
     } catch (SvnInvalidNodeKindException nodeKindException) {
         if (nodeKindException.SvnErrorCode == SvnErrorCode.SVN_ERR_WC_NOT_DIRECTORY)
         {
             return(string.Empty);
         }
         throw;
     }
 }
Esempio n. 18
0
        /// <summary>
        ///     Копирование базового ветки в ветку фитчи
        /// </summary>
        /// <param name="featureName">Название фитчи</param>
        /// <param name="featureNewUrl">URL новой ветки фитчи</param>
        /// <param name="revision">Номер ревизии из которой выделяется копия</param>
        /// <returns>Результат</returns>
        private bool CopyBaseBranch(string featureName, string featureNewUrl, long revision)
        {
            var svnCopyArgs = new SvnCopyArgs {
                LogMessage = string.Format(Resources.SvnUtils_CopyBaseBranch_Init_Feature, featureName),
                Revision   = new SvnRevision(revision)
            };

            svnCopyArgs.Notify += SvnCopyArgsOnNotify;
            try {
                return(RemoteCopy(SvnTarget.FromString(BranchReleaseUrl), new Uri(featureNewUrl), svnCopyArgs));
            } catch (ArgumentNullException argumentNullException) {
                Logger.LogError(argumentNullException.Message,
                                $"Parameter {argumentNullException.ParamName} is empty.");
                return(false);
            } finally {
                svnCopyArgs.Notify -= SvnCopyArgsOnNotify;
            }
        }
Esempio n. 19
0
        public static string UpdateToRevision(string[] args, string revision)
        {
            Parameters parameters;

            if (!Parameters.TryParse(args, out parameters))
            {
                return("False");
            }

            using (var client = new SharpSvn.SvnClient())
            {
                SetUpClient(parameters, client);

                var target = SvnTarget.FromString(parameters.Path);
                SvnInfoEventArgs svnInfoEventArgs;
                SvnUpdateResult  svnUpdateResult;

                if (!client.GetInfo(target, out svnInfoEventArgs))
                {
                    throw new Exception("SVN info failed");
                }

                Uri  svnUrl       = svnInfoEventArgs.Uri;
                long revisionLong = long.Parse(revision);


                //update to revision

                //DebugMessage(parameters, "Updating");
                SvnUpdateArgs SvnArgs = new SvnUpdateArgs();
                //// If args.Revision is not set, it defaults to fetch the HEAD revision.
                SvnArgs.Revision = revisionLong;
                if (client.Update(parameters.Path, SvnArgs, out svnUpdateResult))
                {
                    DebugMessage(parameters, "Done");

                    Console.WriteLine("Updated to r" + svnUpdateResult.Revision);
                    return("true");
                }
                throw new Exception("SVN update failed");
            }
            return("jhgjg");
        }
Esempio n. 20
0
        /// <summary>
        ///     Реинтеграция фитчи в родительскую ветку
        /// </summary>
        public void ReintegrationMergeToBaseBranch()
        {
            string baseWorkingCopyPath = BaseWorkingCopyPath ?? WorkingCopyPath + "_Release";
            string baseWorkingCopyUrl  =
                GetBaseBranchPath(GetFeatureFirstRevisionNumber(WorkingCopyPath), WorkingCopyPath);
            var svnCheckOutArgs = new SvnCheckOutArgs();

            svnCheckOutArgs.Notify += SvnCheckOutArgsOnNotify;
            try {
                CheckOut(SvnUriTarget.FromString(baseWorkingCopyUrl), baseWorkingCopyPath, svnCheckOutArgs);
            } finally {
                svnCheckOutArgs.Notify -= SvnCheckOutArgsOnNotify;
            }

            Info(SvnTarget.FromString(WorkingCopyPath), (sender, args) => { });

            var svnReintegrationMergeArgs = new SvnReintegrationMergeArgs();

            svnReintegrationMergeArgs.Notify   += SvnReintegrationMergeArgsOnNotify;
            svnReintegrationMergeArgs.Conflict += SvnReintegrationMergeArgsOnConflict;

            try {
                string workingCopyUrl = string.Empty;
                Info(WorkingCopyPath, new SvnInfoArgs {
                    Revision = new SvnRevision(SvnRevisionType.Head)
                }
                     , (sender, args) => workingCopyUrl = args.Uri.ToString());
                ReintegrationMerge(baseWorkingCopyPath
                                   , SvnTarget.FromString(workingCopyUrl)
                                   , svnReintegrationMergeArgs);
            } catch (SvnClientNotReadyToMergeException e) {
                Logger.LogError(e.Message, e.Targets.ToString());
            } finally {
                svnReintegrationMergeArgs.Notify   -= SvnReintegrationMergeArgsOnNotify;
                svnReintegrationMergeArgs.Conflict -= SvnReintegrationMergeArgsOnConflict;
            }

            RemovePackageProperty(baseWorkingCopyPath);
        }
Esempio n. 21
0
        /// <summary>
        ///     Обновить рабочую копию
        /// </summary>
        /// <param name="workingCopyPath">Путь к рабочей копии</param>
        /// <returns>Результат</returns>
        private bool UpdateWorkingCopy(string workingCopyPath)
        {
            Info(SvnTarget.FromString(workingCopyPath), (sender, args) => Console.WriteLine(args));
            var svnUpdateArgs = new SvnUpdateArgs {
                IgnoreExternals = false, UpdateParents = true
            };

            svnUpdateArgs.Notify   += SvnUpdateArgsOnNotify;
            svnUpdateArgs.Conflict += SvnUpdateArgsOnConflict;
            svnUpdateArgs.SvnError += SvnUpdateArgsOnSvnError;
            try {
                return(Update(workingCopyPath, svnUpdateArgs));
            } catch (ArgumentNullException argumentNullException) {
                Logger.LogError(argumentNullException.Message,
                                $"Parameter {argumentNullException.ParamName} is empty.");
                return(false);
            } finally {
                svnUpdateArgs.Notify   -= SvnUpdateArgsOnNotify;
                svnUpdateArgs.Conflict -= SvnUpdateArgsOnConflict;
                svnUpdateArgs.SvnError -= SvnUpdateArgsOnSvnError;
            }
        }
Esempio n. 22
0
        private void CarregaListaUsuariosSVN()
        {
            if (_ListaUsuariosSVN != null)
            {
                return;
            }

            string _CaminhoArquivo          = "";
            string _ConteudoArquivoUsuarios = "";

            string _CaminhoPasta = csUtil.PastaLocalExecutavel() + "Access_fontes";

            SvnClient _SvnClient = new SvnClient();
            SvnTarget _SvnTarget = SvnTarget.FromString(_URL_SVN);

            _SvnClient.Authentication.DefaultCredentials = new NetworkCredential(_Usuario_SVN, _Senha_SVN);

            for (int i = 0; i < 5; i++)
            {
                try
                {
                    _SvnClient.CheckOut(new Uri(_URL_SVN + "/branches/_Apoio/Access_fontes"), _CaminhoPasta);
                }
                catch (Exception)
                {
                }
            }

            _CaminhoArquivo          = _CaminhoPasta + "\\Lista_Usuarios.txt";
            _ConteudoArquivoUsuarios = File.ReadAllText(_CaminhoArquivo, Encoding.Default);

            Directory.Delete(_CaminhoPasta, true);

            _ConteudoArquivoUsuarios = _ConteudoArquivoUsuarios.Replace("\r", "");
            _ListaUsuariosSVN        = _ConteudoArquivoUsuarios.Split("\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
        }
Esempio n. 23
0
        private string Diff(string pSourcePath, Uri u)
        {
            if (client == null)
            {
                Init();
            }

            // avoid running commands in parallel so just wait for last commands to finish or timeout after 10 seconds
            int i = 0;

            while (client.IsCommandRunning && i < 100)
            {
                Thread.Sleep(100);
                i++;
            }


            try
            {
                MemoryStream objMemoryStream = new MemoryStream();
                SvnDiffArgs  da = new SvnDiffArgs();
                da.IgnoreAncestry = true;
                da.DiffArguments.Add("-b");
                da.DiffArguments.Add("-w");

                bool b = client.Diff(SvnTarget.FromString(pSourcePath), new SvnUriTarget(u, SvnRevision.Head), da, objMemoryStream);
                objMemoryStream.Position = 0;
                StreamReader strReader = new StreamReader(objMemoryStream);
                string       str       = strReader.ReadToEnd();
                return(str);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Esempio n. 24
0
        private static bool ImportDirectories()
        {
            var    uri = new Uri(string.Format("{0}{1}", svnURL, svnPROJ));
            string dir = Path.Combine(repoDIR, vssPROJ.Substring(2).Replace("/", "\\"));

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

            using (SvnClient svnClient = GetSvnClient())
            {
                var importArgs = new SvnImportArgs
                {
                    LogMessage = string.Format("Initial import from VSS on {0}", DateTime.Now)
                };

                SvnInfoEventArgs infoEventArgs;
                try
                {
                    trunkexists = svnClient.GetInfo(SvnTarget.FromUri(uri), out infoEventArgs);
                    migrateLog.DebugFormat(svnClient.GetInfo(SvnTarget.FromUri(uri), out infoEventArgs) ?
                                           "Getting trunk revision was successful." :
                                           "Getting trunk revision was NOT successful!");

                    migrateLog.DebugFormat("Base Revision: " + infoEventArgs.Revision);

                    if (infoEventArgs.Revision == 0)
                    {
                        if (!svnClient.Import(dir, uri, importArgs))
                        {
                            return(false);
                        }
                    }
                }
                catch (Exception)
                {
                    if (!svnClient.Import(dir, uri, importArgs))
                    {
                        return(false);
                    }
                }

                var tagurl    = new Uri(String.Format("{1}/{0}", svnTAG, svnURL));
                var branchurl = new Uri(String.Format("{1}/{0}", svnBRANCH, svnURL));

                try
                {
                    svnClient.GetInfo(tagurl, out infoEventArgs);
                    svnClient.GetInfo(branchurl, out infoEventArgs);
                    migrateLog.DebugFormat(svnClient.GetInfo(tagurl, out infoEventArgs)?
                                           "Getting tag dir revision was successful." :
                                           "Getting tag dir revision was NOT successful!");

                    migrateLog.DebugFormat(svnClient.GetInfo(branchurl, out infoEventArgs)?
                                           "Getting branch dir revision was successful." :
                                           "Getting branch dir revision was NOT successful!");
                }
                catch (SvnRepositoryIOException)
                {
                    var tagdircreated = svnClient.RemoteCreateDirectory((tagurl), new SvnCreateDirectoryArgs
                    {
                        LogMessage = "Initial creation of tag directory", CreateParents = true
                    });
                    var branchdircreated = svnClient.RemoteCreateDirectory((branchurl),
                                                                           new SvnCreateDirectoryArgs
                    {
                        LogMessage = "Initial creation of branch directory", CreateParents = true
                    });
                }

                try
                {
                    svnClient.GetInfo(uri, out infoEventArgs);
                }
                catch (SvnRepositoryIOException)
                {
                    svnClient.RemoteCreateDirectory((uri),
                                                    new SvnCreateDirectoryArgs
                    {
                        LogMessage = "Initial import", CreateParents = true
                    });
                }


                migrateLog.DebugFormat(dir);
                //Update the author and time of the first import revision to correspond to the first file revision
                //minus a minute in time for proper ordering of the revisions in time);
                if (!string.IsNullOrEmpty(svnREVPROPSPATH))
                {
                    svnClient.GetInfo(trunkexists
                                          ? SvnTarget.FromUri(uri)
                                          : SvnTarget.FromString(dir),
                                      out infoEventArgs);

                    var props = new SvnRevProps(svnREVPROPSPATH, infoEventArgs.Revision);

                    //This helps to make sure the revisions are imported in chronological order
                    props.SetDate(revisions.Keys[0].Time.AddMinutes(-1));
                }

                Cleanup();

                var checkOutArgs = new SvnCheckOutArgs {
                    Depth = SvnDepth.Infinity
                };
                return(svnClient.CheckOut(uri, dir, checkOutArgs));
            }
        }
Esempio n. 25
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);
        }
Esempio n. 26
0
        private static void CheckoutUpdate(Parameters parameters)
        {
            using (var client = new SharpSvn.SvnClient())
            {
                SetUpClient(parameters, client);

                var target = SvnTarget.FromString(parameters.Path);
                SvnInfoEventArgs svnInfoEventArgs;
                SvnUpdateResult  svnUpdateResult;

                var nonExistentUrl = false;
                EventHandler <SvnErrorEventArgs> ignoreNonexistent = (o, eventArgs) =>
                {
                    nonExistentUrl = false;
                    //if (eventArgs.Exception.SubversionErrorCode == 170000)
                    if (eventArgs.Exception.Message.Contains("non-existent in revision"))
                    {
                        nonExistentUrl   = true;
                        eventArgs.Cancel = true;
                    }
                };

                if (client.GetWorkingCopyRoot(parameters.Path) == null)
                {
                    client.SvnError += ignoreNonexistent;
                    var getInfoSucceeded = client.GetInfo(SvnUriTarget.FromString(parameters.Url), out svnInfoEventArgs);
                    client.SvnError -= ignoreNonexistent;

                    if (!getInfoSucceeded)
                    {
                        if (nonExistentUrl)
                        {
                            Console.WriteLine("SVN info reported nonexistent URL; creating remote directory.");
                            if (!client.RemoteCreateDirectory(new Uri(parameters.Url), new SvnCreateDirectoryArgs {
                                CreateParents = true, LogMessage = parameters.Message
                            }))
                            {
                                throw new Exception("Create directory failed on " + parameters.Url);
                            }
                        }
                        else
                        {
                            throw new Exception("SVN info failed");
                        }
                    }

                    DebugMessage(parameters, "Checking out");
                    if (client.CheckOut(SvnUriTarget.FromString(parameters.Url), parameters.Path, out svnUpdateResult))
                    {
                        DebugMessage(parameters, "Done");
                        Console.WriteLine("Checked out r" + svnUpdateResult.Revision);
                        return;
                    }

                    throw new Exception("SVN checkout failed");
                }

                if (!client.GetInfo(target, out svnInfoEventArgs))
                {
                    throw new Exception("SVN info failed");
                }

                if (!UrlsMatch(svnInfoEventArgs.Uri.ToString(), parameters.Url))
                {
                    throw new Exception(string.Format("A different URL is already checked out ({0} != {1})", svnInfoEventArgs.Uri, parameters.Url));
                }

                if (parameters.Cleanup)
                {
                    DebugMessage(parameters, "Cleaning up");
                    client.CleanUp(parameters.Path);
                    DebugMessage(parameters, "Done");
                }

                if (parameters.Revert)
                {
                    DebugMessage(parameters, "Reverting");
                    client.Revert(parameters.Path);
                    DebugMessage(parameters, "Done");
                }

                if (parameters.DeleteUnversioned)
                {
                    DebugMessage(parameters, "Deleting unversioned files");
                    Collection <SvnStatusEventArgs> changedFiles;
                    client.GetStatus(parameters.Path, out changedFiles);
                    foreach (var changedFile in changedFiles)
                    {
                        if (changedFile.LocalContentStatus == SvnStatus.NotVersioned)
                        {
                            if (changedFile.NodeKind == SvnNodeKind.Directory)
                            {
                                DebugMessage(parameters, "NodeKind is directory for [" + changedFile.FullPath + "]");
                            }
                            if ((File.GetAttributes(changedFile.FullPath) & FileAttributes.Directory) == FileAttributes.Directory)
                            {
                                DebugMessage(parameters, "Deleting directory [" + changedFile.FullPath + "] recursively!");
                                Directory.Delete(changedFile.FullPath, true);
                            }
                            else
                            {
                                DebugMessage(parameters, "Deleting file [" + changedFile.FullPath + "]");
                                File.Delete(changedFile.FullPath);
                            }
                        }
                    }
                    DebugMessage(parameters, "Done");
                }

                DebugMessage(parameters, "Updating");
                if (client.Update(parameters.Path, out svnUpdateResult))
                {
                    DebugMessage(parameters, "Done");
                    Console.WriteLine("Updated to r" + svnUpdateResult.Revision);
                    return;
                }

                throw new Exception("SVN update failed");
            }
        }
Esempio n. 27
0
        public static void Diff_ReposDiff(string[] args, long Rev1, long Rev2)
        {
            //string clientDiff = this.RunCommand("svn", "diff -r 1:5 " + this.ReposUrl);

            MemoryStream outstream = new MemoryStream();
            MemoryStream errstream = new MemoryStream();

            SvnDiffArgs a = new SvnDiffArgs();

            Parameters parameters;

            if (!Parameters.TryParse(args, out parameters))
            {
                return;
            }

            using (var client = new SharpSvn.SvnClient())
            {
                SetUpClient(parameters, client);

                var target = SvnTarget.FromString(parameters.Path);
                SvnInfoEventArgs svnInfoEventArgs;
                SvnUpdateResult  svnUpdateResult;

                if (!client.GetInfo(target, out svnInfoEventArgs))
                {
                    throw new Exception("SVN info failed");
                }

                Uri svnUrl = svnInfoEventArgs.Uri;

                a.ErrorStream = errstream;

                try
                {
                    client.Diff(target, new SvnRevisionRange(Rev1, Rev2), a, outstream);
                }

                catch (Exception)
                {
                    throw new Exception("SVN diff failed");
                    //  return ;
                }


                return;
            }



            //string err = Encoding.Default.GetString(errstream.ToArray());
            //Assert.That(err, Is.EqualTo(string.Empty), "Error in diff: " + err);

            //string apiDiff = Encoding.Default.GetString(outstream.ToArray());
            //string[] clientLines = clientDiff.Split('\n');
            //string[] apiLines = apiDiff.Split('\n');
            //Array.Sort<string>(clientLines);
            //Array.Sort<string>(apiLines);

            //Assert.That(apiLines, Is.EqualTo(clientLines), "Diffs differ");
        }
Esempio n. 28
0
        private static void ApplyTag(IVSSItem vssFile, SvnClient svnClient, IVSSVersion vssVersion, Tag tag)
        {
            var copyArgs = new SvnCopyArgs
            {
                LogMessage =
                    string.Format("Released {0}\n{1}", vssVersion.Label, vssVersion.LabelComment)
            };

            migrateLog.DebugFormat("------------------------------------");
            migrateLog.DebugFormat(string.Format("Setting Tag:"));
            migrateLog.DebugFormat(string.Format("Label: {0}", vssVersion.Label));
            migrateLog.DebugFormat(string.Format("Comment: {0}", vssVersion.LabelComment));
            migrateLog.DebugFormat(string.Format("from Url: {0}", tag.fromUrlString));
            migrateLog.DebugFormat(string.Format("to Url: {0}", tag.tagString));


            try
            {
                svnClient.RemoteCopy(SvnTarget.FromString(tag.fromUrlString),
                                     new Uri(tag.tagString),
                                     copyArgs);

                CounterfeitRevProps(svnClient, SvnTarget.FromUri(new Uri(tag.tagString)), vssVersion);
            }


            catch (SvnFileSystemException e)
            {
                //tags with same names get handled here

                if (e.ToString().Contains("already exists"))
                {
                    int index = tag.tagString.IndexOf(svnTAG) + svnTAG.Length + 1;
                    //FIXME: correct calculation of // and /
                    string newstring = tag.tagString.Insert(index, vssFile.Parent.Name + "_");
                    tag.tagString = newstring;
                    migrateLog.DebugFormat("Tag already existing, adding parent name ...");

                    ApplyTag(vssFile, svnClient, vssVersion, tag);

                    return;
                }

                migrateLog.ErrorFormat("Error: Line was: " + tag.fromUrlString);
                migrateLog.ErrorFormat(e.ToString());
                migrateLog.InfoFormat(String.Format("Fallback, tagging repository successful: "
                                                    + (svnClient.RemoteCopy(
                                                           SvnTarget.FromString(String.Format("{0}/{1}", svnURL,
                                                                                              svnPROJ)),
                                                           new Uri(tag.tagString)
                                                           , copyArgs))));


                CounterfeitRevProps(svnClient, SvnTarget.FromUri(new Uri(tag.tagString)), vssVersion);
            }

            catch (Exception e)
            {
                migrateLog.ErrorFormat(e.ToString());
                //Console.Out.WriteLine("Press a key to continue");
                //Console.ReadKey();
            }

            migrateLog.DebugFormat("------------------------------------");
        }
Esempio n. 29
0
 public SvnInfo(string path)
 {
     _client.Info(SvnTarget.FromString(path), new EventHandler <SvnInfoEventArgs>(OnInfo));
 }
Esempio n. 30
0
        public void Copy()
        {
            long lastSyncRevision = 0;

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

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

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

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

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

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

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

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

            SvnLogArgs logArgs = new SvnLogArgs();

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

            logArgs.RetrieveChangedPaths = true;

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

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

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

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

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

                if (_args.SimulationOnly)
                {
                    continue;
                }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

                SvnCommitResult commitResult = null;
                _client.Commit(_args.Destination, commitArgs, out commitResult);
                if (commitResult != null)
                {
                    Console.WriteLine("Commited revision {0}.", commitResult.Revision);
                }
                else
                {
                    Console.WriteLine("There were no committable changes.");
                    Console.WriteLine("Subversion property changes are not supported.");
                }
            }
        }