MacHg / Classes / Sheets / CommitSheet / CommitSheetController.m

  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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
//
//  CommitSheetController.m
//  MacHg
//
//  Created by Jason Harris on 30/04/09.
//  Copyright 2010 Jason F Harris. All rights reserved.
//  This software is licensed under the "New BSD License". The full license text is given in the file License.txt
//

#import "CommitSheetController.h"
#import "MacHgDocument.h"
#import "TaskExecutions.h"
#import "DisclosureBoxController.h"
#import "RepositoryData.h"
#import "FSNodeInfo.h"
#import "FSViewerTable.h"
#import "PatchData.h"
#import "HunkExclusions.h"
#import "LogEntry.h"

NSString* kAmendOption	 = @"amendOption";



// -----------------------------------------------------------------------------------------------------------------------------------------
// MARK: -
// MARK:  CommitFSViewer
// -----------------------------------------------------------------------------------------------------------------------------------------
// MARK: -

@implementation CommitFSViewer
- (void) awakeFromNib
{
	[super awakeFromNib];

	HunkExclusions* exclusions = [self hunkExclusions];
	[self observe:kHunkWasExcluded from:exclusions byCalling:@selector(nodeWasChanged:)];
	[self observe:kHunkWasIncluded from:exclusions byCalling:@selector(nodeWasChanged:)];
	[self observe:kFileWasExcluded from:exclusions byCalling:@selector(nodeWasChanged:)];
	[self observe:kFileWasIncluded from:exclusions byCalling:@selector(nodeWasChanged:)];
}

- (void) nodeWasChanged:(NSNotification*)notification
{
	if ([self showingFilesTable])
	{
		NSDictionary* userInfo = [notification userInfo];
		NSString* absolutePath = fstr(@"%@/%@", nonNil([userInfo objectForKey:kRootPath]), nonNil([userInfo objectForKey:kFileName]));
		FSNodeInfo* changedNode = [[self rootNodeInfo] nodeForPathFromRoot:absolutePath];
		if (changedNode)
			[[[self window] contentView] setNeedsDisplayInRect:[self rectInWindowForNode:changedNode]];
	}
	[(id)parentController performSelectorIfPossible:@selector(validateButtons:) withObject:self];
}

- (NSString*) nibNameForFilesTable   { return @"CommitFilesViewTable"; }
@end





// -----------------------------------------------------------------------------------------------------------------------------------------
// MARK: -
// MARK:  CommitSheetController
// -----------------------------------------------------------------------------------------------------------------------------------------
// MARK: -

@interface CommitSheetController (PrivateAPI)
- (IBAction)	validateButtons:(id)sender;
- (void)		amendOptionChanged;
- (void)		setSheetTitle;
- (NSArray*)	tableLeafNodes;
@end

@implementation CommitSheetController
@synthesize myDocument;
@synthesize	committerOption = committerOption_;
@synthesize	committer = committer_;
@synthesize	dateOption = dateOption_;
@synthesize	date = date_;
@synthesize	amendOption = amendOption_;
@synthesize	commitSubstateOption = commitSubstateOption_;
@synthesize absolutePathsOfFilesToCommit = absolutePathsOfFilesToCommit_;





// -----------------------------------------------------------------------------------------------------------------------------------------
// MARK: -
// MARK: Initialization
// -----------------------------------------------------------------------------------------------------------------------------------------

- (CommitSheetController*) initCommitSheetControllerWithDocument:(MacHgDocument*)doc
{
	myDocument = doc;
	[NSBundle loadNibNamed:@"CommitSheet" owner:self];
	return self;
}


- (void) awakeFromNib
{
	[self  addObserver:self  forKeyPath:kAmendOption  options:NSKeyValueObservingOptionNew  context:NULL];
	cachedCommitMessageForAmend_ = nil;
	
	[previousCommitMessagesTableView setTarget:self];
	[previousCommitMessagesTableView setDoubleAction:@selector(handlePreviousCommitMessagesTableDoubleClick:)];
	[previousCommitMessagesTableView setAction:@selector(handlePreviousCommitMessagesTableClick:)];
}


- (void) observeValueForKeyPath:(NSString*)keyPath  ofObject:(id)object  change:(NSDictionary*)change  context:(void*)context
{
    if ([keyPath isEqualToString:kAmendOption])
		[self amendOptionChanged];
}





