Blame SOURCES/nodejs.req

11ce9e
#!/usr/bin/python
11ce9e
11ce9e
"""
11ce9e
Automatic dependency generator for Node.js libraries.
11ce9e
11ce9e
Parsed from package.json.  See `man npm-json` for details.
11ce9e
"""
11ce9e
11ce9e
# Copyright 2012, 2013 T.C. Hollingsworth <tchollingsworth@gmail.com>
11ce9e
#
11ce9e
# Permission is hereby granted, free of charge, to any person obtaining a copy
11ce9e
# of this software and associated documentation files (the "Software"), to
11ce9e
# deal in the Software without restriction, including without limitation the
11ce9e
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
11ce9e
# sell copies of the Software, and to permit persons to whom the Software is
11ce9e
# furnished to do so, subject to the following conditions:
11ce9e
#
11ce9e
# The above copyright notice and this permission notice shall be included in
11ce9e
# all copies or substantial portions of the Software.
11ce9e
# 
11ce9e
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
11ce9e
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
11ce9e
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
11ce9e
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
11ce9e
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
11ce9e
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
11ce9e
# IN THE SOFTWARE.
11ce9e
11ce9e
from __future__ import unicode_literals
11ce9e
import json
11ce9e
import os
11ce9e
import re
11ce9e
import subprocess
11ce9e
import sys
11ce9e
11ce9e
RE_VERSION = re.compile(r'\s*v?([<>=~^]{0,2})\s*([0-9][0-9\.\-]*)\s*')
11ce9e
11ce9e
def main():
11ce9e
    #npm2rpm uses functions here to write BuildRequires so don't print anything
11ce9e
    #until the very end
11ce9e
    deps = []
11ce9e
11ce9e
    #it's highly unlikely that we'll ever get more than one file but we handle
11ce9e
    #this like all RPM automatic dependency generation scripts anyway
11ce9e
    paths = [path.rstrip() for path in sys.stdin.readlines()]
11ce9e
11ce9e
    for path in paths:
11ce9e
        if not path.endswith('package.json'):
11ce9e
            continue
11ce9e
11ce9e
        # we only want the package.json in the toplevel module directory
11ce9e
        pathparts = path.split(os.sep)
11ce9e
        if not pathparts[-5:-2] == ['usr', 'lib', 'node_modules']:
11ce9e
            continue
11ce9e
        
11ce9e
        fh = open(path)
11ce9e
        metadata = json.load(fh)
11ce9e
        fh.close()
11ce9e
11ce9e
        #write out the node.js interpreter dependency
11ce9e
        req = 'rh-nodejs4-nodejs(engine)'
11ce9e
11ce9e
        if 'engines' in metadata and isinstance(metadata['engines'], dict) \
11ce9e
                                            and 'node' in metadata['engines']:
11ce9e
            deps += process_dep(req, metadata['engines']['node'])
11ce9e
        else:
11ce9e
            deps.append(req)
11ce9e
11ce9e
        if 'dependencies' in metadata:
11ce9e
            if isinstance(metadata['dependencies'], dict):
11ce9e
                for name, version in metadata['dependencies'].iteritems():
11ce9e
                    req = 'rh-nodejs4-npm(' + name + ')'
11ce9e
                    deps += process_dep(req, version)
11ce9e
            elif isinstance(metadata['dependencies'], list):
11ce9e
                for name in metadata['dependencies']:
11ce9e
                    req = 'rh-nodejs4-npm(' + name + ')'
11ce9e
                    deps.append(req)
11ce9e
            elif isinstance(metadata['dependencies'], basestring):
11ce9e
                req = 'rh-nodejs4-npm(' + metadata['dependencies'] + ')'
11ce9e
                deps.append(req)
11ce9e
            else:
11ce9e
                raise TypeError('invalid package.json: dependencies not a valid type')
11ce9e
11ce9e
    print '\n'.join(deps)
11ce9e
    
11ce9e
    # invoke the regular RPM requires generator                
11ce9e
    p = subprocess.Popen(['/usr/lib/rpm/find-requires'], stdout=subprocess.PIPE, stdin=subprocess.PIPE)
11ce9e
    print p.communicate(input='\n'.join(paths))[0]
11ce9e
11ce9e
def process_dep(req, version):
11ce9e
    """Converts an individual npm dependency into RPM dependencies"""
11ce9e
    
11ce9e
    deps = []
11ce9e
    
11ce9e
    #there's no way RPM can do anything like an OR dependency
11ce9e
    if '||' in version:
