Updated source to eliminate stuff deprecated by nim 0.10.2

This commit is contained in:
Louis Berube 2014-12-29 15:38:16 -05:00
commit 383e0f2a4c
7 changed files with 56 additions and 45 deletions

View file

@ -7,7 +7,8 @@ import httpclient, parseopt, os, strutils, osproc, pegs, tables, parseutils,
from sequtils import toSeq from sequtils import toSeq
import nimblepkg/packageinfo, nimblepkg/version, nimblepkg/tools, import nimblepkg/packageinfo, nimblepkg/version, nimblepkg/tools,
nimblepkg/download, nimblepkg/config, nimblepkg/compat nimblepkg/download, nimblepkg/config, nimblepkg/compat,
nimblepkg/nimbletypes
when not defined(windows): when not defined(windows):
from posix import getpid from posix import getpid
@ -18,7 +19,7 @@ type
queryVersions: bool queryVersions: bool
action: TAction action: TAction
config: TConfig config: TConfig
nimbleData: PJsonNode ## Nimbledata.json nimbleData: JsonNode ## Nimbledata.json
TActionType = enum TActionType = enum
ActionNil, ActionUpdate, ActionInit, ActionInstall, ActionSearch, ActionNil, ActionUpdate, ActionInit, ActionInstall, ActionSearch,
@ -137,6 +138,8 @@ proc parseCmdLine(): TOptions =
result.action.typ = ActionInstall result.action.typ = ActionInstall
of "path": of "path":
result.action.typ = ActionPath result.action.typ = ActionPath
else:
discard
result.action.packages = @[] result.action.packages = @[]
of "build": of "build":
result.action.typ = ActionBuild result.action.typ = ActionBuild
@ -177,6 +180,8 @@ proc parseCmdLine(): TOptions =
result.action.projName = key result.action.projName = key
of ActionList, ActionBuild: of ActionList, ActionBuild:
writeHelp() writeHelp()
else:
discard
of cmdLongOption, cmdShortOption: of cmdLongOption, cmdShortOption:
case key case key
of "help", "h": writeHelp() of "help", "h": writeHelp()
@ -184,6 +189,7 @@ proc parseCmdLine(): TOptions =
of "accept", "y": result.forcePrompts = ForcePromptYes of "accept", "y": result.forcePrompts = ForcePromptYes
of "reject", "n": result.forcePrompts = ForcePromptNo of "reject", "n": result.forcePrompts = ForcePromptNo
of "ver": result.queryVersions = true of "ver": result.queryVersions = true
else: discard
of cmdEnd: assert(false) # cannot happen of cmdEnd: assert(false) # cannot happen
if result.action.typ == ActionNil: if result.action.typ == ActionNil:
writeHelp() writeHelp()
@ -266,7 +272,7 @@ proc copyWithExt(origDir, currentDir, dest: string,
result.add copyFileD(path, changeRoot(origDir, dest, path)) result.add copyFileD(path, changeRoot(origDir, dest, path))
proc copyFilesRec(origDir, currentDir, dest: string, proc copyFilesRec(origDir, currentDir, dest: string,
options: TOptions, pkgInfo: TPackageInfo): TSet[string] = options: TOptions, pkgInfo: TPackageInfo): HashSet[string] =
## Copies all the required files, skips files specified in the .nimble file ## Copies all the required files, skips files specified in the .nimble file
## (TPackageInfo). ## (TPackageInfo).
## Returns a list of filepaths to files which have been installed. ## Returns a list of filepaths to files which have been installed.
@ -323,7 +329,7 @@ proc saveNimbleData(options: TOptions) =
proc addRevDep(options: TOptions, dep: tuple[name, version: string], proc addRevDep(options: TOptions, dep: tuple[name, version: string],
pkg: TPackageInfo) = pkg: TPackageInfo) =
let depNameVer = dep.name & '-' & dep.version # let depNameVer = dep.name & '-' & dep.version
if not options.nimbleData["reverseDeps"].hasKey(dep.name): if not options.nimbleData["reverseDeps"].hasKey(dep.name):
options.nimbleData["reverseDeps"][dep.name] = newJObject() options.nimbleData["reverseDeps"][dep.name] = newJObject()
if not options.nimbleData["reverseDeps"][dep.name].hasKey(dep.version): if not options.nimbleData["reverseDeps"][dep.name].hasKey(dep.version):
@ -336,7 +342,7 @@ proc addRevDep(options: TOptions, dep: tuple[name, version: string],
proc removeRevDep(options: TOptions, pkg: TPackageInfo) = proc removeRevDep(options: TOptions, pkg: TPackageInfo) =
## Removes ``pkg`` from the reverse dependencies of every package. ## Removes ``pkg`` from the reverse dependencies of every package.
proc remove(options: TOptions, pkg: TPackageInfo, depTup: TPkgTuple, proc remove(options: TOptions, pkg: TPackageInfo, depTup: TPkgTuple,
thisDep: PJsonNode) = thisDep: JsonNode) =
for ver, val in thisDep: for ver, val in thisDep:
if ver.newVersion in depTup.ver: if ver.newVersion in depTup.ver:
var newVal = newJArray() var newVal = newJArray()
@ -403,7 +409,7 @@ proc processDeps(pkginfo: TPackageInfo, options: TOptions): seq[string] =
# Check if two packages of the same name (but different version) are listed # Check if two packages of the same name (but different version) are listed
# in the path. # in the path.
var pkgsInPath: PStringTable = newStringTable(modeCaseSensitive) var pkgsInPath: StringTableRef = newStringTable(modeCaseSensitive)
for p in result: for p in result:
let (name, version) = getNameVersion(p) let (name, version) = getNameVersion(p)
if pkgsInPath.hasKey(name) and pkgsInPath[name] != version: if pkgsInPath.hasKey(name) and pkgsInPath[name] != version:
@ -430,7 +436,7 @@ proc buildFromDir(pkgInfo: TPackageInfo, paths: seq[string]) =
doCmd(getNimBin() & " $# -d:release --noBabelPath $# \"$#\"" % doCmd(getNimBin() & " $# -d:release --noBabelPath $# \"$#\"" %
[pkgInfo.backend, args, realDir / bin.changeFileExt("nim")]) [pkgInfo.backend, args, realDir / bin.changeFileExt("nim")])
proc saveNimbleMeta(pkgDestDir, url: string, filesInstalled: TSet[string]) = proc saveNimbleMeta(pkgDestDir, url: string, filesInstalled: HashSet[string]) =
var nimblemeta = %{"url": %url} var nimblemeta = %{"url": %url}
nimblemeta["files"] = newJArray() nimblemeta["files"] = newJArray()
for file in filesInstalled: for file in filesInstalled:
@ -442,7 +448,7 @@ proc removePkgDir(dir: string, options: TOptions) =
try: try:
var nimblemeta = parseFile(dir / "nimblemeta.json") var nimblemeta = parseFile(dir / "nimblemeta.json")
if not nimblemeta.hasKey("files"): if not nimblemeta.hasKey("files"):
raise newException(EJsonParsingError, raise newException(JsonParsingError,
"Meta data does not contain required info.") "Meta data does not contain required info.")
for file in nimblemeta["files"]: for file in nimblemeta["files"]:
removeFile(dir / file.str) removeFile(dir / file.str)
@ -455,7 +461,7 @@ proc removePkgDir(dir: string, options: TOptions) =
else: else:
echo("WARNING: Cannot completely remove " & dir & echo("WARNING: Cannot completely remove " & dir &
". Files not installed by nimble are present.") ". Files not installed by nimble are present.")
except EOS, EJsonParsingError: except OSError, JsonParsingError:
echo("Error: Unable to read nimblemeta.json: ", getCurrentExceptionMsg()) echo("Error: Unable to read nimblemeta.json: ", getCurrentExceptionMsg())
if not options.prompt("Would you like to COMPLETELY remove ALL files " & if not options.prompt("Would you like to COMPLETELY remove ALL files " &
"in " & dir & "?"): "in " & dir & "?"):
@ -500,7 +506,7 @@ proc installFromDir(dir: string, latest: bool, options: TOptions,
removeFile(binDir / bin) removeFile(binDir / bin)
## Will contain a list of files which have been installed. ## Will contain a list of files which have been installed.
var filesInstalled: TSet[string] var filesInstalled: HashSet[string]
createDir(pkgDestDir) createDir(pkgDestDir)
if pkgInfo.bin.len > 0: if pkgInfo.bin.len > 0:
@ -710,7 +716,7 @@ proc init(options: TOptions) =
echo("Initializing new Nimble project!") echo("Initializing new Nimble project!")
var var
pkgName, fName: string = "" pkgName, fName: string = ""
outFile: TFile outFile: File
if (options.action.projName != ""): if (options.action.projName != ""):
pkgName = options.action.projName pkgName = options.action.projName
@ -743,7 +749,7 @@ proc init(options: TOptions) =
else: else:
raise newException(ENimble, "Unable to open file " & fName & raise newException(ENimble, "Unable to open file " & fName &
" for writing: " & osErrorMsg()) " for writing: " & osErrorMsg(osLastError()))
proc uninstall(options: TOptions) = proc uninstall(options: TOptions) =
var pkgsToDelete: seq[TPackageInfo] = @[] var pkgsToDelete: seq[TPackageInfo] = @[]

View file

@ -2,7 +2,7 @@
# BSD License. Look at license.txt for more info. # BSD License. Look at license.txt for more info.
import parsecfg, streams, strutils, os import parsecfg, streams, strutils, os
import tools, version import tools, version, nimbletypes
type type
TConfig* = object TConfig* = object
@ -32,7 +32,7 @@ proc parseConfig*(): TConfig =
if f != nil: if f != nil:
echo("Reading from config file at ", confFile) echo("Reading from config file at ", confFile)
var p: TCfgParser var p: CfgParser
open(p, f, confFile) open(p, f, confFile)
while true: while true:
var e = next(p) var e = next(p)

View file

@ -3,7 +3,7 @@
import parseutils, os, osproc, strutils, tables, pegs import parseutils, os, osproc, strutils, tables, pegs
import packageinfo, version, tools import packageinfo, version, tools, nimbletypes
type type
TDownloadMethod* {.pure.} = enum TDownloadMethod* {.pure.} = enum
@ -98,7 +98,7 @@ proc getTagsListRemote*(url: string, meth: TDownloadMethod): seq[string] =
of TDownloadMethod.Git: of TDownloadMethod.Git:
var (output, exitCode) = doCmdEx("git ls-remote --tags " & url) var (output, exitCode) = doCmdEx("git ls-remote --tags " & url)
if exitCode != QuitSuccess: if exitCode != QuitSuccess:
raise newException(EOS, "Unable to query remote tags for " & url & raise newException(OSError, "Unable to query remote tags for " & url &
". Git returned: " & output) ". Git returned: " & output)
for i in output.splitLines(): for i in output.splitLines():
if i == "": continue if i == "": continue
@ -108,9 +108,9 @@ proc getTagsListRemote*(url: string, meth: TDownloadMethod): seq[string] =
of TDownloadMethod.Hg: of TDownloadMethod.Hg:
# http://stackoverflow.com/questions/2039150/show-tags-for-remote-hg-repository # http://stackoverflow.com/questions/2039150/show-tags-for-remote-hg-repository
raise newException(EInvalidValue, "Hg doesn't support remote tag querying.") raise newException(ValueError, "Hg doesn't support remote tag querying.")
proc getVersionList*(tags: seq[string]): TTable[TVersion, string] = proc getVersionList*(tags: seq[string]): Table[TVersion, string] =
# Returns: TTable of version -> git tag name # Returns: TTable of version -> git tag name
result = initTable[TVersion, string]() result = initTable[TVersion, string]()
for tag in tags: for tag in tags:
@ -225,7 +225,7 @@ proc echoPackageVersions*(pkg: TPackage) =
echo(" versions: " & vstr) echo(" versions: " & vstr)
else: else:
echo(" versions: (No versions tagged in the remote repository)") echo(" versions: (No versions tagged in the remote repository)")
except EOS: except OSError:
echo(getCurrentExceptionMsg()) echo(getCurrentExceptionMsg())
of TDownloadMethod.Hg: of TDownloadMethod.Hg:
echo(" versions: (Remote tag retrieval not supported by " & pkg.downloadMethod & ")") echo(" versions: (Remote tag retrieval not supported by " & pkg.downloadMethod & ")")

View file

@ -0,0 +1,7 @@
# BSD License. Look at license.txt for more info.
#
# Various miscellaneous common types reside here, to avoid problems with
# recursive imports
type
ENimble* = object of Exception

View file

@ -1,7 +1,7 @@
# Copyright (C) Dominik Picheta. All rights reserved. # Copyright (C) Dominik Picheta. All rights reserved.
# BSD License. Look at license.txt for more info. # BSD License. Look at license.txt for more info.
import parsecfg, json, streams, strutils, parseutils, os import parsecfg, json, streams, strutils, parseutils, os
import version, tools import version, tools, nimbletypes
type type
## Tuple containing package name and version range. ## Tuple containing package name and version range.
TPkgTuple* = tuple[name: string, ver: PVersionRange] TPkgTuple* = tuple[name: string, ver: PVersionRange]
@ -120,7 +120,7 @@ proc readPackageInfo*(path: string): TPackageInfo =
result.mypath = path result.mypath = path
var fs = newFileStream(path, fmRead) var fs = newFileStream(path, fmRead)
if fs != nil: if fs != nil:
var p: TCfgParser var p: CfgParser
open(p, fs, path) open(p, fs, path)
var currentSection = "" var currentSection = ""
while true: while true:
@ -159,6 +159,7 @@ proc readPackageInfo*(path: string): TPackageInfo =
result.backend = ev.value.toLower() result.backend = ev.value.toLower()
case result.backend.normalize case result.backend.normalize
of "javascript": result.backend = "js" of "javascript": result.backend = "js"
else: discard
else: else:
raise newException(ENimble, "Invalid field: " & ev.key) raise newException(ENimble, "Invalid field: " & ev.key)
of "deps", "dependencies": of "deps", "dependencies":
@ -174,23 +175,23 @@ proc readPackageInfo*(path: string): TPackageInfo =
raise newException(ENimble, "Error parsing .nimble file: " & ev.msg) raise newException(ENimble, "Error parsing .nimble file: " & ev.msg)
close(p) close(p)
else: else:
raise newException(EInvalidValue, "Cannot open package info: " & path) raise newException(ValueError, "Cannot open package info: " & path)
validatePackageInfo(result, path) validatePackageInfo(result, path)
proc optionalField(obj: PJsonNode, name: string, default = ""): string = proc optionalField(obj: JsonNode, name: string, default = ""): string =
## Queries ``obj`` for the optional ``name`` string. ## Queries ``obj`` for the optional ``name`` string.
## ##
## Returns the value of ``name`` if it is a valid string, or aborts execution ## Returns the value of ``name`` if it is a valid string, or aborts execution
## if the field exists but is not of string type. If ``name`` is not present, ## if the field exists but is not of string type. If ``name`` is not present,
## returns ``default``. ## returns ``default``.
if existsKey(obj, name): if hasKey(obj, name):
if obj[name].kind == JString: if obj[name].kind == JString:
return obj[name].str return obj[name].str
else: else:
raise newException(ENimble, "Corrupted packages.json file. " & name & " field is of unexpected type.") raise newException(ENimble, "Corrupted packages.json file. " & name & " field is of unexpected type.")
else: return default else: return default
proc requiredField(obj: PJsonNode, name: string): string = proc requiredField(obj: JsonNode, name: string): string =
## Queries ``obj`` for the required ``name`` string. ## Queries ``obj`` for the required ``name`` string.
## ##
## Aborts execution if the field does not exist or is of invalid json type. ## Aborts execution if the field does not exist or is of invalid json type.
@ -199,7 +200,7 @@ proc requiredField(obj: PJsonNode, name: string): string =
raise newException(ENimble, raise newException(ENimble,
"Package in packages.json file does not contain a " & name & " field.") "Package in packages.json file does not contain a " & name & " field.")
proc fromJson(obj: PJSonNode): TPackage = proc fromJson(obj: JSonNode): TPackage =
## Constructs a TPackage object from a JSON node. ## Constructs a TPackage object from a JSON node.
## ##
## Aborts execution if the JSON node doesn't contain the required fields. ## Aborts execution if the JSON node doesn't contain the required fields.

View file

@ -2,11 +2,8 @@
# BSD License. Look at license.txt for more info. # BSD License. Look at license.txt for more info.
# #
# Various miscellaneous utility functions reside here. # Various miscellaneous utility functions reside here.
import osproc, pegs, strutils, os, parseurl, sets, json import osproc, pegs, strutils, os, uri, sets, json
import version, packageinfo import version, packageinfo, nimbletypes
type
ENimble* = object of EBase
proc doCmd*(cmd: string) = proc doCmd*(cmd: string) =
let bin = cmd.split(' ')[0] let bin = cmd.split(' ')[0]
@ -61,7 +58,7 @@ proc changeRoot*(origRoot, newRoot, path: string): string =
if path.startsWith(origRoot): if path.startsWith(origRoot):
return newRoot / path[origRoot.len .. -1] return newRoot / path[origRoot.len .. -1]
else: else:
raise newException(EInvalidValue, raise newException(ValueError,
"Cannot change root of path: Path does not begin with original root.") "Cannot change root of path: Path does not begin with original root.")
proc copyFileD*(fro, to: string): string = proc copyFileD*(fro, to: string): string =
@ -78,37 +75,37 @@ proc copyDirD*(fro, to: string): seq[string] =
createDir(changeRoot(fro, to, path.splitFile.dir)) createDir(changeRoot(fro, to, path.splitFile.dir))
result.add copyFileD(path, changeRoot(fro, to, path)) result.add copyFileD(path, changeRoot(fro, to, path))
proc getDownloadDirName*(url: string, verRange: PVersionRange): string = proc getDownloadDirName*(uri: string, verRange: PVersionRange): string =
## Creates a directory name based on the specified ``url`` ## Creates a directory name based on the specified ``uri`` (url)
result = "" result = ""
let purl = parseUrl(url) let puri = parseUri(uri)
for i in purl.hostname: for i in puri.hostname:
case i case i
of strutils.Letters, strutils.Digits: of strutils.Letters, strutils.Digits:
result.add i result.add i
else: nil else: discard
result.add "_" result.add "_"
for i in purl.path: for i in puri.path:
case i case i
of strutils.Letters, strutils.Digits: of strutils.Letters, strutils.Digits:
result.add i result.add i
else: nil else: discard
let verSimple = getSimpleString(verRange) let verSimple = getSimpleString(verRange)
if verSimple != "": if verSimple != "":
result.add "_" result.add "_"
result.add verSimple result.add verSimple
proc incl*(s: var TSet[string], v: seq[string] | TSet[string]) = proc incl*(s: var HashSet[string], v: seq[string] | HashSet[string]) =
for i in v: for i in v:
s.incl i s.incl i
proc contains*(j: PJsonNode, elem: PJsonNode): bool = proc contains*(j: JsonNode, elem: JsonNode): bool =
for i in j: for i in j:
if i == elem: if i == elem:
return true return true
proc contains*(j: PJsonNode, elem: tuple[key: string, val: PJsonNode]): bool = proc contains*(j: JsonNode, elem: tuple[key: string, val: JsonNode]): bool =
for key, val in pairs(j): for key, val in pairs(j):
if key == elem.key and val == elem.val: if key == elem.key and val == elem.val:
return true return true

View file

@ -29,7 +29,7 @@ type
of verAny: of verAny:
nil nil
EParseVersion* = object of EInvalidValue EParseVersion* = object of ValueError
proc newVersion*(ver: string): TVersion = return TVersion(ver) proc newVersion*(ver: string): TVersion = return TVersion(ver)
proc newSpecial*(spe: string): TSpecial = return TSpecial(spe) proc newSpecial*(spe: string): TSpecial = return TSpecial(spe)
@ -55,7 +55,7 @@ proc `<`*(ver: TVersion, ver2: TVersion): bool =
if sVerI < sVerI2: if sVerI < sVerI2:
return true return true
elif sVerI == sVerI2: elif sVerI == sVerI2:
nil discard
else: else:
return false return false
@ -229,7 +229,7 @@ proc newVREq*(ver: string): PVersionRange =
result.kind = verEq result.kind = verEq
result.ver = newVersion(ver) result.ver = newVersion(ver)
proc findLatest*(verRange: PVersionRange, versions: TTable[TVersion, string]): tuple[ver: TVersion, tag: string] = proc findLatest*(verRange: PVersionRange, versions: Table[TVersion, string]): tuple[ver: TVersion, tag: string] =
result = (newVersion(""), "") result = (newVersion(""), "")
for ver, tag in versions: for ver, tag in versions:
if not withinRange(ver, verRange): continue if not withinRange(ver, verRange): continue