// -----------------------------------------------------------------------------------------------------------------------------------------
// MARK: -
// MARK: Handle Table Clicks
// -----------------------------------------------------------------------------------------------------------------------------------------

- (IBAction) handlePreviousCommitMessagesTableClick:(id)sender
{	
}

- (IBAction) handlePreviousCommitMessagesTableDoubleClick:(id)sender
{
	NSString* message = [logCommentsTableSourceData objectAtIndex:[previousCommitMessagesTableView clickedRow]];
	[commitMessageTextView insertText:message];
	[theCommitSheet makeFirstResponder:commitMessageTextView];
}


- (IBAction) fsviewerAction:(id)sender
{
}

- (IBAction) fsviewerDoubleAction:(id)sender
{
	[self commitSheetDiffAction:self];
}





// -----------------------------------------------------------------------------------------------------------------------------------------
// MARK: -
// MARK:  Sheet opening
// -----------------------------------------------------------------------------------------------------------------------------------------

- (void) openCommitSheetWithPaths:(NSArray*)paths
{
	logCommentsTableSourceData = nil;
	NSString* rootPath = [myDocument absolutePathOfRepositoryRoot];

	// Report the branch we are about to commit on in the dialog
	NSMutableArray* argsBranch = [NSMutableArray arrayWithObjects:@"branch", nil];
	ExecutionResult* hgBranchResults = [TaskExecutions executeMercurialWithArgs:argsBranch  fromRoot:rootPath  logging:eLoggingNone];
	NSString* newBranchSheetString = fstr(@"to branch: %@", hgBranchResults.outStr);
	[commitSheetBranchString setStringValue: newBranchSheetString];

	NSMutableArray* argsGetUserName = [NSMutableArray arrayWithObjects:@"showconfig", @"ui.username", nil];
	ExecutionResult* userNameResult = [TaskExecutions executeMercurialWithArgs:argsGetUserName  fromRoot:rootPath];

	//[disclosureController setToOpenState:NO withAnimation:NO];
	[self setCommitter:nonNil(userNameResult.outStr)];
	[self setCommitterOption:NO];
	[self setDate:[NSDate date]];
	[self setDateOption:NO];
	if ([amendButton state] == NSOnState)
		[self setAmendOption:NO];

	// Handle the commit substate option
	hasHgSub_ = pathIsExistentFile(fstr(@"%@/.hgsub",rootPath));
	[self setCommitSubstateOption:SubrepoSubstateCommitFromDefauts() == eSubrepositorySubstateDoCommit];
	[commitSubstateButton setHidden:!hasHgSub_];
	
	NSString* currentMessage = [commitMessageTextView string];
	[commitMessageTextView setSelectedRange:NSMakeRange(0, [currentMessage length])];
	[self setSheetTitle];
	[myDocument beginSheet:theCommitSheet];
	[theCommitSheet makeFirstResponder:commitMessageTextView];

	// Store the paths of the files to be committed
	absolutePathsOfFilesToCommit_ = pruneContainedPaths([[myDocument theFSViewer] filterPaths:paths byBitfield:eHGStatusChangedInSomeWay]);
	
	[commitFilesViewer	actionSwitchToFilesTable:self];
	[commitFilesViewer	repositoryDataIsNew];

	// Fetch the last 10 log comments and set the sources so that the table view of these in the commit sheet shows them correctly.
	NSMutableArray* argsLog = [NSMutableArray arrayWithObjects:@"log", @"--limit", @"10", @"--template", @"{desc}\n#^&^#\n", nil];
	ExecutionResult* hgLogResults = [TaskExecutions executeMercurialWithArgs:argsLog  fromRoot:rootPath  logging:eLoggingNone];
	logCommentsTableSourceData = [hgLogResults.outStr componentsSeparatedByString:@"\n#^&^#\n"];
	[previousCommitMessagesTableView reloadData];
	
	LogEntry* parent = [[myDocument repositoryData] entryForRevision:[myDocument getHGParent1Revision]];
	[parent fullyLoadEntry];
	cachedCommitMessageForAmend_ = [parent fullComment];

	amendIsPossible_ = ![myDocument inMergeState] && [[myDocument repositoryData] isTipOfLocalBranch];
	
	[self validateButtons:self];
}


