# Path: alibuild_helpers/utilities.py
# def parseRecipe(reader):
#   assert(reader.__call__)
#   err, spec, recipe = (None, None, None)
#   try:
#     d = reader()
#     header,recipe = d.split("---", 1)
#     spec = yamlLoad(header)
#     validateSpec(spec)
#   except RuntimeError as e:
#     err = str(e)
#   except IOError as e:
#     err = str(e)
#   except SpecError as e:
#     err = "Malformed header for %s\n%s" % (reader.url, str(e))
#   except yaml.scanner.ScannerError as e:
#     err = "Unable to parse %s\n%s" % (reader.url, str(e))
#   except yaml.parser.ParserError as e:
#     err = "Unable to parse %s\n%s" % (reader.url, str(e))
#   except ValueError as e:
#     err = "Unable to parse %s. Header missing." % reader.url
#   return err, spec, recipe
# 
# def getRecipeReader(url, dist=None):
#   m = re.search(r'^dist:(.*)@([^@]+)$', url)
#   if m and dist:
#     return GitReader(url, dist)
#   else:
#     return FileReader(url)
# 
# def parseDefaults(disable, defaultsGetter, log):
#   defaultsMeta, defaultsBody = defaultsGetter()
#   # Defaults are actually special packages. They can override metadata
#   # of any other package and they can disable other packages. For
#   # example they could decide to switch from ROOT 5 to ROOT 6 and they
#   # could disable alien for O2. For this reason we need to parse their
#   # metadata early and extract the override and disable data.
#   defaultsDisable = asList(defaultsMeta.get("disable", []))
#   for x in defaultsDisable:
#     log("Package %s has been disabled by current default.", x)
#   disable.extend(defaultsDisable)
#   if type(defaultsMeta.get("overrides", OrderedDict())) != OrderedDict:
#     return ("overrides should be a dictionary", None, None)
#   overrides, taps = OrderedDict(), {}
#   commonEnv = {"env": defaultsMeta["env"]} if "env" in defaultsMeta else {}
#   overrides["defaults-release"] = commonEnv
#   for k, v in defaultsMeta.get("overrides", {}).items():
#     f = k.split("@", 1)[0].lower()
#     if "@" in k:
#       taps[f] = "dist:"+k
#     overrides[f] = dict(**(v or {}))
#   return (None, overrides, taps)
# 
# Path: alibuild_helpers/utilities.py
# class FileReader(object):
#   def __init__(self, url):
#     self.url = url
#   def __call__(self):
#     return open(self.url).read()
# 
# class GitReader(object):
#   def __init__(self, url, configDir):
#     self.url, self.configDir = url, configDir
#   def __call__(self):
#     m = re.search(r'^dist:(.*)@([^@]+)$', self.url)
#     fn,gh = m.groups()
#     err,d = getstatusoutput(format("GIT_DIR=%(dist)s/.git git show %(gh)s:%(fn)s.sh",
#                                    dist=self.configDir, gh=gh, fn=fn.lower()))
#     if err:
#       raise RuntimeError(format("Cannot read recipe %(fn)s from reference %(gh)s.\n" +
#                                 "Make sure you run first (this will not alter your recipes):\n" +
#                                 "  cd %(dist)s && git remote update -p && git fetch --tags",
#                                 dist=self.configDir, gh=gh, fn=fn))
#     return d
# 
# Path: alibuild_helpers/utilities.py
# def validateDefaults(finalPkgSpec, defaults):
#   if not "valid_defaults" in finalPkgSpec:
#     return (True, "", [])
#   validDefaults = asList(finalPkgSpec["valid_defaults"])
#   nonStringDefaults = [x for x in validDefaults if not type(x) == str]
#   if nonStringDefaults:
#     return (False, "valid_defaults needs to be a string or a list of strings. Found %s." % nonStringDefaults, [])
#   if defaults in validDefaults:
#     return (True, "", validDefaults)
#   return (False, "Cannot compile %s with `%s' default. Valid defaults are\n%s" % 
#                   (finalPkgSpec["package"],
#                    defaults,
#                    "\n".join([" - " + x for x in validDefaults])), validDefaults)
# 
# class SpecError(Exception):
#   pass


