'Take a result from changes() and a MigrationGraph, and fix the names
and dependencies of the changes so they extend the graph from the leaf
nodes for each app.'

def arrange_for_graph(self, changes, graph, migration_name=None):

    leaves = graph.leaf_nodes()
    name_map = {}
    for (app_label, migrations) in list(changes.items()):
        if (not migrations):
            continue
        app_leaf = None
        for leaf in leaves:
            if (leaf[0] == app_label):
                app_leaf = leaf
                break
        if ((app_leaf is None) and (not self.questioner.ask_initial(app_label))):
            for migration in migrations:
                name_map[(app_label, migration.name)] = (app_label, '__first__')
            del changes[app_label]
            continue
        if (app_leaf is None):
            next_number = 1
        else:
            next_number = ((self.parse_number(app_leaf[1]) or 0) + 1)
        for (i, migration) in enumerate(migrations):
            if ((i == 0) and app_leaf):
                migration.dependencies.append(app_leaf)
            if ((i == 0) and (not app_leaf)):
                new_name = (('0001_%s' % migration_name) if migration_name else '0001_initial')
            else:
                new_name = ('%04i_%s' % (next_number, (migration_name or self.suggest_name(migration.operations)[:100])))
            name_map[(app_label, migration.name)] = (app_label, new_name)
            next_number += 1
            migration.name = new_name
    for (app_label, migrations) in changes.items():
        for migration in migrations:
            migration.dependencies = [name_map.get(d, d) for d in migration.dependencies]
    return changes
