Source

Murky with Sparkle / 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
//
//  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;
        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 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: %@", event.path);
    if( _changedPaths.count==0 )
        [self performSelector: @selector(_updateChangedDirs) withObject: nil afterDelay: 0.25];
	
	if(path != nil) {
		[_changedPaths addObject: path];
	}
}
    

- (void) _updateChangedDirs
{
    LogTo(HgRepository, @"Updating changed dirs %@",[[_changedPaths allObjects] componentsJoinedByString: @", "]);
    NSSet *changedPaths = _changedPaths;
    _changedPaths = [NSMutableSet set];
    
    if( [changedPaths containsObject: @".hg/"] )
        if( [self _checkRevisions] )                   // 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( ! [self _checkRevisions] )
        [self _checkWorkingTree: outError];
    return YES;
}


#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: @","];
}    


- (int) _getTip
{
    NSArray *revs = [self _getRevNumbers: @"tip"];
    if( revs.count > 1 )
        return [[revs objectAtIndex: 0] intValue];
    else
        return -1;
}


- (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<0 )
        return NO;
    
    int curTip = _revisions.count>0 ?self.tipRevision.localNumber :-1;
    if( tip != curTip ) {
        // Revisions have changed!
        LogTo(HgRepository,@"Tip changed from %i to %i ... updating revisions", curTip,tip);

        // 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] )
            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 if any:
        NSMutableArray *nuRevisions = [_revisions mutableCopy];
        [nuRevisions removeObject: _uncommittedRevision];
        [nuRevisions addObjectsFromArray: op.revisions];
        [nuRevisions addObject: _uncommittedRevision];
        
        _currentRevision = [nuRevisions objectAtIndex: curRevNo];
        _uncommittedRevision.parent = _currentRevision;
        _uncommittedRevision.parent2 = curParent2>=0 ?[nuRevisions objectAtIndex: curParent2] :nil;
                
        self.revisions = nuRevisions;
        
        [self _checkWorkingTree: &error];
        return YES;
        
    } else if( curRevNo != _uncommittedRevision.parent.localNumber || curParent2 != parent2) {
        // A different revision is current; or the parents have changed
        [self willChangeValueForKey: @"revisions"];
        _currentRevision = [_revisions objectAtIndex: curRevNo];
        _uncommittedRevision.parent = _currentRevision;
        _uncommittedRevision.parent2 = curParent2>=0 ?[_revisions objectAtIndex: curParent2] :nil;
        [self didChangeValueForKey: @"revisions"];
        [self _checkWorkingTree: &error];
        return YES;
    }
    return NO;
}


/** 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;
}

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


- (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] )
            return [[HgOperation alloc] initWithError: @"The path to clone into already exists"];
        NSString *root = [[self class] findRootOf: dstPath localPath: NULL];
        if( root ) {
            NSError *error;
            MYMiscError(&error, @"The path to clone into is already inside a Mercurial repository at %@",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];
}


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


@end