d218d3d076f2d0a4d60dd23e88d2163e84e5a2a3
[openvswitch] / python / ovs / util.py
1 # Copyright (c) 2010, 2011 Nicira Networks
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at:
6 #
7 #     http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 import os
16 import os.path
17 import sys
18
19 PROGRAM_NAME = os.path.basename(sys.argv[0])
20
21 def abs_file_name(dir_, file_name):
22     """If 'file_name' starts with '/', returns a copy of 'file_name'.
23     Otherwise, returns an absolute path to 'file_name' considering it relative
24     to 'dir_', which itself must be absolute.  'dir_' may be None or the empty
25     string, in which case the current working directory is used.
26
27     Returns None if 'dir_' is None and getcwd() fails.
28
29     This differs from os.path.abspath() in that it will never change the
30     meaning of a file name."""
31     if file_name.startswith('/'):
32         return file_name
33     else:
34         if dir_ is None or dir_ == "":
35             try:
36                 dir_ = os.getcwd()
37             except OSError:
38                 return None
39
40         if dir_.endswith('/'):
41             return dir_ + file_name
42         else:
43             return "%s/%s" % (dir_, file_name)