Source

Murky / Source / HgRevision.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
//
//  HgRevision.m
//  Murky
//
//  Copyright 2008-2009 Jens Alfke. All rights reserved.
//

#import "HgRevision.h"
#import "HgUncommittedRevision.h"
#import "HgDir.h"
#import "HgRepository.h"
#import "HgLogOperation.h"
#import "HgTempDir.h"


#define kShortLength 100

const HgRevisionID kZeroRevisionID = { };
const HgRevisionID kUncommittedRevisionID = {{0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
                                              0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF}};

static NSString* StringFromHgRevisionID( HgRevisionID r )
{
    NSMutableString *str = [NSMutableString string];
    for( NSInteger i=0; i<20; i++ ) {
        [str appendFormat: @"%02x", (NSUInteger)r.bytes[i]];
    }
    return str;
}


@implementation HgRevision


- (id) initWithRepository: (HgRepository*)repository
              localNumber: (NSInteger)revision
               identifier: (HgRevisionID)myID
{
    Assert(repository);
    Assert(revision>=0);
    self = [super init];
    if( self ) {
        _repository = repository;
        _localNumber = revision;
        _identifier = myID;
    }
    return self;
}

- (id) copyWithZone: (NSZone*)zone
{
    return NSCopyObject(self, 0, zone);
}


#pragma mark -
#pragma mark ACCESSORS:


- (BOOL) isEqual:  (id)other
{
    return [self class]==[other class] && HgEqualRevisionIDs(_identifier,((HgRevision*)other)->_identifier);
}

- (NSUInteger) hash
{
    return *(const NSUInteger*)&_identifier;    // use start of identifier as hashcode
}

- (NSComparisonResult) compare: (HgRevision*)rev
{
    return (NSInteger)_localNumber - (NSInteger)rev.localNumber;
}


@synthesize repository=_repository, localNumber=_localNumber, identifier=_identifier;


/** Fills in the full info of this revision (and nearby ones) */
- (BOOL) _getDetails {
    NSRange revs = {_localNumber - (_localNumber % 20), 20};
    if (![_repository getDetailsOfRevisions: revs]) {
        Warn(@"HgRevision _getDetails: Failed to get details");
        return NO;
    } else if (!_date)
        Warn(@"HgRevision _getDetails: _date still not set!");
    return YES;
}

- (NSDate*) date {
    if (!_date) [self _getDetails];
    return _date;
}

- (void) setDate: (NSDate*)date {
    _date = date;
}

- (NSString*) comment {
    // Comment might legitimately be nil, so use _date as a test for getting details:
    if (!_date) [self _getDetails];
    return _comment;
}

- (void) setComment: (NSString*)comment {
    _comment = comment;
}

- (NSString*) author {
    if (!_date) [self _getDetails];
    return _author;
}

- (void) setAuthor: (NSString*)author {
    _author = author;
}

- (NSString*) email {
    if (!_date) [self _getDetails];
    return _email;
}

- (void) setEmail: (NSString*)email {
    _email = email;
}

- (NSString*) branch {
    if (!_date) [self _getDetails];
    return _branch;
}

- (void) setBranch: (NSString*)branch {
    _branch = branch;
}


- (NSArray*) parents
{
    if( _parent )
        return [NSArray arrayWithObjects: _parent,_parent2,nil];
    else
        return nil;
}

- (BOOL) isHead {
    // Search all later revisions for one that lists me as a parent:
    NSArray* revisions = [_repository revisions];
    NSUInteger n = revisions.count;
    for (NSUInteger i=_localNumber+1; i<n; i++) {
        HgRevision *rev = [revisions objectAtIndex: i];
        if (rev.parent==self || rev.parent2==self)
            return NO;
    }
    return YES;
}

- (BOOL) isUncommitted            {return NO;}

- (NSString*) localString    {return [NSString stringWithFormat: @"%i",_localNumber];}

- (NSString*) identifierString  {return StringFromHgRevisionID(_identifier);}

