]> git.pld-linux.org Git - packages/git-core-slug.git/blob - git-core-slug-git.patch
- rel 10; better keyboard interrupt handling
[packages/git-core-slug.git] / git-core-slug-git.patch
1 diff --git a/git_slug/gitrepo.py b/git_slug/gitrepo.py
2 index 5234deb..d9f88ee 100644
3 --- a/git_slug/gitrepo.py
4 +++ b/git_slug/gitrepo.py
5 @@ -82,12 +82,21 @@ class GitRepo:
6              'refs/notes/*:refs/notes/*'])
7  
8      def check_remote(self, ref, remote=REMOTE_NAME):
9 +        localref = EMPTYSHA1
10          ref = ref.replace(REFFILE, os.path.join('remotes', remote))
11          try:
12              with open(os.path.join(self.gdir, ref), 'r') as f:
13                  localref = f.readline().strip()
14          except IOError:
15 -            localref = EMPTYSHA1
16 +            try:
17 +                with open(os.path.join(self.gdir, 'packed-refs')) as f:
18 +                    for line in f:
19 +                        line_data = line.split()
20 +                        if len(line_data) == 2 and line_data[1] == ref:
21 +                            localref = line_data[0].strip()
22 +                            break
23 +            except IOError:
24 +                pass
25          return localref
26  
27      def showfile(self, filename, ref="/".join([REMOTE_NAME, "master"])):
28 diff --git a/git_slug/refsdata.py b/git_slug/refsdata.py
29 index 4354ac4..67592f8 100644
30 --- a/git_slug/refsdata.py
31 +++ b/git_slug/refsdata.py
32 @@ -16,7 +16,7 @@ class NoMatchedRepos(Exception):
33  
34  class RemoteRefsData:
35      def __init__(self, stream, pattern, dirpattern=('*',)):
36 -        self.heads = collections.defaultdict(lambda: collections.defaultdict(lambda: EMPTYSHA1))
37 +        self.heads = collections.defaultdict(self.__dict_var__)
38          pats = re.compile('|'.join(fnmatch.translate(os.path.join('refs/heads', p)) for p in pattern))
39          dirpat = re.compile('|'.join(fnmatch.translate(p) for p in dirpattern))
40          for line in stream.readlines():
41 @@ -28,6 +28,12 @@ class RemoteRefsData:
42          if not self.heads:
43              raise NoMatchedRepos
44  
45 +    def __dict_init__(self):
46 +        return EMPTYSHA1
47 +
48 +    def __dict_var__(self):
49 +        return collections.defaultdict(self.__dict_init__)
50 +
51      def put(self, repo, data):
52          for line in data:
53              (sha1_old, sha1, ref) = line.split()
54 diff --git a/slug.py b/slug.py
55 index 69bd3b9..17a67e7 100755
56 --- a/slug.py
57 +++ b/slug.py
58 @@ -7,26 +7,18 @@ import os
59  import shutil
60  import subprocess
61  import queue
62 -import threading
63 -
64 +import multiprocessing
65  import argparse
66  
67  import signal
68  import configparser
69  
70 +from multiprocessing import Pool as WorkerPool
71 +
72  from git_slug.gitconst import GITLOGIN, GITSERVER, GIT_REPO, GIT_REPO_PUSH, REMOTE_NAME, REMOTEREFS
73  from git_slug.gitrepo import GitRepo, GitRepoError
74  from git_slug.refsdata import GitArchiveRefsData, NoMatchedRepos, RemoteRefsError
75  
76 -class Store():
77 -    def __init__(self):
78 -        self.lock = threading.Lock()
79 -        self.items = []
80 -
81 -    def put(self, item):
82 -        with self.lock:
83 -            self.items.append(item)
84 -
85  class UnquoteConfig(configparser.ConfigParser):
86      def get(self, section, option, **kwargs):
87          value = super().get(section, option, **kwargs)
88 @@ -43,25 +35,30 @@ class DelAppend(argparse._AppendAction):
89          item.append(values)
90          setattr(namespace, self.dest, item)
91  
92 -class ThreadFetch(threading.Thread):
93 -    def __init__(self, queue, output, pkgdir, depth=0):
94 -        threading.Thread.__init__(self)
95 -        self.queue = queue
96 -        self.packagesdir = pkgdir
97 -        self.depth = depth
98 -        self.output = output
99 -
100 -    def run(self):
101 -        while True:
102 -            (gitrepo, ref2fetch) = self.queue.get()
103 -            try:
104 -                (stdout, stderr) = gitrepo.fetch(ref2fetch, self.depth)
105 -                if stderr != b'':
106 -                    print('------', gitrepo.gdir[:-len('.git')], '------\n' + stderr.decode('utf-8'))
107 -                    self.output.put(gitrepo)
108 -            except GitRepoError as e:
109 -                print('------', gitrepo.gdir[:-len('.git')], '------\n', e)
110 -            self.queue.task_done()
111 +def cpu_count():
112 +    try:
113 +        return multiprocessing.cpu_count()
114 +    except NotImplementedError:
115 +        pass
116 +    return 4
117 +
118 +def pool_worker_init():
119 +    signal.signal(signal.SIGINT, signal.SIG_IGN)
120 +
121 +def run_worker(function, options, args):
122 +    ret = []
123 +    pool = WorkerPool(options.jobs, pool_worker_init)
124 +    try:
125 +        ret = pool.starmap(function, args)
126 +        pool.close()
127 +        pool.join()
128 +        ret = list(filter(None, ret))
129 +    except KeyboardInterrupt:
130 +        print('Keyboard interrupt received, finishing...', file=sys.stderr)
131 +        pool.terminate()
132 +        pool.join()
133 +        sys.exit(1)
134 +    return ret
135  
136  def readconfig(path):
137      config = UnquoteConfig(delimiters='=', interpolation=None, strict=False)
138 @@ -114,38 +111,45 @@ def getrefs(*args):
139          sys.exit(2)
140      return refs
141  
142 -def fetch_packages(options, return_all=False):
143 -    fetch_queue = queue.Queue()
144 -    updated_repos = Store()
145 -    for i in range(options.jobs):
146 -        t = ThreadFetch(fetch_queue, updated_repos, options.packagesdir, options.depth)
147 -        t.setDaemon(True)
148 -        t.start()
149 -
150 -    signal.signal(signal.SIGINT, signal.SIG_DFL)
151 +def fetch_package(gitrepo, refs_heads, options):
152 +    ref2fetch = []
153 +    for ref in refs_heads:
154 +        if gitrepo.check_remote(ref) != refs_heads[ref]:
155 +            ref2fetch.append('+{}:{}/{}'.format(ref, REMOTEREFS, ref[len('refs/heads/'):]))
156 +    if ref2fetch:
157 +        ref2fetch.append('refs/notes/*:refs/notes/*')
158 +    else:
159 +        return
160  
161 +    try:
162 +        (stdout, stderr) = gitrepo.fetch(ref2fetch, options.depth)
163 +        if stderr != b'':
164 +            print('------', gitrepo.gdir[:-len('.git')], '------\n' + stderr.decode('utf-8'))
165 +            return gitrepo
166 +    except GitRepoError as e:
167 +        print('------', gitrepo.gdir[:-len('.git')], '------\n', e)
168 +         
169 +def fetch_packages(options, return_all=False):
170      refs = getrefs(options.branch, options.repopattern)
171      print('Read remotes data')
172 +    pkgs_new = []
173 +    if options.newpkgs:
174 +        for pkgdir in sorted(refs.heads):
175 +            gitdir = os.path.join(options.packagesdir, pkgdir, '.git')
176 +            if not os.path.isdir(gitdir):
177 +                pkgs_new.append(pkgdir)
178 +
179 +        run_worker(initpackage, options, zip(pkgs_new, [options] * len(pkgs_new)))
180 +
181 +    args = []
182      for pkgdir in sorted(refs.heads):
183 -        gitdir = os.path.join(options.packagesdir, pkgdir, '.git')
184 -        if not os.path.isdir(gitdir):
185 -            if options.newpkgs:
186 -                gitrepo = initpackage(pkgdir, options)
187 -            else:
188 -                continue
189 -        elif options.omitexisting:
190 +        if options.omitexisting and pkgdir not in pkgs_new:
191              continue
192          else:
193              gitrepo = GitRepo(os.path.join(options.packagesdir, pkgdir))
194 -        ref2fetch = []
195 -        for ref in refs.heads[pkgdir]:
196 -            if gitrepo.check_remote(ref) != refs.heads[pkgdir][ref]:
197 -                ref2fetch.append('+{}:{}/{}'.format(ref, REMOTEREFS, ref[len('refs/heads/'):]))
198 -        if ref2fetch:
199 -            ref2fetch.append('refs/notes/*:refs/notes/*')
200 -            fetch_queue.put((gitrepo, ref2fetch))
201 +            args.append((gitrepo, refs.heads[pkgdir], options))
202  
203 -    fetch_queue.join()
204 +    updated_repos = run_worker(fetch_package, options, args)
205  
206      if options.prune:
207          refs = getrefs('*')
208 @@ -158,26 +162,47 @@ def fetch_packages(options, return_all=False):
209      if return_all:
210          return refs.heads
211      else:
212 -        return updated_repos.items
213 +        return updated_repos
214 +
215 +def checkout_package(repo, options):
216 +    try:
217 +        repo.checkout(options.checkout)
218 +    except GitRepoError as e:
219 +        print('Problem with checking branch {} in repo {}: {}'.format(options.checkout, repo.gdir, e), file=sys.stderr)
220  
221  def checkout_packages(options):
222      if options.checkout is None:
223          options.checkout = "/".join([REMOTE_NAME, options.branch[0]])
224      fetch_packages(options)
225      refs = getrefs(options.branch, options.repopattern)
226 +    repos = []
227      for pkgdir in sorted(refs.heads):
228 -        repo = GitRepo(os.path.join(options.packagesdir, pkgdir))
229 -        try:
230 -            repo.checkout(options.checkout)
231 -        except GitRepoError as e:
232 -            print('Problem with checking branch {} in repo {}: {}'.format(options.checkout, repo.gdir, e), file=sys.stderr)
233 +        repos.append(GitRepo(os.path.join(options.packagesdir, pkgdir)))
234 +
235 +    run_worker(checkout_package, options, zip(repos, [options] * len(repos)))
236 +
237 +def clone_package(repo, options):
238 +    try:
239 +        repo.checkout('master')
240 +    except GitRepoError as e:
241 +        print('Problem with checking branch master in repo {}: {}'.format(repo.gdir, e), file=sys.stderr)
242  
243  def clone_packages(options):
244 -    for repo in fetch_packages(options):
245 -        try:
246 -            repo.checkout('master')
247 -        except GitRepoError as e:
248 -            print('Problem with checking branch master in repo {}: {}'.format(repo.gdir, e), file=sys.stderr)
249 +    repos = fetch_packages(options)
250 +    run_worker(clone_package, options, zip(repos, [options] * len(repos)))
251 +
252 +def pull_package(gitrepo, options):
253 +    directory = os.path.basename(gitrepo.wtree)
254 +    try:
255 +        (out, err) = gitrepo.commandexc(['rev-parse', '-q', '--verify', '@{u}'])
256 +        sha1 = out.decode().strip()
257 +        (out, err) = gitrepo.commandexc(['rebase', sha1])
258 +        for line in out.decode().splitlines():
259 +            print(directory,":",line)
260 +    except GitRepoError as e:
261 +        for line in e.args[0].splitlines():
262 +            print("{}: {}".format(directory,line))
263 +        pass
264  
265  def pull_packages(options):
266      repolist = []
267 @@ -189,19 +214,8 @@ def pull_packages(options):
268      else:
269          repolist = fetch_packages(options, False)
270      print('--------Pulling------------')
271 -    for gitrepo in repolist:
272 -        directory = os.path.basename(gitrepo.wtree)
273 -        try:
274 -            (out, err) = gitrepo.commandexc(['rev-parse', '-q', '--verify', '@{u}'])
275 -            sha1 = out.decode().strip()
276 -            (out, err) = gitrepo.commandexc(['rebase', sha1])
277 -            for line in out.decode().splitlines():
278 -                print(directory,":",line)
279 -        except GitRepoError as e:
280 -            for line in e.args[0].splitlines():
281 -                print("{}: {}".format(directory,line))
282 -            pass
283 -
284 +    pool = WorkerPool(options.jobs, pool_worker_init)
285 +    run_worker(pull_package, options, zip(repolist, [options] * len(repolist)))
286  
287  def list_packages(options):
288      refs = getrefs(options.branch, options.repopattern)
289 @@ -213,7 +227,7 @@ common_options.add_argument('-d', '--packagesdir', help='local directory with gi
290      default=os.path.expanduser('~/rpm/packages'))
291  
292  common_fetchoptions = argparse.ArgumentParser(add_help=False, parents=[common_options])
293 -common_fetchoptions.add_argument('-j', '--jobs', help='number of threads to use', default=4, type=int)
294 +common_fetchoptions.add_argument('-j', '--jobs', help='number of threads to use', default=cpu_count(), type=int)
295  common_fetchoptions.add_argument('repopattern', nargs='*', default = ['*'])
296  common_fetchoptions.add_argument('--depth', help='depth of fetch', default=0)
297  
298 @@ -253,10 +267,14 @@ default_options['fetch'] = {'branch': '[*]', 'prune': False, 'newpkgs': False, '
299  
300  pull = subparsers.add_parser('pull', help='git-pull in all existing repositories', parents=[common_fetchoptions],
301          formatter_class=argparse.RawDescriptionHelpFormatter)
302 -pull.add_argument('--all', help='update local branches in all repositories', dest='updateall', action='store_true', default=True)
303 +pull.add_argument('--all', help='update local branches in all repositories', dest='updateall', action='store_true', default=False)
304  pull.add_argument('--noall', help='update local branches only when something has been fetched', dest='updateall', action='store_false', default=True)
305 +newpkgsopt = pull.add_mutually_exclusive_group()
306 +newpkgsopt.add_argument('-n', '--newpkgs', help='download packages that do not exist on local side',
307 +        action='store_true')
308 +newpkgsopt.add_argument('-nn', '--nonewpkgs', help='do not download new packages', dest='newpkgs', action='store_false')
309  pull.set_defaults(func=pull_packages, branch='[*]', prune=False, newpkgs=False, omitexisting=False)
310 -default_options['pull'] = {'branch': ['*'], 'prune': False, 'newpkgs': False, 'omitexisting': False}
311 +default_options['pull'] = {'branch': ['*'], 'prune': False, 'omitexisting': False}
312  
313  checkout =subparsers.add_parser('checkout', help='checkout repositories', parents=[common_fetchoptions],
314          formatter_class=argparse.RawDescriptionHelpFormatter)
This page took 0.08561 seconds and 3 git commands to generate.