- (IBAction) openCommitSheetWithAllFiles:(id)sender
{
	committingAllFiles = YES;
	[self openCommitSheetWithPaths:[myDocument absolutePathOfRepositoryRootAsArray]];
}

- (IBAction) openCommitSheetWithSelectedFiles:(id)sender
{
	if ([[myDocument repositoryData] inMergeState])
	{
		[self openCommitSheetWithAllFiles:sender];
		return;
	}
	
	committingAllFiles = NO;
	NSArray* paths = [myDocument absolutePathsOfChosenFiles];
	if ([paths count] <= 0)
		{ PlayBeep(); DebugLog(@"No files are selected to commit"); return; }

	[self openCommitSheetWithPaths:paths];
}


- (void) setSheetTitle
{
	NSString* newTitle = nil;
	BOOL mergedState = [[myDocument repositoryData] inMergeState];
	BOOL allFiles = committingAllFiles;
	NSString* repositoryShortName = [myDocument selectedRepositoryShortName];
	if (mergedState)
		newTitle = fstr(@"Committing Merged Files in %@", repositoryShortName);
	else if (allFiles && !amendOption_)
		newTitle = fstr(@"Committing All Files in %@", repositoryShortName);
	else if (amendOption_)
		newTitle = fstr(@"Amending Selected Files in %@", repositoryShortName);
	else
		newTitle = fstr(@"Committing Selected Files in %@", repositoryShortName);
	[commitSheetTitle setStringValue:newTitle];
}

- (void) setTooltipMessgaes
{
	NSString* amendTooltipMessage = @"Amend will incorporate the files to be committed into the last changeset.";
	if (!AllowHistoryEditingOfRepositoryFromDefaults())
		amendTooltipMessage = @"History editing needs to be enabled in order to use the amend option.";
	else if ([myDocument inMergeState])
		amendTooltipMessage = @"The changeset to be amended cannot be a merge changeset.";
	else if (![myDocument isCurrentRevisionTip])
		amendTooltipMessage = @"The changeset to be amended must be the tip revision.";
	[amendButton setToolTip:amendTooltipMessage];
	
	NSString* excludeTooltipMessage = @"Exclude files from the commit.";
	if ([myDocument inMergeState])
		excludeTooltipMessage = @"Cannot exclude files during a merge commit.";
	else if (amendOption_)
		excludeTooltipMessage = @"Exclude files from the amend.";
	// [excludePathsButton setToolTip:excludeTooltipMessage];

	NSString* includeTooltipMessage = @"Reinclude files for the commit.";
	if ([myDocument inMergeState])
		includeTooltipMessage = @"Cannot exclude files during a merge commit.";
	else if (amendOption_)
		includeTooltipMessage = @"Reinclude files for the amend.";
	//[includePathsButton setToolTip:includeTooltipMessage];
}

- (void) makeMessageFieldFirstResponder
{
	[theCommitSheet makeFirstResponder:commitMessageTextView];
}





// -----------------------------------------------------------------------------------------------------------------------------------------
// MARK: -
// MARK:  Validation
// -----------------------------------------------------------------------------------------------------------------------------------------

- (BOOL) validateUserInterfaceItem:(id < NSValidatedUserInterfaceItem >)anItem
{
	SEL theAction = [anItem action];
	// CommitSheet contextual items
	if (theAction == @selector(commitSheetDiffAction:))			return [commitFilesViewer nodesAreSelected];
	return NO;
}

- (BOOL) anyHunksToCommit
{
	NSString* rootPath = [myDocument absolutePathOfRepositoryRoot];
	HunkExclusions* hunkExclusions = [self hunkExclusions];
	for(FSNodeInfo* node in [self tableLeafNodes])
	{
		NSString* fileName = pathDifference(rootPath, [node absolutePath]);
		NSSet* hunkExclusionSet = [hunkExclusions hunkExclusionSetForRoot:rootPath andFile:fileName];
		if (IsEmpty(hunkExclusionSet))
			return YES;
		NSSet* validHunkHashSet = [hunkExclusions validHunkHashSetForRoot:rootPath andFile:fileName];
		if (IsNotEmpty(validHunkHashSet) && ![validHunkHashSet isSubsetOfSet:hunkExclusionSet])
			return YES;
	}
	return NO;
}

