~monodevelop-bzr/monodevelop-bzr/trunk

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
// Copyright (C) 2008 by Levi Bard <taktaktaktaktaktaktaktaktaktak@gmail.com>
//		
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//	
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//   
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

using System;
using System.IO;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Xml;

using MonoDevelop.Core;
using MonoDevelop.Core.Execution;
using MonoDevelop.Core.ProgressMonitoring;

namespace MonoDevelop.VersionControl.Bazaar
{
	public class BazaarCommandClient: BazaarClient
	{
		private static readonly string	client = "bzr",
										  versionRegex = @"(?<version>[\d\.]+)[\s]*$",
										  statusRegex = @"^(?<property>[-?+R ])(?<status>[NCDIMR ])[A-Z]*\s*(?<file>.+?)( => (?<replacefile>.*))?$",
										  revisionRegex = @"^(?<revision>\d+): (?<committer>.*) (?<date>\d{4}-\d{2}-\d{2}) (?<message>.*)",
										  rootUrlRegex = @"^\s*branch root: (?<url>.*)",
										  urlRegex = @"^[^\s]+://",
										  branchRegex = @"^\s*(?<type>(parent|push|submit)) branch:\s+(?<path>.*)";
		
		private delegate int Launcher (string command, string args, string baseDirectory, IProgressMonitor monitor, out string output, out string error);

		private Launcher launch;
		private ProcessWrapper p;
		private bool error;

		public override string Version {
			get 
			{
				if (null != version) {
					string  output = string.Empty,
							error = string.Empty,
							versionLine = string.Empty;
	
					if (0 != ExecuteShell (client, "xmlversion", ".", null, out output, out error)) {
						ClientError (client, output, error);
					}
					
					try {
						XmlDocument doc = new XmlDocument ();
						doc.LoadXml (output);
						version = doc.SelectSingleNode ("/version/bazaar/version").InnerText;
					} catch {
						throw new BazaarCommandException ("Unable to get version");
					}
				}
				return version;
			}// get
		}// Version
		private string version;

		
		public BazaarCommandClient (bool debug)
		{
			p = Runtime.ProcessService.StartProcess ("bzr", "shell", ".", (ProcessEventHandler)null, null, null, true);
//			launch = (debug? new Launcher (LaunchLocal): new Launcher (ExecuteCommand));
			launch = new Launcher (ExecuteShell);
		}

		#region " BazaarClient Implementation "
		
		public override IList<string> List (string path, bool recurse, ListKind kind)
		{
			string   output = string.Empty,
			         error = string.Empty,
			         line = string.Empty;
			int success = ExecuteShell (client, string.Format ("xmlls {0} {1} '{2}'", (recurse? string.Empty: "--non-recursive"), (ListKind.All == kind)? string.Empty: "--kind=" + listKinds[kind], path), ".", null, out output, out error);
			List<string> files = new List<string> ();

			if (0 != success){ ClientError (client, output, error); }
			
			XmlDocument doc = new XmlDocument ();
			doc.LoadXml (output);
			foreach (XmlNode node in doc.SelectNodes ("/list/item/path")) {
				files.Add (node.InnerText);
			}

			return files;
		}// List

		public override IList<LocalStatus> Status (string path, BazaarRevision revision) {
			string   output = string.Empty,
			         error = string.Empty,
			         line = string.Empty,
			         baseDir = Directory.Exists (path)? path: Path.GetDirectoryName (path),
			         repoBaseDir = GetLocalBasePath (path);
			Regex	matchStatus = new Regex (statusRegex, RegexOptions.Compiled),
					 matchRevision = new Regex (revisionRegex, RegexOptions.Compiled);
			Match match = null;
			List<LocalStatus> statuses = new List<LocalStatus> ();
			string lastRevision = "-1";
			bool modified = false;
			bool found = false;
			

			if (0 != ExecuteShell (client, string.Format ("xmlstatus {0} '{1}'", (null == revision)? string.Empty: string.Format ("-r {0}..{1}", ((BazaarRevision)revision.GetPrevious ()).Rev, revision.Rev),  path), ".", null, out output, out error)) {
				ClientError (client, output, error);
			}
			
			if (!string.IsNullOrEmpty (output)) {
				try {
					string fullPath = Path.GetFullPath (path);
					XmlDocument doc = new XmlDocument ();
					doc.LoadXml (output);
					foreach (string statusString in longStatuses.Keys) {
						foreach (XmlNode node in doc.SelectNodes (string.Format ("/status/{0}/file | status/{0}/directory", statusString))) {
							string file = node.InnerText;
							if (file.EndsWith("*", StringComparison.Ordinal)) {
								file = file.Remove (file.Length-1);
							}
							if (fullPath.EndsWith (file, StringComparison.Ordinal)){ found = true; }
							if (longStatuses[statusString] == ItemStatus.Modified) {
								modified = true; 
							}
							statuses.Add (new LocalStatus (lastRevision, Path.Combine (repoBaseDir, file), longStatuses[statusString]));
						}
					}
				} catch {
					lock(p){ this.error = true; }
				}
			}

			if (!found){ 
				modified = modified && Directory.Exists (path);
				statuses.Insert (0, new LocalStatus (lastRevision, path, modified? ItemStatus.Modified: ItemStatus.Unchanged));
			}

			return statuses;
		}// Status

