Exemple #1
0
class ZincAnalysisElementDiff(object):
  def __init__(self, left_elem, right_elem, keys_only_headers=None):
    left_type = type(left_elem)
    right_type = type(right_elem)
    if left_type != right_type:
      raise Exception('Cannot compare elements of types %s and %s' % (left_type, right_type))
    self._arg_diffs = OrderedDict()
    for header, left_dict, right_dict in zip(left_elem.headers, left_elem.args, right_elem.args):
      keys_only = header in (keys_only_headers or [])
      self._arg_diffs[header] = DictDiff(left_dict, right_dict, keys_only=keys_only)

  def is_different(self):
    return any([x.is_different() for x in self._arg_diffs.values()])

  def __unicode__(self):
    parts = []
    for header, arg_diff in self._arg_diffs.items():
      if arg_diff.is_different():
        parts.append('Section "%s" differs:\n' % header)
        parts.append(arg_diff)
        parts.append('\n\n')
    return ''.join(parts)  # '' is a unicode, so the entire result will be.

  def __str__(self):
    if Compatibility.PY3:
      return self.__unicode__()
    else:
      return self.__unicode__().encode('utf-8')
Exemple #2
0
  def _record(self, goal, elapsed):
    phase = Phase.of(goal)

    phase_timings = self._timings.get(phase)
    if phase_timings is None:
      phase_timings = OrderedDict(())
      self._timings[phase] = phase_timings

    goal_timings = phase_timings.get(goal)
    if goal_timings is None:
      goal_timings = []
      phase_timings[goal] = goal_timings

    goal_timings.append(elapsed)
Exemple #3
0
 def __init__(self, left_elem, right_elem, keys_only_headers=None):
   left_type = type(left_elem)
   right_type = type(right_elem)
   if left_type != right_type:
     raise Exception('Cannot compare elements of types %s and %s' % (left_type, right_type))
   self._arg_diffs = OrderedDict()
   for header, left_dict, right_dict in zip(left_elem.headers, left_elem.args, right_elem.args):
     keys_only = header in (keys_only_headers or [])
     self._arg_diffs[header] = DictDiff(left_dict, right_dict, keys_only=keys_only)
Exemple #4
0
  def _topological_sort(self, phase_info_by_phase):
    dependees_by_phase = OrderedDict()

    def add_dependee(phase, dependee=None):
      dependees = dependees_by_phase.get(phase)
      if dependees is None:
        dependees = set()
        dependees_by_phase[phase] = dependees
      if dependee:
        dependees.add(dependee)

    for phase, phase_info in phase_info_by_phase.items():
      add_dependee(phase)
      for dependency in phase_info.phase_dependencies:
        add_dependee(dependency, phase)

    satisfied = set()
    while dependees_by_phase:
      count = len(dependees_by_phase)
      for phase, dependees in dependees_by_phase.items():
        unsatisfied = len(dependees - satisfied)
        if unsatisfied == 0:
          satisfied.add(phase)
          dependees_by_phase.pop(phase)
          yield phase_info_by_phase[phase]
          break
      if len(dependees_by_phase) == count:
        for dependees in dependees_by_phase.values():
          dependees.difference_update(satisfied)
        # TODO(John Sirois): Do a better job here and actually collect and print cycle paths
        # between Goals/Tasks.  The developer can most directly address that data.
        raise self.PhaseCycleError('Cycle detected in phase dependencies:\n\t{0}'
                                   .format('\n\t'.join('{0} <- {1}'.format(phase, list(dependees))
                                                       for phase, dependees
                                                       in dependees_by_phase.items())))
Exemple #5
0
  def _topological_sort(self, goal_info_by_goal):
    dependees_by_goal = OrderedDict()

    def add_dependee(goal, dependee=None):
      dependees = dependees_by_goal.get(goal)
      if dependees is None:
        dependees = set()
        dependees_by_goal[goal] = dependees
      if dependee:
        dependees.add(dependee)

    for goal, goal_info in goal_info_by_goal.items():
      add_dependee(goal)
      for dependency in goal_info.goal_dependencies:
        add_dependee(dependency, goal)

    satisfied = set()
    while dependees_by_goal:
      count = len(dependees_by_goal)
      for goal, dependees in dependees_by_goal.items():
        unsatisfied = len(dependees - satisfied)
        if unsatisfied == 0:
          satisfied.add(goal)
          dependees_by_goal.pop(goal)
          yield goal_info_by_goal[goal]
          break
      if len(dependees_by_goal) == count:
        for dependees in dependees_by_goal.values():
          dependees.difference_update(satisfied)
        # TODO(John Sirois): Do a better job here and actually collect and print cycle paths
        # between Goals/Tasks.  The developer can most directly address that data.
        raise self.GoalCycleError('Cycle detected in goal dependencies:\n\t{0}'
                                   .format('\n\t'.join('{0} <- {1}'.format(goal, list(dependees))
                                                       for goal, dependees
                                                       in dependees_by_goal.items())))
Exemple #6
0
  def _mapped_dependencies(self, jardepmap, binary, confs):
    # TODO(John Sirois): rework product mapping towards well known types

    # Generate a map of jars for each unique artifact (org, name)
    externaljars = OrderedDict()
    visited = set()
    for conf in confs:
      mapped = jardepmap.get((binary, conf))
      if mapped:
        for basedir, jars in mapped.items():
          for externaljar in jars:
            if (basedir, externaljar) not in visited:
              visited.add((basedir, externaljar))
              keys = jardepmap.keys_for(basedir, externaljar)
              for key in keys:
                if isinstance(key, tuple) and len(key) == 3:
                  org, name, configuration = key
                  classpath_entry = externaljars.get((org, name))
                  if not classpath_entry:
                    classpath_entry = {}
                    externaljars[(org, name)] = classpath_entry
                  classpath_entry[conf] = os.path.join(basedir, externaljar)
    return externaljars.values()