- (IBAction) validateButtons:(id)sender
{
	BOOL pathsAreSelected = [commitFilesViewer nodesAreSelected];
	BOOL canAllowAmend = AllowHistoryEditingOfRepositoryFromDefaults() && amendIsPossible_ && ![myDocument inMergeState];
	BOOL okToCommit = IsNotEmpty([commitMessageTextView string]) && [self anyHunksToCommit];
	NSString* diffButtonMessage = pathsAreSelected ? @"Diff Selected" : @"Diff All";
	
	dispatch_async(mainQueue(), ^{
		[diffButton setTitle:diffButtonMessage];
		[okButton setEnabled:okToCommit];
		[amendButton setEnabled:canAllowAmend];
		[self setTooltipMessgaes];
		[self setSheetTitle];
	});
}


// This sets the commit message field into a "disabled" appearance state when the amend option is checked, and swaps out the
// message, forthe old message, etc.
- (void) amendOptionChanged
{
	NSString* currentMessage = [[commitMessageTextView string] copy];
	[commitMessageTextView setSelectedRange:NSMakeRange(0, [currentMessage length])];
	[commitMessageTextView insertText:cachedCommitMessageForAmend_];
	cachedCommitMessageForAmend_ = currentMessage;
	[self validateButtons:self];
}




// -----------------------------------------------------------------------------------------------------------------------------------------
// MARK: -
// MARK:  Table Handling
// -----------------------------------------------------------------------------------------------------------------------------------------

- (NSInteger) numberOfRowsInTableView:(NSTableView*)aTableView
{
	if (aTableView == previousCommitMessagesTableView)
		return [logCommentsTableSourceData count];
	return 0;
}

- (id) tableView:(NSTableView*)aTableView objectValueForTableColumn:(NSTableColumn*)aTableColumn row:(NSInteger)rowIndex
{
	if (aTableView == previousCommitMessagesTableView)
		return [logCommentsTableSourceData objectAtIndex:rowIndex];
	return @" ";
}

- (NSArray*) tableLeafNodes
{
	return [[commitFilesViewer theFilesTable] leafNodeForTableRow];
}

- (NSArray*) tableLeafPaths
{
	return pathsOfFSNodes([[commitFilesViewer theFilesTable] leafNodeForTableRow]);
}





// -----------------------------------------------------------------------------------------------------------------------------------------
// MARK: -
// MARK:  Committing
// -----------------------------------------------------------------------------------------------------------------------------------------

- (NSArray*) argumentsForUserDataMessage
{
	NSString* theMessage = [commitMessageTextView string];
	NSMutableArray* args = [NSMutableArray arrayWithObjects:@"--message", theMessage, nil];
	if ([self committerOption] && IsNotEmpty([self committer]))
		[args addObject:@"--user" followedBy:[self committer]];
	if ([self dateOption] && IsNotEmpty([self date]))
		[args addObject:@"--date" followedBy:[[self date] isodateDescription]];
	return args;
}


- (void) handleCommitSubrepoSubstateOption:(NSMutableArray*)commandArgs
{
	if (hasHgSub_ && [commitSubstateButton state] == NSOffState)
	{
		[commandArgs addObject:@"-X" followedBy:@".hgsub"];
		[commandArgs addObject:@"-X" followedBy:@".hgsubstate"];
	}
}

- (void) sheetActionSimpleCommit:(NSArray*)pathsToCommit
{
	NSString* rootPath = [myDocument absolutePathOfRepositoryRoot];
	[myDocument dispatchToMercurialQueuedWithDescription:@"Committing Files" process:^{
		NSMutableArray* args = [NSMutableArray arrayWithObjects:@"commit", nil];
		[self handleCommitSubrepoSubstateOption:args];
		[myDocument registerPendingRefresh:pathsToCommit];
		[args addObjectsFromArray:[self argumentsForUserDataMessage]];
		if (![myDocument inMergeState])
			[args addObjectsFromArray:pathsToCommit];
		
		[myDocument delayEventsUntilFinishBlock:^{
			[TaskExecutions executeMercurialWithArgs:args  fromRoot:rootPath];
			[myDocument addToChangedPathsDuringSuspension:pathsToCommit];
		}];			
	}];
}

