Source

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

#import "HgRepository.h"
#import "HgUncommittedRevision.h"
#import "HgDir.h"
#import "HgOperation.h"
#import "HgLogOperation.h"
#import "HgConfigFile.h"
#import "MYDirectoryWatcher.h"


@interface HgRepository (Internal)
@property (copy) NSArray* revisions;
- (BOOL) _checkWorkingTreePaths: (NSSet*)paths error: (NSError**)outError;
- (BOOL) _checkWorkingTree: (NSError**)outError;
- (BOOL) _checkRevisions;
@end


static NSString* stringForURL( NSURL *url )
{
    NSCParameterAssert(url);
    if( url.isFileURL )
        return url.path;
    else
        return url.absoluteString;
}


@implementation HgRepository


+ (NSString*) findRootOf: (NSString*)absPath
               localPath: (NSString**)outLocalPath
{
    absPath = [absPath stringByStandardizingPath];  // Resolves '..', '~', symlinks
    if (!absPath || !absPath.isAbsolutePath)
        return nil;
    
    // Look for a ".hg" subdirectory. While not found, walk up to the parent directory:
    NSString *path = absPath;
    while(YES){
        NSString *hgDirPath = [path stringByAppendingPathComponent: @".hg"];
        BOOL isDir;
        if( [[NSFileManager defaultManager] fileExistsAtPath: hgDirPath isDirectory: &isDir]
               && isDir ) {
            if( outLocalPath ) {
                if( path.length+1 < absPath.length )
                    *outLocalPath = [absPath substringFromIndex: path.length+1];
                else
                    *outLocalPath = nil;
            }
            if( ! [path hasSuffix: @"/"] )
                path = [path stringByAppendingString: @"/"];
            return path;
        }
        NSString *oldPath = path;
        path = [path stringByDeletingLastPathComponent];
        if( [oldPath isEqualToString: path] )
            return nil;
    }
}


- (id) initWithPath: (NSString*)path
          localPath: (NSString**)localPath
{
    Assert([path hasPrefix: @"/"]);
    
    self = [super init];
    if (self != nil) {
        NSString *root = [[self class] findRootOf: path localPath: localPath];
        if( ! root )
            return nil;
        _absolutePath = [root copy];
        
        _uncommittedRevision = [[HgUncommittedRevision alloc] initWithRepository: self];
        
        _changedPaths = [NSMutableSet set];
        _watcher = [[MYDirectoryWatcher alloc] initWithDirectory: _absolutePath
                                                          target: self 
                                                          action: @selector(_dirChanged:)];
        _watcher.latency = 5;
        [_watcher.runLoopModes addObject: NSModalPanelRunLoopMode];
        if( ! [_watcher start] )
            Warn(@"HgRepository: Couldn't start MYDirectoryWatcher on %@",_absolutePath);
        Log(@"Opened %@", self);
    }
    return self;
}


- (id) initNewWithPath: (NSString*)path 
                 error: (NSError**)outError
{
    HgOperation *op = [[HgOperation alloc] initWithDirectory: nil
                                                     command: @"init",
                                                              @"--", path, nil];
    if( ! [op run: outError] )
        return nil;
    
    return [self initWithPath: path localPath: NULL];
}


- (NSString*) description {
    return $sprintf(@"%@[%@]", [self class], [self absolutePath]);
}


- (HgConfigFile*) configFile
{
    if( ! _hgrc ) 
        _hgrc = [[HgConfigFile alloc] initWithFile: [[self absolutePath] stringByAppendingPathComponent: @".hg/hgrc"]];
    else
        [_hgrc sync];
    return _hgrc;
}


@synthesize absolutePath=_absolutePath, uncommittedRevision=_uncommittedRevision;


- (NSURL*) URL
{
    return [NSURL fileURLWithPath: _absolutePath];
}

- (NSString*) name
{
    return _absolutePath.lastPathComponent;
}

- (NSString*) webName
{
    NSString *name = [[self configFile] valueForKey: @"name" inStanza: @"web"];
    if( ! name )
        name = self.name;
    return name;
}

- (NSString*) webDescription
{
    return [[self configFile] valueForKey: @"description" inStanza: @"web"];
}


