Refactor duplicated code in dependencies handling

Whether we're dealing with depends-on or needed-by, the code is
essentially the same, so let's refactor it.

Change-Id: Ibea8a46059b0da5b23af33236bc53952d90e716e