- (BOOL) commit_setupForAmend
{
	NSString* rootPath = [myDocument absolutePathOfRepositoryRoot];
	
	if (DisplayWarningForAmendFromDefaults())
	{
		BOOL pathsAreRootPath = [[absolutePathsOfFilesToCommit_ lastObject] isEqual:rootPath];
		NSString* mainMessage = fstr(@"Amending the latest revision with %@ files", pathsAreRootPath ? @"all" : @"the selected");
		NSString* subMessage  = fstr(@"Are you sure you want to amend the latest revision in the repository “%@”.", [myDocument selectedRepositoryShortName]);
		int result = RunCriticalAlertPanelOptionsWithSuppression(mainMessage, subMessage, @"Amend", @"Cancel", nil, MHGDisplayWarningForAmend);
		if (result != NSAlertFirstButtonReturn)
			[NSException raise:@"UserCanceled" format:@"The user canceled this operation", nil];
	}	
	
	NSString* parent1RevisionStr = numberAsString([myDocument getHGParent1Revision]);

	if ([myDocument inMergeState])
		[NSException raise:@"Merge" format:@"The Amend operation could not proceed. The repository is in a merge state.", nil];

	if (![[myDocument repositoryData] isTipOfLocalBranch])
		[NSException raise:@"Descendants" format:@"The Amend operation could not proceed. The revision to amend %@ has other descedants.", parent1RevisionStr, nil];

	NSMutableArray*  qimportArgs   = [NSMutableArray arrayWithObjects:@"qimport", @"--config", @"extensions.hgext.mq=", @"--rev", parent1RevisionStr, @"--name", @"macHgAmendPatch", @"--git", nil];
	ExecutionResult* qimportResult = [myDocument executeMercurialWithArgs:qimportArgs  fromRoot:rootPath  whileDelayingEvents:YES];
	if ([qimportResult hasErrors])
		[NSException raise:@"QImporting" format:@"The Amend operation could not proceed. The process of importing the existing patch reported the error: %@.", [qimportResult errStr], nil];
	return YES;
}

- (void) commit_backupContestedFiles:(NSArray*)contestedPaths into:(NSString*)tempDirectoryPath withRoot:(NSString*)rootPath
{
	if (IsEmpty(contestedPaths))
		return;
	if (!tempDirectoryPath)
		[NSException raise:@"TempDirectory" format:@"Unable to create a necessary temporary directory. Aborting the operation.", nil];
	for (NSString* originalPath in contestedPaths)
	{
		NSError* err = nil;
		NSString* backupPath =  fstr(@"%@/%@",tempDirectoryPath, pathDifference(rootPath, originalPath));
		[[NSFileManager defaultManager] copyItemAtPath:originalPath toPath:backupPath withIntermediateDirectories:YES error:&err];
		if (err)
		{
			NSString* operation = ([amendButton state] == NSOnState) ? @"amend" : @"commit";
			[NSException raise:@"Backup" format:@"Unable to backup files before the main %@ (Mac OS reports: %@). Aborting the %@.", operation, [err localizedDescription], operation, nil];
		}
	}	
}

- (void) commit_restoreContestedFiles:(NSArray*)contestedPaths from:(NSString*)tempDirectoryPath withRoot:(NSString*)rootPath
{
	for (NSString* originalPath in contestedPaths)
	{
		NSError* err = nil;
		NSString* backupPath =  fstr(@"%@/%@",tempDirectoryPath, pathDifference(rootPath, originalPath));
		[[NSFileManager defaultManager] removeItemAtPath:originalPath error:&err];
		[NSApp presentAnyErrorsAndClear:&err];
		[[NSFileManager defaultManager] copyItemAtPath:backupPath toPath:originalPath error:&err];
		[NSApp presentAnyErrorsAndClear:&err];
	}
	moveFilesToTheTrash([NSArray arrayWithObject:tempDirectoryPath]);
}

