pip-pop源码分析

pip-pop源码分析

项目相关

项目地址:https://github.com/kennethreitz/pip-pop.git
文件内容:

|+---bin
| pip-diff
| pip-grep
|LICENSE (就是项目遵守的协议,看了下是MIT协议。
|README.rst (相当于README.md|requirements.txt (依赖包
|setup.py (安装脚本

相关库:

docopt    命令行参数分析库

源码

setup.py

"""
pip-pop manages your requirements files.
"""
import sys
from setuptools import setup
setup(
    name='pip-pop', 
    version='0.1.0',
    url='https://github.com/kennethreitz/pip-pop';,
    license='MIT', 
    author='Kenneth Reitz',
    author_email='[email protected]',
    description=__doc__.strip('\n'),
    #packages=[],
    scripts=['bin/pip-diff', 'bin/pip-grep'],
    #include_package_data=True,
    zip_safe=False,
    platforms='any', #全平台
    install_requires=['docopt', 'pip>=1.5.0'], #项目的安装使用要求
    tests_require=['tox'],
    classifiers=[
        # As from https://pypi.python.org/pypi?%3Aaction=list_classifiers
        #'Development Status :: 1 - Planning',
        #'Development Status :: 2 - Pre-Alpha',
        #'Development Status :: 3 - Alpha',
        'Development Status :: 4 - Beta',
        #'Development Status :: 5 - Production/Stable',
        #'Development Status :: 6 - Mature',
        #'Development Status :: 7 - Inactive',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: Implementation :: CPython',
        'Programming Language :: Python :: Implementation :: PyPy',
        'Intended Audience :: Developers',
        'Intended Audience :: System Administrators',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Topic :: System :: Systems Administration',
    ]
)

pip.grep

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Usage:
  pip-grep [-s]  ...
Options:
  -h --help     Show this screen.
"""
import os
from docopt import docopt
from pip.req import parse_requirements
from pip.index import PackageFinder
from pip._vendor.requests import session

requests = session()

class Requirements(object):
    def __init__(self, reqfile=None):
        super(Requirements, self).__init__()
        self.path = reqfile #文件路径
        self.requirements = []
        if reqfile:
            self.load(reqfile) #获取文件中信息

    def __repr__(self):
        return ''.format(self.path)

    def load(self, reqfile):
        if not os.path.exists(reqfile): #文件不存在
            raise ValueError('The given requirements file does not exist.')
        finder = PackageFinder([], [], session=requests) #
        for requirement in parse_requirements(reqfile, finder=finder, session=requests): #文件中的每一行信息以及来源 是键值对
            if requirement.req: #文件中的每一行信息
                if not getattr(requirement.req, 'name', None):
                    # Prior to pip 8.1.2 the attribute `name` did not exist.
                    requirement.req.name = requirement.req.project_name 
                self.requirements.append(requirement.req) #将文件中每一行信息都append到列表中
def grep(reqfile, packages, silent=False):
    try:
        r = Requirements(reqfile) 
    except ValueError:
        if not silent:
            print('There was a problem loading the given requirement file.')
        exit(os.EX_NOINPUT)
    for req in r.requirements: #得到文件中每一行的信息
        if req.name in packages: #和命令行中输入的packages字段进行对照
            if not silent:
                print('Package {} found!'.format(req.name)) #说明要查找的字段存在,也就是package存在
            exit(0)
    if not silent:
        print('Not found.')
    exit(1)

def main():
    args = docopt(__doc__, version='pip-grep') #获取命令行的输入信息
    kwargs = {'reqfile': args[''], 'packages': args[''], 'silent': args['-s']} #定义一个字典保存命令行输入的信息
    grep(**kwargs) #按照命令行信息处理reqfile

if __name__ == '__main__':
    main()

pip-diff

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Usage:
  pip-diff (--fresh | --stale)   [--exclude ...]
  pip-diff (-h | --help)
Options:
  -h --help     Show this screen.
  --fresh       List newly added packages.
  --stale       List removed packages.
"""
import os
from docopt import docopt
from pip.req import parse_requirements
from pip.index import PackageFinder
from pip._vendor.requests import session

requests = session()

class Requirements(object):
    def __init__(self, reqfile=None):
        super(Requirements, self).__init__()
        self.path = reqfile
        self.requirements = []
        if reqfile:
            self.load(reqfile)
    def __repr__(self):
        return ''.format(self.path)
    def load(self, reqfile):
        if not os.path.exists(reqfile):
            raise ValueError('The given requirements file does not exist.')
        finder = PackageFinder([], [], session=requests)
        for requirement in parse_requirements(reqfile, finder=finder, session=requests):
            if requirement.req:
                if not getattr(requirement.req, 'name', None):
                    # Prior to pip 8.1.2 the attribute `name` did not exist.
                    requirement.req.name = requirement.req.project_name
                self.requirements.append(requirement.req)
    def diff(self, requirements, ignore_versions=False, excludes=None):
        r1 = self
        r2 = requirements
        results = {'fresh': [], 'stale': []}
        # Generate fresh packages.
        other_reqs = (
            [r.name for r in r1.requirements]
            if ignore_versions else r1.requirements
        )
        for req in r2.requirements:
            r = req.name if ignore_versions else req
            if r not in other_reqs and r not in excludes:
                results['fresh'].append(req) #r2中不在r1中的添加
        # Generate stale packages.
        other_reqs = (
            [r.name for r in r2.requirements]
            if ignore_versions else r2.requirements
        )
        for req in r1.requirements:
            r = req.name if ignore_versions else req
            if r not in other_reqs and r not in excludes:
                results['stale'].append(req) #在r1中不在r2中的添加
        return results
def diff(r1, r2, include_fresh=False, include_stale=False, excludes=None):
    include_versions = True if include_stale else False
    excludes = excludes if len(excludes) else []
    try:
        r1 = Requirements(r1) #将文件r1中的信息按行添加到r1对象的requirements中
        r2 = Requirements(r2)
    except ValueError:
        print('There was a problem loading the given requirements files.')
        exit(os.EX_NOINPUT)
    results = r1.diff(r2, ignore_versions=True, excludes=excludes)

    if include_fresh:
        for line in results['fresh']:
            print(line.name if include_versions else line)
    if include_stale:
        for line in results['stale']:
            print(line.name if include_versions else line)
def main():
    args = docopt(__doc__, version='pip-diff')
    kwargs = { #分解命令行信息
        'r1': args[''],
        'r2': args[''],
        'include_fresh': args['--fresh'],
        'include_stale': args['--stale'],
        'excludes': args['']
    }
    diff(**kwargs) 
if __name__ == '__main__':
    main()

你可能感兴趣的:(杂项)