- (void) dumpTo: (NSMutableString*)dump {
    [dump appendFormat: @"%@ %@ :", [self class], _absolutePath];
    for (HgRevision *rev in _revisions) {
        [dump appendString: @"\n\t"];
        [rev dumpTo: dump];
    }
}


#pragma mark -
#pragma mark WORKING TREE TRACKING:


- (void) _dirChanged: (MYDirectoryEvent*)event
{
    NSString *path=event.relativePath;
    if (!path)
        return;     // only happens if MYDirectoryWatch is confused by the path
    if( [path hasPrefix: @".hg/"] )
        path = @".hg";
    if( [_changedPaths containsObject: path] )
        return;                                     // we're already going to update this dir
    for( NSString *changedPath in _changedPaths ) {
        if( [path hasPrefix: changedPath] )
            return;                                 // ...or an ancestor of it
    }
    LogTo(HgRepository, @"dir changed: %@ (%@)", path, event.path);
    if( _changedPaths.count==0 )
        [self performSelector: @selector(_updateChangedDirs) withObject: nil afterDelay: 0.25];
    [_changedPaths addObject: path];
}
    

- (void) _updateChangedDirs
{
    LogTo(HgRepository, @"Updating changed dirs %@",[[_changedPaths allObjects] componentsJoinedByString: @", "]);
    NSSet *changedPaths = _changedPaths;
    _changedPaths = [NSMutableSet set];
    
    if( [changedPaths containsObject: @".hg"] ) {
        [self updateStatus: nil];                   // Hg metadata changed, so do a full update
        return;
    }
    
    NSError *error;
    [self _checkWorkingTreePaths: changedPaths error: &error];
}


- (void) ignoreNextFileChanges
{
    [_watcher stopTemporarily];
}


- (BOOL) updateStatus: (NSError**)outError
{
    if (outError) *outError = nil;
    return [self _checkRevisions]  || [self _checkWorkingTree: outError];
}


#pragma mark -
#pragma mark REVISIONS:


- (NSArray*) _getRevNumbers: (NSString*)cmd
{
    HgOperation *op = [[HgOperation alloc] initWithDirectory: self
                                                     command: cmd,
                                                               @"--template", @"{rev},", nil];
    if( ! [op run] )
        return nil;
    return [op.output componentsSeparatedByString: @","];
}    


/** Returns the local revision number of the tip, or NSNotFound if there are no revisions */
- (int) _getTip
{
    NSArray *revs = [self _getRevNumbers: @"tip"];
    if( revs.count > 1 )
        return [[revs objectAtIndex: 0] intValue];
    else
        return NSNotFound;
}


/** Gets the parent(s) of the current revision. Returns NO on failure.
    *outRev2 will be -1 unless the current revision is a merge.
    *outRev1 will be -1 if the repository is new and has no committed revisions yet. */
- (BOOL) _getParent1: (int*)outRev1 parent2: (int*)outRev2
{
    *outRev1 = *outRev2 = -1;
    NSArray *revs = [self _getRevNumbers: @"parents"];
    if( revs.count > 0 ) {
        NSString *str = [revs objectAtIndex: 0];
        if( str.length > 0 ) {
            *outRev1 = str.intValue;
            str = [revs objectAtIndex: 1];
            if( str.length > 0 )
                *outRev2 = str.intValue;
        }
        return YES;
    }
    return NO;
}    


/** Updates the status of the given paths. */
- (BOOL) _checkWorkingTreePaths: (NSSet*)paths error: (NSError**)outError
{
    return [_uncommittedRevision updatePaths: paths error: outError];
}


- (BOOL) _checkWorkingTree: (NSError**)outError
{
    return [self _checkWorkingTreePaths: [NSSet setWithObject: @""] error: outError];
}


/** Checks whether revisions have been added or whether the current revision has changed. 
    If so, it updates my state and returns YES. */