		public override string GetPathUrl (string path) {
			string   url = null,
			         output = string.Empty,
			         error = string.Empty;
			
			if (0 != ExecuteShell (client, string.Format ("xmlinfo '{0}'", path), ".", null, out output, out error)) {
				ClientError (client, output, error);
			}
			
			XmlDocument doc = new XmlDocument ();
			doc.LoadXml (output);
			XmlNode node = doc.SelectSingleNode("/info/location/branch_root");
			if (null == node){ node = doc.SelectSingleNode("/info/location/repository_branch"); }
			if (null != node){ url = node.InnerText; }
			if (null != url && !Regex.IsMatch(url, urlRegex)) {
				url = "file://" + Path.GetFullPath (url);
			}

			return url;
		}// GetPathUrl

		public override void Update (string localPath, bool recurse, IProgressMonitor monitor) {
			string output, error;
			
			if (0 != launch (client, string.Format ("update '{0}'", localPath), ".", monitor, out output, out error)) {
				ClientError (client, output, error);
			}
		}// Update

		public override void Revert (string localPath, bool recurse, IProgressMonitor monitor, BazaarRevision toRevision) {
			string output, error;

			if (0 != launch (client, string.Format ("revert -r {0} '{1}'", toRevision.Rev, localPath), ".", monitor, out output, out error)) {
				ClientError (client, output, error);
			}
		}// Revert

		
		public override void Add (string localPath, bool recurse, IProgressMonitor monitor) {
			string output, error;

			if (0 != launch (client, string.Format ("add {0} '{1}'", (recurse? string.Empty: "--no-recurse"), localPath), ".", monitor, out output, out error)) {
				ClientError (client, output, error);
			}
		}// Add

		public override void Checkout (string url, string targetLocalPath, BazaarRevision rev, bool recurse, IProgressMonitor monitor) {
			string output, error;

			if (0 != launch (client, string.Format ("checkout -r {0} '{1}' '{2}'", rev.Rev, url, targetLocalPath), ".", monitor, out output, out error)) {
				ClientError (client, output, error);
			}

		}// Checkout

		public override void Branch (string branchLocation, string localPath, IProgressMonitor monitor)
		{
			string output, error;

			if (0 != launch (client, string.Format ("branch '{0}' '{1}'", branchLocation, localPath), ".", monitor, out output, out error)) {
				ClientError (client, output, error);
			}
		}// Branch
		
		public override string GetTextAtRevision (string path, BazaarRevision rev) {
			string   output = string.Empty,
			         error = string.Empty;

			if (0 != launch (client, string.Format ("cat -r {0} '{1}'", rev.Rev, path), ".", null, out output, out error)) {
				ClientError (client, output, error);
			}

			return output;
		}// GetTextAtRevision

