Skip to content
This repository
Browse code

Migrated from argparse to argh (a high-level wrapper)

  • Loading branch information...
commit a201de1d70536e7e4637a6079f03174b7b493ffa 1 parent 4c44bf8
Michele Lacchia authored April 07, 2011
126  pyg/__init__.py
... ...
@@ -1,5 +1,6 @@
1 1
 import os
2 2
 import sys
  3
+import urllib2
3 4
 
4 5
 import _opts as opts
5 6
 from .types import PygError, InstallationError, AlreadyInstalled
@@ -9,78 +10,83 @@
9 10
 
10 11
 
11 12
 def _set_up():
12  
-    import argparse
  13
+    from argh import ArghParser, arg, command
13 14
 
14  
-    parser = argparse.ArgumentParser(prog='pyg')
  15
+    parser = ArghParser(prog='pyg')
15 16
     parser.add_argument('-v', '--version', action='version', version=__version__)
16  
-    sub = parser.add_subparsers()
17  
-    
18  
-    sub_inst = sub.add_parser('install')
19  
-    sub_inst.add_argument('packname')
20  
-    sub_inst.add_argument('-r', '--req-file', action='store_true', help='Install packages from the specified requirement file')
21  
-    sub_inst.add_argument('-f', '--file', action='store_true', help='Do not download the package but use the local file')
22  
-    sub_inst.add_argument('-u', '--upgrade', action='store_true', help='If the package is already installed')
23  
-    sub_inst.add_argument('-n', '--no-deps', action='store_true', help='Do not install dependencies')
24  
-    sub_inst.add_argument('-i', '--index-url', default='http://pypi.python.org/pypi', metavar='<url>', help='Base URL of Python Package Index (default to %(default)s)')
25  
-    sub_inst.add_argument('-b', '--install-base', metavar='<path>', help='Base installation directory')
26  
-    sub_inst.add_argument('--user', action='store_true', help='Install to user site')
27  
-    sub_inst.set_defaults(func=opts.install_func)
28  
-
29  
-    sub_un = sub.add_parser('uninstall')
30  
-    sub_un.add_argument('packname', nargs='+')
31  
-    sub_un.add_argument('-r', '--req-file', metavar='<path>', help='Uninstall all the packages listed in the given requirement file')
32  
-    sub_un.add_argument('-y', '--yes', action='store_true', help='Do not ask confirmation of uninstall deletions')
33  
-    sub_un.set_defaults(func=opts.uninst_func)
34  
-
35  
-    sub_rm = sub.add_parser('rm')
36  
-    sub_rm.add_argument('packname', nargs='+')
37  
-    sub_rm.add_argument('-r', '--req-file', metavar='<path>', help='Uninstall all the packages listed in the given requirement file')
38  
-    sub_rm.add_argument('-y', '--yes', action='store_true', help='Do not ask confirmation of uninstall deletions')
39  
-    sub_rm.set_defaults(func=opts.uninst_func)
  17
+
  18
+
  19
+    @ arg('packname')
  20
+    @ arg('-r', '--req-file', action='store_true', help='Install packages from the specified requirement file')
  21
+    @ arg('-f', '--file', action='store_true', help='Do not download the package but use the local file')
  22
+    @ arg('-u', '--upgrade', action='store_true', help='If the package is already installed')
  23
+    @ arg('-n', '--no-deps', action='store_true', help='Do not install dependencies')
  24
+    @ arg('-i', '--index-url', default='http://pypi.python.org/pypi', metavar='<url>', help='Base URL of Python Package Index (default to %(default)s)')
  25
+    @ arg('-b', '--install-base', metavar='<path>', help='Base installation directory')
  26
+    @ arg('--user', action='store_true', help='Install to user site')
  27
+    def install(args):
  28
+        opts.install_func(args)
  29
+
  30
+    @ arg('packname', nargs='+')
  31
+    @ arg('-r', '--req-file', metavar='<path>', help='Uninstall all the packages listed in the given requirement file')
  32
+    @ arg('-y', '--yes', action='store_true', help='Do not ask confirmation of uninstall deletions')
  33
+    def uninstall(args):
  34
+        opts.uninst_func(args)
  35
+
  36
+    @ arg('packname', nargs='+')
  37
+    @ arg('-r', '--req-file', metavar='<path>', help='Uninstall all the packages listed in the given requirement file')
  38
+    @ arg('-y', '--yes', action='store_true', help='Do not ask confirmation of uninstall deletions')
  39
+    def rm(args):
  40
+        uninstall(args)
40 41
     