import unittest
import platform
from alibuild_helpers.utilities import parseRecipe, getRecipeReader, parseDefaults
from alibuild_helpers.utilities import FileReader, GitReader
from alibuild_helpers.utilities import validateDefaults, SpecError
  from collections import OrderedDict
  from ordereddict import OrderedDict
    err, meta, body = parseRecipe(BufferReader("test_broken_5.sh", TEST_BROKEN_5))
    self.assertEqual(err, ERROR_MSG_5)
    err, meta, body = parseRecipe(BufferReader("test_broken_6.sh", TEST_BROKEN_6))
    self.assertEqual(err.strip(), ERROR_MSG_6.strip())

  def test_getRecipeReader(self):
    f = getRecipeReader("foo")
    self.assertEqual(type(f), FileReader)
    f = getRecipeReader("dist:foo@master")
    self.assertEqual(type(f), FileReader)
    f = getRecipeReader("dist:foo@master", "alidist")
    self.assertEqual(type(f), GitReader)

  def test_parseDefaults(self):
    disable = ["bar"]
    err, overrides, taps = parseDefaults(disable,
                                        lambda: ({ "disable": "foo",
                                                   "overrides": OrderedDict({"ROOT@master": {"requires": "GCC"}})},
                                                 ""),
                                        Recoder())
    self.assertEqual(disable, ["bar", "foo"])
    self.assertEqual(overrides, {'defaults-release': {}, 'root': {'requires': 'GCC'}})
    self.assertEqual(taps, {'root': 'dist:ROOT@master'})

  def test_validateDefault(self):
    ok, out, validDefaults = validateDefaults({"something": True}, "release")
    self.assertEqual(ok, True)
    ok, out, validDefaults = validateDefaults({"package": "foo","valid_defaults": ["o2", "o2-dataflow"]}, "release")
    self.assertEqual(ok, False)
    self.assertEqual(out, 'Cannot compile foo with `release\' default. Valid defaults are\n - o2\n - o2-dataflow')

# Path: alibuild_helpers/utilities.py
# def parseRecipe(reader):
#   assert(reader.__call__)
#   err, spec, recipe = (None, None, None)
#   try:
#     d = reader()
#     header,recipe = d.split("---", 1)
#     spec = yamlLoad(header)
#     validateSpec(spec)
#   except RuntimeError as e:
#     err = str(e)
#   except IOError as e:
#     err = str(e)
#   except SpecError as e:
#     err = "Malformed header for %s\n%s" % (reader.url, str(e))
#   except yaml.scanner.ScannerError as e:
#     err = "Unable to parse %s\n%s" % (reader.url, str(e))
#   except yaml.parser.ParserError as e:
#     err = "Unable to parse %s\n%s" % (reader.url, str(e))
#   except ValueError as e:
#     err = "Unable to parse %s. Header missing." % reader.url
#   return err, spec, recipe
# 
# def getRecipeReader(url, dist=None):
#   m = re.search(r'^dist:(.*)@([^@]+)$', url)
#   if m and dist:
#     return GitReader(url, dist)
#   else:
#     return FileReader(url)
# 
# def parseDefaults(disable, defaultsGetter, log):
#   defaultsMeta, defaultsBody = defaultsGetter()
#   # Defaults are actually special packages. They can override metadata
#   # of any other package and they can disable other packages. For
#   # example they could decide to switch from ROOT 5 to ROOT 6 and they
#   # could disable alien for O2. For this reason we need to parse their
#   # metadata early and extract the override and disable data.
#   defaultsDisable = asList(defaultsMeta.get("disable", []))
#   for x in defaultsDisable:
#     log("Package %s has been disabled by current default.", x)
#   disable.extend(defaultsDisable)
#   if type(defaultsMeta.get("overrides", OrderedDict())) != OrderedDict:
#     return ("overrides should be a dictionary", None, None)
#   overrides, taps = OrderedDict(), {}
#   commonEnv = {"env": defaultsMeta["env"]} if "env" in defaultsMeta else {}
#   overrides["defaults-release"] = commonEnv
#   for k, v in defaultsMeta.get("overrides", {}).items():
#     f = k.split("@", 1)[0].lower()
#     if "@" in k:
#       taps[f] = "dist:"+k
#     overrides[f] = dict(**(v or {}))
#   return (None, overrides, taps)
# 
# Path: alibuild_helpers/utilities.py
# class FileReader(object):
#   def __init__(self, url):
#     self.url = url
#   def __call__(self):
#     return open(self.url).read()
# 
# class GitReader(object):
#   def __init__(self, url, configDir):
#     self.url, self.configDir = url, configDir
#   def __call__(self):
#     m = re.search(r'^dist:(.*)@([^@]+)$', self.url)
#     fn,gh = m.groups()
#     err,d = getstatusoutput(format("GIT_DIR=%(dist)s/.git git show %(gh)s:%(fn)s.sh",
#                                    dist=self.configDir, gh=gh, fn=fn.lower()))
#     if err:
#       raise RuntimeError(format("Cannot read recipe %(fn)s from reference %(gh)s.\n" +
#                                 "Make sure you run first (this will not alter your recipes):\n" +
#                                 "  cd %(dist)s && git remote update -p && git fetch --tags",
#                                 dist=self.configDir, gh=gh, fn=fn))
#     return d
# 
# Path: alibuild_helpers/utilities.py
# def validateDefaults(finalPkgSpec, defaults):
#   if not "valid_defaults" in finalPkgSpec:
#     return (True, "", [])
#   validDefaults = asList(finalPkgSpec["valid_defaults"])
#   nonStringDefaults = [x for x in validDefaults if not type(x) == str]
#   if nonStringDefaults:
#     return (False, "valid_defaults needs to be a string or a list of strings. Found %s." % nonStringDefaults, [])
#   if defaults in validDefaults:
#     return (True, "", validDefaults)
#   return (False, "Cannot compile %s with `%s' default. Valid defaults are\n%s" % 
#                   (finalPkgSpec["package"],
#                    defaults,
#                    "\n".join([" - " + x for x in validDefaults])), validDefaults)
# 
# class SpecError(Exception):
#   pass