- (NSString*) shortComment
{
    if( ! _shortComment ) {
        NSString *comment = self.comment;
        if( comment ) {
            NSMutableString *c = [comment mutableCopy];
            if( c.length >= kShortLength )
                [c replaceCharactersInRange: NSMakeRange(kShortLength-3,c.length-(kShortLength-3)) 
                                 withString: NSLocalizedString(@"...", 
                                                               @"Appended to truncated comment string in revision table")];
            [c replaceOccurrencesOfString: @"\n" withString: @" " options: 0  range: NSMakeRange(0,c.length)];
            _shortComment = c;
        } else
            _shortComment = @"";
    }
    return _shortComment;
}

+ (NSSet*) keyPathsForValuesAffectingShortComment {
    return [NSSet setWithObject: @"comment"];
}


- (NSString*) description
{
    return [NSString stringWithFormat: @"#%@: %@", self.localString,self.shortComment];
}


- (NSString*) formattedDate
{
    static NSDateFormatter *sFmt;
    if( ! sFmt ) {
        sFmt = [[NSDateFormatter alloc] init];
        sFmt.dateStyle = NSDateFormatterLongStyle;
        sFmt.timeStyle = NSDateFormatterLongStyle;
    }
    return [sFmt stringFromDate: self.date];
}


- (NSString*) formattedDescription
{
    NSMutableString *desc = [NSMutableString stringWithFormat: @"#%i: [%@]\n%@\n%@ <%@>\n",
                             _localNumber,
                             self.identifierString,
                             self.formattedDate,
                             self.author,self.email];
    [desc appendString: @"____________________\n\n"];
    if( _comment.length > 0 )
        [desc appendString: _comment];
    return desc;
}

static NSRange replace(NSMutableAttributedString *desc, NSString *src, NSString *dst) {
    NSRange r = [desc.string rangeOfString: src];
    if (r.length) {
        [desc replaceCharactersInRange: r withString: (dst ?: @"")];
        r.length = dst.length;
    }
    return r;
}

static void replaceAndLink(NSMutableAttributedString *desc, NSString *src, NSString *dst, 
                           NSURL *url, NSString *tooltip) {
    NSRange r = replace(desc,src,dst);
    if (r.length > 0) {
        if (url) 
            [desc addAttribute: NSLinkAttributeName value: url range: r];
        if (tooltip)
            [desc addAttribute: NSToolTipAttributeName value: tooltip range: r];
    }
}