- (BOOL) _checkRevisions
{
    // Run "hg parents" to get current revision number:
    NSError *error;
    int curRevNo, curParent2;
    if( ! [self _getParent1: &curRevNo parent2: &curParent2] )
        return NO;
    
    HgRevision *parent2Rev = _uncommittedRevision.parent2;
    int parent2 = parent2Rev ?parent2Rev.localNumber :-1;

    // Run "hg tip" to get tip revision number:
    int tip = [self _getTip];
    if( tip==NSNotFound )
        return NO;
    
    NSMutableArray *nuRevisions = [_revisions mutableCopy];
    
    HgRevision *tipRevision = self.tipRevision;
    int curTip = tipRevision ?tipRevision.localNumber :-1;
    if( tip > curTip ) {
        // New revisions have been added!
        LogTo(HgRepository,@"_checkRevisions: Tip changed from %i to %i (cur=%i) ... updating revisions", curTip,tip, curRevNo);

        // Run "hg log" to get all revisions of this repository:
        if (!_revisions)
            _revisions = [NSArray array];   // Because HgLogOperation will call my -revisions
        HgLogMode mode = kHgLogModeFull;
        if (tip-curTip > 100)
            mode = kHgLogModeMinimal;       // Speeds up initial open of large repos
        HgLogOperation *op = [[HgLogOperation alloc] initWithRepository: self 
                                                                   file: nil 
                                                                   mode: mode];
        if( curTip >= 0 )
            op.range = NSMakeRange(curTip+1, tip-curTip); // only need to ask about the new revisions
        if( ! [op run] ) {
            //FIX: It's bad design to pop up UI from within model code. Especially a blocking alert!
            // But it's important to notify the user if the 'hg log' failed. Probably the best solution
            // is to add a 'delegate' property that can be notified of errors.
            [NSApp presentError: op.error];
            return NO;
        }
        Assert([[op.revisions objectAtIndex: 0] localNumber]==curTip+1,
                  @"Unexpected revision numbers from log: expected starting %u, got %u", 
                  curTip+1, [[op.revisions objectAtIndex: 0] localNumber]);
        
        // Add the new revisions, but before the uncommitted one:
        [nuRevisions removeObject: _uncommittedRevision];
        [nuRevisions addObjectsFromArray: op.revisions];
        [nuRevisions addObject: _uncommittedRevision];
        
    } else if( tip < curTip ) {
        // Revisions have been removed, due to a rollback:
        [nuRevisions removeObjectsInRange: NSMakeRange(tip+1, curTip-tip)];
                
    } else if( curRevNo != _uncommittedRevision.parent.localNumber || curParent2 != parent2) {
        // A different revision is current; or the parents have changed
        LogTo(HgRepository, @"_checkRevisions: Current revision changed to %i/%i", curRevNo,curParent2);
    } else {
        LogTo(HgRepository,@"_checkRevisions: No change");
        return NO;
    }

    // Revision list must end with the uncommitted revision:
    if (nuRevisions.count==0)
        nuRevisions = $array(_uncommittedRevision);
    else
        AssertEq([nuRevisions lastObject],_uncommittedRevision);
    
    // Now update my public properties ... very carefully.
    [self willChangeValueForKey: @"currentRevision"];
    [self willChangeValueForKey: @"revisions"];
    _currentRevision = curRevNo>=0 ?[nuRevisions objectAtIndex: curRevNo] :nil;
    
    // Update parents of the uncommitted revision.
    // Needs to be done in this order to avoid triggering assertion failures. (See issue #147)
    _uncommittedRevision.parent2 = nil;
    _uncommittedRevision.parent = _currentRevision;
    if (curParent2>=0)
        _uncommittedRevision.parent2 = [nuRevisions objectAtIndex: curParent2];
    
    _headRevisions = nil;  // invalidate cache
    if (!$equal(nuRevisions,self.revisions))
        self.revisions = nuRevisions;
    [self didChangeValueForKey: @"revisions"];
    [self didChangeValueForKey: @"currentRevision"];
    // ...done updating public properties.

    [self _checkWorkingTree: &error];
    return YES;
}


/** Batch-loads the detail info of a range of revisions. */
- (BOOL) getDetailsOfRevisions: (NSRange)revNoRange {
    unsigned nRevisions = _revisions.count;
    if (nRevisions > 0 && [[_revisions lastObject] isUncommitted])
        nRevisions--;
    Assert(revNoRange.location < nRevisions, @"Invalid start revision");
    revNoRange.length = MIN(revNoRange.length, nRevisions - revNoRange.location);
    
    LogTo(HgRepository, @"Getting details of revisions [%u..%u]", 
            revNoRange.location, revNoRange.location+revNoRange.length-1);
    HgLogOperation *op = [[HgLogOperation alloc] initWithRepository: self 
                                                               file: nil 
                                                               mode: kHgLogModeFull];
    op.range = revNoRange;
    return [op run];
}