41  
-    sub_list = sub.add_parser('list')
42  
-    sub_list.add_argument('packname')
43  
-    sub_list.set_defaults(func=opts.list_func)
44  
-
45  
-    sub_fr = sub.add_parser('freeze')
46  
-    sub_fr.add_argument('-c', '--count', action='store_true', help='Only returns requirements count')
47  
-    sub_fr.add_argument('-f', '--file', metavar='<path>', help='Writes requirements into the specified file')
48  
-    sub_fr.set_defaults(func=opts.freeze_func)
49  
-
50  
-    sub_ln = sub.add_parser('link')
51  
-    sub_ln.add_argument('path')
52  
-    sub_ln.set_defaults(func=opts.link_func)
53  
-
54  
-    sub_uln = sub.add_parser('unlink')
55  
-    sub_uln.add_argument('path', nargs='?')
56  
-    sub_uln.add_argument('-a', '--all', action='store_true', help='Remove all links')
57  
-    sub_uln.set_defaults(func=opts.unlink_func)
58  
-
59  
-    sub_search = sub.add_parser('search')
60  
-    sub_search.add_argument('packname')
61  
-    sub_search.set_defaults(func=opts.search_func)
62  
-
63  
-    sub_ck = sub.add_parser('check')
64  
-    sub_ck.add_argument('packname')
65  
-    sub_ck.set_defaults(func=opts.check_func)
66  
-
67  
-    sub_down = sub.add_parser('download')
68  
-    sub_down.add_argument('packname')
69  
-    sub_down.add_argument('-u', '--unpack', action='store_true', help='Once downloaded, unpack the package')
70  
-    sub_down.add_argument('-d', '--download-dir', default='.', metavar='<path>', help='The destination directory')
71  
-    sub_down.add_argument('-p', '--prefer', metavar='<ext>', help='The preferred file type for the download')
72  
-    sub_down.set_defaults(func=opts.download_func)
  42
+    @ command
  43
+    def list(packname):
  44
+        opts.list_func(packname)
  45
+
  46
+    @ arg('-c', '--count', action='store_true', help='Only returns requirements count')
  47
+    @ arg('-f', '--file', metavar='<path>', help='Writes requirements into the specified file')
  48
+    def freeze(args):
  49
+        opts.freeze_func(args)
  50
+
  51
+    @ command
  52
+    def link(path):
  53
+        opts.link_func(path)
  54
+
  55
+    @ arg('path', nargs='?')
  56
+    @ arg('-a', '--all', action='store_true', help='Remove all links')
  57
+    def unlink(args):
  58
+        opts.unlink_func(args)
  59
+
  60
+    @ command
  61
+    def search(packname):
  62
+        opts.search_func(packname)
  63
+
  64
+    @ command
  65
+    def check(packname):
  66
+        opts.check_func(packname)
  67
+
  68
+    @ arg('packname')
  69
+    @ arg('-u', '--unpack', action='store_true', help='Once downloaded, unpack the package')
  70
+    @ arg('-d', '--download-dir', default='.', metavar='<path>', help='The destination directory')
  71
+    @ arg('-p', '--prefer', metavar='<ext>', help='The preferred file type for the download')
  72
+    def download(args):
  73
+        opts.download_func(args)
  74
+
  75
+    parser.add_commands([install, uninstall, rm, list, freeze, link, unlink, list, search, check, download])
73 76
     return parser
74 77
 
75 78
 def main():
76 79
     try:
77 80
         parser = _set_up()
78  
-        args = parser.parse_args()
79  
-        args.func(args)
  81
+        args = parser.dispatch()
80 82
     except (PygError, InstallationError):
81 83
         sys.exit(1)
82 84
     except AlreadyInstalled:
83 85
         sys.exit(0)
  86
+    except urllib2.HTTPError as e:
  87
+        sys.exit(e.msg)
  88
+    except urllib2.URLError as e:
  89
+        sys.exit('urllib error: {0}'.format(e.reason))
84 90
     sys.exit(0)
85 91
 
86 92
 if __name__ == '__main__':
17  pyg/_opts.py
@@ -97,16 +97,16 @@ def uninst_func(args):
97 97
         except PygError:
98 98
             continue
99 99
 
100  
-def link_func(args):
101  
-    return link(args.path)
  100
+def link_func(path):
  101
+    return link(path)
102 102
 
103 103
 def unlink_func(args):
104 104
     if args.all:
105  
-        return os.remove(pyg_links())
  105
+        return os.remove(PYG_LINKS)
106 106
     return unlink(args.path)
107 107
 
108  
-def check_func(args):
109  
-    return sys.stdout.write(str(is_installed(args.packname)) + '\n')
  108
+def check_func(name):
  109
+    return sys.stdout.write(str(is_installed(name)) + '\n')
110 110
 
111 111
 def freeze_func(args):
112 112
     f = freeze()
@@ -119,9 +119,8 @@ def freeze_func(args):
119 119
             req_file.write(f)
120 120
     return sys.stdout.write(f)
121 121
 
122  
-def list_func(args):
  122
+def list_func(name):
123 123
     res = []
124  
-    name = args.packname
125 124
     versions = PyPI().package_releases(name, True)
126 125
     if not versions:
127 126
         versions = map(str, sorted(WebManager.versions_from_html(name), reverse=True))
@@ -132,8 +131,8 @@ def list_func(args):
132 131
             res.append(v)
133 132
     return sys.stdout.write('\n'.join(res) + '\n')
134 133
 
