summaryrefslogtreecommitdiff
path: root/bin/dulwich
blob: b9a2465580647da07c626cae0b3252b17886cbc2 (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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
#!/usr/bin/python -u
#
# dulwich - Simple command-line interface to Dulwich
# Copyright (C) 2008-2011 Jelmer Vernooij <jelmer@samba.org>
# vim: expandtab
#
# Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
# General Public License as public by the Free Software Foundation; version 2.0
# or (at your option) any later version. You can redistribute it and/or
# modify it under the terms of either of these two licenses.
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# You should have received a copy of the licenses; if not, see
# <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
# and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
# License, Version 2.0.
#

"""Simple command-line interface to Dulwich>

This is a very simple command-line wrapper for Dulwich. It is by
no means intended to be a full-blown Git command-line interface but just
a way to test Dulwich.
"""

import os
import sys
from getopt import getopt
import optparse
import signal

def signal_int(signal, frame):
    sys.exit(1)

signal.signal(signal.SIGINT, signal_int)

from dulwich import porcelain
from dulwich.client import get_transport_and_path
from dulwich.errors import ApplyDeltaError
from dulwich.index import Index
from dulwich.pack import Pack, sha_to_hex
from dulwich.patch import write_tree_diff
from dulwich.repo import Repo


class Command(object):
    """A Dulwich subcommand."""

    def run(self, args):
        """Run the command."""
        raise NotImplementedError(self.run)


class cmd_archive(Command):

    def run(self, args):
        opts, args = getopt(args, "", [])
        client, path = get_transport_and_path(args.pop(0))
        location = args.pop(0)
        committish = args.pop(0)
        porcelain.archive(location, committish, outstream=sys.stdout,
            errstream=sys.stderr)


class cmd_add(Command):

    def run(self, args):
        opts, args = getopt(args, "", [])

        porcelain.add(".", paths=args)


class cmd_rm(Command):

    def run(self, args):
        opts, args = getopt(args, "", [])

        porcelain.rm(".", paths=args)


class cmd_fetch_pack(Command):

    def run(self, args):
        opts, args = getopt(args, "", ["all"])
        opts = dict(opts)
        client, path = get_transport_and_path(args.pop(0))
        r = Repo(".")
        if "--all" in opts:
            determine_wants = r.object_store.determine_wants_all
        else:
            determine_wants = lambda x: [y for y in args if not y in r.object_store]
        client.fetch(path, r, determine_wants)


class cmd_fetch(Command):

    def run(self, args):
        opts, args = getopt(args, "", [])
        opts = dict(opts)
        client, path = get_transport_and_path(args.pop(0))
        r = Repo(".")
        if "--all" in opts:
            determine_wants = r.object_store.determine_wants_all
        refs = client.fetch(path, r, progress=sys.stdout.write)
        print("Remote refs:")
        for item in refs.items():
            print("%s -> %s" % item)


class cmd_log(Command):

    def run(self, args):
        parser = optparse.OptionParser()
        parser.add_option("--reverse", dest="reverse", action="store_true",
                          help="Reverse order in which entries are printed")
        parser.add_option("--name-status", dest="name_status", action="store_true",
                          help="Print name/status for each changed file")
        options, args = parser.parse_args(args)

        porcelain.log(".", paths=args, reverse=options.reverse,
                      name_status=options.name_status,
                      outstream=sys.stdout)


class cmd_diff(Command):

    def run(self, args):
        opts, args = getopt(args, "", [])

        if args == []:
            print("Usage: dulwich diff COMMITID")
            sys.exit(1)

        r = Repo(".")
        commit_id = args[0]
        commit = r[commit_id]
        parent_commit = r[commit.parents[0]]
        write_tree_diff(sys.stdout, r.object_store, parent_commit.tree, commit.tree)


class cmd_dump_pack(Command):

    def run(self, args):
        opts, args = getopt(args, "", [])

        if args == []:
            print("Usage: dulwich dump-pack FILENAME")
            sys.exit(1)

        basename, _ = os.path.splitext(args[0])
        x = Pack(basename)
        print("Object names checksum: %s" % x.name())
        print("Checksum: %s" % sha_to_hex(x.get_stored_checksum()))
        if not x.check():
            print("CHECKSUM DOES NOT MATCH")
        print("Length: %d" % len(x))
        for name in x:
            try:
                print("\t%s" % x[name])
            except KeyError as k:
                print("\t%s: Unable to resolve base %s" % (name, k))
            except ApplyDeltaError as e:
                print("\t%s: Unable to apply delta: %r" % (name, e))


class cmd_dump_index(Command):

    def run(self, args):
        opts, args = getopt(args, "", [])

        if args == []:
            print("Usage: dulwich dump-index FILENAME")
            sys.exit(1)

        filename = args[0]
        idx = Index(filename)

        for o in idx:
            print(o, idx[o])


class cmd_init(Command):

    def run(self, args):
        opts, args = getopt(args, "", ["bare"])
        opts = dict(opts)

        if args == []:
            path = os.getcwd()
        else:
            path = args[0]

        porcelain.init(path, bare=("--bare" in opts))


class cmd_clone(Command):

    def run(self, args):
        opts, args = getopt(args, "", ["bare"])
        opts = dict(opts)

        if args == []:
            print("usage: dulwich clone host:path [PATH]")
            sys.exit(1)

        source = args.pop(0)
        if len(args) > 0:
            target = args.pop(0)
        else:
            target = None

        porcelain.clone(source, target, bare=("--bare" in opts))


class cmd_commit(Command):

    def run(self, args):
        opts, args = getopt(args, "", ["message"])
        opts = dict(opts)
        porcelain.commit(".", message=opts["--message"])


class cmd_commit_tree(Command):

    def run(self, args):
        opts, args = getopt(args, "", ["message"])
        if args == []:
            print("usage: dulwich commit-tree tree")
            sys.exit(1)
        opts = dict(opts)
        porcelain.commit_tree(".", tree=args[0], message=opts["--message"])


class cmd_update_server_info(Command):

    def run(self, args):
        porcelain.update_server_info(".")


class cmd_symbolic_ref(Command):

    def run(self, args):
        opts, args = getopt(args, "", ["ref-name", "force"])
        if not args:
            print("Usage: dulwich symbolic-ref REF_NAME [--force]")
            sys.exit(1)

        ref_name = args.pop(0)
        porcelain.symbolic_ref(".", ref_name=ref_name, force='--force' in args)


class cmd_show(Command):

    def run(self, args):
        opts, args = getopt(args, "", [])
        porcelain.show(".", args)


class cmd_diff_tree(Command):

    def run(self, args):
        opts, args = getopt(args, "", [])
        if len(args) < 2:
            print("Usage: dulwich diff-tree OLD-TREE NEW-TREE")
            sys.exit(1)
        porcelain.diff_tree(".", args[0], args[1])


class cmd_rev_list(Command):

    def run(self, args):
        opts, args = getopt(args, "", [])
        if len(args) < 1:
            print('Usage: dulwich rev-list COMMITID...')
            sys.exit(1)
        porcelain.rev_list('.', args)


class cmd_tag(Command):

    def run(self, args):
        opts, args = getopt(args, '', [])
        if len(args) < 2:
            print('Usage: dulwich tag NAME')
            sys.exit(1)
        porcelain.tag('.', args[0])


class cmd_repack(Command):

    def run(self, args):
        opts, args = getopt(args, "", [])
        opts = dict(opts)
        porcelain.repack('.')


class cmd_reset(Command):

    def run(self, args):
        opts, args = getopt(args, "", ["hard", "soft", "mixed"])
        opts = dict(opts)
        mode = ""
        if "--hard" in opts:
            mode = "hard"
        elif "--soft" in opts:
            mode = "soft"
        elif "--mixed" in opts:
            mode = "mixed"
        porcelain.reset('.', mode=mode, *args)


class cmd_daemon(Command):

    def run(self, args):
        from dulwich import log_utils
        from dulwich.protocol import TCP_GIT_PORT
        parser = optparse.OptionParser()
        parser.add_option("-l", "--listen_address", dest="listen_address",
                          default="localhost",
                          help="Binding IP address.")
        parser.add_option("-p", "--port", dest="port", type=int,
                          default=TCP_GIT_PORT,
                          help="Binding TCP port.")
        options, args = parser.parse_args(args)

        log_utils.default_logging_config()
        if len(args) >= 1:
            gitdir = args[0]
        else:
            gitdir = '.'
        from dulwich import porcelain
        porcelain.daemon(gitdir, address=options.listen_address,
                         port=options.port)


class cmd_web_daemon(Command):

    def run(self, args):
        from dulwich import log_utils
        parser = optparse.OptionParser()
        parser.add_option("-l", "--listen_address", dest="listen_address",
                          default="",
                          help="Binding IP address.")
        parser.add_option("-p", "--port", dest="port", type=int,
                          default=8000,
                          help="Binding TCP port.")
        options, args = parser.parse_args(args)

        log_utils.default_logging_config()
        if len(args) >= 1:
            gitdir = args[0]
        else:
            gitdir = '.'
        from dulwich import porcelain
        porcelain.web_daemon(gitdir, address=options.listen_address,
                             port=options.port)


class cmd_receive_pack(Command):

    def run(self, args):
        parser = optparse.OptionParser()
        options, args = parser.parse_args(args)
        if len(args) >= 1:
            gitdir = args[0]
        else:
            gitdir = '.'
        porcelain.receive_pack(gitdir)


class cmd_upload_pack(Command):

    def run(self, args):
        parser = optparse.OptionParser()
        options, args = parser.parse_args(args)
        if len(args) >= 1:
            gitdir = args[0]
        else:
            gitdir = '.'
        porcelain.upload_pack(gitdir)


class cmd_status(Command):

    def run(self, args):
        parser = optparse.OptionParser()
        options, args = parser.parse_args(args)
        if len(args) >= 1:
            gitdir = args[0]
        else:
            gitdir = '.'
        status = porcelain.status(gitdir)
        if any(names for (kind, names) in status.staged.items()):
            sys.stdout.write("Changes to be committed:\n\n")
            for kind, names in status.staged.items():
                for name in names:
                    sys.stdout.write("\t%s: %s\n" % (
                        kind, name.decode(sys.getfilesystemencoding())))
            sys.stdout.write("\n")
        if status.unstaged:
            sys.stdout.write("Changes not staged for commit:\n\n")
            for name in status.unstaged:
                sys.stdout.write("\t%s\n" %
                        name.decode(sys.getfilesystemencoding()))
            sys.stdout.write("\n")
        if status.untracked:
            sys.stdout.write("Untracked files:\n\n")
            for name in status.untracked:
                sys.stdout.write("\t%s\n" % name)
            sys.stdout.write("\n")


class cmd_ls_remote(Command):

    def run(self, args):
        opts, args = getopt(args, '', [])
        if len(args) < 1:
            print('Usage: dulwich ls-remote URL')
            sys.exit(1)
        refs = porcelain.ls_remote(args[0])
        for ref in sorted(refs):
            sys.stdout.write("%s\t%s\n" % (ref, refs[ref]))


class cmd_ls_tree(Command):

    def run(self, args):
        parser = optparse.OptionParser()
        parser.add_option("-r", "--recursive", action="store_true",
                          help="Recusively list tree contents.")
        parser.add_option("--name-only", action="store_true",
                          help="Only display name.")
        options, args = parser.parse_args(args)
        try:
            treeish = args.pop(0)
        except IndexError:
            treeish = None
        porcelain.ls_tree(
            '.', treeish, outstream=sys.stdout, recursive=options.recursive,
            name_only=options.name_only)


class cmd_pack_objects(Command):

    def run(self, args):
        opts, args = getopt(args, '', ['stdout'])
        opts = dict(opts)
        if len(args) < 1 and not '--stdout' in args:
            print('Usage: dulwich pack-objects basename')
            sys.exit(1)
        object_ids = [l.strip() for l in sys.stdin.readlines()]
        basename = args[0]
        if '--stdout' in opts:
            packf = getattr(sys.stdout, 'buffer', sys.stdout)
            idxf = None
            close = []
        else:
            packf = open(basename + '.pack', 'w')
            idxf = open(basename + '.idx', 'w')
            close = [packf, idxf]
        porcelain.pack_objects('.', object_ids, packf, idxf)
        for f in close:
            f.close()


class cmd_pull(Command):

    def run(self, args):
        parser = optparse.OptionParser()
        options, args = parser.parse_args(args)
        try:
            from_location = args[0]
        except IndexError:
            from_location = None
        porcelain.pull('.', from_location)


class cmd_remote_add(Command):

    def run(self, args):
        parser = optparse.OptionParser()
        options, args = parser.parse_args(args)
        porcelain.remote_add('.', args[0], args[1])


class cmd_remote(Command):

    subcommands = {
        "add": cmd_remote_add,
    }

    def run(self, args):
        if not args:
            print("Supported subcommands: %s" % ', '.join(self.subcommands.keys()))
            return False
        cmd = args[0]
        try:
            cmd_kls = self.subcommands[cmd]
        except KeyError:
            print('No such subcommand: %s' % args[0])
            return False
        return cmd_kls(args[1:])


class cmd_help(Command):

    def run(self, args):
        parser = optparse.OptionParser()
        parser.add_option("-a", "--all", dest="all",
                          action="store_true",
                          help="List all commands.")
        options, args = parser.parse_args(args)

        if options.all:
            print('Available commands:')
            for cmd in sorted(commands):
                print('  %s' % cmd)
        else:
            print("""\
The dulwich command line tool is currently a very basic frontend for the
Dulwich python module. For full functionality, please see the API reference.

For a list of supported commands, see 'dulwich help -a'.
""")


commands = {
    "add": cmd_add,
    "archive": cmd_archive,
    "clone": cmd_clone,
    "commit": cmd_commit,
    "commit-tree": cmd_commit_tree,
    "daemon": cmd_daemon,
    "diff": cmd_diff,
    "diff-tree": cmd_diff_tree,
    "dump-pack": cmd_dump_pack,
    "dump-index": cmd_dump_index,
    "fetch-pack": cmd_fetch_pack,
    "fetch": cmd_fetch,
    "help": cmd_help,
    "init": cmd_init,
    "log": cmd_log,
    "ls-remote": cmd_ls_remote,
    "ls-tree": cmd_ls_tree,
    "pack-objects": cmd_pack_objects,
    "pull": cmd_pull,
    "receive-pack": cmd_receive_pack,
    "remote": cmd_remote,
    "repack": cmd_repack,
    "reset": cmd_reset,
    "rev-list": cmd_rev_list,
    "rm": cmd_rm,
    "show": cmd_show,
    "status": cmd_status,
    "symbolic-ref": cmd_symbolic_ref,
    "tag": cmd_tag,
    "update-server-info": cmd_update_server_info,
    "upload-pack": cmd_upload_pack,
    "web-daemon": cmd_web_daemon,
    }

if len(sys.argv) < 2:
    print("Usage: %s <%s> [OPTIONS...]" % (sys.argv[0], "|".join(commands.keys())))
    sys.exit(1)

cmd = sys.argv[1]
try:
    cmd_kls = commands[cmd]
except KeyError:
    print("No such subcommand: %s" % cmd)
    sys.exit(1)
# TODO(jelmer): Return non-0 on errors
cmd_kls().run(sys.argv[2:])