- (NSAttributedString*) richFormattedDescription
{
    static NSAttributedString *sTemplate;
    if (!sTemplate) {
        NSString *templatePath = [[NSBundle bundleForClass: [self class]]
                                  pathForResource: @"RevisionDescriptionTemplate" ofType: @"rtf"];
        Assert(templatePath);
        sTemplate = [[NSAttributedString alloc] initWithPath: templatePath documentAttributes: NULL];
        Assert(sTemplate);
    }
    
    NSURL *email = nil;
    if ([self.email rangeOfString: @"@"].length > 0) {
        NSString *name = [self.repository.name stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        email = [NSURL URLWithString: $sprintf(@"mailto:%@?subject=Re:%%20%@",
                 self.email, name)];
    }
    
    NSMutableAttributedString *desc = [sTemplate mutableCopy];
    replace(desc, @"DESCRIPTION",(_comment ?: @""));
    replaceAndLink(desc, @"AUTHOR",     self.author, email, self.email);
    replace(desc, @"BRANCH",       self.branch ? self.branch : @"default");
    replace(desc, @"DATE",       self.formattedDate);
    replace(desc, @"IDENTIFIER", self.identifierString);
    replace(desc, @"LOCAL",      _localNumber !=NSNotFound ?$sprintf(@"%i",_localNumber): nil);
    return desc;
}


- (void) dumpTo: (NSMutableString*)dump {
    static NSDateFormatter *sFmt;
    if( ! sFmt ) {
        sFmt = [[NSDateFormatter alloc] init];
        sFmt.dateStyle = NSDateFormatterShortStyle;
        sFmt.timeStyle = NSDateFormatterShortStyle;
    }
    if (self.isUncommitted)
        [dump appendString: @"#UNC: "];
    else
        [dump appendFormat: @"#%3i: ", self.localNumber];
    if (_parent) {
        [dump appendFormat: @"[#%3i", _parent.localNumber];
        if (_parent2)
            [dump appendFormat: @", #%3i", _parent2.localNumber];
        [dump appendString: @"] "];
    }
    if (self.identifierString)
        [dump appendFormat: @"%@… ", [self.identifierString substringToIndex: 8]];
    if (self.date)
        [dump appendString: [sFmt stringFromDate: self.date]];
}


// some sanity checks (see issue #11)
- (HgRevision*) parent  {return _parent;}
- (HgRevision*) parent2 {return _parent2;}

- (void) setParent: (HgRevision*)parent {
    if (parent != _parent) {
        if (parent) {
            Assert(parent!=self);
            Assert(parent!=_parent2);
            Assert(!parent.isUncommitted);
        }
        [_parent release];
        _parent = [parent retain];
    }
}

- (void) setParent2: (HgRevision*)parent {
    if (parent != _parent2) {
        if (parent) {
            Assert(parent!=self);
            Assert(parent!=_parent);
            Assert(!parent.isUncommitted);
        }
        [_parent2 release];
        _parent2 = [parent retain];
    }
}


- (BOOL) descendsFrom: (HgRevision*)ancestor
{
    for( HgRevision *rev=self; rev; rev=rev->_parent ) {
        if( rev->_localNumber < ancestor->_localNumber )
            break;
        else if( rev->_localNumber == ancestor->_localNumber )
            return YES;
        else if( rev->_parent2 && [rev->_parent2 descendsFrom: ancestor] )    // recurse down 2nd parent
            return YES;
    }
    return NO;
}

- (HgRevision*) commonAncestorWith: (HgRevision*)otherRevision {
    Assert(otherRevision);
    for (HgRevision *ancestor=self; ancestor; ancestor=ancestor->_parent) {
        if ([otherRevision descendsFrom: ancestor])
            return ancestor;
    }
    return nil;
}


- (NSString*) absolutePath
{
    return _repository.absolutePath;
}


#pragma mark -
#pragma mark FILES:


- (BOOL) updateStatus: (HgDir*)dir error: (NSError**)outError
{
    if( dir==nil )
        dir = _root;
    NSMutableArray *args = [NSMutableArray array];
    if( !self.isUncommitted ) {
        [args addObjectsFromArray: [NSArray arrayWithObjects: @"--rev", (_parent ?_parent.identifierString :@"00000000"),
                                                              @"--rev", self.identifierString,
                                                              nil]];
    }
    [args addObjectsFromArray: [NSArray arrayWithObjects: @"--all", @"--", dir.path, nil]];
    HgOperation *op = [[HgOperation alloc] initWithDirectory: self
                                                     command: @"status"
                                                   arguments: args];
    BOOL ok = [op run: outError];
    if (!ok)
        return NO;
    
    [dir updateStatusFromOutput: [op.output componentsSeparatedByString: @"\n"]
                  isMergeStatus: NO];

    // Look for merge conflicts:
    if (self.isUncommitted) {
        LogTo(HgRepository, @"Checking for merge conflicts...");
        op = [[HgOperation alloc] initWithDirectory: self
                                            command: @"resolve", @"-l", nil];
        ok = [op run: outError];
        if (ok) {
            [dir updateStatusFromOutput: [op.output componentsSeparatedByString: @"\n"]
                          isMergeStatus: YES];
        }
    }

    // Status changes may propagate all the way up to the root
    [dir.root _computeStatus];

    return ok;
}    


- (HgDir*) root
{
    if( ! _root ) {
        HgDir *root = [[HgDir alloc] initRootOfRevision: self];
        NSError *error;
        if( ! [self updateStatus: root error: &error] )
            Warn(@"-[HgRevision root] failed! %@",error);
        _root = root;
    }
    return _root;
}

- (NSArray*) rootAsArray    // used only by the NSTreeController in Repo.nib
{
    return [NSArray arrayWithObject: self.root];
}


- (HgFile*) fileAtPath: (NSString*)path
{
    if( ! _root )
        (void)self.root;
    return [_root fileAtPath: path];
}


static BOOL isFileUnclean( HgFile* file ) {return file.status != kClean;}

- (NSArray*) uncleanFiles       // observable!
{
    if( ! _uncleanFiles )
        _uncleanFiles = [self.root allFilesMatching: FunctionPredicate(isFileUnclean)];
    return _uncleanFiles;
}


#pragma mark -
#pragma mark FILE CONTENTS / COMPARISONS:


- (NSData*) getFileContents: (HgFile*)file error: (NSError**)outError
{
    HgOperation *op = [[HgOperation alloc] initWithDirectory: file.root
                                                     command: @"cat",
                       @"--rev", [NSString stringWithFormat: @"%i",_localNumber], @"--", file.path, nil];
    if( ! [op run] ) {
        if (outError) *outError = op.error;
        return nil;
    }
    return op.outputData;
}


- (NSString*) getPathToFileContents: (HgFile*)file inTempDir: (HgTempDir*)tempDir error: (NSError**)outError
{
    Assert(tempDir);
    NSData *contents = [self getFileContents: file error: outError];
    if( ! contents )
        return nil;
    return [tempDir writeData: contents 
                  toFileNamed: [NSString stringWithFormat: @"(%@) %@",self.localString,file.name] 
                        error: outError];
}


- (NSString*) diffFile: (HgFile*)file withRevisionNumber: (NSInteger)otherRev error: (NSError**)outError
{
    Assert(otherRev>=0 && otherRev!=NSNotFound);
    if( otherRev==_localNumber )
        return @"";
    [file.repository ignoreNextFileChanges];       // ignore temp file that "hg diff" creates in the repo root dir
    HgOperation *op = [[HgOperation alloc] initWithDirectory: file.root
                                                     command: @"diff",
                       @"--rev", [NSString stringWithFormat: @"%i",MIN(otherRev,_localNumber)],
                       @"--rev", [NSString stringWithFormat: @"%i",MAX(otherRev,_localNumber)],
                       @"--", file.path, nil];
    if( ! [op run] ) {
        if (outError) *outError = op.error;
        return nil;
    }
    return op.output ?: @"";    
}


- (NSString*) compareFile: (HgFile*)file withRevisionNumber: (NSInteger)otherRev error: (NSError**)outError
{
    Assert(otherRev>=0 && otherRev!=NSNotFound);
    if( otherRev==_localNumber )
        return @"";
    [file.repository ignoreNextFileChanges];       // ignore temp file that "hg diff" creates in the repo root dir
    HgOperation *op = [[HgOperation alloc] initWithDirectory: file.root
                                                     command: @"extdiff", @"-p", @"/usr/bin/opendiff", @"-o", @"",
                       @"--rev", [NSString stringWithFormat: @"%i",MIN(otherRev,_localNumber)],
                       @"--rev", [NSString stringWithFormat: @"%i",MAX(otherRev,_localNumber)],
                       @"--", file.path, nil];
    if( ! [op run] ) {
        if (outError) *outError = op.error;
        return nil;
    }
    return op.output;    
}


- (NSString*) diffFile: (HgFile*)file withRevision: (HgRevision*)other error: (NSError**)outError
{
    if( other.isUncommitted )
        return [other diffFile: file withRevisionNumber: _localNumber error: outError];
    else
        return [self diffFile: file withRevisionNumber: other.localNumber error: outError]; 
}

- (NSString*) annotateFile: (HgFile*)file error: (NSError**)outError
{
    NSString *revStr = self.isUncommitted ?@"tip"
                                          :[NSString stringWithFormat: @"%i",_localNumber];
    HgOperation *op = [[HgOperation alloc] initWithDirectory: file.root
                                                     command: @"annotate",
                       @"--number",
                       @"--rev", revStr,
                       @"--", file.path, nil];
    if( ! [op run] ) {
        if (outError) *outError = op.error;
        return nil;
    }
    return op.output;    
}


#pragma mark -
#pragma mark REVISION OPERATIONS:


- (NSArray*) outgoingRevisionsForRepository: (NSURL*)otherRepo
{
    HgLogOperation *op = [[HgLogOperation alloc] initOutgoingWithRevision: self
                                                                otherRepo: otherRepo];
    if( ! [op run] )
        return nil;
    return op.revisions;
}


@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.