		public override BazaarRevision[] GetHistory (BazaarRepository repo, string localFile, BazaarRevision since) {
			string   output = string.Empty,
			         error = string.Empty,
			         baseDir = (Directory.Exists (localFile)? localFile: Path.GetDirectoryName (localFile));
			Regex	matchRevision = new Regex (revisionRegex, RegexOptions.Compiled);
			Match	revisionMatch = null;
			List<BazaarRevision> revisions = new List<BazaarRevision> ();
			List<RevisionPath> changedFiles = null;
			IList<LocalStatus> statuses = null;


			if (0 != launch (client, string.Format ("log --line -r {0}.. '{1}'", since.Rev, localFile), ".", null, out output, out error)) {
				ClientError (client, output, error);
			}

			using (StringReader reader = new StringReader (output)) {
				for (string line; null != (line = reader.ReadLine ()) ;) {
					revisionMatch = matchRevision.Match (line);
					if (revisionMatch.Success && revisionMatch.Groups["revision"].Success && revisionMatch.Groups["committer"].Success && revisionMatch.Groups["date"].Success && revisionMatch.Groups["message"].Success) {
						statuses = Status (repo.LocalBasePath, new BazaarRevision (repo, revisionMatch.Groups["revision"].Value));
						changedFiles = new List<RevisionPath> (statuses.Count);

						foreach (LocalStatus status in statuses) {
							changedFiles.Add (new RevisionPath (Path.Combine (baseDir, status.Filename), ConvertAction (status.Status), status.Status.ToString ()));
						}// add revisionpath for each status

						revisions.Add (new BazaarRevision (repo, revisionMatch.Groups["revision"].Value, DateTime.Parse (revisionMatch.Groups["date"].Value), revisionMatch.Groups["committer"].Value, revisionMatch.Groups["message"].Value, changedFiles.ToArray ()));
					}// successfully parsed revision
				}// for each line
			}// parse log output

			return revisions.ToArray ();
		}// GetHistory

		public override void Merge (string mergeLocation, string localPath, bool remember, BazaarRevision start, BazaarRevision end, IProgressMonitor monitor) {
			string   output, error,
			         baseDir = (Directory.Exists (localPath)? localPath: Path.GetDirectoryName (localPath));
			StringBuilder args = new StringBuilder ("merge");

			if (remember)
				args.Append(" --remember");

			args.AppendFormat (" {0}", BuildRevisionSpec (start, end));
			args.AppendFormat (" {0}", mergeLocation);
			
			if (0 != launch (client, args.ToString (), baseDir, monitor, out output, out error)) {
				ClientError (client, output, error);
			}
		}// Merge

		public override void Push (string pushLocation, string localPath, IProgressMonitor monitor) {
			string   output, error;

			if (0 != launch (client, string.Format ("push --create-prefix --use-existing-dir '{0}'", pushLocation), localPath, monitor, out output, out error)) {
				ClientError (client, output, error);
			}
		}// Push

		public override void Pull (string pullLocation, string localPath, bool remember, IProgressMonitor monitor) {
			string   output,
					 error;

			if(0 != launch (client, string.Format("pull {0}{1}", remember? string.Empty: "--remember ", pullLocation), localPath, monitor, out output, out error)) {
				ClientError (client, output, error);
			}
		}// Pull
		
		public override void Commit (ChangeSet changeSet, IProgressMonitor monitor) {
			string   output,
			         error;
			StringBuilder localpaths = new StringBuilder ();

			foreach (ChangeSetItem item in changeSet.Items) {
				localpaths.AppendFormat ("'{0}' ", item.LocalPath);
			}

			if (0 != launch (client, string.Format ("commit -m '{0}' {1}", changeSet.GlobalComment, localpaths.ToString ()), changeSet.BaseLocalPath, monitor, out output, out error)) {
				ClientError (client, output, error);
			}
		}// Commit

		// `bzr diff` exit values
		// 0: no changes
		// 1: successful diff with changes
		// 2: unrepresentable changes
		// 3: error
		public override DiffInfo[] Diff (string basePath, string[] files) {
			string   output = string.Empty,
			         error = string.Empty;
			string[] diffFiles = files;

			List<DiffInfo> diffs = new List<DiffInfo> ();

			if (null == files) {
				IList<LocalStatus> statuses = Status (basePath, null);
				List<string> actualFiles = new List<string> ();

				foreach (LocalStatus status in statuses) {
					if (status.Status != ItemStatus.Unchanged){ actualFiles.Add (status.Filename); }
				}// add each modified file for diffing

				diffFiles = actualFiles.ToArray ();
			}
			
			foreach (string file in diffFiles) {
				launch (client, string.Format ("diff '{0}'", file), basePath, null, out output, out error);
				if (!string.IsNullOrEmpty (output)) {
					diffs.Add (new DiffInfo (file, output));
				}
			}// diff each file

			return diffs.ToArray ();
		}// Diff

		public override void Remove (string path, bool force, IProgressMonitor monitor) {
			string   output,
			         error;
			
			if (0 != launch (client, string.Format ("remove {0} '{1}'", force? "--force": string.Empty, path), ".", monitor, out output, out error)) {
				ClientError (client, output, error);
			}
		}// Remove

		public override void Resolve (string path, bool recurse, IProgressMonitor monitor)
		{
			string   output,
			         error;

			if (0 != launch (client, string.Format ("resolve '{0}'", path), ".", monitor, out output, out error)) {
				ClientError (client, output, error);
			}
		}// Resolve