- (void) sheetActionCommitWithUncontestedPaths:(NSArray*)uncontestedPaths andContestedPaths:(NSArray*)contestedPaths amending:(BOOL)amend
{
	NSString* rootPath = [myDocument absolutePathOfRepositoryRoot];
	NSString* operation = amend ? @"amend" : @"commit";
	NSString* errorTitle = fstr(@"Aborted %@", amend ? @"Amend" : @"Commit");
	NSString* operationTitle = fstr(@"%@ Files", amend ? @"Amending" : @"Committing");
	
	// Get contested Patch File
	NSString* contestedPatchFile = nil;
	if (IsNotEmpty(contestedPaths))
	{
		NSMutableArray* argsDiff = [NSMutableArray arrayWithObjects:@"diff", nil];
		[argsDiff addObject:@"--unified" followedBy:fstr(@"%d",NumContextLinesForDifferencesWebviewFromDefaults())];
		[argsDiff addObjectsFromArray:contestedPaths];
		ExecutionResult* diffResult = [TaskExecutions executeMercurialWithArgs:argsDiff  fromRoot:rootPath logging:eLoggingNone];
		PatchData* patchData = IsNotEmpty(diffResult.outStr) ? [PatchData patchDataFromDiffContents:diffResult.outStr] : nil;
		contestedPatchFile = [patchData tempFileWithPatchBodyExcluding:[self hunkExclusions] withRoot:rootPath];
	}
	
	// Create temporary Directory and copy contested files to this directory
	NSString* commitPartsDirectory = fstr(@"%@/%@", rootPath, @".hg/macHgParts");
	NSString* tempDirectoryPath = tempDirectoryPathWithTemplate(@"MacHgContestedFilePatchBackupDir.XXXXXXXXXX", commitPartsDirectory);
	@try
	{
		[self commit_backupContestedFiles:contestedPaths into:tempDirectoryPath withRoot:rootPath];
		if (amend)
			[self commit_setupForAmend];
	}
	@catch (NSException* e)
	{
		if ([[e name] isEqualToString:@"UserCanceled"])
			return;
		NSRunCriticalAlertPanel(errorTitle, [e reason], @"OK", nil, nil);
		return;
	}
	
	NSArray* commitCommandArguments = [self argumentsForUserDataMessage];
	
	[myDocument dispatchToMercurialQueuedWithDescription:operationTitle process:^{

		[myDocument registerPendingRefresh:uncontestedPaths];
		[myDocument registerPendingRefresh:contestedPaths];

		[myDocument delayEventsUntilFinishBlock:^{
			@try
			{
				// Revert the contested files to their original state
				if (IsNotEmpty(contestedPaths))
				{
					NSMutableArray* argsRevert = [NSMutableArray arrayWithObjects:@"revert", @"--no-backup", nil];
					[argsRevert addObjectsFromArray:contestedPaths];
					ExecutionResult* revertResult = [TaskExecutions executeMercurialWithArgs:argsRevert  fromRoot:rootPath logging:eLoggingNone];
					if ([revertResult hasErrors])
						[NSException raise:@"Reverting" format:@"During the process needed to %@ the files, the step of reverting the files with excluded hunks reported the error: %@.", operation, [revertResult errStr], nil];
				}

				// Patch the contested files to the desired state, (if all the hunks are descelected in the contested files the
				// patch will be empty) 
				if (contestedPatchFile)
				{
					NSMutableArray*  importArgs   = [NSMutableArray arrayWithObjects:@"import", @"--no-commit", @"--force", contestedPatchFile, nil];
					ExecutionResult* importResult = [TaskExecutions executeMercurialWithArgs:importArgs  fromRoot:rootPath logging:eLoggingNone];
					if ([importResult hasErrors])
						[NSException raise:@"Importing" format:@"During the process needed to %@ the files, the step of adjusting the files to exclude the specified hunks reported the error: %@.", operation, [importResult errStr], nil];
				}
				
				if (!amend)
				{
					// Do the commit
					NSMutableArray* commitArgs = [NSMutableArray arrayWithObjects:@"commit", nil];
					[self handleCommitSubrepoSubstateOption:commitArgs];
					[commitArgs addObjectsFromArray:commitCommandArguments];
					[commitArgs addObjectsFromArray:uncontestedPaths];
					[commitArgs addObjectsFromArray:contestedPaths];
					ExecutionResult* commitResult = [TaskExecutions executeMercurialWithArgs:commitArgs  fromRoot:rootPath logging:eLoggingNone];
					if ([commitResult hasErrors])
						[NSException raise:@"Committing" format:@"During the process needed to %@ the files, the step of commiting the adjusted files reported the error: %@.", operation, [commitResult errStr], nil];
				}
				else
				{
					// Do the refresh
					NSMutableArray* qrefreshArgs = [NSMutableArray arrayWithObjects:@"qrefresh", @"--config", @"extensions.hgext.mq=", @"--short", nil];
					[self handleCommitSubrepoSubstateOption:qrefreshArgs];
					[qrefreshArgs addObjectsFromArray:commitCommandArguments];
					[qrefreshArgs addObjectsFromArray:uncontestedPaths];
					[qrefreshArgs addObjectsFromArray:contestedPaths];
					ExecutionResult* qrefreshResult = [myDocument executeMercurialWithArgs:qrefreshArgs  fromRoot:rootPath  whileDelayingEvents:YES];
					if ([qrefreshResult hasErrors])
						[NSException raise:@"Refreshing" format:@"The amend operation could not proceed. The patch refresh process reported the error: %@. Please back out any patch operations.", [qrefreshResult errStr], nil];
					
					// Do the queue finish
					NSMutableArray*  qfinishArgs   = [NSMutableArray arrayWithObjects:@"qfinish", @"--config", @"extensions.hgext.mq=", @"macHgAmendPatch", nil];
					ExecutionResult* qfinishResult = [myDocument executeMercurialWithArgs:qfinishArgs  fromRoot:rootPath  whileDelayingEvents:YES];
					if ([qfinishResult hasErrors])
						[NSException raise:@"Finishing" format:@"The amend operation could not proceed. The patch finish process reported the error: %@. Please back out any patch operations.", [qfinishResult errStr], nil];
				}
			}
			@catch (NSException * e)
			{
				[amendButton setState:NSOffState];
				NSRunCriticalAlertPanel(errorTitle, [e reason], @"OK", nil, nil);
			}
			@finally
			{
				// Replace the contested files with their original backups
				[self commit_restoreContestedFiles:contestedPaths from:tempDirectoryPath withRoot:rootPath];
				[myDocument addToChangedPathsDuringSuspension:contestedPaths];
				[myDocument addToChangedPathsDuringSuspension:uncontestedPaths];
			}
		}];			
	}];
}