Exemple #7
0
  def __init__(self, timer=None):
    """Creates a timer that uses time.time for timing intervals by default.

    :param timer:  A callable that returns the current time in fractional seconds.
    """
    self._now = timer or time.time
    if not(callable(self._now)):
      # TODO(John Sirois): `def jake(bob): pass` is also callable - we want a no-args callable -
      # create a better check.
      raise ValueError('Timer must be a callable object.')

    self._timings = OrderedDict()
    self._elapsed = None
    self._start = self._now()
Exemple #8
0
class Timer(object):
  """Provides timing support for goal execution."""

  @classmethod
  @contextmanager
  def begin(cls, timer=None):
    """Begins a new ``Timer`` and yields it in a with context.

    The timer will be finished if not already by the block yielded to.
    """
    t = Timer(timer)
    try:
      yield t
    finally:
      t.finish()

  def __init__(self, timer=None):
    """Creates a timer that uses time.time for timing intervals by default.

    :param timer:  A callable that returns the current time in fractional seconds.
    """
    self._now = timer or time.time
    if not(callable(self._now)):
      # TODO(John Sirois): `def jake(bob): pass` is also callable - we want a no-args callable -
      # create a better check.
      raise ValueError('Timer must be a callable object.')

    self._timings = OrderedDict()
    self._elapsed = None
    self._start = self._now()

  def finish(self):
    """Finishes this timer if not already finished.

    Calls to ``timed`` after this will raise a ValueError since the timing window is complete.
    """
    if self._elapsed is None:
      self._elapsed = self._now() - self._start

  @property
  def timings(self):
    """Returns the phase timings as an ordered mapping from the ``Phase`` objects executed to
    ordered mappings of the ``Goal`` objects executed in the phase to the list of timings
    corresponding to each execution of the goal.

    Note that the list of timings will be singleton for all goals except those participating in a
    ``Group``.  Grouped goals will have or more timings in the list corresponding to each chunk of
    targets the goal executed against when iterating the group.
    """
    return self._timings

  @property
  def elapsed(self):
    """Returns the total elapsed time in fractional seconds from the creation of this timer until
    it was ``finished``.
    """
    if self._elapsed is None:
      raise ValueError('Timer has not been finished yet.')
    return self._elapsed

  @contextmanager
  def timed(self, goal):
    """Records the time taken to execute the yielded block an records this timing against the given
    goal's total runtime.
    """
    if self._elapsed is not None:
      raise ValueError('This timer is already finished.')

    start = self._now()
    try:
      yield
    finally:
      self._record(goal, self._now() - start)

  def _record(self, goal, elapsed):
    phase = Phase.of(goal)

    phase_timings = self._timings.get(phase)
    if phase_timings is None:
      phase_timings = OrderedDict(())
      self._timings[phase] = phase_timings

    goal_timings = phase_timings.get(goal)
    if goal_timings is None:
      goal_timings = []
      phase_timings[goal] = goal_timings

    goal_timings.append(elapsed)

  def render_timing_report(self):
    """Renders this timer's timings into the classic pants timing report format."""
    report = ('Timing report\n'
              '=============\n')
    for phase, timings in self.timings.items():
      phase_time = None
      for goal, times in timings.items():
        if len(times) > 1:
          report += '[%(phase)s:%(goal)s(%(numsteps)d)] %(timings)s -> %(total).3fs\n' % {
            'phase': phase.name,
            'goal': goal.name,
            'numsteps': len(times),
            'timings': ','.join('%.3fs' % t for t in times),
            'total': sum(times)
          }
        else:
          report += '[%(phase)s:%(goal)s] %(total).3fs\n' % {
            'phase': phase.name,
            'goal': goal.name,
            'total': sum(times)
          }
        if not phase_time:
          phase_time = 0
        phase_time += sum(times)
      if len(timings) > 1:
        report += '[%(phase)s] total: %(total).3fs\n' % {
          'phase': phase.name,
          'total': phase_time
        }
    report += 'total: %.3fs' % self.elapsed
    return report
Exemple #9
0
        for file in files:
          file = file.decode('utf-8')
          full_path = os.path.join(root, file)
          relpath = os.path.relpath(full_path, basedir)
          if prefix:
            relpath = os.path.join(prefix.decode('utf-8'), relpath)
          zip.write(full_path, relpath)
    return zippath


TAR = TarArchiver('w:', 'tar')
TGZ = TarArchiver('w:gz', 'tar.gz')
TBZ2 = TarArchiver('w:bz2', 'tar.bz2')
ZIP = ZipArchiver(ZIP_DEFLATED)

_ARCHIVER_BY_TYPE = OrderedDict(tar=TGZ, tgz=TGZ, tbz2=TBZ2, zip=ZIP)

TYPE_NAMES = frozenset(_ARCHIVER_BY_TYPE.keys())


def archiver(typename):
  """Returns Archivers in common configurations.

  The typename must correspond to one of the following:
  'tar'   Returns a tar archiver that applies no compression and emits .tar files.
  'tgz'   Returns a tar archiver that applies gzip compression and emits .tar.gz files.
  'tbz2'  Returns a tar archiver that applies bzip2 compression and emits .tar.bz2 files.
  'zip'   Returns a zip archiver that applies standard compression and emits .zip files.
  """
  archiver = _ARCHIVER_BY_TYPE.get(typename)
  if not archiver: