import re


def GetTagsFromLocation(tags, test_location, component, watchlists):
  """Updates location-based tags for a test.

  Args:
    tags ([str]): Tags that specify the category of the test.
    test_location (TestLocation): The location of a test in the source tree.
    component (str): The component of the test.
    watchlists (dict): Mapping from directories to watchlists.
  Returns:
    Alphabetically sorted tags for a test with updated location-based tags.
  """
  new_tags = set([
      t for t in (tags or [])
      if not t.startswith(('watchlist::', 'directory::', 'source::',
                           'parent_component::', 'component::'))
  ])

  file_path = test_location.file_path
  index = len(file_path)
  while index > 0:
    index = file_path.rfind('/', 0, index)
    if index > 0:
      new_tags.add('directory::%s' % file_path[0:index + 1])
  new_tags.add('source::%s' % file_path)

  for watchlist, pattern in watchlists.iteritems():
    if re.search(pattern, file_path):
      new_tags.add('watchlist::%s' % watchlist)

  new_tags.add('component::%s' % component)
  new_tags.add('parent_component::%s' % component)
  index = len(component)
  while index > 0:
    index = component.rfind('>', 0, index)
    if index > 0:
      new_tags.add('parent_component::%s' % component[0:index])
  return sorted(new_tags)