blob: 79ee05186e155af11aa957cfb4a092cf802fb40e [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 Gregorio09aa3f52011-03-21 15:08:18 -040021def 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
Joe Gregorio09aa3f52011-03-21 15:08:18 -040033 try:
34 sys.path.remove(os.path.abspath(os.path.curdir))
35 except ValueError:
36 pass
Tom Miller7c95d812010-10-11 11:50:52 -070037 missing_pkgs = []
Tom Miller7c95d812010-10-11 11:50:52 -070038 for pkg in third_party_reqs:
39 try:
40 __import__(pkg)
41 except ImportError:
42 missing_pkgs.append(pkg)
43 # JSON support gets its own special logic
44 try:
45 import_json(sys.path)
46 except ImportError:
47 missing_pkgs.append('simplejson')
48
49 sys.path = sys_path_original
50 return missing_pkgs
51
52
53def import_json(import_path=None):
54 """Return a package that will provide JSON support.
55
56 Args:
57 import_path: list Value to assing to sys.path before checking for packages.
58 Default None for default sys.path.
59 Return:
60 A package, one of 'json' (if running python 2.6),
61 'django.utils.simplejson' (if django is installed)
62 'simplejson' (if third party library simplejson is found)
63 Raises:
64 ImportError if none of those packages are found.
65 """
66 import sys
67 sys_path_orig = sys.path[:]
68 if import_path is not None:
69 sys.path = import_path
70
71 try:
72 # Should work for Python 2.6.
73 pkg = __import__('json')
74 except ImportError:
75 try:
76 pkg = __import__('django.utils').simplejson
77 except ImportError:
78 try:
79 pkg = __import__('simplejson')
80 except ImportError:
81 pkg = None
82
83 if import_path is not None:
84 sys.path = sys_path_orig
85 if pkg:
86 return pkg
87 else:
Joe Gregorio6429bf62011-03-01 22:53:21 -080088 raise ImportError('Cannot find json support')