blob: 6ea7edc263f6305c2dd091254368b9b580c98f2b [file] [log] [blame]
Tom Miller7c95d812010-10-11 11:50:52 -07001# Copyright (C) 2010 Google Inc.
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"""Utility functions for setup.py file(s)."""
16
17
18__author__ = 'tom.h.miller@gmail.com (Tom Miller)'
19
20
Joe Gregorio6429bf62011-03-01 22:53:21 -080021def get_missing_requirements(third_party_reqs ):
Tom Miller7c95d812010-10-11 11:50:52 -070022 """Return a list of missing third party packages."""
23 import sys
24
25 sys_path_original = sys.path[:]
26 # Remove the current directory from the list of paths to check when
27 # importing modules.
28 try:
29 # Sometimes it's represented by an empty string?
30 sys.path.remove('')
31 except ValueError:
32 import os.path
33 sys.path.remove(os.path.abspath(os.path.curdir))
34 missing_pkgs = []
Tom Miller7c95d812010-10-11 11:50:52 -070035 for pkg in third_party_reqs:
36 try:
37 __import__(pkg)
38 except ImportError:
39 missing_pkgs.append(pkg)
40 # JSON support gets its own special logic
41 try:
42 import_json(sys.path)
43 except ImportError:
44 missing_pkgs.append('simplejson')
45
46 sys.path = sys_path_original
47 return missing_pkgs
48
49
50def import_json(import_path=None):
51 """Return a package that will provide JSON support.
52
53 Args:
54 import_path: list Value to assing to sys.path before checking for packages.
55 Default None for default sys.path.
56 Return:
57 A package, one of 'json' (if running python 2.6),
58 'django.utils.simplejson' (if django is installed)
59 'simplejson' (if third party library simplejson is found)
60 Raises:
61 ImportError if none of those packages are found.
62 """
63 import sys
64 sys_path_orig = sys.path[:]
65 if import_path is not None:
66 sys.path = import_path
67
68 try:
69 # Should work for Python 2.6.
70 pkg = __import__('json')
71 except ImportError:
72 try:
73 pkg = __import__('django.utils').simplejson
74 except ImportError:
75 try:
76 pkg = __import__('simplejson')
77 except ImportError:
78 pkg = None
79
80 if import_path is not None:
81 sys.path = sys_path_orig
82 if pkg:
83 return pkg
84 else:
Joe Gregorio6429bf62011-03-01 22:53:21 -080085 raise ImportError('Cannot find json support')