		public override Dictionary<string, BranchType> GetKnownBranches (string path)
		{
			string   output,
			         error;
			Dictionary<string, BranchType> branches = new Dictionary<string, BranchType> ();

			// TODO: move to xmlinfo
			if (0 != launch (client, string.Format("info '{0}'", path), ".", null, out output, out error)) {
				return branches;
			}

			Match match = null;
			BranchType btype;

			using(StringReader reader = new StringReader (output)) {
				for (string line; null != (line = reader.ReadLine ());) {
					match = Regex.Match(line, branchRegex, RegexOptions.Compiled);
					if (match.Success && match.Groups["type"].Success && match.Groups["path"].Success && 
					branchTypes.TryGetValue (match.Groups["type"].Value, out btype)) {
						branches[match.Groups["path"].Value] = btype;
					}// if we matched a good branch line
				}// parse each line
			}// reader
			
			return branches;
		}// GetKnownBranches
		
		#endregion

		/// <summary>
		/// Convenience method for formatting exception message
		/// </summary>
		private static void ClientError (string client, string output, string error)
		{
			throw new BazaarCommandException (string.Format ("Error invoking {0}: {1}{2}{3}", client, output, Environment.NewLine, error));
		}// ClientError

		/// <summary>
		/// Builds a revision spec argument string
		/// </summary>
		/// <param name="start">
		/// A <see cref="BazaarRevision"/>: The starting revision, 
		/// or a revision using BazaarRevision.NONE to omit
		/// </param>
		/// <param name="end">
		/// A <see cref="BazaarRevision"/>: The ending revision
		/// </param>
		/// <returns>
		/// A <see cref="System.String"/>: A revision spec argument string,
		/// or string.Empty 
		/// </returns>
		private static string BuildRevisionSpec (BazaarRevision start, BazaarRevision end)
		{
			string revisionSpec = string.Empty;
			
			if (BazaarRevision.NONE == start.Rev) {
				if (BazaarRevision.NONE != end.Rev) {
					revisionSpec = string.Format ("-r {0}", end.Rev);
				}
			} else {
				revisionSpec = string.Format ("-r {0}..{1}", start.Rev, end.Rev);
			}

			return revisionSpec;
		}// BuildRevisionSpec

		/// <summary>
		/// Executes a build command
		/// </summary>
		/// <param name="command">
		/// The executable to be launched
		/// <see cref="System.String"/>
		/// </param>
		/// <param name="args">
		/// The arguments to command
		/// <see cref="System.String"/>
		/// </param>
		/// <param name="baseDirectory">
		/// The directory in which the command will be executed
		/// <see cref="System.String"/>
		/// </param>
		/// <param name="monitor">
		/// The progress monitor to be used
		/// <see cref="IProgressMonitor"/>
		/// </param>
		/// <param name="output">
		/// Error output will be stored here
		/// <see cref="System.String"/>
		/// </param>
		/// <returns>
		/// The exit code of the command
		/// <see cref="System.Int32"/>
		/// </returns>
		int ExecuteCommand (string command, string args, string baseDirectory, IProgressMonitor monitor, out string output, out string error)
		{
			output = string.Empty;
			int exitCode = -1;
			
			StringWriter swError = new StringWriter (),
			             swOutput = new StringWriter ();
			ProcessWrapper p = null;
			ProcessStartInfo psi = new ProcessStartInfo (command, args);

			psi.WorkingDirectory = baseDirectory;
			psi.RedirectStandardOutput = psi.RedirectStandardError = true;
			
			try {
				// System.Console.WriteLine ("Running: {0} {1}", command, args);
				p = Runtime.ProcessService.StartProcess (command, args, baseDirectory, swOutput, swError, null);
				if (Thread.CurrentThread.Priority == ThreadPriority.Lowest) {
					p.PriorityClass = ProcessPriorityClass.Idle;
				}// set priority on child processes
				
				p.WaitForOutput ();
				output = swOutput.ToString ();
				error = swError.ToString ();
				exitCode = p.ExitCode;
				
				if (null != monitor) {
					monitor.Log.WriteLine (output);
					monitor.Log.WriteLine (error);
					if (monitor.IsCancelRequested) {
						monitor.Log.WriteLine (GettextCatalog.GetString ("Bazaar operation cancelled"));
						monitor.ReportError (GettextCatalog.GetString ("Bazaar operation cancelled"), null);
						if (exitCode == 0)
							exitCode = -1;
					}
				}
			} finally {
				p.Dispose ();
				swOutput.Close ();
				swError.Close ();
			}
			
			return exitCode;
		}
		
