2 // PBGitCommitController.m
5 // Created by Pieter de Bie on 19-09-08.
6 // Copyright 2008 __MyCompanyName__. All rights reserved.
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;
24 @implementation PBGitCommitController
26 @synthesize files, status, busy, amend;
30 self.files = [NSMutableArray array];
34 [commitMessageView setTypingAttributes:[NSDictionary dictionaryWithObject:[NSFont fontWithName:@"Monaco" size:12.0] forKey:NSFontAttributeName]];
36 [unstagedFilesController setFilterPredicate:[NSPredicate predicateWithFormat:@"hasUnstagedChanges == 1"]];
37 [cachedFilesController setFilterPredicate:[NSPredicate predicateWithFormat:@"hasStagedChanges == 1"]];
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]]];
47 [webController closeView];
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];
65 - (void) setAmend:(BOOL)newAmend
67 if (newAmend == amend)
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:]
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];
80 amendEnvironment = [NSDictionary dictionaryWithObjectsAndKeys:[match objectAtIndex:1], @"GIT_AUTHOR_NAME",
81 [match objectAtIndex:2], @"GIT_AUTHOR_EMAIL",
82 [match objectAtIndex:3], @"GIT_AUTHOR_DATE",
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;
100 - (NSArray *) linesFromNotification:(NSNotification *)notification
102 NSDictionary *userInfo = [notification userInfo];
103 NSData *data = [userInfo valueForKey:NSFileHandleNotificationDataItem];
107 NSString* string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
111 // Strip trailing newline
112 if ([string hasSuffix:@"\n"])
113 string = [string substringToIndex:[string length]-1];
115 NSArray *lines = [string componentsSeparatedByString:@"\0"];
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";
130 - (void) refresh:(id) sender
132 if (![repository workingDirectory])
135 self.status = @"Refreshing index…";
137 // If self.busy reaches 0, all tasks have finished
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];
152 [handle readToEndOfFileInBackgroundAndNotify];
155 handle = [repository handleInWorkDirForArguments:[NSArray arrayWithObjects:@"diff-files", @"-z", nil]];
156 [nc addObserver:self selector:@selector(readUnstagedFiles:) name:NSFileHandleReadToEndOfFileCompletionNotification object:handle];
158 [handle readToEndOfFileInBackgroundAndNotify];
161 handle = [repository handleInWorkDirForArguments:[NSArray arrayWithObjects:@"diff-index", @"--cached", @"-z", [self parentTree], nil]];
162 [nc addObserver:self selector:@selector(readCachedFiles:) name:NSFileHandleReadToEndOfFileCompletionNotification object:handle];
164 [handle readToEndOfFileInBackgroundAndNotify];
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 :)
181 NSMutableArray *deleteFiles = [NSMutableArray array];
182 for (PBChangedFile *file in files) {
183 if (!file.hasStagedChanges && !file.hasUnstagedChanges)
184 [deleteFiles addObject:file];
187 if ([deleteFiles count]) {
188 [self willChangeValueForKey:@"files"];
189 for (PBChangedFile *file in deleteFiles)
190 [files removeObject:file];
191 [self didChangeValueForKey:@"files"];
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)
205 [dictionary setObject:fileStatus forKey:path];
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
218 for (NSString *line in lines) {
221 fileStatus = [line componentsSeparatedByString:@" "];
226 [dictionary setObject:fileStatus forKey:line];
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
239 NSString *mode = [[fileStatus objectAtIndex:0] substringFromIndex:1];
240 NSString *sha = [fileStatus objectAtIndex:2];
243 file.hasStagedChanges = YES;
244 file.commitBlobSHA = sha;
245 file.commitBlobMode = mode;
247 file.hasUnstagedChanges = YES;
249 // Untracked file, set status to NEW, only unstaged changes
250 file.hasStagedChanges = NO;
251 file.hasUnstagedChanges = YES;
254 [dictionary removeObjectForKey:file.path];
255 } else { // Object not found, let's remove it from the changes
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;
266 if (![[dictionary allKeys] count])
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"])
279 file.status = MODIFIED;
282 file.commitBlobMode = [[fileStatus objectAtIndex:0] substringFromIndex:1];
283 file.commitBlobSHA = [fileStatus objectAtIndex:2];
286 file.hasStagedChanges = staged;
287 file.hasUnstagedChanges = !staged;
289 [files addObject: file];
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
313 self.status = [@"Commit failed: " stringByAppendingString:reason];
314 [[repository windowController] showMessageSheet:@"Commit failed" infoText:reason];
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."];
325 if ([[cachedFilesController arrangedObjects] count] == 0) {
326 [[repository windowController] showMessageSheet:@"No changes to commit" infoText:@"You must first stage some changes before committing"];
330 NSString *commitMessage = [commitMessageView string];
331 if ([commitMessage length] < 3) {
332 [[repository windowController] showMessageSheet:@"Commitmessage missing" infoText:@"Please enter a commit message before committing"];
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;
344 commitSubject = [commitMessage substringToIndex:newLine.location];
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];
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"];
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];
369 NSString *commit = [repository outputForArguments:arguments
370 inputString:commitMessage
371 byExtendingEnvironment:amendEnvironment
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]
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]];
391 [webController setStateMessage:[NSString stringWithFormat:@"Successfully created commit %@", commit]];
393 repository.hasChanged = YES;
395 [commitMessageView setString:@""];
397 amendEnvironment = nil;
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];
416 [array addObject:@"--cached"];
418 [array addObject:@"--reverse"];
421 NSString *error = [repository outputForArguments:array
425 // FIXME: show this error, rather than just logging it
427 NSLog(@"Error: %@", error);
429 // TODO: We should do this smarter by checking if the file diff is empty, which is faster.