- (NSArray*) revisions
{
    if( ! _revisions ) {
        _revisions = [NSArray array];   // in case of re-entrant call during _checkRevisions!
        [self _checkRevisions];
    }
    return _revisions;
}

- (void) setRevisions: (NSArray*)revisions
{
    _revisions = [revisions copy];
}

- (HgRevision*) currentRevision
{
    if( ! _revisions )
        (void)self.revisions;
    return _currentRevision;
}

- (HgRevision*) tipRevision
{
    unsigned n = _revisions.count;
    if( n==0 )
        return nil;
    HgRevision *r = [self.revisions objectAtIndex: n-1];
    if( ! r.isUncommitted )
        return r;
    else if( n >= 2 )
        return [_revisions objectAtIndex: n-2];
    else
        return nil;
}

- (HgUncommittedRevision*) modifiedRevision
{
    if (_uncommittedRevision.root.isUncommitted)
        return _uncommittedRevision;
    else
        return nil;
}

- (BOOL) isUncommitted
{
    return _uncommittedRevision.root.isUncommitted;
}

- (HgRevision*) revisionWithID: (HgRevisionID)revID
{
    for( HgRevision *rev in self.revisions )
        if( HgEqualRevisionIDs(revID,rev.identifier) )
            return rev;
    return nil;
}

- (NSSet*) headRevisions {
    if (!_headRevisions) {
        // Find all committed revisions that are not parents.
        NSMutableSet* heads = [NSMutableSet setWithArray: _revisions];
        for (HgRevision *rev in _revisions) {
            if (rev.isUncommitted) {
                [heads removeObject: rev];
            } else {
                HgRevision* parent = rev.parent;
                if (parent)
                    [heads removeObject:parent];
                parent = rev.parent2;
                if (parent)
                    [heads removeObject:parent];
            }
        }
        _headRevisions = [heads copy];
        LogTo(HgRepository, @"heads = %@", heads);
    }
    return _headRevisions;
}

+ (NSArray*) keyPathsForValuesAffectingCurrentRevision      {return [NSArray arrayWithObject: @"revisions"];}
+ (NSArray*) keyPathsForValuesAffectingTipRevision          {return [NSArray arrayWithObject: @"revisions"];}
+ (NSArray*) keyPathsForValuesAffectingIsUncommitted        {return [NSArray arrayWithObject: @"revisions"];}
+ (NSArray*) keyPathsForValuesAffectingHeadRevisions        {return [NSArray arrayWithObject: @"revisions"];}

+ (NSArray*) keyPathsForValuesAffectingModifiedRevision {
    return $array(@"revisions", @"uncommittedRevision.root.isUncommitted");
}


- (NSArray*) revisionsOfFile: (HgFile*)file error: (NSError**)outError
{
    HgLogOperation *op = [[HgLogOperation alloc] initWithRepository: self 
                                                               file: file 
                                                               mode: kHgLogModeListRevs];
    if( ! [op run: outError] )
        return nil;
    NSIndexSet *revs = op.revisionNumbers;  //! Could cache this per file-path
    return [_revisions objectsAtIndexes: revs];
}


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


#pragma mark -
#pragma mark ACTIONS:


