Removes redundant /.. elements in the path. Returns an empty path if the * specified path has a broken number of directories for its number of ..s */
| 315 | /** Removes redundant <dir>/.. elements in the path. Returns an empty path if the |
| 316 | * specified path has a broken number of directories for its number of ..s */ |
| 317 | std::string Path_Compact( const std::string & sRawPath, char slash ) |
| 318 | { |
| 319 | if( slash == 0 ) |
| 320 | slash = Path_GetSlash(); |
| 321 | |
| 322 | std::string sPath = Path_FixSlashes( sRawPath, slash ); |
| 323 | std::string sSlashString( 1, slash ); |
| 324 | |
| 325 | // strip out all /./ |
| 326 | for( std::string::size_type i = 0; (i + 3) < sPath.length(); ) |
| 327 | { |
| 328 | if( sPath[ i ] == slash && sPath[ i+1 ] == '.' && sPath[ i+2 ] == slash ) |
| 329 | { |
| 330 | sPath.replace( i, 3, sSlashString ); |
| 331 | } |
| 332 | else |
| 333 | { |
| 334 | ++i; |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | |
| 339 | // get rid of trailing /. but leave the path separator |
| 340 | if( sPath.length() > 2 ) |
| 341 | { |
| 342 | std::string::size_type len = sPath.length(); |
| 343 | if( sPath[ len-1 ] == '.' && sPath[ len-2 ] == slash ) |
| 344 | { |
| 345 | // sPath.pop_back(); |
| 346 | sPath[len-1] = 0; // for now, at least |
| 347 | } |
| 348 | } |
| 349 | |
| 350 | // get rid of leading ./ |
| 351 | if( sPath.length() > 2 ) |
| 352 | { |
| 353 | if( sPath[ 0 ] == '.' && sPath[ 1 ] == slash ) |
| 354 | { |
| 355 | sPath.replace( 0, 2, "" ); |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | // each time we encounter .. back up until we've found the previous directory name |
| 360 | // then get rid of both |
| 361 | std::string::size_type i = 0; |
| 362 | while( i < sPath.length() ) |
| 363 | { |
| 364 | if( i > 0 && sPath.length() - i >= 2 |
| 365 | && sPath[i] == '.' |
| 366 | && sPath[i+1] == '.' |
| 367 | && ( i + 2 == sPath.length() || sPath[ i+2 ] == slash ) |
| 368 | && sPath[ i-1 ] == slash ) |
| 369 | { |
| 370 | // check if we've hit the start of the string and have a bogus path |
| 371 | if( i == 1 ) |
| 372 | return ""; |
| 373 | |
| 374 | // find the separator before i-1 |
no test coverage detected