// -----------------------------------------------------------------------------------------------------------------------------------------
// MARK: -
// MARK:  Actions
// -----------------------------------------------------------------------------------------------------------------------------------------

- (IBAction) sheetButtonOk:(id)sender
{
	NSString* root = [myDocument absolutePathOfRepositoryRoot];
	
	[theCommitSheet makeFirstResponder:theCommitSheet];	// Make the fields of the sheet commit any changes they currently have

	NSArray* commitData = [self tableLeafPaths];
	NSArray*   contestedPaths = [[self hunkExclusions]   contestedPathsIn:commitData  forRoot:root];
	NSArray* uncontestedPaths = [[self hunkExclusions] uncontestedPathsIn:commitData  forRoot:root];
	BOOL inMerge = [[myDocument repositoryData] inMergeState];
	BOOL simpleOperation = 	IsEmpty(contestedPaths);
	BOOL amend = ([amendButton state] == NSOnState);
	
	// This is more a check here, error handling should have caught this before now if the files were empty.
	if (IsEmpty(commitData))
	{
		PlayBeep();
		DebugLog(@"Nothing to commit");
		[NSApp endSheet:theCommitSheet];
		[theCommitSheet orderOut:sender];
		return;
	}

	[myDocument removeAllUndoActionsForDocument];
	
	if ((simpleOperation && !amend) || inMerge)
		[self sheetActionSimpleCommit:absolutePathsOfFilesToCommit_];
	else
		[self sheetActionCommitWithUncontestedPaths:uncontestedPaths andContestedPaths:contestedPaths amending:amend];

	[myDocument endSheet:theCommitSheet];
}


- (IBAction) commitSheetDiffAction:(id)sender
{
	NSArray* nodesToDiff = [commitFilesViewer nodesAreSelected] ? [commitFilesViewer chosenNodes] : [self tableLeafNodes];
	NSArray* pathsToDiff = pathsOfFSNodes(nodesToDiff);
	[myDocument viewDifferencesInCurrentRevisionFor:pathsToDiff toRevision:nil]; // nil indicates the current revision
	[self makeMessageFieldFirstResponder];
}


