// // FreeTar // NSString_PathUtils.m // // Copyright (c) 2002 Murray M Johnson // // http://homepage.mac.com/mjsoftware/ // mjsoftware@mac.com // // // This file is part of FreeTar version 1.1. // // FreeTar is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // FreeTar is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with FreeTar; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #import "NSString_PathUtils.h" @implementation NSString(PathUtils) - (NSString*) pathRelativeTo:(NSString*)baseDir { NSArray* base_cmpnts; NSArray* self_cmpnts; NSMutableArray* output_cmpnts; int c; int start_c1; int start_c2; // split baseDir into it's components base_cmpnts = [baseDir pathComponents]; // split self into it's components self_cmpnts = [self pathComponents]; // allocate output components output_cmpnts = [NSMutableArray arrayWithCapacity:[self_cmpnts count]]; // figure out how many directories to back up: start_c1 = [base_cmpnts count] - 1; if([self_cmpnts count] - 2 < start_c1) start_c1 = [self_cmpnts count] - 2; start_c2 = 0; for(c = start_c1; c >= 0; --c) { if( (c >= [base_cmpnts count] && c < [self_cmpnts count]) || (c < [base_cmpnts count] && c >= [self_cmpnts count]) || (![[base_cmpnts objectAtIndex:c] isEqualToString:[self_cmpnts objectAtIndex:c]])) { // need to go back one directory [output_cmpnts addObject:@".."]; } else { // paths are the same at this index, we can stop // set start_c for next loop start_c2 = c + 1; // stop loop break; } } // now loop to add the forward directories for(c = start_c2; c < [self_cmpnts count]; ++c) { [output_cmpnts addObject:[self_cmpnts objectAtIndex:c]]; } return [NSString pathWithComponents:output_cmpnts]; } @end