+ (HgOperation*) cloneRevision: (NSString*)revisionID
                       fromURL: (NSURL*)srcURL
                         toURL: (NSURL*)dstURL
                       options: (HgTransferOptions)options
{
    Assert(dstURL);
    if( dstURL.isFileURL ) {
        NSString *dstPath = dstURL.path;
        if( [[NSFileManager defaultManager] fileExistsAtPath: dstPath] ) {
            NSError *error;
            MYMiscError(&error, @"", 
                        NSLocalizedString(@"The path to clone into already exists",
                                          @"Error message for failed hg clone"));
            return [[HgOperation alloc] initWithError: error];
        }
        NSString *root = [[self class] findRootOf: dstPath localPath: NULL];
        if( root ) {
            NSError *error;
            MYMiscError(&error, NSLocalizedString(@"The path to clone into is already inside a Mercurial repository at %@",
                                                  @"Error message for failed hg clone"),
                        root);
            return [[HgOperation alloc] initWithError: error];
        }
    }
    
    NSMutableArray *args = [NSMutableArray arrayWithObjects: @"--", stringForURL(srcURL), stringForURL(dstURL), nil];
    if( !(options & kHgUpdateAfterwards) )
        [args insertObject: @"--noupdate" atIndex: 0];
    if( options & kHgNoHardLinks )
        [args insertObject: @"--pull" atIndex: 0];
    if( options & kHgUncompressed )
        [args insertObject: @"--uncompressed" atIndex: 0];
    if( revisionID ) {
        [args insertObject: @"--rev" atIndex: 0];
        [args insertObject: revisionID atIndex: 1];
    }
    return [[HgOperation alloc] initWithDirectory: nil
                                          command: @"clone"
                                        arguments: args];
}


- (HgOperation*) transferRevisions: (HgTransferOp)transferOp
                           options: (HgTransferOptions)options
                   otherRepository: (NSURL*)otherRepo
{
    if( transferOp==kHgClone )
        return [[self class] cloneRevision: nil
                                   fromURL: self.URL
                                     toURL: otherRepo
                                   options: options];
    
    NSString *cmd;
    NSMutableArray *args = [NSMutableArray arrayWithObject: stringForURL(otherRepo)];
    if( transferOp==kHgPull ) {
        cmd = @"pull";
        if( options & kHgUpdateAfterwards )
            [args insertObject: @"--update" atIndex: 0];
    } else {
        cmd = @"push";
        [self ignoreNextFileChanges];
    }
    if( options & kHgForceTransfer )
        [args insertObject: @"--force" atIndex: 0];

    return [[HgOperation alloc] initWithDirectory: self
                                          command: cmd
                                        arguments: args];
}


// common code shared between -update and -merge.
- (BOOL) updateOrMerge: (NSString*)command
              revision: (HgRevision*)rev     // nil means tip
                output: (NSString**)outOutput
                 error: (NSError**)outError
{
    NSArray *args = nil;
    if( rev ) {
        Assert(!rev.isUncommitted,@"Can't update/merge to uncommitted revision");
        args = [NSArray arrayWithObjects: @"--rev", rev.identifierString, nil];
    }
    HgOperation *op = [[HgOperation alloc] initWithDirectory: self
                                                     command: command
                                                   arguments: args];
    [self ignoreNextFileChanges];
    BOOL ok = [op run: outError];
    if( outOutput )
        *outOutput = op.outputAndError;
    [self _checkRevisions];
    return ok;
}

- (BOOL) updateToRevision: (HgRevision*)rev     // nil means tip
                   output: (NSString**)outOutput
                    error: (NSError**)outError {
    return [self updateOrMerge: @"update"  revision: rev output: outOutput error: outError];
}

- (BOOL) mergeWithRevision: (HgRevision*)withRevision 
                    output: (NSString**)outOutput
                     error: (NSError**)outError
{
    return [self updateOrMerge: @"merge" revision: withRevision output: outOutput error: outError];
}

- (BOOL) canMergeWithRevision: (HgRevision*)withRevision {
    if (_uncommittedRevision.parent2 != nil)
        return NO;                      // already in the middle of a merge
    if (_uncommittedRevision.root.status != kClean)
        return NO;                      // can't merge a dirty working tree
    if (withRevision) {
        // The revision must not be an ancestor of the current working tree.
        return withRevision != _uncommittedRevision
            && ! [_uncommittedRevision descendsFrom: withRevision];
    } else {
        // 'hg help merge' says: "If no revision is specified, the working directory's parent is a head
        // revision, and the current branchcontains exactly one other head, the other head is merged
        // with by default. Otherwise, an explicit revision with which to merge with must be provided."
        NSSet *heads = self.headRevisions;
        return heads.count == 2
            && [heads containsObject: _uncommittedRevision.parent];
    }
}


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