# Path: tests/test_parseRecipe.py
import unittest
import platform
from alibuild_helpers.utilities import parseRecipe, getRecipeReader, parseDefaults
from alibuild_helpers.utilities import FileReader, GitReader
from alibuild_helpers.utilities import validateDefaults, SpecError
  from collections import OrderedDict
  from ordereddict import OrderedDict

    err, meta, body = parseRecipe(BufferReader("test_broken_5.sh", TEST_BROKEN_5))
    self.assertEqual(err, ERROR_MSG_5)
    err, meta, body = parseRecipe(BufferReader("test_broken_6.sh", TEST_BROKEN_6))
    self.assertEqual(err.strip(), ERROR_MSG_6.strip())

  def test_getRecipeReader(self):
    f = getRecipeReader("foo")
    self.assertEqual(type(f), FileReader)
    f = getRecipeReader("dist:foo@master")
    self.assertEqual(type(f), FileReader)
    f = getRecipeReader("dist:foo@master", "alidist")
    self.assertEqual(type(f), GitReader)

  def test_parseDefaults(self):
    disable = ["bar"]
    err, overrides, taps = parseDefaults(disable,
                                        lambda: ({ "disable": "foo",
                                                   "overrides": OrderedDict({"ROOT@master": {"requires": "GCC"}})},
                                                 ""),
                                        Recoder())
    self.assertEqual(disable, ["bar", "foo"])
    self.assertEqual(overrides, {'defaults-release': {}, 'root': {'requires': 'GCC'}})
    self.assertEqual(taps, {'root': 'dist:ROOT@master'})

  def test_validateDefault(self):
    ok, out, validDefaults = validateDefaults({"something": True}, "release")
    self.assertEqual(ok, True)
    ok, out, validDefaults = validateDefaults({"package": "foo","valid_defaults": ["o2", "o2-dataflow"]}, "release")
    self.assertEqual(ok, False)
    self.assertEqual(out, 'Cannot compile foo with `release\' default. Valid defaults are\n - o2\n - o2-dataflow')

    ok, out, validDefaults = validateDefaults({"package": "foo","valid_defaults": ["o2", "o2-dataflow"]}, "o2")