private void Run(Stream stream) { string tmpFolder = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); try { using (SvnClient client = new SvnClient()) { //client.Authentication.Clear(); client.Authentication.UserNamePasswordHandlers += Authentication_UserNamePasswordHandlers; SvnUpdateResult res; bool downloaded = client.Export(SvnTarget.FromUri(SvnUri), tmpFolder, out res); if (downloaded == false) { throw new Exception("Download Failed"); } } using (ZipFile zipFile = new ZipFile()) { zipFile.AddDirectory(tmpFolder, GetFolderName()); zipFile.Save(stream); } } finally { if (File.Exists(tmpFolder)) { File.Delete(tmpFolder); } } }
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); }
public void GetFile(string svnFileUrl, string destinationFolder, bool force, string versionSpec) { SvnExportArgs args = new SvnExportArgs(); args.Overwrite = force; args.Revision = ConvertToRevsion(versionSpec); try { if (!Directory.Exists(destinationFolder)) { Directory.CreateDirectory(destinationFolder); } _svn.Export(new Uri(svnFileUrl), destinationFolder, args); } catch (SvnIllegalTargetException) { //if force = false, the exisiting file should not be overwritten and no error should be shown if (force) { throw; } } }
private void Diff(string file, string diffToolPath) { using (SvnClient client = new SvnClient()) { string filePath = REPO_URL + @"test\test.txt"; string temp = @"F:\svn"; client.Export(new SvnUriTarget(new Uri(filePath), SvnRevision.Head), temp); } }
public bool exportFileFromLog(SvnLogEventArgs log, string expdir, bool excDel) { Console.WriteLine(string.Format(@"リビジョン:{0} を抽出します。", log.Revision)); var revname = retPadLeftZero(log.Revision); var toRevPath = expdir + @"\" + @"r" + revname; this._exlStm.addRevSht(@"r" + revname, log.LogMessage); var trgtFlLst = this.filterLogFiles(log.ChangedPaths, this._filterList, revname, excDel); if (trgtFlLst.Count == 0) { Directory.CreateDirectory(toRevPath + @"_対象なし"); return(false); } var root = this._reporoot; var args = new SvnExportArgs() { Depth = SvnDepth.Files }; var addCmd = @"echo F | xcopy /v /y ""{0}"" ""{1}"" " + Environment.NewLine + @"svn add ""{1}"" "; var delCmd = @"if exist ""{0}"" ( " + Environment.NewLine + @" svn delete ""{0}"" " + Environment.NewLine + @")"; Directory.CreateDirectory(toRevPath); var sw = createCopyBatStrm(expdir, revname); foreach (var i in trgtFlLst) { var flPth = getFilePath(i.Path); var topath = toRevPath + flPth; if (i.Action != SvnChangeAction.Delete) { var srcp = Path.Combine(root.ToString() , i.RepositoryPath.ToString()); var todir = Path.GetDirectoryName(topath); if (!Directory.Exists(todir)) { Directory.CreateDirectory(todir); } _svncl.Export(new SvnUriTarget(srcp, log.Revision), topath, args); sw.WriteLine(string.Format(addCmd, topath, @"%dstRoot%" + flPth)); } else { sw.WriteLine(string.Format(delCmd, @"%dstRoot" + flPth)); } } this.setCommitComment(expdir, sw, log, revname); sw.Close(); return(true); }
public static void ExportFile(string source, string target, string SVNUser, string SVNPassword) { using (SvnClient client = new SvnClient()) { client.LoadConfiguration(Path.Combine(Path.GetTempPath(), "Svn"), true); client.Authentication.SslServerTrustHandlers += delegate(object sender, SvnSslServerTrustEventArgs e) { e.Cancel = false; }; client.Authentication.DefaultCredentials = new System.Net.NetworkCredential(SVNUser, SVNPassword); client.Export(new SvnUriTarget(source), target, new SvnExportArgs()); } }
public static FileInfo DownloadFileUsingSvnCheckout(Dto.SqlFile sqlFile, NetworkCredential networkCredential, string serverPath) { using (var client = new SvnClient()) { client.LoadConfiguration(serverPath); client.Authentication.DefaultCredentials = networkCredential; client.Export(new SvnUriTarget(sqlFile.URL), serverPath); } return(new FileInfo(Path.Combine(serverPath, sqlFile.Name))); }
public void Export_Forced() { SvnSandBox sbox = new SvnSandBox(this); sbox.Create(SandBoxRepository.Default); string WcPath = sbox.Wc; Uri WcUri = sbox.Uri; string exportDir = Path.Combine(sbox.GetTempDir("ExportTests"), "exportTo"); using (SvnClient client = NewSvnClient(true, false)) { string file = Path.Combine(WcPath, "ExportFile"); TouchFile(file); client.Add(file); client.Commit(WcPath); Assert.That(Directory.Exists(exportDir), Is.False); client.Export(WcUri, exportDir); Assert.That(Directory.Exists(exportDir), Is.True); Assert.That(File.Exists(Path.Combine(exportDir, "ExportFile"))); Assert.That(!Directory.Exists(Path.Combine(exportDir, ".svn"))); ForcedDeleteDirectory(exportDir); Assert.That(Directory.Exists(exportDir), Is.False); client.Export(new SvnPathTarget(WcPath), exportDir); Assert.That(Directory.Exists(exportDir), Is.True); Assert.That(File.Exists(Path.Combine(exportDir, "ExportFile"))); ForcedDeleteDirectory(exportDir); } }
/// <summary> /// 导出指定版本的文件到本地 /// </summary> /// <param name="url"></param> /// <param name="filePath"></param> /// <param name="revision"></param> /// <param name="exportPath"></param> /// <returns></returns> public static bool ExportFile(string url, string filePath, long revision, string exportPath) { if (!Directory.Exists(exportPath)) { Directory.CreateDirectory(exportPath); } exportPath = Path.Combine(exportPath, Path.GetFileName(filePath)); using (SvnClient client = GetSvnClient()) { return(client.Export(new SvnUriTarget(Path.Combine(url, filePath), revision), exportPath)); } }
/// <summary> /// 将SVN中某文件的某个版本保存到本地指定路径 /// </summary> public static bool ExportSvnFileToLocal(string svnFilePath, string savePath, SvnRevision svnRevision, out Exception exception) { SvnExportArgs exportArgs = new SvnExportArgs(); exportArgs.Overwrite = true; exportArgs.Revision = svnRevision; try { bool result = _svnClient.Export(svnFilePath, savePath, exportArgs); exception = null; return(result); } catch (Exception e) { exception = e; return(false); } }
private void Diff() { using (SvnClient client = new SvnClient()) { string filePath = REPO_URL + @"test\test.txt"; string temp = @"F:\svn"; SvnExportArgs args = new SvnExportArgs(); args.Overwrite = true; client.Export(new SvnUriTarget(new Uri(filePath), SvnRevision.Head), temp, args); string argu = WORKSPACE + @"test\test.txt" + " " + temp + @"\test.txt"; Process tmerger = new Process(); tmerger.StartInfo.FileName = DIFF_TOOLS; tmerger.StartInfo.Arguments = argu; tmerger.Start(); } }
public override string Export(IPackageTree packageTree, FileSystemInfo destination) { SvnUpdateResult result = null; using (var client = new SvnClient()) { try { client.Export(Url, destination.FullName, new SvnExportArgs { Overwrite = true }, out result); } catch (SvnRepositoryIOException sre) { HandleExceptions(sre); } catch (SvnObstructedUpdateException sue) { HandleExceptions(sue); } } return(result.Revision.ToString()); }
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; }
static void Main(string[] args) { client.Authentication.Clear(); client.Authentication.UserNamePasswordHandlers += (sender, e) => { e.UserName = "******"; e.Password = "******"; }; client.Conflict += (sender, e) => { Console.WriteLine(" {0}", "there is conflict in your local, please dealing with it first!"); }; while (true) { Console.Write(">"); var cmd_str = Console.ReadLine(); if (String.IsNullOrEmpty(cmd_str)) { continue; } var arr_cmd = cmd_str.Split(new String[] { " " }, StringSplitOptions.RemoveEmptyEntries); var cmd = arr_cmd[0]; var cmd_param = String.Empty; if (arr_cmd.Length >= 2) { cmd_param = arr_cmd[1]; } if (cmd == "getinfo") { if (cmd_param == String.Empty || cmd_param == "remote") { string repoUrl = "svn://118.25.197.165/test_szp"; Console.WriteLine(" to getinfo {0} ...", repoUrl); SvnInfoEventArgs info; client.GetInfo(new Uri(repoUrl), out info); Console.WriteLine(" Reversion:{0} lastChangedReversion:{1} lastChangedTime:{2} islocked:{3}" , info.Revision , info.LastChangeRevision , info.LastChangeTime , info.Lock != null ); } else { var local_path = String.Format(@"E:\SVN_BASE\{0}", cmd_param); Console.WriteLine(" to getinfo {0} ...", local_path); try { SvnInfoEventArgs info; client.GetInfo(new SvnPathTarget(local_path), out info); Console.WriteLine(" Reversion:{0} lastChangedReversion:{1} lastChangedTime:{2} islocked:{3}" , info.Revision , info.LastChangeRevision , info.LastChangeTime , info.Lock != null ); } catch (SvnException svnEx) { if (svnEx.SvnErrorCode == SvnErrorCode.SVN_ERR_WC_PATH_NOT_FOUND) { Console.WriteLine(" {0}", "it is not a svn path! your should add it into svn."); } else if (svnEx.SvnErrorCode == SvnErrorCode.SVN_ERR_WC_NOT_WORKING_COPY) { Console.WriteLine(" {0}", "it is not a svn dir! your should checkout this dir."); } else { Console.WriteLine(" {0}({1})", svnEx.Message, svnEx.SvnErrorCode); } } } } else if (cmd == "checkout") { var local_path = String.Format(@"E:\SVN_BASE\{0}\", cmd_param); Console.WriteLine(" to checkout {0} ...", local_path); var repo_url = "svn://118.25.197.165/test_szp"; var r = client.CheckOut(new SvnUriTarget(repo_url), local_path); if (r) { Console.WriteLine(" {0}", "check out successfully!"); } else { Console.WriteLine(" {0}", "check out faild!"); } } else if (cmd == "getstate") { var local_path = String.Format(@"E:\SVN_BASE\{0}", cmd_param); Console.WriteLine(" to getstate {0} ...", local_path); var r = SvnTools.IsManagedPath(local_path); if (r) { Console.WriteLine(" {0} is svn local path", local_path); } else { Console.WriteLine(" {0} is not svn local path", local_path); } } else if (cmd == "geturi") { var local_path = String.Format(@"E:\SVN_BASE\{0}", cmd_param); Console.WriteLine(" to geturi {0} ...", local_path); var uri = client.GetUriFromWorkingCopy(local_path); Console.WriteLine(" {0} ====svn==== {1}", local_path, uri); } else if (cmd == "add") { var local_path = String.Format(@"E:\SVN_BASE\{0}", cmd_param); Console.WriteLine(" to add {0} ...", local_path); var r = client.Add(local_path); if (r) { Console.WriteLine(" add {0} successfully!", local_path); } else { Console.WriteLine(" faild to add {0} !", local_path); } } else if (cmd == "commit") { var local_path = String.Format(@"E:\SVN_BASE\{0}", cmd_param); Console.WriteLine(" to commit {0} ...", local_path); var arg = new SvnCommitArgs(); arg.LogMessage = String.Format("test {0:MM:dd HH:mm}", DateTime.Now); SvnCommitResult result; try { var r = client.Commit(local_path, arg, out result); if (r) { Console.WriteLine(" {0}", "commit successfully!"); } else { Console.WriteLine(" {0}", "faild to commit!"); } } catch (SvnException svnEx) { if (svnEx.SvnErrorCode == SvnErrorCode.SVN_ERR_FS_BAD_LOCK_TOKEN) { Console.WriteLine(" {0} ({1})", "faild to commit!", "another locked this node!"); } else if (svnEx.SvnErrorCode == SvnErrorCode.SVN_ERR_FS_TXN_OUT_OF_DATE) { Console.WriteLine(" {0} ({1})", "faild to commit!", "please first update!"); } else if (svnEx.SvnErrorCode == SvnErrorCode.SVN_ERR_WC_FOUND_CONFLICT) { Console.WriteLine(" {0} ({1})", "faild to commit!", "please dealing with conflict!"); } else { Console.WriteLine(" {0} ({1})", svnEx.Message, svnEx.SvnErrorCode); } } } else if (cmd == "update") { var local_path = String.Format(@"E:\SVN_BASE\{0}", cmd_param); Console.WriteLine(" to update {0} ...", local_path); var r = client.Update(local_path); if (r) { Console.WriteLine(" {0}", "Update successfully!"); } else { Console.WriteLine(" {0}", "Update faild!"); } } else if (cmd == "remotelock") { var local_path = String.Format(@"E:\SVN_BASE\{0}", cmd_param); Console.WriteLine(" to lock {0} ...", local_path); var uri = client.GetUriFromWorkingCopy(local_path); var r = client.RemoteLock(uri, String.Format("test lock {0:MM-dd HH:mm}", DateTime.Now)); if (r) { Console.WriteLine(" remote lock {0} successfully!", local_path); } else { Console.WriteLine(" faild to remote lock {0}!", local_path); } } else if (cmd == "remoteunlock") { var local_path = String.Format(@"E:\SVN_BASE\{0}", cmd_param); Console.WriteLine(" to unlock {0} ...", local_path); var uri = client.GetUriFromWorkingCopy(local_path); var r = client.RemoteUnlock(uri); if (r) { Console.WriteLine(" remote unlock {0} successfully!", local_path); } else { Console.WriteLine(" faild to remote lock {0}!", local_path); } } else if (cmd == "lock") { var local_path = String.Format(@"E:\SVN_BASE\{0}", cmd_param); Console.WriteLine(" to lock {0} ...", local_path); //var uri = client.GetUriFromWorkingCopy(local_path); var r = client.Lock(local_path, String.Format("test lock {0:MM-dd HH:mm}", DateTime.Now)); if (r) { Console.WriteLine(" lock {0} successfully!", local_path); } else { Console.WriteLine(" faild to lock {0}!", local_path); } } else if (cmd == "unlock") { var local_path = String.Format(@"E:\SVN_BASE\{0}", cmd_param); Console.WriteLine(" to unlock {0} ...", local_path); //var uri = client.GetUriFromWorkingCopy(local_path); var r = client.Unlock(local_path); if (r) { Console.WriteLine(" unlock {0} successfully!", local_path); } else { Console.WriteLine(" faild to lock {0}!", local_path); } } else if (cmd == "export") { var local_path = String.Format(@"E:\SVN_BASE\{0}", cmd_param); var dest_path = arr_cmd[2]; Console.WriteLine(" to unlock {0} ...", local_path); var uri = client.GetUriFromWorkingCopy(local_path); try { var r = client.Export(new SvnUriTarget(uri), dest_path); if (r) { Console.WriteLine(" export {0} to {1} successfully!", uri, dest_path); } else { Console.WriteLine(" faild to export {0} to {1}!", uri, dest_path); } } catch (SvnException svnEx) { Console.WriteLine(" {0}(1)", svnEx.Message, svnEx.SvnErrorCode); } } else if (cmd == "help" || cmd == "?") { Console.WriteLine(" 1.getinfo [localpath] or [null] or [remotepath]"); Console.WriteLine(" 2.getstate [localpath]"); Console.WriteLine(" 2.geturi [localpath]"); Console.WriteLine(" 3.checkout [localpath]"); Console.WriteLine(" 4.add [localpath]"); Console.WriteLine(" 5.commit [localpath]"); Console.WriteLine(" 6.update [localpath]"); Console.WriteLine(" 7.lock [localpath]"); Console.WriteLine(" 8.unlock [localpath]"); Console.WriteLine(" 9.remotelock [localpath]"); Console.WriteLine(" 10.remoteunlock [localpath]"); Console.WriteLine(" 10.export [localpath] [localpath]"); } } }
public override string Export(IPackageTree packageTree, FileSystemInfo destination) { SvnUpdateResult result = null; using (var client = new SvnClient()) { try { client.Export(Url, destination.FullName, new SvnExportArgs { Overwrite = true }, out result); } catch (SvnRepositoryIOException sre) { HandleExceptions(sre); } catch (SvnObstructedUpdateException sue) { HandleExceptions(sue); } } return result.Revision.ToString(); }
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."); } } }
static void Main(string[] args) { Console.WriteLine("Добро пожаловать в установщик продуктов компании \"Правильные измерения\"!"); string userName = "******"; string gitPublicApiUrl = "https://api.github.com/orgs/" + userName + "/repos?per_page=1000"; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; LBL_START: Console.WriteLine("Список продуктов загружается...\n"); using (WebClient webClient = new WebClient()) { webClient.Headers["User-Agent"] = "Mozilla/5.0"; var json = webClient.DownloadString(gitPublicApiUrl); var repositoryList = RepositoryList.FromJson(json); int i = 0; foreach (var repository in repositoryList) { Console.WriteLine(i.ToString() + ": " + repository.Name); i++; } Console.WriteLine(); INPUT_IDX: Console.Write("Введите индекс репозитория для копирования: "); string inpStr = Console.ReadLine().Trim(); int selectedIdx = 0; bool res = int.TryParse(inpStr, out selectedIdx); if (!res || selectedIdx < 0 || selectedIdx > repositoryList.Count) { goto INPUT_IDX; } string repositoryName = repositoryList[selectedIdx].Name; string projectName = repositoryList[selectedIdx].Description; string remoteURL = "https://github.com/" + userName + "/" + repositoryName + "/trunk/"; bool bFullProject = false; if (projectName != null && projectName.Length > 0) { Console.Write("Введите [1] для копирования всего проекта, если нужен лишь исполнимый файл, нажмите ввод: "); inpStr = Console.ReadLine().Trim(); if (inpStr.Length == 0) { remoteURL = $"https://github.com/{userName}/{repositoryName}/trunk/{projectName}/bin/Debug/"; } else { bFullProject = true; } } LBL_REPEAT: string targetDirectory = @"C:\" + userName + @"\" + repositoryName; Console.WriteLine("\nURL: " + remoteURL); Console.WriteLine("Дирректория установки: " + targetDirectory); Console.WriteLine("Копировать весь проект: " + bFullProject); if (Directory.Exists(targetDirectory)) { Console.Write("\nУдаляем старые файлы..."); Directory.Delete(targetDirectory, true); Console.Write("Готово!\n"); } else { Console.WriteLine(""); } Console.Write("Ожидайте..."); SvnClient svnClient = new SvnClient(); SvnUriTarget target = new SvnUriTarget(remoteURL); SvnExportArgs svnExpArgs = new SvnExportArgs(); try { svnClient.Export(target, targetDirectory, svnExpArgs, out SvnUpdateResult svnUpdRes); Console.Write("Завершено!\n"); if (Directory.Exists(targetDirectory)) { Process.Start(targetDirectory); } } catch (Exception ex) { Console.Write("ОШИБКА:\n" + ex.Message + "\n"); } Console.WriteLine("Выход - ESC, Повтор - SPACE, начать заново - любая клавиша"); ConsoleKeyInfo cki = Console.ReadKey(); if (cki.Key == ConsoleKey.Escape) { Environment.Exit(-1); } else if (cki.Key == ConsoleKey.Spacebar) { Console.Clear(); goto LBL_REPEAT; } else { Console.Clear(); goto LBL_START; } } }
public XmlDocument getSVNDifferFiles() { //获取最大的版本号 this.getLastVersion(); // diff xml XmlDocument newDoc = new XmlDocument(); XmlDeclaration xmldecl = newDoc.CreateXmlDeclaration("1.0", "UTF-8", null); newDoc.AppendChild(xmldecl); XmlElement newRoot = newDoc.CreateElement("files"); newDoc.AppendChild(newRoot); newRoot.SetAttribute("version", PackageSubVM.Instance.Version); long fileSizes = 0; int index = 0; string[] szFilter = PackageSubVM.Instance.Filter.Split(new char[1] { ':' }); SvnClient svnClient = new SvnClient(); //List<SvnDiffSummaryEventArgs> list; System.Collections.ObjectModel.Collection <SvnDiffSummaryEventArgs> list; svnClient.GetDiffSummary(new SvnUriTarget(PackageSubVM.Instance.SVNPath, Int32.Parse(PackageSubVM.Instance.BeginVersion)), new SvnUriTarget(PackageSubVM.Instance.SVNPath, Int32.Parse(PackageSubVM.Instance.EndVersion)), out list); foreach (SvnDiffSummaryEventArgs item in list) { if (szFilter.Contains(Path.GetExtension(item.Path)) || szFilter.Contains(Path.GetFileName(item.Path))) { continue; } string fullFileName = szResourceOutPath + "\\" + item.Path; if (item.NodeKind == SvnNodeKind.Directory) { if (Directory.Exists(fullFileName) == false) { DirectoryInfo info = Directory.CreateDirectory(fullFileName); } continue; } string outPath = Path.GetDirectoryName(fullFileName); if (Directory.Exists(outPath) == false) { DirectoryInfo info = Directory.CreateDirectory(outPath); } try { SvnClient exportSVN = new SvnClient(); SvnExportArgs ex = new SvnExportArgs(); ex.Overwrite = true; long size = 0; if (item.DiffKind != SvnDiffKind.Deleted) { exportSVN.Export(new SvnUriTarget(item.ToUri, Int32.Parse(PackageSubVM.Instance.EndVersion)), fullFileName, ex); index = index + 1; this.createXmlNode(newDoc, newRoot, item.Path, this.createFileMD5(fullFileName, out size), "1", index); fileSizes += size; } else { this.createXmlNode(newDoc, newRoot, item.Path, "this is a delete file.", "0", index); } } catch (Exception ee) { MessageBox.Show(ee.Message); Console.WriteLine(ee.Message); } } newRoot.SetAttribute("lastVersion", szLastVersion); newRoot.SetAttribute("size", fileSizes.ToString()); return(newDoc); }
public XmlDocument getSVNDifferFiles() { //获取最大的版本号 this.getLastVersion(); // diff xml XmlDocument newDoc = new XmlDocument(); XmlDeclaration xmldecl = newDoc.CreateXmlDeclaration("1.0", "UTF-8", null); newDoc.AppendChild(xmldecl); XmlElement newRoot = newDoc.CreateElement("files"); newDoc.AppendChild(newRoot); newRoot.SetAttribute("version", PackageSubVM.Instance.Version); long fileSizes = 0; int index = 0; string[] szFilter = PackageSubVM.Instance.Filter.Split(new char[1] { ':' }); SvnClient svnClient = new SvnClient(); //List<SvnDiffSummaryEventArgs> list; System.Collections.ObjectModel.Collection<SvnDiffSummaryEventArgs> list; svnClient.GetDiffSummary(new SvnUriTarget(PackageSubVM.Instance.SVNPath, Int32.Parse(PackageSubVM.Instance.BeginVersion)), new SvnUriTarget(PackageSubVM.Instance.SVNPath, Int32.Parse(PackageSubVM.Instance.EndVersion)), out list); foreach (SvnDiffSummaryEventArgs item in list) { if (szFilter.Contains(Path.GetExtension(item.Path)) || szFilter.Contains(Path.GetFileName(item.Path))) { continue; } string fullFileName = szResourceOutPath + "\\" + item.Path; if (item.NodeKind == SvnNodeKind.Directory) { if (Directory.Exists(fullFileName) == false) { DirectoryInfo info = Directory.CreateDirectory(fullFileName); } continue; } string outPath = Path.GetDirectoryName(fullFileName); if (Directory.Exists(outPath) == false) { DirectoryInfo info = Directory.CreateDirectory(outPath); } try { SvnClient exportSVN = new SvnClient(); SvnExportArgs ex = new SvnExportArgs(); ex.Overwrite = true; long size = 0; if (item.DiffKind != SvnDiffKind.Deleted) { exportSVN.Export(new SvnUriTarget(item.ToUri, Int32.Parse(PackageSubVM.Instance.EndVersion)), fullFileName, ex); index = index + 1; this.createXmlNode(newDoc, newRoot, item.Path, this.createFileMD5(fullFileName, out size), "1", index); fileSizes += size; } else { this.createXmlNode(newDoc, newRoot, item.Path, "this is a delete file.", "0", index); } } catch (Exception ee) { MessageBox.Show(ee.Message); Console.WriteLine(ee.Message); } } newRoot.SetAttribute("lastVersion", szLastVersion); newRoot.SetAttribute("size", fileSizes.ToString()); return newDoc; }
public static bool TraerObjeto(string origen, string destino, string usuario, string clave, out string respuesta, int revision = -1) { try { destino = destino.ToUpper(); // Obtener la ruta del repositorio int index = Cadena.EncontrarEnesimaCoincidencia('/', origen, 4); string repositorio = origen.Substring(0, index); string instancia = repositorio.Substring(repositorio.LastIndexOf('/') + 1); // Verificar si existen subcarpetas if (origen.Substring(index + 1).IndexOf('/') > 0) { // Existe una subcarpeta // Obtener lista de subcarpetas string[] subCarpetas = ListarCarpetas(repositorio, usuario, clave); string subCarpeta = origen.Substring(index + 1, Cadena.EncontrarEnesimaCoincidencia('/', origen, 5) - index - 1); string subCarpetaCorregida = Cadena.EncontrarTextoEnArreglo(subCarpeta, subCarpetas); if (String.IsNullOrEmpty(subCarpetaCorregida)) { respuesta = String.Format("No se encuentra la carpeta {0} en el versionador", subCarpeta); return(false); } string urlCorregidaBase = String.Concat(repositorio, "/", subCarpetaCorregida); // Obtener lista de objetos string[] objetos = ListarArchivos(urlCorregidaBase, usuario, clave); string objeto = origen.Substring(Cadena.EncontrarEnesimaCoincidencia('/', origen, 5) + 1); string objetoCorregido = Cadena.EncontrarTextoEnArreglo(objeto, objetos); if (String.IsNullOrEmpty(objetoCorregido)) { respuesta = String.Format("No se encuentra el objeto {0} en el versionador", objeto); return(false); } string urlCorregido = String.Concat(urlCorregidaBase, "/", objetoCorregido); // Verificar si la carpeta del repositorio=instancia existe if (!Directory.Exists(destino)) { // No existe la carpeta, crearla Directory.CreateDirectory(destino); } // Verificar si el archivo existe string rutaArchivoLocal = String.Concat(destino, "\\", objetoCorregido); if (File.Exists(rutaArchivoLocal)) { // Si existe el archivo, eliminarlo File.Delete(rutaArchivoLocal); } // Traer el objeto a la carpeta destino SvnClient svnClient = new SvnClient(); svnClient.Authentication.ForceCredentials(usuario, clave); //svnClient.Authentication.Clear(); //svnClient.Authentication.DefaultCredentials = //new NetworkCredential(usuario, clave); if (revision == -1) { svnClient.Export(urlCorregido, rutaArchivoLocal); } else { SvnRevision rev = new SvnRevision(revision); svnClient.Export(urlCorregido, rutaArchivoLocal, new SvnExportArgs() { Revision = rev }); } } else { // El archivo se encuentra en la raíz del repositorio. string[] objetos = ListarArchivos(repositorio, usuario, clave); string objeto = origen.Substring(Cadena.EncontrarEnesimaCoincidencia('/', origen, 4) + 1); string objetoCorregido = Cadena.EncontrarTextoEnArreglo(objeto, objetos); if (String.IsNullOrEmpty(objetoCorregido)) { respuesta = String.Format("No se encuentra el objeto {0} en el versionador", objeto); return(false); } string urlCorregido = String.Concat(instancia, "\\", objetoCorregido); // Verificar si el archivo existe string rutaArchivoLocal = String.Concat(instancia, "\\", repositorio, "\\", objetoCorregido); if (File.Exists(rutaArchivoLocal)) { // Si existe el archivo, eliminarlo File.Delete(rutaArchivoLocal); } // Traer el objeto a la carpeta destino SvnClient svnClient = new SvnClient(); svnClient.Authentication.DefaultCredentials = new NetworkCredential(usuario, clave); svnClient.Export(urlCorregido, destino); } respuesta = String.Format("{0} Copiado satisfactoriamente", origen); return(true); } catch (SvnRepositoryIOException ex) { respuesta = ex.Message; return(false); } }
/// <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 = GetTarget(); return client.Export(target, DestinationPath); }
public void Copy() { Console.Write("Collecting svn log: "); if (_args.RevisionRange != null) { Console.Write("{0}:{1} ", _args.RevisionRange.StartRevision, _args.RevisionRange.EndRevision); } // fetch the source svn respository and SvnInfo sourceInfo = new SvnInfo(_args.Source); Console.WriteLine("Source SVN root: {0}", sourceInfo.Info.RepositoryRoot); Console.WriteLine("Source SVN uri: {0}", sourceInfo.Info.Uri); string sourceRelativePath = sourceInfo.Info.Uri.ToString().Remove( 0, sourceInfo.Info.RepositoryRoot.ToString().Length - 1); Console.WriteLine("Relative path: {0}", sourceRelativePath); SvnLogArgs logArgs = new SvnLogArgs(); logArgs.StrictNodeHistory = true; logArgs.ThrowOnError = true; logArgs.Range = _args.RevisionRange; logArgs.RetrieveChangedPaths = true; _client.Log(_args.Source, logArgs, new EventHandler <SvnLogEventArgs>(OnLog)); Console.WriteLine(); Console.WriteLine("Collected {0} revisions.", _revisions.Count); SvnTarget fromSvnTarget = SvnTarget.FromString(_args.Source); foreach (KeyValuePair <long, SvnLogEventArgs> revisionPair in _revisions) { SvnLogEventArgs revision = revisionPair.Value; Console.WriteLine("Revision {0} ({1})", revision.Revision, revision.Time); if (_args.simulationOnly) { continue; } SvnExportArgs exportArgs = new SvnExportArgs(); exportArgs.Overwrite = true; exportArgs.ThrowOnError = true; exportArgs.Revision = revision.Revision; SvnUpdateResult exportResult = null; _client.Export(fromSvnTarget, _args.Destination, exportArgs, out exportResult); if (revision.ChangedPaths == null) { throw new Exception(string.Format("No changed paths in rev. {0}", revision.Revision)); } SortedList <string, SvnChangeItem> changeItems = new SortedList <string, SvnChangeItem>(); foreach (SvnChangeItem changeItem in revision.ChangedPaths) { changeItems.Add(changeItem.Path, changeItem); } foreach (SvnChangeItem changeItem in changeItems.Values) { string targetSvnPath = changeItem.Path.Remove(0, sourceRelativePath.Length); string targetOSPath = targetSvnPath.Replace("/", @"\"); string targetPath = Path.Combine(_args.Destination, targetOSPath); Console.WriteLine("{0} {1}", changeItem.Action, changeItem.Path); switch (changeItem.Action) { case SvnChangeAction.Add: { Console.WriteLine(" A {0}", targetPath); SvnAddArgs svnAddArgs = new SvnAddArgs(); svnAddArgs.ThrowOnError = true; svnAddArgs.Depth = SvnDepth.Empty; _client.Add(targetPath, svnAddArgs); } break; case SvnChangeAction.Delete: { Console.WriteLine(" D {0}", targetPath); SvnDeleteArgs svnDeleteArgs = new SvnDeleteArgs(); svnDeleteArgs.ThrowOnError = true; _client.Delete(targetPath, svnDeleteArgs); } break; } } SvnCommitArgs commitArgs = new SvnCommitArgs(); commitArgs.LogMessage = revision.LogMessage; commitArgs.LogMessage += string.Format("\nCopied from {0}, rev. {1} by {2} @ {3} {4}", sourceInfo.Info.Uri, revision.Revision, revision.Author, revision.Time.ToShortDateString(), revision.Time.ToShortTimeString()); commitArgs.ThrowOnError = true; Console.WriteLine("Commiting {0}", _args.Destination); Console.WriteLine("----------------------------------------------------------------------------"); Console.WriteLine(commitArgs.LogMessage); Console.WriteLine("----------------------------------------------------------------------------"); if (_args.prompt) { while (true) { Console.Write("Commit? [Y/N] "); char k = Char.ToLower(Console.ReadKey().KeyChar); Console.WriteLine(); if (k == 'y') { break; } if (k == 'n') { throw new Exception("Aborted by user."); } } } _client.Commit(_args.Destination, commitArgs); } }