summaryrefslogtreecommitdiffstats
path: root/src/pyfedpkg/initial_merge.py
blob: 5bc119fe68248945c632e208515323044aadbda3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
#!/usr/bin/python
# initial_merge.py - perform initial merge after dist-git migration

"""\
Performs a 'git merge' of all git branches with the same content
(i.e. with the same package spec files, patch files, etc.), regardless
of their history.

This is useful after Fedora's dist-cvs to dist-git migration, as often
different branches have different histories but the same content on the
filesystem.

After these initial merges of identical trees, future merges between
the branches will be a lot easier: Easier to follow in the dependency
graph, and easier to perform without conflicts.
"""

# TODO: Use more pyfedpkg.* functions and/or git.* functions instead
#       of direct calls to git.

import argparse
import sys
import os
import subprocess
import pyfedpkg


__all__ = [
    'get_parser',
    'handle_path',
    'handle_curdir'
    ]


global global_dry_run
global_dry_run = False
# global_dry_run = True


def run_cmd_out(cmd, dry_run=None, shell=False):
    if dry_run==None:
        global global_dry_run
        dry_run = global_dry_run
    if dry_run:
        print 'RUN-', cmd
    else:
        print 'RUN:', cmd
    if dry_run:
        return (0,'','')
    proc = subprocess.Popen(cmd,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE,
                            shell=shell)
    stdout, stderr = proc.communicate()
    return (proc.returncode,stdout,stderr)


def run_cmd(cmd, dry_run=None, shell=False):
    retcode, stdout, stderr = run_cmd_out(cmd, dry_run=dry_run, shell=shell)
    sys.stdout.write(stdout)
    sys.stdout.write(stderr)
    return retcode


def cmp_Branch(a, b):
    if a.sha == b.sha:
        return cmp(a.localbranch,b.localbranch)
    else:
        return cmp(a.sha,b.sha)


class Branch:

    def __init__(self, string):
        self.sha, self.origbranch = string.split()
        a = self.origbranch.split('/')
        assert(a[0] == 'origin')
        assert(a[-1] == 'master')
        self.localbranch = a[1]

    def __repr__(self):
        return "%(sha)s %(origbranch)s" % self.__dict__


def do_initial_merge(into, to_merge):
    print
    print "######## Merging", [ x.localbranch for x in to_merge ], \
        "into", into.localbranch, "########"
    pyfedpkg.switch_branch(into.localbranch)
    ret = run_cmd(['git', 'merge',
                   '-m', '"Initial peudo merge for dist-git setup"',
                   '-s', 'ours'] +
                  [ x.origbranch for x in to_merge])
    assert(ret == 0)
    for t in to_merge:
        pyfedpkg.switch_branch(t.localbranch)
        ret = run_cmd(['git', 'merge', into.localbranch])
        assert(ret == 0)
    pyfedpkg.switch_branch(into.localbranch)


class Consumer:

    def __reset(self):
        self.branch_list = []

    def __init__(self):
        self.__reset()

    def __git_merge(self):
        head = self.branch_list[-1]
        others = self.branch_list[:-1]
        do_initial_merge(head, others)

    def __flush(self):
        if len(self.branch_list) < 2:
            return
        # print "Flush", self.branch_list
        self.__git_merge()
        self.__reset()

    def eat(self, item):
        if self.branch_list:
            last = self.branch_list[-1]
            if last.sha == item.sha:
                # print "  ", "=", item
                self.branch_list.extend([item])
            else:
                # print "  ", "?", item
                self.__flush()
                self.branch_list = [item]
        else:
            self.branch_list = [item]

    def finish(self):
        self.__flush()


def handle_curdir():
    git_branch_cmd = """for branch in $(git branch -r | grep -v '/HEAD'); do echo "$(git rev-parse "$branch^{tree}") $branch"; done"""
    retcode, stdout, stderr = run_cmd_out(git_branch_cmd,
                                          dry_run=False, shell=True)
    assert(retcode == 0)
    assert(stderr == "")
    # print "RESULT:"
    # sys.stdout.write(stdout)

    a = stdout.splitlines()
    a = [ Branch(s) for s in a ]
    a.sort(cmp_Branch)
    # print "SORTED:"
    for x in a: print "  ", x

    # print "ITERATING:"
    n = 0
    c = Consumer()
    while n < len(a):
        c.eat(a[n])
        n = n + 1
    c.finish()

    print
    print "FINISHED."


def handle_path(path=None):
    if not path:
        path = os.getcwd()
    oldcwd = os.getcwd()
    os.chdir(path)
    print "########", "Entering", path, "########"
    handle_curdir()
    print "Leaving", os.getcwd()
    os.chdir(oldcwd)


class Action(argparse.Action):

    def __init__(self, *args, **kwargs):
        super(Action, self).__init__(*args, **kwargs)
        self.default_value = ['.']

    def __call__(self, parser, namespace, values, option_string=None):
        if values:
            setattr(namespace, self.dest, values)
        else:
            setattr(namespace, self.dest, self.default)


def fedpkg_command(args):
    global global_dry_run
    global_dry_run = args.dry_run
    if global_dry_run:
        print "NOTE: Running in dry-run mode, i.e. we will not actually perform any merges."
    for repo in args.repos:
        handle_path(repo)


_module_doc = __doc__


def get_parser(subparsers):
    sp = subparsers.add_parser('initial-merge',
                               help = 'git merge to join branches with identical trees',
                               formatter_class=argparse.RawDescriptionHelpFormatter,
                               description = _module_doc)
    sp.add_argument('-n', '--dry-run',
                    dest='dry_run',
                    action='store_const', const=True,
                    default=False,
                    help = ('Whether to actually perform the merges. '+
                            'Local tracking branches will be created anyway.'))
    sp.add_argument('repos', metavar='repo-path',
                    nargs='*', default=['.'],
                    action=Action,
                    help = 'Path to a repo to initial-merge')
    sp.set_defaults(command = fedpkg_command)
    return sp