11ce9e
        sys.stderr.write("WARNING: The {0} dependency contains an ".format(req) +
11ce9e
            "OR (||) dependency: '{0}.\nPlease manually include ".format(version) +
11ce9e
            "a versioned dependency in your spec file if necessary")
11ce9e
        deps.append(req)
11ce9e
            
11ce9e
    elif ' - ' in version:
11ce9e
        gt, lt = version.split(' - ')
11ce9e
        deps.append(req + ' >= ' + gt)
11ce9e
        deps.append(req + ' <= ' + lt)
11ce9e
        
11ce9e
    else:
11ce9e
        m = re.match(RE_VERSION, version)
11ce9e
11ce9e
        if m:
11ce9e
            deps += convert_dep(req, m.group(1), m.group(2))
11ce9e
11ce9e
            #There could be up to two versions here (e.g.">1.0 <3.1")
11ce9e
            if len(version) > m.end():
11ce9e
                m = re.match(RE_VERSION, version[m.end():])
11ce9e
11ce9e
                if m:
11ce9e
                    deps += convert_dep(req, m.group(1), m.group(2))
11ce9e
        else:
11ce9e
            deps.append(req)
11ce9e
11ce9e
    return deps
11ce9e
            
11ce9e
def convert_dep(req, operator, version):
11ce9e
    """Converts one of the two possibly listed versions into an RPM dependency"""
11ce9e
    
11ce9e
    deps = []
11ce9e
11ce9e
    #any version will do
11ce9e
    if not version or version == '*':
11ce9e
        deps.append(req)
11ce9e
11ce9e
    #any prefix but ~ makes things dead simple
11ce9e
    elif operator in ['>', '<', '<=', '>=', '=']:
11ce9e
        deps.append(' '.join([req, operator, version]))
11ce9e
11ce9e
    #oh boy, here we go...
11ce9e
    else:
11ce9e
        #split the dotted portions into a list (handling trailing dots properly)
11ce9e
        parts = [part if part else 'x' for part in version.split('.')]
11ce9e
        parts = [int(part) if part != 'x' and not '-' in part
11ce9e
                                                    else part for part in parts]
11ce9e
11ce9e
        # 1 or 1.x or 1.x.x or ~1 or ^1
11ce9e
        if len(parts) == 1 or parts[1] == 'x':
11ce9e
            if parts[0] != 0:
11ce9e
                deps.append('{0} >= {1}'.format(req, parts[0]))
11ce9e
            deps.append('{0} < {1}'.format(req, parts[0]+1))
11ce9e
11ce9e
        # 1.2.3 or 1.2.3-4 or 1.2.x or ~1.2.3 or ^1.2.3 or 1.2
11ce9e
        elif len(parts) == 3 or operator != '~':
11ce9e
            # 1.2.x or 1.2
11ce9e
            if len(parts) == 2 or parts[2] == 'x':
11ce9e
                deps.append('{0} >= {1}.{2}'.format(req, parts[0], parts[1]))
11ce9e
                deps.append('{0} < {1}.{2}'.format(req, parts[0], parts[1]+1))
11ce9e
            # ~1.2.3 or ^0.1.2 (zero is special with the caret operator)
11ce9e
            elif operator == '~' or (operator == '^' and parts[0] == 0 and parts[1] > 0):
11ce9e
                deps.append('{0} >= {1}'.format(req, version))
11ce9e
                deps.append('{0} < {1}.{2}'.format(req, parts[0], parts[1]+1))
11ce9e
            #^1.2.3
11ce9e
            elif operator == '^' and parts[0:1] != [0,0]:
11ce9e
                deps.append('{0} >= {1}'.format(req, version))
11ce9e
                deps.append('{0} < {1}'.format(req, parts[0]+1))
11ce9e
            # 1.2.3 or 1.2.3-4 or ^0.0.3
11ce9e
            else:
11ce9e
                deps.append('{0} = {1}'.format(req, version))
11ce9e
11ce9e
        # ~1.2
11ce9e
        elif operator == '~':
11ce9e
            deps.append('{0} >= {1}'.format(req, version))
11ce9e
            deps.append('{0} < {1}'.format(req, parts[0]+1))
11ce9e
        
11ce9e
        #^1.2
11ce9e
        elif operator == '^':
11ce9e
            deps.append('{0} >= {1}'.format(req, version))
11ce9e
            deps.append('{0} < {1}'.format(req, parts[0]+1))
11ce9e
            
11ce9e
11ce9e
    return deps
11ce9e
            
11ce9e
if __name__ == '__main__':
11ce9e
    main()