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
|
#
# $Id: path.py,v 1.5 2001/11/25 14:13:39 doughellmann Exp $
#
# Copyright 2001 Doug Hellmann.
#
#
# All Rights Reserved
#
# Permission to use, copy, modify, and distribute this software and
# its documentation for any purpose and without fee is hereby
# granted, provided that the above copyright notice appear in all
# copies and that both that copyright notice and this permission
# notice appear in supporting documentation, and that the name of Doug
# Hellmann not be used in advertising or publicity pertaining to
# distribution of the software without specific, written prior
# permission.
#
# DOUG HELLMANN DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
# INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
# NO EVENT SHALL DOUG HELLMANN BE LIABLE FOR ANY SPECIAL, INDIRECT OR
# CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
# OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
"""Provide a common set of path management functions.
Many of the os.path functions are fronted by functions here to allow
for tracing and consistent use of those functions.
"""
__rcs_info__ = {
#
# Creation Information
#
'module_name' : '$RCSfile: path.py,v $',
'rcs_id' : '$Id: path.py,v 1.5 2001/11/25 14:13:39 doughellmann Exp $',
'creator' : 'Doug Hellmann <DougHellmann@bigfoot.com>',
'project' : 'UNSPECIFIED',
'created' : 'Sat, 03-Feb-2001 12:49:56 EST',
#
# Current Information
#
'author' : '$Author: doughellmann $',
'version' : '$Revision: 1.5 $',
'date' : '$Date: 2001/11/25 14:13:39 $',
}
try:
__version__ = __rcs_info__['version'].split(' ')[1]
except:
__version__ = '0.0'
#
# Import system modules
#
import string
import os
import sys
import glob
#
# Import Local modules
#
from happydoclib.StreamFlushTest import StreamFlushTest
#
# Module
#
def rmkdir(path):
"Create a directory and all of its children."
if not path:
return
parts = os.path.split(path)
if len(parts) > 1:
parent, child = parts
if not (os.path.isdir(parent) or os.path.islink(parent)):
rmkdir(parent)
if not (os.path.isdir(path) or os.path.islink(path)):
os.mkdir(path)
return
def applyPrefixToPath(path, prefix):
"Add the prefix value to every part of a given path."
parts = string.split( path, os.sep )
#print 'PARTS:', parts
prefix_len = len(prefix)
real_parts = []
for p in parts:
if not p:
pass
elif p not in ( '.', '..' ) and (p[:prefix_len] != prefix):
#print 'modifying "%s"' % p
p = '%s%s' % (prefix, p)
real_parts.append(p)
#print 'REAL PARTS:', real_parts
name = apply(os.path.join, real_parts)
if path and path[0] == os.sep:
name = os.sep + name
return name
def removePrefix(path, prefix):
"Remove prefix from the beginning of path, if present."
one_up = os.path.dirname(path)
common_prefix = commonPrefix(one_up, prefix)
#print 'PATH: removePrefix( %s, %s )' % (path, prefix)
#print 'PATH: common_prefix', common_prefix
if common_prefix == prefix:
path = path[len(common_prefix):]
while path and (path[0] == os.sep):
path = path[1:]
#print 'PATH: result', path
return path
def commonPrefix(path1, path2):
"""Find parts of path1 and path2 at the beginning of each which are the same.
Arguments
path1 -- A filesystem path.
path2 -- A filesystem path.
Returns a string containing the full path which occurs at the
beginning of both path1 and path2.
This function differs from os.path.commonprefix in that a part of
the path is considered the same only if the *full* directory or
subdirectory name matches.
"""
#print 'commonPrefix(%s, %s)' % (path1, path2)
if not path1 or not path2:
return ''
path1_parts = string.split(path1, os.sep)
path2_parts = string.split(path2, os.sep)
common = []
for p1, p2 in map(None, path1_parts, path2_parts):
if p1 == p2:
common.append(p1)
else:
break
common = string.join(common, os.sep)
if path1 and path1[0] == '/' and common and common[0] != '/':
common = '/' + common
#print '->"%s"' % common
return common
def joinWithCommonMiddle(path1prefix, path1, path2):
"""Join path1 and path2.
Arguments
path1prefix -- Beginning of path1 which should be ignored for
comparisons between path1 and path2.
path1 -- First path to join.
path2 -- Second path to join, may have part of path1 after
path1prefix.
This function is a bit weird. The result of::
joinWithCommonMiddle('/root/one', '/root/one/two', 'two/three/filename.txt')
is::
/root/one/two/three/filename.txt
"""
#
# Find the part of path1 which is *not* part of path1prefix
#
#print 'joinWithCommonMiddle(%s, %s, %s)' % (path1prefix, path1, path2)
common_prefix = commonPrefix(path1prefix, path1)
#print ' common prefix:', common_prefix
real_base = removePrefix(path1, common_prefix)
#print ' real base:', real_base
#
# Remove the prefix common to the docset_real_base and
# file_name.
#
common_prefix = commonPrefix(real_base, path2)
#print ' common prefix with real base and path2:', common_prefix
path2 = removePrefix(path2, common_prefix)
#print ' fixed path2:', path2
name = join( path1, path2 )
#print '->"%s"' % name
return name
def computeRelativeHTMLLink(fromName, toName, baseDirectory):
"""Compute the relative link between fromName and toName.
Parameters
'fromName' -- Named output node from which to compute the link.
'toName' -- Named output node to which link should point.
'baseDirectory' -- Name of the base directory in which both
fromName and toName will reside.
Both fromName and toName are strings refering to URL targets.
This method computes the relative positions of the two nodes
and returns a string which, if used as the HREF in a link in
fromName will point directly to toName.
"""
dbg=0
if dbg: print '\nPATH: FROM: ', fromName
if dbg: print 'PATH: TO : ', toName
if dbg: print 'PATH: BASE: ', baseDirectory
#
# Normalize directory names
#
fromName = os.path.normpath(fromName)
toName = os.path.normpath(toName)
if dbg: print 'PATH: FROM NORMALIZED : ', fromName
if dbg: print 'PATH: TO NORMALIZED : ', toName
#
# Remove the base directory prefix from both
#
fromName = removePrefix(fromName, baseDirectory)
toName = removePrefix(toName, baseDirectory)
if dbg: print 'PATH: FROM - PREFIX : ', fromName
if dbg: print 'PATH: TO - PREFIX : ', toName
if fromName == toName:
if dbg: print '\tPATH: same name'
relative_link = os.path.basename(toName)
else:
common_prefix = commonPrefix(os.path.dirname(fromName), os.path.dirname(toName))
from_name_no_prefix = fromName[len(common_prefix):]
while from_name_no_prefix and (from_name_no_prefix[0] == os.sep):
from_name_no_prefix = from_name_no_prefix[1:]
if dbg: print '\tPATH: from, no prefix:', from_name_no_prefix
if dbg and from_name_no_prefix == 'z.html':
raise 'debug'
subdir_path = os.path.dirname(from_name_no_prefix)
parts = string.split(subdir_path, os.sep)
if dbg: print '\tPATH: parts:', parts
if parts and parts[0]:
levels = len(string.split(subdir_path, os.sep))
else:
levels = 0
up_levels = (os.pardir + os.sep) * levels
to_name_no_prefix = toName[len(common_prefix):]
if to_name_no_prefix and (to_name_no_prefix[0] == os.sep):
to_name_no_prefix = to_name_no_prefix[1:]
relative_link = "%s%s" % (up_levels, to_name_no_prefix)
if dbg: print 'PATH: LINK: ', relative_link, '\n'
return relative_link
def findFilesInDir(directoryName, filenamePattern='*'):
"""Find all files in the directory which match the glob pattern.
Parameters
directoryName -- String containing the name of a directory on
the file system.
filenamePattern -- String containing a regular expression to be
used by the glob module for matching when looking for files in
'directoryName'.
"""
search_pat = os.path.join( directoryName, filenamePattern )
found = glob.glob( search_pat )
return found
def removeRelativePrefix(filename):
"""Remove './', '../', etc. from the front of filename.
Returns a new string, unless no changes are made.
"""
if filename and filename[0] in '.':
while filename and (filename[0] in './'):
filename = filename[1:]
return filename
##
## os.path functions
##
def join( *args ):
"os.path.join"
return apply(os.path.join, args)
def cwd():
"os.getcwd"
return os.getcwd()
def normpath( p ):
"os.path.normpath"
return os.path.normpath(p)
def isdir( f ):
"os.path.isdir"
return os.path.isdir(f)
def exists( f ):
"os.path.exists"
return os.path.exists(f)
def basename( f ):
"os.path.basename"
return os.path.basename(f)
def dirname( f ):
"os.path.dirname"
return os.path.dirname(f)
def splitext( f ):
"os.path.splitext"
return os.path.splitext(f)
def split( f ):
"os.path.split"
return os.path.split(f)
class PathTest(StreamFlushTest):
def testApplyPrefixToPath(self):
expected = '/BLAH_tmp/BLAH_foo'
actual = applyPrefixToPath('/tmp/foo', 'BLAH_')
assert actual == expected, \
'Path modification failed.\n\tExpected "%s",\n\tgot "%s"' \
% (expected, actual)
return
def testApplyPrefixToPathEmpty(self):
expected = ''
actual = applyPrefixToPath('', 'BLAH_')
assert actual == expected, \
'Path modification failed.\n\tExpected "%s",\n\tgot "%s"' \
% (expected, actual)
return
def testApplyPrefixToPathRelative(self):
expected = '../BLAH_tmp/BLAH_foo'
actual = applyPrefixToPath('../tmp/foo', 'BLAH_')
assert actual == expected, \
'Path modification failed.\n\tExpected "%s",\n\tgot "%s"' \
% (expected, actual)
return
def testRemovePrefix(self):
expected = 'foo'
actual = removePrefix('/tmp/foo', '/tmp')
assert actual == expected, \
'Path modification failed.\n\tExpected "%s",\n\tgot "%s"' \
% (expected, actual)
return
def testRemovePrefixNotThere(self):
expected = 'tmp/foo'
actual = removePrefix('/tmp/foo', '/blah')
assert actual == expected, \
'Path modification failed.\n\tExpected "%s",\n\tgot "%s"' \
% (expected, actual)
return
def testRemovePrefixEmptyPath(self):
expected = ''
actual = removePrefix('', '/blah')
assert actual == expected, \
'Path modification failed.\n\tExpected "%s",\n\tgot "%s"' \
% (expected, actual)
return
def testRemovePrefixEmptyPrefix(self):
expected = 'tmp/foo'
actual = removePrefix('/tmp/foo', '')
assert actual == expected, \
'Path modification failed.\n\tExpected "%s",\n\tgot "%s"' \
% (expected, actual)
return
def testCommonPrefix(self):
expected = '/tmp'
actual = commonPrefix('/tmp/foo', '/tmp/blah')
assert actual == expected, \
'Path modification failed.\n\tExpected "%s",\n\tgot "%s"' \
% (expected, actual)
return
def testCommonPrefixNone(self):
expected = ''
actual = commonPrefix('/var/tmp/foo', '/tmp/blah')
assert actual == expected, \
'Path modification failed.\n\tExpected "%s",\n\tgot "%s"' \
% (expected, actual)
return
def testCommonPrefixEmptyPaths(self):
expected = ''
actual = commonPrefix('', '/tmp/blah')
assert actual == expected, \
'Path modification failed.\n\tExpected "%s",\n\tgot "%s"' \
% (expected, actual)
expected = ''
actual = commonPrefix('/var/tmp/foo', '')
assert actual == expected, \
'Path modification failed.\n\tExpected "%s",\n\tgot "%s"' \
% (expected, actual)
return
def testJoinWithCommonMiddle(self):
expected = '/root/one/two/three/filename.txt'
actual = joinWithCommonMiddle('/root/one', '/root/one/two', 'two/three/filename.txt')
assert actual == expected, \
'Path modification failed.\n\tExpected "%s",\n\tgot "%s"' \
% (expected, actual)
return
def testJoinWithCommonMiddleNotCommon(self):
expected = '/root/one/four/two/three/filename.txt'
actual = joinWithCommonMiddle('/root/one/five', '/root/one/four', 'two/three/filename.txt')
assert actual == expected, \
'Path modification failed.\n\tExpected "%s",\n\tgot "%s"' \
% (expected, actual)
return
def testJoinWithCommonMiddleEmptyPrefix(self):
expected = '/root/one/four/two/three/filename.txt'
actual = joinWithCommonMiddle('', '/root/one/four', 'two/three/filename.txt')
assert actual == expected, \
'Path modification failed.\n\tExpected "%s",\n\tgot "%s"' \
% (expected, actual)
return
def testJoinWithCommonMiddleEmptyPath1(self):
expected = 'two/three/filename.txt'
actual = joinWithCommonMiddle('/root/one/five', '', 'two/three/filename.txt')
assert actual == expected, \
'Path modification failed.\n\tExpected "%s",\n\tgot "%s"' \
% (expected, actual)
return
def testJoinWithCommonMiddleEmptyPath2(self):
expected = '/root/one/two/'
actual = joinWithCommonMiddle('/root/one', '/root/one/two', '')
assert actual == expected, \
'Path modification failed.\n\tExpected "%s",\n\tgot "%s"' \
% (expected, actual)
return
def testComputeRelativeHTMLLink(self):
expected = 'my.gif'
actual = computeRelativeHTMLLink('index.html', 'my.gif', '/tmp/base/dir')
assert actual == expected, \
'Path modification failed.\n\tExpected "%s",\n\tgot "%s"' \
% (expected, actual)
return
def testComputeRelativeHTMLLinkUpOneDirectory(self):
expected = '../my.gif'
actual = computeRelativeHTMLLink('index.html', '../my.gif', '/tmp/base/dir')
assert actual == expected, \
'Path modification failed.\n\tExpected "%s",\n\tgot "%s"' \
% (expected, actual)
return
def testComputeRelativeHTMLLinkInParentDirectory(self):
expected = '../my.gif'
actual = computeRelativeHTMLLink('/tmp/base/dir/index.html',
'/tmp/base/my.gif',
'/tmp/base')
assert actual == expected, \
'Path modification failed.\n\tExpected "%s",\n\tgot "%s"' \
% (expected, actual)
return
def testRemoveRelativePrefixCurrentDir(self):
expected = 'foo'
actual = removeRelativePrefix('./foo')
assert actual == expected, \
'Path modification failed.\n\tExpected "%s",\n\tgot "%s"' \
% (expected, actual)
return
def testRemoveRelativePrefixParentDir(self):
expected = 'foo'
actual = removeRelativePrefix('../foo')
assert actual == expected, \
'Path modification failed.\n\tExpected "%s",\n\tgot "%s"' \
% (expected, actual)
return
def testJoin(self):
expected = os.path.join('tmp', 'foo')
actual = join('tmp', 'foo')
assert actual == expected, \
'Path modification failed.\n\tExpected "%s",\n\tgot "%s"' \
% (expected, actual)
return
|