- (IBAction) sheetButtonCancel:(id)sender
{
	[myDocument endSheet:theCommitSheet];
}


- (void)textDidChange:(NSNotification*) aNotification
{
	[self validateButtons:[aNotification object]];
}





// -----------------------------------------------------------------------------------------------------------------------------------------
// MARK: -
// MARK:  FSViewer Protocol Methods
// -----------------------------------------------------------------------------------------------------------------------------------------

// All Controllers which embed a FSBrowser must conform to this protocol
- (NSArray*) statusLinesForPaths:(NSArray*)absolutePaths withRootPath:(NSString*)rootPath
{
	NSArray* restrictedPaths = restrictPathsToPaths(absolutePaths,absolutePathsOfFilesToCommit_);

	// Get status of everything relevant and return this array for use by the node tree to re-flush stale parts of it (or all of it.)
	NSMutableArray* argsStatus = [NSMutableArray arrayWithObjects:@"status", @"--added", @"--removed", @"--deleted", @"--modified", nil];
	[argsStatus addObjectsFromArray:restrictedPaths];
	
	ExecutionResult* results = [TaskExecutions executeMercurialWithArgs:argsStatus  fromRoot:rootPath  logging:eLoggingNone];
	
	if ([results hasErrors])
	{
		// Try a second time
		sleep(0.5);
		results = [TaskExecutions executeMercurialWithArgs:argsStatus  fromRoot:rootPath  logging:eLoggingNone];
	}
	if ([results.errStr length] > 0)
	{
		[results logMercurialResult];
		// for an error rather than warning fail by returning nil. Maybe later we will return error codes.
		if ([results hasErrors])
			return  nil;
	}
	NSArray* lines = [results.outStr componentsSeparatedByString:@"\n"];
	return IsNotEmpty(lines) ? lines : [NSArray array];
}

// Get any resolve status lines and change the resolved code 'R' to 'V' so that this status letter doesn't conflict with the other
// status letters.
- (NSArray*) resolveStatusLines:(NSArray*)absolutePaths  withRootPath:(NSString*)rootPath
{
	NSArray* restrictedPaths = restrictPathsToPaths(absolutePaths,absolutePathsOfFilesToCommit_);
	
	// Get status of everything relevant and return this array for use by the node tree to re-flush stale parts of it (or all of it.)
	NSMutableArray* argsResolveStatus = [NSMutableArray arrayWithObjects:@"resolve", @"--list", nil];
	[argsResolveStatus addObjectsFromArray:restrictedPaths];
	
	ExecutionResult* results = [TaskExecutions executeMercurialWithArgs:argsResolveStatus fromRoot:rootPath  logging:eLoggingNone];
	if ([results hasErrors])
	{
		[results logMercurialResult];
		return nil;
	}
	NSArray* lines = [results.outStr componentsSeparatedByString:@"\n"];
	NSMutableArray* newLines = [[NSMutableArray alloc] init];
	for (NSString* line in lines)
		if (IsNotEmpty(line))
		{
			if ([line characterAtIndex:0] == 'R')
				[newLines addObject:fstr(@"V%@",[line substringFromIndex:1])];
			else
				[newLines addObject:line];
		}
	return newLines;
}

- (BOOL) writePaths:(NSArray*)paths toPasteboard:(NSPasteboard*)pasteboard
{
	[pasteboard declareTypes:[NSArray arrayWithObject:NSFilenamesPboardType] owner:self];
	[pasteboard setPropertyList:paths forType:NSFilenamesPboardType];	
	return IsNotEmpty(paths) ? YES : NO;
}

- (BOOL)			autoExpandViewerOutlines						{ return NO; }
- (HunkExclusions*) hunkExclusions							{ return [myDocument hunkExclusions]; }
- (void)			setMyDocumentFromParent					{ };
- (void)			didSwitchViewTo:(FSViewerNum)viewNumber { };
- (BOOL)			controlsMainFSViewer					{ return NO; }
- (void)			updateCurrentPreviewImage				{ };



@end
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.