8de3f91
#!/usr/bin/python3
8de3f91
8de3f91
"""Modify a dependency listed in a package.json file"""
8de3f91
8de3f91
# Copyright 2013 T.C. Hollingsworth <tchollingsworth@gmail.com>
8de3f91
#
8de3f91
# Permission is hereby granted, free of charge, to any person obtaining a copy
8de3f91
# of this software and associated documentation files (the "Software"), to
8de3f91
# deal in the Software without restriction, including without limitation the
8de3f91
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
8de3f91
# sell copies of the Software, and to permit persons to whom the Software is
8de3f91
# furnished to do so, subject to the following conditions:
8de3f91
#
8de3f91
# The above copyright notice and this permission notice shall be included in
8de3f91
# all copies or substantial portions of the Software.
8de3f91
#
8de3f91
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
8de3f91
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
8de3f91
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
8de3f91
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
8de3f91
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
8de3f91
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
8de3f91
# IN THE SOFTWARE.
8de3f91
8de3f91
import json
8de3f91
import optparse
8de3f91
import os
8de3f91
import re
8de3f91
import shutil
8de3f91
import sys
8de3f91
8de3f91
RE_VERSION = re.compile(r'\s*v?([<>=~^]{0,2})\s*([0-9][0-9\.\-]*)\s*')
8de3f91
8de3f91
p = optparse.OptionParser(
8de3f91
        description='Modifies dependency entries in package.json files')
8de3f91
8de3f91
p.add_option('-r', '--remove', action='store_true')
8de3f91
p.add_option('-m', '--move', action='store_true')
8de3f91
p.add_option('--dev', action='store_const', const='devDependencies', 
8de3f91
             dest='deptype', help='affect devDependencies')
8de3f91
p.add_option('--optional', action='store_const', const='optionalDependencies', 
8de3f91
             dest='deptype', help='affect optionalDependencies')
8de3f91
p.add_option('--caret', action='store_true',
8de3f91
             help='convert all or specified dependencies to use the caret operator')
8de3f91
8de3f91
options, args = p.parse_args()
8de3f91
8de3f91
if not os.path.exists('package.json~'):
8de3f91
    shutil.copy2('package.json', 'package.json~')
8de3f91
8de3f91
md = json.load(open('package.json'))
8de3f91
8de3f91
deptype = options.deptype if options.deptype is not None else 'dependencies'
8de3f91
8de3f91
if deptype not in md:
8de3f91
    md[deptype] = {}
8de3f91
8de3f91
# convert alternate JSON dependency representations to a dictionary
8de3f91
if not options.caret and not isinstance(md[deptype], dict):
8de3f91
    if isinstance(md[deptype], list):
8de3f91
        deps = md[deptype]
8de3f91
        md[deptype] = {}
8de3f91
        for dep in deps:
8de3f91
            md[deptype][dep] = '*'
8de3f91
    elif isinstance(md[deptype], str):
8de3f91
        md[deptype] = { md[deptype] : '*' }
8de3f91
8de3f91
if options.remove:
8de3f91
    dep = args[0]
8de3f91
    del md[deptype][dep]
8de3f91
elif options.move:
8de3f91
    dep = args[0]
8de3f91
    ver = None
8de3f91
    for fromtype in ['dependencies', 'optionalDependencies', 'devDependencies']:
8de3f91
        if fromtype in md:
8de3f91
            if isinstance(md[fromtype], dict) and dep in md[fromtype]:
8de3f91
                ver = md[fromtype][dep]
8de3f91
                del md[fromtype][dep]
8de3f91
            elif isinstance(md[fromtype], list) and md[fromtype].count(dep) > 0:
8de3f91
                ver = '*'
8de3f91
                md[fromtype].remove(dep)
8de3f91
            elif isinstance(md[fromtype], str) and md[fromtype] == dep:
8de3f91
                ver = '*'
8de3f91
                del md[fromtype]
8de3f91
    if ver != None:
8de3f91
        md[deptype][dep] = ver
8de3f91
elif options.caret:
8de3f91
    if not isinstance(md[deptype], dict):
8de3f91
        sys.stderr.write('All dependencies are unversioned.  Unable to apply ' +
8de3f91
                         'caret operator.\n')
8de3f91
        sys.exit(2)
8de3f91
        
8de3f91
    deps = args if len(args) > 0 else md[deptype].keys()
8de3f91
    for dep in deps:
8de3f91
        if md[deptype][dep][0] == '^':
8de3f91
            continue
8de3f91
        elif md[deptype][dep][0] in ('~','0','1','2','3','4','5','6','7','8','9'):
8de3f91
            ver = re.match(RE_VERSION, md[deptype][dep]).group(2)
8de3f91
            md[deptype][dep] = '^' + ver
8de3f91
        else:
8de3f91
            sys.stderr.write('Attempted to convert non-numeric or tilde ' +
8de3f91
                'dependency to caret.  This is not permitted.\n')
8de3f91
            sys.exit(1)
8de3f91
else:
8de3f91
    dep = args[0]
8de3f91
8de3f91
    if len(args) > 1:
8de3f91
        ver = args[1]
8de3f91
    else:
8de3f91
        ver = '*'
8de3f91
8de3f91
    md[deptype][dep] = ver
8de3f91
8de3f91
fh = open('package.json', 'w')
8de3f91
data = json.JSONEncoder(indent=4).encode(md)
8de3f91
fh.write(data)
8de3f91
fh.close()