Merge commit 'origin/jg/tree_context'
[GitX.git] / PBGitCommitController.m
blob5b29f689114ca79a0d330fbe9722d72ff14ae9c1
1 //
2 //  PBGitCommitController.m
3 //  GitX
4 //
5 //  Created by Pieter de Bie on 19-09-08.
6 //  Copyright 2008 __MyCompanyName__. All rights reserved.
7 //
9 #import "PBGitCommitController.h"
10 #import "NSFileHandleExt.h"
11 #import "PBChangedFile.h"
12 #import "PBWebChangesController.h"
13 #import "NSString_RegEx.h"
16 @interface PBGitCommitController (PrivateMethods)
17 - (NSArray *) linesFromNotification:(NSNotification *)notification;
18 - (void) doneProcessingIndex;
19 - (NSMutableDictionary *)dictionaryForLines:(NSArray *)lines;
20 - (void) addFilesFromDictionary:(NSMutableDictionary *)dictionary staged:(BOOL)staged tracked:(BOOL)tracked;
21 - (void)processHunk:(NSString *)hunk stage:(BOOL)stage reverse:(BOOL)reverse;
22 @end
24 @implementation PBGitCommitController
26 @synthesize files, status, busy, amend;
28 - (void)awakeFromNib
30         self.files = [NSMutableArray array];
31         [super awakeFromNib];
32         [self refresh:self];
34         [commitMessageView setTypingAttributes:[NSDictionary dictionaryWithObject:[NSFont fontWithName:@"Monaco" size:12.0] forKey:NSFontAttributeName]];
35         
36         [unstagedFilesController setFilterPredicate:[NSPredicate predicateWithFormat:@"hasUnstagedChanges == 1"]];
37         [cachedFilesController setFilterPredicate:[NSPredicate predicateWithFormat:@"hasStagedChanges == 1"]];
38         
39         [unstagedFilesController setSortDescriptors:[NSArray arrayWithObjects:
40                 [[NSSortDescriptor alloc] initWithKey:@"status" ascending:false],
41                 [[NSSortDescriptor alloc] initWithKey:@"path" ascending:true], nil]];
42         [cachedFilesController setSortDescriptors:[NSArray arrayWithObject:
43                 [[NSSortDescriptor alloc] initWithKey:@"path" ascending:true]]];
45 - (void) removeView
47         [webController closeView];
48         [super finalize];
51 - (IBAction)signOff:(id)sender
53         if (![repository.config valueForKeyPath:@"user.name"] || ![repository.config valueForKeyPath:@"user.email"])
54                 return [[repository windowController] showMessageSheet:@"User's name not set" infoText:@"Signing off a commit requires setting user.name and user.email in your git config"];
55         NSString *SOBline = [NSString stringWithFormat:@"Signed-off-by: %@ <%@>",
56                                 [repository.config valueForKeyPath:@"user.name"],
57                                 [repository.config valueForKeyPath:@"user.email"]];
59         if([commitMessageView.string rangeOfString:SOBline].location == NSNotFound) {
60                 commitMessageView.string = [NSString stringWithFormat:@"%@\n\n%@",
61                                 commitMessageView.string, SOBline];
62         }
65 - (void) setAmend:(BOOL)newAmend
67         if (newAmend == amend)
68                 return;
70         amend = newAmend;
71         amendEnvironment = nil;
73         // If we amend, we want to keep the author information for the previous commit
74         // We do this by reading in the previous commit, and storing the information
75         // in a dictionary. This dictionary will then later be read by [self commit:]
76         if (amend) {
77                 NSString *message = [repository outputForCommand:@"cat-file commit HEAD"];
78                 NSArray *match = [message substringsMatchingRegularExpression:@"\nauthor ([^\n]*) <([^\n>]*)> ([0-9]+[^\n]*)\n" count:3 options:0 ranges:nil error:nil];
79                 if (match)
80                         amendEnvironment = [NSDictionary dictionaryWithObjectsAndKeys:[match objectAtIndex:1], @"GIT_AUTHOR_NAME",
81                                 [match objectAtIndex:2], @"GIT_AUTHOR_EMAIL",
82                                 [match objectAtIndex:3], @"GIT_AUTHOR_DATE",
83                                  nil];
85                 // Replace commit message with the old one if it's less than 3 characters long.
86                 // This is just a random number.
87                 if ([[commitMessageView string] length] <= 3) {
88                         // Find the commit message
89                         NSRange r = [message rangeOfString:@"\n\n"];
90                         if (r.location != NSNotFound)
91                                 message = [message substringFromIndex:r.location + 2];
93                         commitMessageView.string = message;
94                 }
95         }
97         [self refresh:self];
100 - (NSArray *) linesFromNotification:(NSNotification *)notification
102         NSDictionary *userInfo = [notification userInfo];
103         NSData *data = [userInfo valueForKey:NSFileHandleNotificationDataItem];
104         if (!data)
105                 return NULL;
106         
107         NSString* string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
108         if (!string)
109                 return NULL;
110         
111         // Strip trailing newline
112         if ([string hasSuffix:@"\n"])
113                 string = [string substringToIndex:[string length]-1];
114         
115         NSArray *lines = [string componentsSeparatedByString:@"\0"];
116         return lines;
119 - (NSString *) parentTree
121         NSString *parent = amend ? @"HEAD^" : @"HEAD";
123         if (![repository parseReference:parent])
124                 // We don't have a head ref. Return the empty tree.
125                 return @"4b825dc642cb6eb9a060e54bf8d69288fbee4904";
127         return parent;
130 - (void) refresh:(id) sender
132         if (![repository workingDirectory])
133                 return;
135         self.status = @"Refreshing index…";
137         // If self.busy reaches 0, all tasks have finished
138         self.busy = 0;
140         // Refresh the index, necessary for the next methods (that's why it's blocking)
141         // FIXME: Make this non-blocking. This call can be expensive in large repositories
142         [repository outputInWorkdirForArguments:[NSArray arrayWithObjects:@"update-index", @"-q", @"--unmerged", @"--ignore-missing", @"--refresh", nil]];
144         NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; 
145         [nc removeObserver:self]; 
147         // Other files (not tracked, not ignored)
148         NSArray *arguments = [NSArray arrayWithObjects:@"ls-files", @"--others", @"--exclude-standard", @"-z", nil];
149         NSFileHandle *handle = [repository handleInWorkDirForArguments:arguments];
150         [nc addObserver:self selector:@selector(readOtherFiles:) name:NSFileHandleReadToEndOfFileCompletionNotification object:handle]; 
151         self.busy++;
152         [handle readToEndOfFileInBackgroundAndNotify];
153         
154         // Unstaged files
155         handle = [repository handleInWorkDirForArguments:[NSArray arrayWithObjects:@"diff-files", @"-z", nil]];
156         [nc addObserver:self selector:@selector(readUnstagedFiles:) name:NSFileHandleReadToEndOfFileCompletionNotification object:handle]; 
157         self.busy++;
158         [handle readToEndOfFileInBackgroundAndNotify];
160         // Staged files
161         handle = [repository handleInWorkDirForArguments:[NSArray arrayWithObjects:@"diff-index", @"--cached", @"-z", [self parentTree], nil]];
162         [nc addObserver:self selector:@selector(readCachedFiles:) name:NSFileHandleReadToEndOfFileCompletionNotification object:handle]; 
163         self.busy++;
164         [handle readToEndOfFileInBackgroundAndNotify];
167 - (void) updateView
169         [self refresh:nil];
172 // This method is called for each of the three processes from above.
173 // If all three are finished (self.busy == 0), then we can delete
174 // all files previously marked as deletable
175 - (void) doneProcessingIndex
177         // if we're still busy, do nothing :)
178         if (--self.busy)
179                 return;
181         NSMutableArray *deleteFiles = [NSMutableArray array];
182         for (PBChangedFile *file in files) {
183                 if (!file.hasStagedChanges && !file.hasUnstagedChanges)
184                         [deleteFiles addObject:file];
185         }
187         if ([deleteFiles count]) {
188                 [self willChangeValueForKey:@"files"];
189                 for (PBChangedFile *file in deleteFiles)
190                         [files removeObject:file];
191                 [self didChangeValueForKey:@"files"];
192         }
193         self.status = @"Ready";
196 - (void) readOtherFiles:(NSNotification *)notification;
198         NSArray *lines = [self linesFromNotification:notification];
199         NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] initWithCapacity:[lines count]];
200         // We fake this files status as good as possible.
201         NSArray *fileStatus = [NSArray arrayWithObjects:@":000000", @"100644", @"0000000000000000000000000000000000000000", @"0000000000000000000000000000000000000000", @"A", nil];
202         for (NSString *path in lines) {
203                 if ([path length] == 0)
204                         continue;
205                 [dictionary setObject:fileStatus forKey:path];
206         }
207         [self addFilesFromDictionary:dictionary staged:NO tracked:NO];
208         [self doneProcessingIndex];
211 - (NSMutableDictionary *)dictionaryForLines:(NSArray *)lines
213         NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:[lines count]/2];
215         // Fill the dictionary with the new information
216         NSArray *fileStatus;
217         BOOL even = FALSE;
218         for (NSString *line in lines) {
219                 if (!even) {
220                         even = TRUE;
221                         fileStatus = [line componentsSeparatedByString:@" "];
222                         continue;
223                 }
225                 even = FALSE;
226                 [dictionary setObject:fileStatus forKey:line];
227         }
228         return dictionary;
231 - (void) addFilesFromDictionary:(NSMutableDictionary *)dictionary staged:(BOOL)staged tracked:(BOOL)tracked
233         // Iterate over all existing files
234         for (PBChangedFile *file in files) {
235                 NSArray *fileStatus = [dictionary objectForKey:file.path];
236                 // Object found, this is still a cached / uncached thing
237                 if (fileStatus) {
238                         if (tracked) {
239                                 NSString *mode = [[fileStatus objectAtIndex:0] substringFromIndex:1];
240                                 NSString *sha = [fileStatus objectAtIndex:2];
242                                 if (staged) {
243                                         file.hasStagedChanges = YES;
244                                         file.commitBlobSHA = sha;
245                                         file.commitBlobMode = mode;
246                                 } else
247                                         file.hasUnstagedChanges = YES;
248                         } else {
249                                 // Untracked file, set status to NEW, only unstaged changes
250                                 file.hasStagedChanges = NO;
251                                 file.hasUnstagedChanges = YES;
252                                 file.status = NEW;
253                         }
254                         [dictionary removeObjectForKey:file.path];
255                 } else { // Object not found, let's remove it from the changes
256                         if (staged)
257                                 file.hasStagedChanges = NO;
258                         else if (tracked && file.status != NEW) // Only remove it if it's not an untracked file. We handle that with the other thing
259                                 file.hasUnstagedChanges = NO;
260                         else if (!tracked && file.status == NEW)
261                                 file.hasUnstagedChanges = NO;
262                 }
263         }
265         // Do new files
266         if (![[dictionary allKeys] count])
267                 return;
269         [self willChangeValueForKey:@"files"];
270         for (NSString *path in [dictionary allKeys]) {
271                 NSArray *fileStatus = [dictionary objectForKey:path];
273                 PBChangedFile *file = [[PBChangedFile alloc] initWithPath:path];
274                 if ([[fileStatus objectAtIndex:4] isEqualToString:@"D"])
275                         file.status = DELETED;
276                 else if([[fileStatus objectAtIndex:0] isEqualToString:@":000000"])
277                         file.status = NEW;
278                 else
279                         file.status = MODIFIED;
281                 if (staged) {
282                         file.commitBlobMode = [[fileStatus objectAtIndex:0] substringFromIndex:1];
283                         file.commitBlobSHA = [fileStatus objectAtIndex:2];
284                 }
286                 file.hasStagedChanges = staged;
287                 file.hasUnstagedChanges = !staged;
289                 [files addObject: file];
290         }
291         [self didChangeValueForKey:@"files"];
294 - (void) readUnstagedFiles:(NSNotification *)notification
296         NSArray *lines = [self linesFromNotification:notification];
297         NSMutableDictionary *dic = [self dictionaryForLines:lines];
298         [self addFilesFromDictionary:dic staged:NO tracked:YES];
299         [self doneProcessingIndex];
302 - (void) readCachedFiles:(NSNotification *)notification
304         NSArray *lines = [self linesFromNotification:notification];
305         NSMutableDictionary *dic = [self dictionaryForLines:lines];
306         [self addFilesFromDictionary:dic staged:YES tracked:YES];
307         [self doneProcessingIndex];
310 - (void) commitFailedBecause:(NSString *)reason
312         self.busy--;
313         self.status = [@"Commit failed: " stringByAppendingString:reason];
314         [[repository windowController] showMessageSheet:@"Commit failed" infoText:reason];
315         return;
318 - (IBAction) commit:(id) sender
320         if ([[NSFileManager defaultManager] fileExistsAtPath:[repository.fileURL.path stringByAppendingPathComponent:@"MERGE_HEAD"]]) {
321                 [[repository windowController] showMessageSheet:@"Cannot commit merges" infoText:@"GitX cannot commit merges yet. Please commit your changes from the command line."];
322                 return;
323         }
325         if ([[cachedFilesController arrangedObjects] count] == 0) {
326                 [[repository windowController] showMessageSheet:@"No changes to commit" infoText:@"You must first stage some changes before committing"];
327                 return;
328         }               
329         
330         NSString *commitMessage = [commitMessageView string];
331         if ([commitMessage length] < 3) {
332                 [[repository windowController] showMessageSheet:@"Commitmessage missing" infoText:@"Please enter a commit message before committing"];
333                 return;
334         }
336         [cachedFilesController setSelectionIndexes:[NSIndexSet indexSet]];
337         [unstagedFilesController setSelectionIndexes:[NSIndexSet indexSet]];
339         NSString *commitSubject;
340         NSRange newLine = [commitMessage rangeOfString:@"\n"];
341         if (newLine.location == NSNotFound)
342                 commitSubject = commitMessage;
343         else
344                 commitSubject = [commitMessage substringToIndex:newLine.location];
345         
346         commitSubject = [@"commit: " stringByAppendingString:commitSubject];
348         NSString *commitMessageFile;
349         commitMessageFile = [repository.fileURL.path
350                                                  stringByAppendingPathComponent:@"COMMIT_EDITMSG"];
352         [commitMessage writeToFile:commitMessageFile atomically:YES encoding:NSUTF8StringEncoding error:nil];
354         self.busy++;
355         self.status = @"Creating tree..";
356         NSString *tree = [repository outputForCommand:@"write-tree"];
357         if ([tree length] != 40)
358                 return [self commitFailedBecause:@"Could not create a tree"];
360         int ret;
362         NSMutableArray *arguments = [NSMutableArray arrayWithObjects:@"commit-tree", tree, nil];
363         NSString *parent = amend ? @"HEAD^" : @"HEAD";
364         if ([repository parseReference:parent]) {
365                 [arguments addObject:@"-p"];
366                 [arguments addObject:parent];
367         }
369         NSString *commit = [repository outputForArguments:arguments
370                                                                                   inputString:commitMessage
371                                                            byExtendingEnvironment:amendEnvironment
372                                                                                          retValue: &ret];
374         if (ret || [commit length] != 40)
375                 return [self commitFailedBecause:@"Could not create a commit object"];
377         if (![repository executeHook:@"pre-commit" output:nil])
378                 return [self commitFailedBecause:@"Pre-commit hook failed"];
380         if (![repository executeHook:@"commit-msg" withArgs:[NSArray arrayWithObject:commitMessageFile] output:nil])
381     return [self commitFailedBecause:@"Commit-msg hook failed"];
383         [repository outputForArguments:[NSArray arrayWithObjects:@"update-ref", @"-m", commitSubject, @"HEAD", commit, nil]
384                                                   retValue: &ret];
385         if (ret)
386                 return [self commitFailedBecause:@"Could not update HEAD"];
388         if (![repository executeHook:@"post-commit" output:nil])
389                 [webController setStateMessage:[NSString stringWithFormat:@"Post-commit hook failed, however, successfully created commit %@", commit]];
390         else
391                 [webController setStateMessage:[NSString stringWithFormat:@"Successfully created commit %@", commit]];
393         repository.hasChanged = YES;
394         self.busy--;
395         [commitMessageView setString:@""];
396         amend = NO;
397         amendEnvironment = nil;
398         [self refresh:self];
399         self.amend = NO;
402 - (void) stageHunk:(NSString *)hunk reverse:(BOOL)reverse
404         [self processHunk:hunk stage:TRUE reverse:reverse];
407 - (void)discardHunk:(NSString *)hunk
409         [self processHunk:hunk stage:FALSE reverse:TRUE];
412 - (void)processHunk:(NSString *)hunk stage:(BOOL)stage reverse:(BOOL)reverse
414         NSMutableArray *array = [NSMutableArray arrayWithObjects:@"apply", nil];
415         if (stage)
416                 [array addObject:@"--cached"];
417         if (reverse)
418                 [array addObject:@"--reverse"];
420         int ret = 1;
421         NSString *error = [repository outputForArguments:array
422                                                                                  inputString:hunk
423                                                                                         retValue:&ret];
425         // FIXME: show this error, rather than just logging it
426         if (ret)
427                 NSLog(@"Error: %@", error);
429         // TODO: We should do this smarter by checking if the file diff is empty, which is faster.
430         [self refresh:self]; 
433 @end