		int LaunchLocal (string command, string args, string baseDir, IProgressMonitor monitor, out string stdout, out string stderr) {
			ProcessStartInfo psi = new ProcessStartInfo (command, args);
			int exitCode = -1;
			
			psi.UseShellExecute = false;
			psi.RedirectStandardOutput = true;
			psi.RedirectStandardError = true;
			psi.RedirectStandardInput = false;
			psi.WorkingDirectory = baseDir;
			
			using (Process p = Process.Start (psi)) {
				p.WaitForExit ();
				exitCode = p.ExitCode;
	
				stdout = p.StandardOutput.ReadToEnd ();
				stderr = p.StandardError.ReadToEnd ();
			}
	
			return exitCode;
		}// LaunchLocal
		
		/// <summary>
		/// Execute using bzr shell process
		/// </summary>
		int ExecuteShell (string command, string args, string baseDirectory, IProgressMonitor monitor, out string output, out string error)
		{
			output = error = string.Empty;
			int exitCode = 0;
			bool isXml = ((!string.IsNullOrEmpty (args)) && args.StartsWith ("xml"));
			
			try {
				lock (p) {
					// Console.WriteLine ("bzr {1} ({2}) ({3})", command, args, baseDirectory, args.StartsWith ("xml"));
					if (this.error) {
						// Flush output
						ReadOutput (false);
						this.error = false;
					}
					
					p.StandardInput.WriteLine ("cd {0}", baseDirectory);
					p.StandardInput.WriteLine ("{1}", command, args);
					p.StandardInput.WriteLine ("echo");
					Thread.Sleep(50);
					output = string.Join (Environment.NewLine, ReadOutput (isXml));
					
					if (null != monitor && !isXml) {
						monitor.Log.WriteLine (output);
						monitor.Log.WriteLine (error);
						if (monitor.IsCancelRequested) {
							monitor.Log.WriteLine (GettextCatalog.GetString ("Bazaar operation cancelled"));
							monitor.ReportError (GettextCatalog.GetString ("Bazaar operation cancelled"), null);
							if (0 == exitCode){ exitCode = -1; }
						}
					}
				}
			} catch(Exception e) {
				Console.WriteLine ("{0}{1}{2}", e.Message, Environment.NewLine, e.StackTrace);
				exitCode = -1;
			}
			return exitCode;
		}// ExecuteShell
		
		private static Regex endOutputRegex = new Regex (@"[\p{IsC}](]0;)?bzr[^<]*>\s*(.*)", RegexOptions.Compiled);
		private static Regex xmlRegex = new Regex (@"^.*(<\?xml[^>]*><(?<element>\w+).*</\k<element>>)$", RegexOptions.Compiled);
		/// <summary>
		/// Reads process output
		/// </summary>
		/// <returns>
		/// A <see cref="System.String[]"/>: The lines output by the parser process
		/// </returns>
		private string[] ReadOutput (bool xml)
		{
			List<string> result = new List<string> ();
			int  count = 0,
			     j = 0;
			bool endOutput = false;
			
			DataReceivedEventHandler gotdata = delegate(object sender, DataReceivedEventArgs e) {
				string data = endOutputRegex.Replace (e.Data, "$2");
				// Console.WriteLine (data);
				if (endOutput || ((xml || endOutputRegex.IsMatch (e.Data)) && 0 == data.Trim().Length && 0 != result.Count)) {
					endOutput = true;
					return;
				}
				if (xml) {
					Match match = xmlRegex.Match (data);
					if (match.Success) {
						// Console.WriteLine(match.Groups[1].Value);
						lock (result){ result.Add (match.Groups[1].Value); }
					}
				} else {
					// Console.WriteLine(data);
					lock(result){ result.Add(data); }
				}
			};
			
			p.OutputDataReceived += gotdata;

			for (int i=0;(!endOutput) && i<20 && j<200; ++i, ++j) {
				lock (result){ count = result.Count; }
				p.BeginOutputReadLine ();
				Thread.Sleep (50);
				p.CancelOutputRead ();
				lock (result) {
					if (0 == result.Count || result.Count != count){ i=0; }
				}
			}
			
			if(200 <= j){ error = true; }
			
			p.OutputDataReceived -= gotdata;
			
			return result.ToArray();
		}// ReadOutput
	}// BazaarCommandClient
}