Merge branch 'master' into native-pkg-support

This commit is contained in:
Araq 2016-12-31 02:12:00 +01:00
commit 6368ccb0df
28 changed files with 698 additions and 194 deletions

View file

@ -14,14 +14,17 @@ when not defined(nimscript):
BuildFailed* = object of NimbleError
PackageInfo* = object
mypath*: string ## The path of this .nimble file
myPath*: string ## The path of this .nimble file
isNimScript*: bool ## Determines if this pkg info was read from a nims file
isMinimal*: bool
isInstalled*: bool ## Determines if the pkg this info belongs to is installed
postHooks*: HashSet[string] ## Useful to know so that Nimble doesn't execHook unnecessarily
preHooks*: HashSet[string]
name*: string
## The version specified in the .nimble file.Assuming info is non-minimal,
## it will always be a non-special version such as '0.1.4'
version*: string
specialVersion*: string ## Either `myVersion` or a special version such as #head.
author*: string
description*: string
license*: string

View file

@ -91,8 +91,10 @@ proc getTagsListRemote*(url: string, meth: DownloadMethod): seq[string] =
raise newException(OSError, "Unable to query remote tags for " & url &
". Git returned: " & output)
for i in output.splitLines():
if i == "": continue
let start = i.find("refs/tags/")+"refs/tags/".len
let refStart = i.find("refs/tags/")
# git outputs warnings, empty lines, etc
if refStart == -1: continue
let start = refStart+"refs/tags/".len
let tag = i[start .. i.len-1]
if not tag.endswith("^{}"): result.add(tag)
@ -116,12 +118,12 @@ proc getDownloadMethod*(meth: string): DownloadMethod =
else:
raise newException(NimbleError, "Invalid download method: " & meth)
proc getHeadName*(meth: DownloadMethod): string =
proc getHeadName*(meth: DownloadMethod): Version =
## Returns the name of the download method specific head. i.e. for git
## it's ``head`` for hg it's ``tip``.
case meth
of DownloadMethod.git: "head"
of DownloadMethod.hg: "tip"
of DownloadMethod.git: newVersion("#head")
of DownloadMethod.hg: newVersion("#tip")
proc checkUrlType*(url: string): DownloadMethod =
## Determines the download method based on the URL.
@ -136,7 +138,7 @@ proc isURL*(name: string): bool =
name.startsWith(peg" @'://' ")
proc doDownload*(url: string, downloadDir: string, verRange: VersionRange,
downMethod: DownloadMethod, options: Options): VersionRange =
downMethod: DownloadMethod, options: Options): Version =
## Downloads the repository specified by ``url`` using the specified download
## method.
##
@ -152,7 +154,7 @@ proc doDownload*(url: string, downloadDir: string, verRange: VersionRange,
# https://github.com/nim-lang/nimble/issues/22
meth
if $latest.ver != "":
result = parseVersionRange($latest.ver)
result = latest.ver
else:
# Result should already be set to #head here.
assert(not result.isNil)
@ -170,20 +172,20 @@ proc doDownload*(url: string, downloadDir: string, verRange: VersionRange,
removeDir(downloadDir)
if verRange.kind == verSpecial:
# We want a specific commit/branch/tag here.
if verRange.spe == newSpecial(getHeadName(downMethod)):
if verRange.spe == getHeadName(downMethod):
doClone(downMethod, url, downloadDir) # Grab HEAD.
else:
# Grab the full repo.
doClone(downMethod, url, downloadDir, tip = false)
# Then perform a checkout operation to get the specified branch/commit.
doCheckout(downMethod, downloadDir, $verRange.spe)
result = verRange
result = verRange.spe
else:
case downMethod
of DownloadMethod.git:
# For Git we have to query the repo remotely for its tags. This is
# necessary as cloning with a --depth of 1 removes all tag info.
result = parseVersionRange("#head")
result = getHeadName(downMethod)
let versions = getTagsListRemote(url, downMethod).getVersionList()
if versions.len > 0:
getLatestByTag:
@ -197,7 +199,7 @@ proc doDownload*(url: string, downloadDir: string, verRange: VersionRange,
verifyClone()
of DownloadMethod.hg:
doClone(downMethod, url, downloadDir)
result = parseVersionRange("#tip")
result = getHeadName(downMethod)
let versions = getTagsList(downloadDir, downMethod).getVersionList()
if versions.len > 0:

View file

@ -23,7 +23,7 @@ type
actionNil, actionRefresh, actionInit, actionDump, actionPublish,
actionInstall, actionSearch,
actionList, actionBuild, actionPath, actionUninstall, actionCompile,
actionCustom, actionTasks
actionDoc, actionCustom, actionTasks
Action* = object
case typ*: ActionType
@ -36,7 +36,7 @@ type
search*: seq[string] # Search string.
of actionInit, actionDump:
projName*: string
of actionCompile:
of actionCompile, actionDoc:
file*: string
backend*: string
compileOptions*: seq[string]
@ -61,6 +61,8 @@ Commands:
build Builds a package.
c, cc, js [opts, ...] f.nim Builds a file inside a package. Passes options
to the Nim compiler.
doc, doc2 [opts, ...] f.nim Builds documentation for a file inside a
package. Passes options to the Nim compiler.
refresh [url] Refreshes the package list. A package list URL
can be optionally specified.
search pkg/tag Searches for a specified package. Search is
@ -74,7 +76,10 @@ Commands:
path pkgname ... Shows absolute path to the installed packages
specified.
dump [pkgname] Outputs Nimble package information for
external tools.
external tools. The argument can be a
.nimble file, a project directory or
the name of an installed package.
Options:
-h, --help Print this help message.
@ -111,6 +116,8 @@ proc parseActionType*(action: string): ActionType =
result = actionBuild
of "c", "compile", "js", "cpp", "cc":
result = actionCompile
of "doc", "doc2":
result = actionDoc
of "init":
result = actionInit
of "dump":
@ -137,7 +144,7 @@ proc initAction*(options: var Options, key: string) =
case options.action.typ
of actionInstall, actionPath:
options.action.packages = @[]
of actionCompile:
of actionCompile, actionDoc:
options.action.compileOptions = @[]
options.action.file = ""
if keyNorm == "c" or keyNorm == "compile": options.action.backend = ""
@ -219,7 +226,7 @@ proc parseArgument*(key: string, result: var Options) =
raise newException(NimbleError,
"Can only initialize one package at a time.")
result.action.projName = key
of actionCompile:
of actionCompile, actionDoc:
result.action.file = key
of actionList, actionBuild, actionPublish:
writeHelp()
@ -258,7 +265,7 @@ proc parseFlag*(flag, val: string, result: var Options) =
wasFlagHandled = false
else:
case result.action.typ
of actionCompile:
of actionCompile, actionDoc:
if val == "":
result.action.compileOptions.add("--" & flag)
else:

View file

@ -4,7 +4,7 @@ import parsecfg, json, streams, strutils, parseutils, os, sets, tables
import version, tools, common, options, cli
type
Package* = object
Package* = object ## Definition of package from packages.json.
# Required fields in a package.
name*: string
url*: string # Download location.
@ -21,7 +21,8 @@ type
url*: string
proc initPackageInfo*(path: string): PackageInfo =
result.mypath = path
result.myPath = path
result.specialVersion = ""
result.preHooks.init()
result.postHooks.init()
# reasonable default:
@ -58,7 +59,6 @@ proc getNameVersion*(pkgpath: string): tuple[name, version: string] =
##
## Also works for file paths like:
## ``/home/user/.nimble/pkgs/package-0.1/package.nimble``
if pkgPath.splitFile.ext == ".nimble" or pkgPath.splitFile.ext == ".babel":
return getNameVersion(pkgPath.splitPath.head)
@ -196,11 +196,19 @@ proc getInstalledPkgsMin*(libsDir: string, options: Options):
var pkg = initPackageInfo(nimbleFile)
pkg.name = name
pkg.version = version
pkg.specialVersion = version
pkg.isMinimal = true
pkg.isInstalled = true
result.add((pkg, meta))
proc findPkg*(pkglist: seq[tuple[pkginfo: PackageInfo, meta: MetaData]],
proc withinRange*(pkgInfo: PackageInfo, verRange: VersionRange): bool =
## Determines whether the specified package's version is within the
## specified range. The check works with ordinary versions as well as
## special ones.
return withinRange(newVersion(pkgInfo.version), verRange) or
withinRange(newVersion(pkgInfo.specialVersion), verRange)
proc findPkg*(pkglist: seq[tuple[pkgInfo: PackageInfo, meta: MetaData]],
dep: PkgTuple,
r: var PackageInfo): bool =
## Searches ``pkglist`` for a package of which version is within the range
@ -212,26 +220,27 @@ proc findPkg*(pkglist: seq[tuple[pkginfo: PackageInfo, meta: MetaData]],
for pkg in pkglist:
if cmpIgnoreStyle(pkg.pkginfo.name, dep.name) != 0 and
cmpIgnoreStyle(pkg.meta.url, dep.name) != 0: continue
if withinRange(newVersion(pkg.pkginfo.version), dep.ver):
if not result or newVersion(r.version) < newVersion(pkg.pkginfo.version):
if withinRange(pkg.pkgInfo, dep.ver):
let isNewer = (not r.version.isNil) and
newVersion(r.version) < newVersion(pkg.pkginfo.version)
if not result or isNewer:
r = pkg.pkginfo
result = true
proc findAllPkgs*(pkglist: seq[tuple[pkginfo: PackageInfo, meta: MetaData]],
proc findAllPkgs*(pkglist: seq[tuple[pkgInfo: PackageInfo, meta: MetaData]],
dep: PkgTuple): seq[PackageInfo] =
## Searches ``pkglist`` for packages of which version is within the range
## of ``dep.ver``. This is similar to ``findPkg`` but returns multiple
## packages if multiple are found.
result = @[]
for pkg in pkglist:
if cmpIgnoreStyle(pkg.pkginfo.name, dep.name) != 0 and
if cmpIgnoreStyle(pkg.pkgInfo.name, dep.name) != 0 and
cmpIgnoreStyle(pkg.meta.url, dep.name) != 0: continue
if withinRange(newVersion(pkg.pkginfo.version), dep.ver):
if withinRange(pkg.pkgInfo, dep.ver):
result.add pkg.pkginfo
proc getRealDir*(pkgInfo: PackageInfo): string =
## Returns the ``pkgInfo.srcDir`` or the .mypath directory if package does
## not specify the src dir.
## Returns the directory containing the package source files.
if pkgInfo.srcDir != "" and not pkgInfo.isInstalled:
result = pkgInfo.mypath.splitFile.dir / pkgInfo.srcDir
else:
@ -282,6 +291,104 @@ proc validatePackagesList*(path: string): bool =
except ValueError, JsonParsingError:
return false
proc checkInstallFile(pkgInfo: PackageInfo,
origDir, file: string): bool =
## Checks whether ``file`` should be installed.
## ``True`` means file should be skipped.
for ignoreFile in pkgInfo.skipFiles:
if ignoreFile.endswith("nimble"):
raise newException(NimbleError, ignoreFile & " must be installed.")
if samePaths(file, origDir / ignoreFile):
result = true
break
for ignoreExt in pkgInfo.skipExt:
if file.splitFile.ext == ('.' & ignoreExt):
result = true
break
if file.splitFile().name[0] == '.': result = true
proc checkInstallDir(pkgInfo: PackageInfo,
origDir, dir: string): bool =
## Determines whether ``dir`` should be installed.
## ``True`` means dir should be skipped.
for ignoreDir in pkgInfo.skipDirs:
if samePaths(dir, origDir / ignoreDir):
result = true
break
let thisDir = splitPath(dir).tail
assert thisDir != ""
if thisDir[0] == '.': result = true
if thisDir == "nimcache": result = true
proc findWithExt(dir: string, pkgInfo: PackageInfo): seq[string] =
## Returns the filenames of the files that should be copied.
result = @[]
for kind, path in walkDir(dir):
if kind == pcDir:
result.add findWithExt(path, pkgInfo)
else:
if path.splitFile.ext[1 .. ^1] in pkgInfo.installExt:
result.add path
proc getFilesInDir(dir: string): seq[string] =
## Returns a list of paths to files inside the specified directory and any
## subdirectories that are in it.
result = @[]
for kind, path in walkDir(dir):
if kind == pcDir:
result.add getFilesInDir(path)
else:
result.add path
proc getInstallFiles*(realDir: string, pkgInfo: PackageInfo,
options: Options): seq[string] =
## Returns a list of files within the ``realDir`` that should be installed.
result = @[]
let whitelistMode =
pkgInfo.installDirs.len != 0 or
pkgInfo.installFiles.len != 0 or
pkgInfo.installExt.len != 0
if whitelistMode:
for file in pkgInfo.installFiles:
let src = realDir / file
if not src.existsFile():
if options.prompt("Missing file " & src & ". Continue?"):
continue
else:
raise NimbleQuit(msg: "")
result.add src
for dir in pkgInfo.installDirs:
# TODO: Allow skipping files inside dirs?
let src = realDir / dir
if not src.existsDir():
if options.prompt("Missing directory " & src & ". Continue?"):
continue
else:
raise NimbleQuit(msg: "")
result.add getFilesInDir(src)
result.add findWithExt(realDir, pkgInfo)
else:
for kind, file in walkDir(realDir):
if kind == pcDir:
let skip = pkgInfo.checkInstallDir(realDir, file)
if skip: continue
result.add getInstallFiles(file, pkgInfo, options)
else:
let skip = pkgInfo.checkInstallFile(realDir, file)
if skip: continue
result.add file
when isMainModule:
doAssert getNameVersion("/home/user/.nimble/libs/packagea-0.1") ==
("packagea", "0.1")
@ -289,14 +396,8 @@ when isMainModule:
("package-a", "0.1")
doAssert getNameVersion("/home/user/.nimble/libs/package-a-0.1/package.nimble") ==
("package-a", "0.1")
validatePackageName("foo_bar")
validatePackageName("f_oo_b_a_r")
try:
validatePackageName("foo__bar")
assert false
except NimbleError:
assert true
doAssert getNameVersion("/home/user/.nimble/libs/package-#head") ==
("package", "#head")
doAssert toValidPackageName("foo__bar") == "foo_bar"
doAssert toValidPackageName("jhbasdh!£$@%#^_&*_()qwe") == "jhbasdh_qwe"

View file

@ -14,13 +14,18 @@ type
ValidationError* = object of NimbleError
warnInstalled*: bool # Determines whether to show a warning for installed pkgs
warnAll*: bool
proc newValidationError(msg: string, warnInstalled: bool): ref ValidationError =
proc newValidationError(msg: string, warnInstalled: bool,
hint: string, warnAll: bool): ref ValidationError =
result = newException(ValidationError, msg)
result.warnInstalled = warnInstalled
result.warnAll = warnAll
result.hint = hint
proc raiseNewValidationError(msg: string, warnInstalled: bool) =
raise newValidationError(msg, warnInstalled)
proc raiseNewValidationError(msg: string, warnInstalled: bool,
hint: string = "", warnAll = false) =
raise newValidationError(msg, warnInstalled, hint, warnAll)
proc validatePackageName*(name: string) =
## Raises an error if specified package name contains invalid characters.
@ -49,6 +54,10 @@ proc validatePackageName*(name: string) =
else:
prevWasUnderscore = false
if name.endsWith("pkg"):
raiseNewValidationError("\"$1\" is an invalid package name: cannot end" &
" with \"pkg\"" % name, false)
proc validateVersion*(ver: string) =
for c in ver:
if c notin ({'.'} + Digits):
@ -56,7 +65,57 @@ proc validateVersion*(ver: string) =
"Version may only consist of numbers and the '.' character " &
"but found '" & c & "'.", false)
proc validatePackageInfo(pkgInfo: PackageInfo, path: string) =
proc validatePackageStructure(pkgInfo: PackageInfo, options: Options) =
## This ensures that a package's source code does not leak into
## another package's namespace.
## https://github.com/nim-lang/nimble/issues/144
let realDir = pkgInfo.getRealDir()
for path in getInstallFiles(realDir, pkgInfo, options):
# Remove the root to leave only the package subdirectories.
# ~/package-0.1/package/utils.nim -> package/utils.nim.
var trailPath = changeRoot(realDir, "", path)
if trailPath.startsWith(DirSep): trailPath = trailPath[1 .. ^1]
let (dir, file, ext) = trailPath.splitFile
# We're only interested in nim files, because only they can pollute our
# namespace.
if ext != (ExtSep & "nim"):
continue
if dir.len == 0:
if file != pkgInfo.name:
let msg = ("File inside package '$1' is outside of permitted " &
"namespace, should be " &
"named '$2' but was named '$3' instead. This will be an error" &
" in the future.") %
[pkgInfo.name, pkgInfo.name & ext, file & ext]
let hint = ("Rename this file to '$1', move it into a '$2' " &
"subdirectory, or prevent its installation by adding " &
"`skipFiles = @[\"$3\"]` to the .nimble file. See " &
"https://github.com/nim-lang/nimble#libraries for more info.") %
[pkgInfo.name & ext, pkgInfo.name & DirSep, file & ext]
raiseNewValidationError(msg, true, hint, true)
else:
assert(not pkgInfo.isMinimal)
let correctDir =
if pkgInfo.name in pkgInfo.bin:
pkgInfo.name & "pkg"
else:
pkgInfo.name
if not (dir.startsWith(correctDir & DirSep) or dir == correctDir):
let msg = ("File '$1' inside package '$2' is outside of the" &
" permitted namespace" &
", should be inside a directory named '$3' but is in a" &
" directory named '$4' instead. This will be an error in the " &
"future.") %
[file & ext, pkgInfo.name, correctDir, dir]
let hint = ("Rename the directory to '$1' or prevent its " &
"installation by adding `skipDirs = @[\"$2\"]` to the " &
".nimble file.") % [correctDir, dir]
raiseNewValidationError(msg, true, hint, true)
proc validatePackageInfo(pkgInfo: PackageInfo, options: Options) =
let path = pkgInfo.myPath
if pkgInfo.name == "":
raiseNewValidationError("Incorrect .nimble file: " & path &
" does not contain a name field.", false)
@ -83,7 +142,8 @@ proc validatePackageInfo(pkgInfo: PackageInfo, path: string) =
raiseNewValidationError("'" & pkgInfo.backend &
"' is an invalid backend.", false)
validateVersion(pkgInfo.version)
validatePackageStructure(pkginfo, options)
proc nimScriptHint*(pkgInfo: PackageInfo) =
if not pkgInfo.isNimScript:
@ -172,7 +232,7 @@ proc readPackageInfoFromNimble(path: string; result: var PackageInfo) =
else:
raise newException(ValueError, "Cannot open package info: " & path)
proc readPackageInfo*(nf: NimbleFile, options: Options,
proc readPackageInfo(nf: NimbleFile, options: Options,
onlyMinimalInfo=false): PackageInfo =
## Reads package info from the specified Nimble file.
##
@ -182,17 +242,20 @@ proc readPackageInfo*(nf: NimbleFile, options: Options,
## If both fail then returns an error.
##
## When ``onlyMinimalInfo`` is true, only the `name` and `version` fields are
## populated. The isNimScript field can also be relied on.
## populated. The ``isNimScript`` field can also be relied on.
##
## This version uses a cache stored in ``options``, so calling it multiple
## times on the same ``nf`` shouldn't require re-evaluation of the Nimble
## file.
assert fileExists(nf)
# Check the cache.
if options.pkgInfoCache.hasKey(nf):
return options.pkgInfoCache[nf]
result = initPackageInfo(nf)
let minimalInfo = getNameVersion(nf)
validatePackageName(nf.splitFile.name)
@ -208,9 +271,8 @@ proc readPackageInfo*(nf: NimbleFile, options: Options,
if not success:
if onlyMinimalInfo:
let tmp = getNameVersion(nf)
result.name = tmp.name
result.version = tmp.version
result.name = minimalInfo.name
result.version = minimalInfo.version
result.isNimScript = true
result.isMinimal = true
else:
@ -225,14 +287,40 @@ proc readPackageInfo*(nf: NimbleFile, options: Options,
" " & getCurrentExceptionMsg() & "."
raise newException(NimbleError, msg)
validatePackageInfo(result, nf)
# By default specialVersion is the same as version.
result.specialVersion = result.version
# The package directory name may include a "special" version
# (example #head). If so, it is given higher priority and therefore
# overwrites the .nimble file's version.
let version = parseVersionRange(minimalInfo.version)
if version.kind == verSpecial:
result.specialVersion = minimalInfo.version
if not result.isMinimal:
options.pkgInfoCache[nf] = result
# Validate the rest of the package info last.
validateVersion(result.version)
validatePackageInfo(result, options)
proc getPkgInfoFromFile*(file: NimbleFile, options: Options): PackageInfo =
## Reads the specified .nimble file and returns its data as a PackageInfo
## object. Any validation errors are handled and displayed as warnings.
try:
result = readPackageInfo(file, options)
except ValidationError:
let exc = (ref ValidationError)(getCurrentException())
if exc.warnAll:
display("Warning:", exc.msg, Warning, HighPriority)
display("Hint:", exc.hint, Warning, HighPriority)
else:
raise
proc getPkgInfo*(dir: string, options: Options): PackageInfo =
## Find the .nimble file in ``dir`` and parses it, returning a PackageInfo.
let nimbleFile = findNimbleFile(dir, true)
result = readPackageInfo(nimbleFile, options)
getPkgInfoFromFile(nimbleFile, options)
proc getInstalledPkgs*(libsDir: string, options: Options):
seq[tuple[pkginfo: PackageInfo, meta: MetaData]] =
@ -240,7 +328,7 @@ proc getInstalledPkgs*(libsDir: string, options: Options):
##
## ``libsDir`` is in most cases: ~/.nimble/pkgs/
const
readErrorMsg = "Installed package $1 v$2 is outdated or corrupt."
readErrorMsg = "Installed package '$1@$2' is outdated or corrupt."
validationErrorMsg = readErrorMsg & "\nPackage did not pass validation: $3"
hintMsg = "The corrupted package will need to be removed manually. To fix" &
" this error message, remove $1."
@ -257,16 +345,17 @@ proc getInstalledPkgs*(libsDir: string, options: Options):
let nimbleFile = findNimbleFile(path, false)
if nimbleFile != "":
let meta = readMetaData(path)
var pkg: PackageInfo
try:
var pkg = readPackageInfo(nimbleFile, options, onlyMinimalInfo=false)
pkg.isInstalled = true
result.add((pkg, meta))
pkg = readPackageInfo(nimbleFile, options, onlyMinimalInfo=false)
except ValidationError:
let exc = (ref ValidationError)(getCurrentException())
exc.msg = createErrorMsg(validationErrorMsg, path, exc.msg)
exc.hint = hintMsg % path
if exc.warnInstalled:
if exc.warnInstalled or exc.warnAll:
display("Warning:", exc.msg, Warning, HighPriority)
# Don't show hints here because they are only useful for package
# owners.
else:
raise exc
except:
@ -276,5 +365,19 @@ proc getInstalledPkgs*(libsDir: string, options: Options):
exc.hint = hintMsg % path
raise exc
pkg.isInstalled = true
result.add((pkg, meta))
proc isNimScript*(nf: string, options: Options): bool =
result = readPackageInfo(nf, options).isNimScript
when isMainModule:
validatePackageName("foo_bar")
validatePackageName("f_oo_b_a_r")
try:
validatePackageName("foo__bar")
assert false
except NimbleError:
assert true
echo("Everything passed!")

View file

@ -5,7 +5,6 @@
import strutils, tables, hashes, parseutils
type
Version* = distinct string
Special* = distinct string
VersionRangeEnum* = enum
verLater, # > V
@ -23,7 +22,7 @@ type
of verLater, verEarlier, verEqLater, verEqEarlier, verEq:
ver*: Version
of verSpecial:
spe*: Special
spe*: Version
of verIntersect:
verILeft, verIRight: VersionRange
of verAny:
@ -36,18 +35,25 @@ type
NimbleError* = object of Exception
hint*: string
proc newVersion*(ver: string): Version = return Version(ver)
proc newSpecial*(spe: string): Special = return Special(spe)
proc newVersion*(ver: string): Version =
doAssert(ver[0] in {'#', '\0'} + Digits)
return Version(ver)
proc `$`*(ver: Version): string {.borrow.}
proc hash*(ver: Version): Hash {.borrow.}
proc `$`*(ver: Special): string {.borrow.}
proc isNil*(ver: Version): bool {.borrow.}
proc hash*(ver: Special): Hash {.borrow.}
proc isSpecial*(ver: Version): bool =
return ($ver)[0] == '#'
proc `<`*(ver: Version, ver2: Version): bool =
# Handling for special versions such as "#head" or "#branch".
if ver.isSpecial or ver2.isSpecial:
return false
# Handling for normal versions such as "0.1.0" or "1.0".
var sVer = string(ver).split('.')
var sVer2 = string(ver2).split('.')
for i in 0..max(sVer.len, sVer2.len)-1:
@ -65,6 +71,9 @@ proc `<`*(ver: Version, ver2: Version): bool =
return false
proc `==`*(ver: Version, ver2: Version): bool =
if ver.isSpecial or ver2.isSpecial:
return ($ver).toLowerAscii() == ($ver2).toLowerAscii()
var sVer = string(ver).split('.')
var sVer2 = string(ver2).split('.')
for i in 0..max(sVer.len, sVer2.len)-1:
@ -79,9 +88,6 @@ proc `==`*(ver: Version, ver2: Version): bool =
else:
return false
proc `==`*(spe: Special, spe2: Special): bool =
return ($spe).toLowerAscii() == ($spe2).toLowerAscii()
proc `<=`*(ver: Version, ver2: Version): bool =
return (ver == ver2) or (ver < ver2)
@ -97,39 +103,36 @@ proc `==`*(range1: VersionRange, range2: VersionRange): bool =
of verAny: true
proc withinRange*(ver: Version, ran: VersionRange): bool =
case ran.kind
of verLater:
return ver > ran.ver
of verEarlier:
return ver < ran.ver
of verEqLater:
return ver >= ran.ver
of verEqEarlier:
return ver <= ran.ver
of verEq:
return ver == ran.ver
of verSpecial:
return false
of verIntersect:
return withinRange(ver, ran.verILeft) and withinRange(ver, ran.verIRight)
of verAny:
return true
proc withinRange*(spe: Special, ran: VersionRange): bool =
case ran.kind
of verLater, verEarlier, verEqLater, verEqEarlier, verEq, verIntersect:
return false
of verSpecial:
return spe == ran.spe
of verAny:
return true
if ver.isSpecial:
case ran.kind
of verLater, verEarlier, verEqLater, verEqEarlier, verEq, verIntersect:
return false
of verSpecial:
return ver == ran.spe
of verAny:
return true
else:
case ran.kind
of verLater:
return ver > ran.ver
of verEarlier:
return ver < ran.ver
of verEqLater:
return ver >= ran.ver
of verEqEarlier:
return ver <= ran.ver
of verEq:
return ver == ran.ver
of verSpecial:
return false
of verIntersect:
return withinRange(ver, ran.verILeft) and withinRange(ver, ran.verIRight)
of verAny:
return true
proc contains*(ran: VersionRange, ver: Version): bool =
return withinRange(ver, ran)
proc contains*(ran: VersionRange, spe: Special): bool =
return withinRange(spe, ran)
proc makeRange*(version: string, op: string): VersionRange =
new(result)
if version == "":
@ -153,9 +156,13 @@ proc makeRange*(version: string, op: string): VersionRange =
proc parseVersionRange*(s: string): VersionRange =
# >= 1.5 & <= 1.8
new(result)
if s.len == 0:
result.kind = verAny
return
if s[0] == '#':
result.kind = verSpecial
result.spe = s[1 .. s.len-1].Special
result.spe = s.Version
return
var i = 0
@ -200,6 +207,15 @@ proc parseVersionRange*(s: string): VersionRange =
"Unexpected char in version range: " & s[i])
inc(i)
proc toVersionRange*(ver: Version): VersionRange =
## Converts a version to either a verEq or verSpecial VersionRange.
new(result)
if ver.isSpecial:
result.kind = verSpecial
result.spe = ver
else:
result.kind = verEq
result.ver = ver
proc parseRequires*(req: string): PkgTuple =
try:
@ -231,7 +247,7 @@ proc `$`*(verRange: VersionRange): string =
of verEq:
result = ""
of verSpecial:
return "#" & $verRange.spe
return $verRange.spe
of verIntersect:
return $verRange.verILeft & " & " & $verRange.verIRight
of verAny:
@ -312,13 +328,26 @@ when isMainModule:
#doAssert newVersion("0.1-rc1") < newVersion("0.1")
# Special tests
doAssert newSpecial("ab26sgdt362") != newSpecial("ab26saggdt362")
doAssert newSpecial("ab26saggdt362") == newSpecial("ab26saggdt362")
doAssert newSpecial("head") == newSpecial("HEAD")
doAssert newSpecial("head") == newSpecial("head")
doAssert newVersion("#ab26sgdt362") != newVersion("#qwersaggdt362")
doAssert newVersion("#ab26saggdt362") == newVersion("#ab26saggdt362")
doAssert newVersion("#head") == newVersion("#HEAD")
doAssert newVersion("#head") == newVersion("#head")
var sp = parseVersionRange("#ab26sgdt362")
doAssert newSpecial("ab26sgdt362") in sp
doAssert newSpecial("ab26saggdt362") notin sp
doAssert newVersion("#ab26sgdt362") in sp
doAssert newVersion("#ab26saggdt362") notin sp
doAssert newVersion("#head") in parseVersionRange("#head")
# TODO: It may be worth changing this in the future, although we can't be
# certain that #head is in fact newer than v0.1.0.
doAssert(not(newVersion("#head") > newVersion("0.1.0")))
# An empty version range should give verAny
doAssert parseVersionRange("").kind == verAny
# toVersionRange tests
doAssert toVersionRange(newVersion("#head")).kind == verSpecial
doAssert toVersionRange(newVersion("0.2.0")).kind == verEq
echo("Everything works!")