135  
-def search_func(args):
136  
-    res = PyPI().search({'name': args.packname})
  134
+def search_func(name):
  135
+    res = PyPI().search({'name': name})
137 136
     return sys.stdout.write('\n'.join('{name}  {version} - {summary}'.format(**i) for i in \
138 137
                             sorted(res, key=lambda i: i['_pypi_ordering'], reverse=True)) + '\n')
139 138
 
1  pyg/req.py
@@ -24,6 +24,7 @@ class Requirement(object):
24 24
              '>': operator.gt,
25 25
              '<=': operator.le,
26 26
              '<': operator.lt,
  27
+             '!=': lambda a,b: a != b,
27 28
              None: lambda a,b: True
28 29
              }
29 30
 
18  pyg/types.py
@@ -3,13 +3,19 @@
3 3
 import sys
4 4
 import tarfile
5 5
 import pkg_resources
  6
+from StringIO import StringIO
6 7
 
  8
+from pkgtools.pkg import Egg as EggTools
7 9
 from .scripts import script_args
8 10
 from .locations import EASY_INSTALL, INSTALL_DIR, BIN
9 11
 from .utils import TempDir, ZipFile, call_setup, name_from_egg, glob, ext
10 12
 from .log import logger
11 13
 
12 14
 
  15
+class i(StringIO):
  16
+    def fileno(self):
  17
+        pass
  18
+
13 19
 ## A generic error thrown by Pyg
14 20
 class PygError(Exception):
15 21
     pass
@@ -156,12 +162,6 @@ def install(self):
156 162
             ## When using this file for the first time
157 163
             except IndexError:
158 164
                 pass
159  
-        try:
160  
-            with open(os.path.join(eggpath, 'EGG-INFO', 'requires.txt')) as f:
161  
-                for line in f:
162  
-                    self.reqset.add(line.strip())
163  
-        except IOError:
164  
-            pass
165 165
         dist = pkg_resources.get_distribution(self.packname)
166 166
         for name, content, mode in script_args(dist):
167 167
             logger.info('Installing {0} script to {1}', name, BIN)
@@ -169,6 +169,12 @@ def install(self):
169 169
             with open(target, 'w' + mode) as f:
170 170
                 f.write(content)
171 171
                 os.chmod(target, 0755)
  172
+        with TempDir() as tempdir:
  173
+            try:
  174
+                for req in EggTools(self.fobj, tempdir).file('requires.txt'):
  175
+                    self.reqset.add(req)
  176
+            except KeyError:
  177
+                logger.debug('requires.txt not found')
172 178
 
173 179
 
174 180
 class Archive(object):
2  pyg/utils.py
@@ -41,6 +41,8 @@ def link(path):
41 41
     if not os.path.exists(path):
42 42
         logger.error('{0} does not exist', path)
43 43
     if not os.path.exists(PYG_LINKS):
  44
+        if not os.path.exists(os.path.dirname(PYG_LINKS)):
  45
+            os.makedirs(os.path.dirname(PYG_LINKS))
44 46
         open(PYG_LINKS, 'w').close()
45 47
     path = os.path.abspath(path)
46 48
     logger.info('Linking {0} in {1}...', path, PYG_LINKS)
10  pyg/web.py
... ...
@@ -1,30 +1,26 @@
1 1
 import re
2 2
 import os
3 3
 import urllib2
4  
-import xmlrpclib
5 4
 
  5
+from pkgtools.pypi import PyPI
6 6
 from .types import PygError, Version, args_manager
7 7
 from .utils import FileMapper, ext, right_egg, version_egg
8 8
 from .log import logger
9 9
 
10 10
 
11  
-__all__ = ['WebManager', 'PackageManager', 'PyPI', 'PREFERENCES']
  11
+__all__ = ['WebManager', 'PackageManager', 'PREFERENCES']
12 12
 
13 13
 
14 14
 ## This constants holds files priority
15 15
 PREFERENCES = ('.egg', '.tar.gz', '.tar.bz2', '.zip')
16 16
 
17 17
 
18  
-def PyPI(index_url='http://pypi.python.org/pypi'):
19  
-    return xmlrpclib.ServerProxy(index_url, xmlrpclib.Transport())
20  
-
21  
-
22 18
 class WebManager(object):
23 19
 
24 20
     _versions_re = r'{0}-(\d+\.?(?:\d\.?|\d\w)*)-?.*'
25 21
 
26 22
     def __init__(self, req):
27  
-        self.pypi = PyPI(args_manager['index_url'])
  23
+        self.pypi = PyPI(index_url=args_manager['index_url'])
28 24
         self.req = req
29 25
         self.name = self.req.name
30 26
         self.versions = None
2  setup.py
@@ -3,7 +3,7 @@
3 3
 from setuptools import setup, find_packages
4 4
 
5 5
 
6  
-requires = ['setuptools']
  6
+requires = ['setuptools', 'pkgtools']
7 7
 try:
8 8
     import argparse
9 9
 except ImportError:

0 notes on commit a201de1

Please sign in to comment.
Something went wrong with that request. Please try again.