File: recipe.py

package info (click to toggle)
git-build-recipe 0.3.4
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 280 kB
  • ctags: 453
  • sloc: python: 3,353; makefile: 4
file content (1337 lines) | stat: -rw-r--r-- 47,365 bytes parent folder | download | duplicates (2)
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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
# Copyright 2015 Canonical Ltd.
#
# This program is free software: you can redistribute it and/or modify it 
# under the terms of the GNU General Public License version 3, as published 
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but 
# WITHOUT ANY WARRANTY; without even the implied warranties of 
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR 
# PURPOSE.  See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along 
# with this program.  If not, see <http://www.gnu.org/licenses/>.

"""Handle recipe parsing and substitution variables."""

import datetime
from functools import lru_cache
import logging
import os
import subprocess
import sys
from urllib.parse import urlparse

import dateutil.parser
from debian import debian_support


MERGE_INSTRUCTION = "merge"
NEST_PART_INSTRUCTION = "nest-part"
NEST_INSTRUCTION = "nest"
RUN_INSTRUCTION = "run"
USAGE = {
    MERGE_INSTRUCTION: 'merge NAME BRANCH [REVISION]',
    NEST_INSTRUCTION: 'nest NAME BRANCH TARGET-DIR [REVISION]',
    NEST_PART_INSTRUCTION:
        'nest-part NAME BRANCH SUBDIR [TARGET-DIR [REVISION]]',
    RUN_INSTRUCTION: 'run COMMAND',
    }

SAFE_INSTRUCTIONS = [
    MERGE_INSTRUCTION, NEST_PART_INSTRUCTION, NEST_INSTRUCTION]


class FormattedError(Exception):

    def __init__(self, **kwargs):
        super().__init__()
        for key, value in kwargs.items():
            setattr(self, key, value)

    def __str__(self):
        return self._fmt % dict(self.__dict__)

    def __repr__(self):
        return "%s(%s)" % (self.__class__.__name__, str(self))

    def __eq__(self, other):
        if self.__class__ is not other.__class__:
            return NotImplemented
        return self.__dict__ == other.__dict__

    def __ne__(self, other):
        if self.__class__ is not other.__class__:
            return NotImplemented
        return self.__dict__ != other.__dict__

    __hash__ = Exception.__hash__


class SubstitutionUnavailable(FormattedError):

    _fmt = "Substitution for %(name)s not available: %(reason)s"

    def __init__(self, name, reason):
        super().__init__(name=name, reason=reason)


class SubstitutionVariable:
    """A substitution variable for a version string."""

    def replace(self, value):
        """Replace name with value."""
        raise NotImplementedError(self.replace)

    @classmethod
    def available_in(cls, format):
        """Check if this variable is available in a particular format."""
        raise NotImplementedError(cls.available_in)


class SimpleSubstitutionVariable(SubstitutionVariable):

    name = None

    minimum_format = None

    def replace(self, value):
        if not self.name in value:
            return value
        return value.replace(self.name, self.get())

    def get(self):
        raise NotImplementedError(self.value)

    @classmethod
    def available_in(self, format):
        return format >= self.minimum_format


class BranchSubstitutionVariable(SimpleSubstitutionVariable):

    basename = None

    def __init__(self, branch_name=None):
        super().__init__()
        self.branch_name = branch_name

    @classmethod
    def determine_name(cls, branch_name):
        if branch_name is None:
            return "{%s}" % cls.basename
        else:
            return "{%s:%s}" % (cls.basename, branch_name)

    @property
    def name(self):
        return self.determine_name(self.branch_name)


class TimeVariable(SimpleSubstitutionVariable):

    name = "{time}"

    minimum_format = 0.1

    def __init__(self, time):
        self._time = time

    def get(self):
        return self._time.strftime("%Y%m%d%H%M")


class DateVariable(SimpleSubstitutionVariable):

    name = "{date}"

    minimum_format = 0.1

    def __init__(self, time):
        self._time = time

    def get(self):
        return self._time.strftime("%Y%m%d")


class RevisionVariable(BranchSubstitutionVariable):

    minimum_format = 0.1

    def __init__(self, branch):
        super().__init__(branch.name)
        self.branch = branch
        self.commit = branch.commit


class RevnoVariable(RevisionVariable):
    """A {revno} substitution variable.

    This is a distinctly un-git-like bzr-ism, and is therefore a hack.  Most
    users should use {revtime} or {revdate} instead, which is monotonically
    increasing, or perhaps also {git-commit} to ensure uniqueness (but note
    that commit hashes do not increase monotonically, so are not normally
    suitable in version strings).  However, this can result in very long
    version strings, especially if there are multiple branches involved; so
    this may for instance be useful as {revno:packaging} to encode the
    length of the packaging branch.

    This produces an approximation of a bzr revno by taking the length of
    the left-hand history.
    """

    basename = "revno"

    minimum_format = 0.1

    def get(self):
        return self.branch.git_output(
            "rev-list", "--first-parent", "--count", self.commit).rstrip("\n")


class RevtimeVariable(RevisionVariable):

    basename = "revtime"

    minimum_format = 0.4

    def get(self):
        dt = dateutil.parser.parse(self.branch.git_output(
            "log", "-1", "--date=iso", "--format=format:%cd", self.commit))
        return dt.astimezone(datetime.timezone.utc).strftime("%Y%m%d%H%M")


class RevdateVariable(RevisionVariable):

    basename = "revdate"

    minimum_format = 0.4

    def get(self):
        dt = dateutil.parser.parse(self.branch.git_output(
            "log", "-1", "--date=iso", "--format=format:%cd", self.commit))
        return dt.astimezone(datetime.timezone.utc).strftime("%Y%m%d")


class GitCommitVariable(RevisionVariable):

    basename = "git-commit"

    minimum_format = 0.4

    def get(self):
        return self.branch.git_output(
            "rev-parse", "--short", self.commit).rstrip("\n")


class LatestTagVariable(RevisionVariable):

    basename = "latest-tag"

    minimum_format = 0.4

    def get(self):
        # Capture stderr so that exceptions are useful.  We know that git
        # describe does not write to stderr on success.
        return self.branch.git_output(
            "describe", "--tags", "--abbrev=0", self.commit,
            stderr=subprocess.STDOUT).rstrip("\n")


branch_vars = [
    GitCommitVariable,
    LatestTagVariable,
    RevdateVariable,
    RevtimeVariable,
    ]
simple_vars = [
    TimeVariable,
    DateVariable,
    ]


class TargetAlreadyExists(FormattedError):

    _fmt = "%(target)s already exists, but has no .git directory."

    def __init__(self, target):
        super().__init__(target=target)


class GitCommandFailed(FormattedError):

    _fmt = "git %(command)s failed:\n%(output)s"

    def __init__(self, output):
        super().__init__(command=self._cmd, output=output)


class FetchFailed(GitCommandFailed):

    _cmd = "fetch"


class CloneFailed(GitCommandFailed):

    _cmd = "clone"


class CheckoutFailed(GitCommandFailed):

    _cmd = "checkout"


class MergeFailed(GitCommandFailed):

    _cmd = "merge"


# Some default configuration to make writing recipes more pleasant.
insteadof = {
    "lp:": "https://git.launchpad.net/"
    }


def pull_or_clone(base_branch, target_path):
    """Make target_path match base_branch, either by pulling or by cloning."""
    base_branch.path = target_path
    if os.path.exists(target_path) and not os.listdir(target_path):
        os.rmdir(target_path)
    if not os.path.exists(target_path):
        os.makedirs(target_path)
        base_branch.git_call("init")
        for short, base in insteadof.items():
            base_branch.git_call("config", "url.%s.insteadOf" % base, short)
    elif not os.path.exists(os.path.join(target_path, ".git")):
        raise TargetAlreadyExists(target_path)
    try:
        fetch_branches(base_branch)
    except subprocess.CalledProcessError as e:
        raise FetchFailed(e.output)
    try:
        base_branch.resolve_commit()
        # Check out the commit hash directly to detach HEAD and ensure
        # commits (eg. by a merge instruction) don't affect substitution
        # variables.
        # If someone sneakily names a branch after a commit then all
        # hell will break loose (really, git? there's no way to force
        # checkout to interpret its argument as a commit?), but that's
        # their problem.
        base_branch.git_call("checkout", base_branch.commit)
    except subprocess.CalledProcessError as e:
        raise CheckoutFailed(e.output)


def fetch_branches(child_branch):
    url = child_branch.url
    parsed_url = urlparse(url)
    if not parsed_url.scheme and not parsed_url.path.startswith("/"):
        url = os.path.abspath(url)
    # Fetch all remote branches, the remote HEAD, and (implicitly) any
    # tags that reference commits in those refs. Tags that aren't on a
    # branch won't be fetched.
    child_branch.git_call(
        "fetch", url,
        "HEAD:refs/remotes/%s/HEAD" % child_branch.remote_name,
        "refs/heads/*:refs/remotes/%s/*" % child_branch.remote_name)


@lru_cache(maxsize=1)
def _git_version():
    raw_git_version = subprocess.check_output(
        ["dpkg-query", "-W", "-f", "${Version}", "git"],
        universal_newlines=True)
    return debian_support.Version(raw_git_version)


def merge_branch(child_branch, target_path):
    """Merge the branch specified by `child_branch`.

    :param child_branch: A `RecipeBranch` identifying the branch and commit
        to merge from.
    :param target_path: The tree to merge into.
    """
    child_branch.path = target_path
    fetch_branches(child_branch)
    try:
        child_branch.resolve_commit()
        cmd = ["merge", "--commit"]
        if _git_version() >= "1:2.9.0":
            cmd.append("--allow-unrelated-histories")
        cmd.extend(["-m", "Merge %s" % child_branch.get_revspec()])
        cmd.append(child_branch.commit)
        child_branch.git_call(*cmd)
    except subprocess.CalledProcessError as e:
        raise MergeFailed(e.output)


def nest_part_branch(child_branch, target_path, subpath, target_subdir=None):
    """Nest the branch subdirectory specified by `child_branch`.

    :param child_branch: A `RecipeBranch` identifying the branch and commit
        to merge from.
    :param target_path: The tree to merge into.
    :param subpath: Only merge files from `child_branch` that are from this
        path.  For example, subpath="/debian" will only merge changes from
        that directory.
    :param target_subdir: Optional directory in `target_path` to merge that
        subpath into.  Defaults to the basename of `subpath`.
    """
    subpath = subpath.lstrip("/")
    if target_subdir is None:
        target_subdir = os.path.basename(subpath)
    # XXX should handle updating as well
    assert not os.path.exists(target_subdir)
    child_branch.path = target_path
    fetch_branches(child_branch)
    child_branch.resolve_commit()
    child_branch.git_call(
        "read-tree", "--prefix", target_subdir, "-u",
        child_branch.commit + ":" + subpath)


def _build_inner_tree(base_branch, target_path):
    revision_of = ""
    if base_branch.revspec is not None:
        revision_of = "revision '%s' of " % base_branch.revspec
    logging.info(
        "Retrieving %s'%s' to put at '%s'." %
        (revision_of, base_branch.url, target_path))
    pull_or_clone(base_branch, target_path)
    base_branch.resolve_commit()
    for instruction in base_branch.child_branches:
        instruction.apply(target_path)


def _resolve_revisions_recurse(new_branch, substitute_branch_vars,
                               if_changed_from=None):
    changed = False
    if substitute_branch_vars is not None:
        # XXX need to make sure new_branch has been fetched
        new_branch.resolve_commit()
        substitute_branch_vars(new_branch)
    if (if_changed_from is not None and
        (new_branch.revspec is not None or
         if_changed_from.revspec is not None)):
        if if_changed_from.revspec is not None:
            # XXX resolve revspec
            changed_commit = if_changed_from.revspec
        else:
            changed_commit = new_branch.commit
        if new_branch.commit != changed_commit:
            changed = True
    for index, instruction in enumerate(new_branch.child_branches):
        child_branch = instruction.recipe_branch
        if_changed_child = None
        if if_changed_from is not None:
            if_changed_child = (
                if_changed_from.child_branches[index].recipe_branch)
        if child_branch is not None:
            child_changed = _resolve_revisions_recurse(
                child_branch, substitute_branch_vars,
                if_changed_from=if_changed_child)
            if child_changed:
                changed = child_changed
    return changed


def resolve_revisions(base_branch, if_changed_from=None,
                      substitute_branch_vars=None):
    """Resolve all the unknowns in `base_branch`.

    This walks the `RecipeBranch` and calls `substitute_branch_vars` for
    each child branch.

    If `if_changed_from` is not None then it should be a second
    `RecipeBranch` to compare `base_branch` against.  If the shape or the
    commit IDs differ then the function will return True.

    :param base_branch: The `RecipeBranch` we plan to build.
    :param if_changed_from: The `RecipeBranch` that we want to compare
        against.
    :param substitute_branch_vars: Callable called for each `RecipeBranch`.
    :return: False if `if_changed_from` is not None, and the shape and
        commits of the two branches are the same.  True otherwise.
    """
    changed = False
    if if_changed_from is not None:
        changed = base_branch.different_shape_to(if_changed_from)
    if_changed_from_revisions = None if changed else if_changed_from

    if substitute_branch_vars is not None:
        real_substitute_branch_vars = (
            lambda child_branch: substitute_branch_vars(
                base_branch, child_branch))
    else:
        real_substitute_branch_vars = None
    changed_revisions = _resolve_revisions_recurse(
        base_branch, real_substitute_branch_vars,
        if_changed_from=if_changed_from_revisions)
    if not changed:
        changed = changed_revisions
    if if_changed_from is not None and not changed:
        return False
    return True


def build_tree(base_branch, target_path):
    logging.info("Building tree.")
    _build_inner_tree(base_branch, target_path)


class ChildBranch:
    """A child branch in a recipe.

    If the nest path is not None it is the path relative to the recipe
    branch where the child branch should be placed.  If it is None then the
    child branch should be merged instead of nested.
    """

    can_have_children = False

    def __init__(self, recipe_branch, nest_path=None):
        self.recipe_branch = recipe_branch
        self.nest_path = nest_path

    def apply(self, target_path):
        raise NotImplementedError(self.apply)

    def as_tuple(self):
        return (self.recipe_branch, self.nest_path)

    def _get_commit_part(self):
        if self.recipe_branch.commit is not None:
            return " git-commit:%s" % self.recipe_branch.commit
        elif self.recipe_branch.revspec is not None:
            return " %s" % self.recipe_branch.revspec
        else:
            return ""

    def __repr__(self):
        return "<%s %r>" % (self.__class__.__name__, self.nest_path)


class CommandInstruction(ChildBranch):

    def apply(self, target_path):
        # it's a command
        logging.info("Running '%s' in '%s'." % (self.nest_path, target_path))
        subprocess.check_call(
            self.nest_path, cwd=target_path, shell=True, stdin=subprocess.PIPE)

    def as_text(self):
        return "%s %s" % (RUN_INSTRUCTION, self.nest_path)


class MergeInstruction(ChildBranch):

    def apply(self, target_path):
        revision_of = ""
        if self.recipe_branch.revspec is not None:
            revision_of = "revision '%s' of " % self.recipe_branch.revspec
        logging.info(
            "Merging %s'%s' in to '%s'." %
            (revision_of, self.recipe_branch.url, target_path))
        merge_branch(self.recipe_branch, target_path)

    def as_text(self):
        commit_part = self._get_commit_part()
        return "%s %s %s%s" % (
            MERGE_INSTRUCTION, self.recipe_branch.name,
            self.recipe_branch.url, commit_part)

    def __repr__(self):
        return "<%s %r>" % (self.__class__.__name__, self.recipe_branch.name)


class NestPartInstruction(ChildBranch):

    def __init__(self, recipe_branch, subpath, target_subdir):
        ChildBranch.__init__(self, recipe_branch)
        self.subpath = subpath
        self.target_subdir = target_subdir

    def apply(self, target_path):
        nest_part_branch(
            self.recipe_branch, target_path, self.subpath,
            target_subdir=self.target_subdir)

    def as_text(self):
        commit_part = self._get_commit_part()
        if commit_part:
            target_subdir = self.target_subdir
            if target_subdir is None:
                target_subdir = self.subpath
            target_commit_part = " %s%s" % (target_subdir, commit_part)
        elif self.target_subdir is not None:
            target_commit_part = " %s" % self.target_subdir
        else:
            target_commit_part = ""
        return "%s %s %s %s%s" % (
            NEST_PART_INSTRUCTION, self.recipe_branch.name,
            self.recipe_branch.url, self.subpath, target_commit_part)


class NestInstruction(ChildBranch):

    can_have_children = True

    def apply(self, target_path):
        _build_inner_tree(
            self.recipe_branch,
            target_path=os.path.join(target_path, self.nest_path))

    def as_text(self):
        commit_part = self._get_commit_part()
        return "%s %s %s %s%s" % (
            NEST_INSTRUCTION, self.recipe_branch.name,
            self.recipe_branch.url, self.nest_path, commit_part)

    def __repr__(self):
        return "<%s %r>" % (self.__class__.__name__,
            self.recipe_branch.name)


class RecipeBranch:
    """A nested structure that represents a Recipe.

    A RecipeBranch has a name and a url (the name can be None for the root
    branch), and optionally child branches that are either merged or nested.

    The `child_branches` attribute is a list of tuples of `ChildBranch`
    objects.  The commit attribute records the commit that the `url` and
    `revspec` resolved to when the `RecipeBranch` was built, or None if it
    has not been built.

    :ivar commit: After this recipe branch has been built, this is set to
        the commit object name that was merged/nested from the branch at
        `self.url`.
    """

    def __init__(self, name, url, revspec=None):
        """Create a `RecipeBranch`.

        :param name: The name for the branch, or None if it is the root.
        :param url: The URL from which to retrieve the branch.
        :param revspec: A revision (as in `git rev-parse`) for the commit to
            use, or None (the default) to use `HEAD`.
        """
        self.name = name
        self.url = url
        self.revspec = revspec
        self.child_branches = []
        self.commit = None
        self.path = None

    @property
    def remote_name(self):
        if self.name is None:
            return 'source'
        return 'source-%s' % self.name

    def _get_git_path(self):
        if self.path is not None:
            return self.path
        elif not urlparse(self.url).scheme:
            return self.url
        else:
            # XXX more specific exception type
            raise Exception(
                "Repository at %s has not been cloned yet" % self.url)

    def git_call(self, *args, **kwargs):
        cmd = ["git", "-C", self._get_git_path()] + list(args)
        silent = kwargs.pop("silent", False)
        # This allows any raised CalledProcessError to contain the output.
        # Writing to stdout/stderr depending on return code is an
        # approximation, but preserves interleaving and should do the job
        # well enough.
        try:
            output = subprocess.check_output(
                cmd, stderr=subprocess.STDOUT, universal_newlines=True,
                **kwargs)
            if silent:
                sys.stdout.write(output)
        except subprocess.CalledProcessError as e:
            if silent:
                sys.stderr.write(e.output)
            raise

    def git_output(self, *args, **kwargs):
        return subprocess.check_output(
            ["git", "-C", self._get_git_path()] + list(args),
            universal_newlines=True, **kwargs)

    def get_revspec(self):
        return self.revspec if self.revspec is not None else "HEAD"

    def resolve_commit(self):
        """Resolve the commit for this branch."""
        # Capturing stderr is a bit dodgy, but it's the most convenient way
        # to capture it for any exceptions.  We know that git rev-parse does
        # not write to stderr on success.
        try:
            self.commit = self.git_output(
                "rev-parse", "%s/%s" % (self.remote_name, self.get_revspec()),
                stderr=subprocess.STDOUT).rstrip("\n")
            return
        except subprocess.CalledProcessError:
            pass
        # Not a remote-prefixed ref. Try a global search.
        # XXX: This allows cross-branch pollution, but we don't have
        # much choice without reimplementing rev-parse ourselves.
        self.commit = self.git_output(
            "rev-parse", self.get_revspec(),
            stderr=subprocess.STDOUT).rstrip("\n")

    def merge_branch(self, branch):
        """Merge a child branch into this one.

        :param branch: The `RecipeBranch` to merge.
        """
        self.child_branches.append(MergeInstruction(branch))

    def nest_part_branch(self, branch, subpath=None, target_subdir=None):
        """Merge subdir of a child branch into this one.

        :param branch: The `RecipeBranch` to merge.
        :param subpath: Only merge files from `branch` that are from this
            path.  For example, subpath="/debian" will only merge changes
            from that directory.
        :param target_subdir: Optional directory in the target tree to merge
            that subpath into.  Defaults to the basename of `subpath`.
        """
        self.child_branches.append(
            NestPartInstruction(branch, subpath, target_subdir))

    def nest_branch(self, location, branch):
        """Nest a child branch into this one.

        :param location: The relative path at which this branch should be
            nested.
        :param branch: The `RecipeBranch` to nest.
        """
        if any(location == b.nest_path for b in self.child_branches):
            raise AssertionError(
                "%s already has a branch nested there" % location)
        self.child_branches.append(NestInstruction(branch, location))

    def run_command(self, command):
        """Set a command to be run.

        :param command: The command to be run.
        """
        self.child_branches.append(CommandInstruction(None, command))

    def different_shape_to(self, other_branch):
        """Test whether the name, url, and child_branches are the same."""
        if self.name != other_branch.name:
            return True
        if self.url != other_branch.url:
            return True
        if len(self.child_branches) != len(other_branch.child_branches):
            return True
        for index, instruction in enumerate(self.child_branches):
            child_branch = instruction.recipe_branch
            nest_location = instruction.nest_path
            other_instruction = other_branch.child_branches[index]
            other_child_branch = other_instruction.recipe_branch
            other_nest_location = other_instruction.nest_path
            if nest_location != other_nest_location:
                return True
            if ((child_branch is None and other_child_branch is not None) or
                    (child_branch is not None and other_child_branch is None)):
                return True
            # If child_branch is None then other_child_branch must be None
            # too, meaning that they are both run instructions.  We would
            # compare their nest locations (commands), but that has already
            # been done, so just guard.
            if (child_branch is not None and
                    child_branch.different_shape_to(other_child_branch)):
                return True
        return False

    def iter_all_instructions(self):
        """Iter over all instructions under this branch."""
        for instruction in self.child_branches:
            yield instruction
            child_branch = instruction.recipe_branch
            if child_branch is None:
                continue
            for instruction in child_branch.iter_all_instructions():
                yield instruction

    def iter_all_branches(self):
        """Iterate over all branches."""
        yield self
        for instruction in self.child_branches:
            child_branch = instruction.recipe_branch
            if child_branch is None:
                continue
            for subbranch in child_branch.iter_all_branches():
                yield subbranch

    def lookup_branch(self, name):
        """Look up a branch by its name."""
        for branch in self.iter_all_branches():
            if branch.name == name:
                return branch
        else:
            raise KeyError(name)

    def list_branch_names(self):
        """List all of the branch names under this one.

        :return: A list of the branch names.
        :rtype: list(str)
        """
        return [
            branch.name for branch in self.iter_all_branches()
            if branch.name is not None]

    def __repr__(self):
        return "<%s %r>" % (self.__class__.__name__, self.name)


class BaseRecipeBranch(RecipeBranch):
    """The `RecipeBranch` that is at the root of a recipe."""

    def __init__(self, url, deb_version, format_version, revspec=None):
        """Create a `BaseRecipeBranch`.

        :param deb_version: The template to use for the version number.
            Should be None for anything except the root branch.
        """
        super().__init__(None, url, revspec=revspec)
        self.deb_version = deb_version
        self.format_version = format_version
        if not urlparse(url).scheme:
            self.path = url

    def _add_child_branches_to_manifest(self, child_branches, indent_level):
        manifest = ""
        for instruction in child_branches:
            manifest += "%s%s\n" % ("  " * indent_level, instruction.as_text())
            if instruction.can_have_children:
                manifest += self._add_child_branches_to_manifest(
                    instruction.recipe_branch.child_branches, indent_level + 1)
        return manifest

    def __str__(self):
        return self.get_recipe_text(validate=True)

    def get_recipe_text(self, validate=False):
        manifest = "# git-build-recipe format %s" % str(self.format_version)
        if self.deb_version is not None:
            # TODO: should we store the expanded version that was used?
            manifest += " deb-version %s" % self.deb_version
        manifest += "\n"
        if self.commit is not None:
            manifest += "%s git-commit:%s\n" % (self.url, self.commit)
        elif self.revspec is not None:
            manifest += "%s %s\n" % (self.url, self.revspec)
        else:
            manifest += "%s\n" % self.url
        manifest += self._add_child_branches_to_manifest(
            self.child_branches, 0)
        if validate:
            # Sanity check.
            # TODO: write a function that compares the result of this parse
            # with the branch that we built it from.
            RecipeParser(manifest).parse()
        return manifest


class RecipeParseError(FormattedError):

    _fmt = "Error parsing %(filename)s:%(line)s:%(char)s: %(problem)s."

    def __init__(self, filename, line, char, problem):
        super().__init__(
            filename=filename, line=line, char=char, problem=problem)


class InstructionParseError(RecipeParseError):

    _fmt = RecipeParseError._fmt + "\nUsage: %(usage)s"

    def __init__(self, filename, line, char, problem, instruction):
        super().__init__(filename, line, char, problem)
        self.usage = USAGE[instruction]


class ForbiddenInstructionError(RecipeParseError):

    def __init__(self, filename, line, char, problem, instruction_name=None):
        super().__init__(filename, line, char, problem)
        self.instruction_name = instruction_name


class RecipeParser:
    """Parse a recipe.

    The parse() method is probably the only one that interests you.
    """

    whitespace_chars = " \t"
    eol_char = "\n"
    digit_chars = ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9")

    NEWEST_VERSION = 0.4

    def __init__(self, f):
        """Create a `RecipeParser`.

        :param f: Either the recipe as a string, or a file-like object to
            take it from.
        """
        if getattr(f, "read", None) is not None:
            self.text = f.read()
        else:
            self.text = f
        self.filename = None
        if hasattr(f, "name"):
            self.filename = f.name
        if self.filename is None:
            self.filename = "recipe"

    def parse(self, permitted_instructions=None):
        """Parse the recipe.

        :param permitted_instructions: A list of instructions that you want
            to allow.  Defaults to None allowing them all.
        :type permitted_instructions: list(str) or None
        :return: A `RecipeBranch` representing the recipe.
        """
        self.lines = self.text.split("\n")
        self.index = 0
        self.line_index = 0
        self.current_line = self.lines[self.line_index]
        self.current_indent_level = 0
        self.seen_nicks = set()
        self.seen_paths = {".": 1}
        version, deb_version = self.parse_header()
        self.version = version
        last_instruction = None
        active_branches = []
        last_branch = None
        while self.line_index < len(self.lines):
            if self.is_blankline():
                self.new_line()
                continue
            comment = self.parse_comment_line()
            if comment is not None:
                self.new_line()
                continue
            old_indent_level = self.parse_indent()
            if old_indent_level is not None:
                if (old_indent_level < self.current_indent_level
                    and last_instruction != NEST_INSTRUCTION):
                    self.throw_parse_error(
                        "Not allowed to indent unless after a '%s' line" %
                        NEST_INSTRUCTION)
                if old_indent_level < self.current_indent_level:
                    active_branches.append(last_branch)
                else:
                    unindent = self.current_indent_level - old_indent_level
                    active_branches = active_branches[:unindent]
            if last_instruction is None:
                url = self.take_to_whitespace("branch to start from")
                revspec = self.parse_optional_revspec()
                self.new_line()
                last_branch = BaseRecipeBranch(
                    url, deb_version, self.version, revspec=revspec)
                active_branches = [last_branch]
                last_instruction = ""
            else:
                instruction = self.parse_instruction(
                    permitted_instructions=permitted_instructions)
                if instruction == RUN_INSTRUCTION:
                    self.parse_whitespace(
                        "the command", instruction=instruction)
                    command = self.take_to_newline().strip()
                    self.new_line()
                    active_branches[-1].run_command(command)
                else:
                    branch_id = self.parse_branch_id(instruction)
                    url = self.parse_branch_url(instruction)
                    if instruction == NEST_INSTRUCTION:
                        location = self.parse_branch_location(instruction)
                    if instruction == NEST_PART_INSTRUCTION:
                        path = self.parse_subpath(instruction)
                        target_subdir = self.parse_optional_path()
                        if target_subdir == "":
                            target_subdir = None
                            revspec = None
                        else:
                            revspec = self.parse_optional_revspec()
                    else:
                        revspec = self.parse_optional_revspec()
                    self.new_line(instruction)
                    last_branch = RecipeBranch(branch_id, url, revspec=revspec)
                    if instruction == NEST_INSTRUCTION:
                        active_branches[-1].nest_branch(location, last_branch)
                    elif instruction == MERGE_INSTRUCTION:
                        active_branches[-1].merge_branch(last_branch)
                    elif instruction == NEST_PART_INSTRUCTION:
                        active_branches[-1].nest_part_branch(
                            last_branch, path, target_subdir)
                last_instruction = instruction
        if len(active_branches) == 0:
            self.throw_parse_error("Empty recipe")
        return active_branches[0]

    def parse_header(self):
        self.parse_char("#")
        # Try git-build-recipe last even though it's now the preferred form,
        # in order that user-visible error messages look sensible.
        try:
            self.parse_word("bzr-builder", require_whitespace=False)
        except RecipeParseError:
            self.parse_word("git-build-recipe", require_whitespace=False)
        self.parse_word("format")
        version, version_str = self.peek_float("format version")
        if version > self.NEWEST_VERSION:
            self.throw_parse_error("Unknown format: '%s'" % str(version))
        self.take_chars(len(version_str))
        deb_version = self.parse_optional_deb_version()
        self.new_line()
        return version, deb_version

    def parse_instruction(self, permitted_instructions=None):
        if self.version < 0.2:
            options = (MERGE_INSTRUCTION, NEST_INSTRUCTION)
            options_str = "'%s' or '%s'" % options
        elif self.version < 0.3:
            options = (MERGE_INSTRUCTION, NEST_INSTRUCTION, RUN_INSTRUCTION)
            options_str = "'%s', '%s', or '%s'" % options
        else:
            options = (
                MERGE_INSTRUCTION, NEST_INSTRUCTION, NEST_PART_INSTRUCTION,
                RUN_INSTRUCTION)
            options_str = "'%s', '%s', '%s', or '%s'" % options
        instruction = self.peek_to_whitespace()
        if instruction is None:
            self.throw_parse_error(
                "End of line while looking for %s" % options_str)
        if instruction in options:
            if permitted_instructions is not None:
                if instruction not in permitted_instructions:
                    self.throw_parse_error(
                        "The '%s' instruction is forbidden" % instruction,
                        cls=ForbiddenInstructionError,
                        instruction_name=instruction)
            self.take_chars(len(instruction))
            return instruction
        self.throw_parse_error(
            "Expecting %s, got '%s'" % (options_str, instruction))

    def parse_branch_id(self, instruction):
        self.parse_whitespace("the branch id", instruction=instruction)
        branch_id = self.peek_to_whitespace()
        if branch_id is None:
            self.throw_parse_error(
                "End of line while looking for the branch id",
                cls=InstructionParseError, instruction=instruction)
        if branch_id in self.seen_nicks:
            self.throw_parse_error(
                "'%s' was already used to identify a branch." % branch_id)
        self.take_chars(len(branch_id))
        self.seen_nicks.add(branch_id)
        return branch_id

    def parse_branch_url(self, instruction):
        self.parse_whitespace("the branch url", instruction=instruction)
        return self.take_to_whitespace("the branch url", instruction)

    def parse_branch_location(self, instruction):
        # FIXME: Needs a better term
        self.parse_whitespace("the location to nest")
        location = self.peek_to_whitespace()
        if location is None:
            self.throw_parse_error(
                "End of line while looking for the location to nest",
                cls=InstructionParseError, instruction=instruction)
        norm_location = os.path.normpath(location)
        if norm_location in self.seen_paths:
            self.throw_parse_error(
                "The path '%s' is a duplicate of the one used on line %d." % (
                    location, self.seen_paths[norm_location]),
                cls=InstructionParseError, instruction=instruction)
        if os.path.isabs(norm_location):
            self.throw_parse_error(
                "Absolute paths are not allowed: %s" % location,
                cls=InstructionParseError, instruction=instruction)
        if norm_location.startswith(".."):
            self.throw_parse_error(
                "Paths outside the current directory are not allowed: %s" % (
                    location),
                cls=InstructionParseError, instruction=instruction)
        self.take_chars(len(location))
        self.seen_paths[norm_location] = self.line_index + 1
        return location

    def parse_subpath(self, instruction):
        self.parse_whitespace("the subpath to merge", instruction=instruction)
        return self.take_to_whitespace("the subpath to merge", instruction)

    def parse_revspec(self):
        self.parse_whitespace("the revspec")
        return self.take_to_whitespace("the revspec")

    def parse_optional_deb_version(self):
        self.parse_whitespace("'deb-version'", require=False)
        actual = self.peek_to_whitespace()
        if actual is None:
            # End of line, no version
            return None
        if actual != "deb-version":
            self.throw_expecting_error("deb-version", actual)
        self.take_chars(len("deb-version"))
        self.parse_whitespace("a value for 'deb-version'")
        return self.take_to_whitespace("a value for 'deb-version'")

    def parse_optional_revspec(self):
        self.parse_whitespace(None, require=False)
        revspec = self.peek_to_whitespace()
        if revspec is not None:
            self.take_chars(len(revspec))
        return revspec

    def parse_optional_path(self):
        self.parse_whitespace(None, require=False)
        path = self.peek_to_whitespace()
        if path is not None:
            self.take_chars(len(path))
        return path

    def throw_parse_error(self, problem, cls=None, **kwargs):
        if cls is None:
            cls = RecipeParseError
        raise cls(
            self.filename, self.line_index + 1, self.index + 1, problem,
            **kwargs)

    def throw_expecting_error(self, expected, actual):
        self.throw_parse_error("Expecting '%s', got '%s'" % (expected, actual))

    def throw_eol(self, expected):
        self.throw_parse_error("End of line while looking for '%s'" % expected)

    def new_line(self, instruction=None):
        # Jump over any whitespace
        self.parse_whitespace(None, require=False)
        remaining = self.peek_to_whitespace()
        if remaining is not None:
            kwargs = {}
            if instruction is not None:
                kwargs = {
                    "cls": InstructionParseError,
                    "instruction": instruction,
                    }
            self.throw_parse_error(
                "Expecting the end of the line, got '%s'" % remaining,
                **kwargs)
        self.index = 0
        self.line_index += 1
        if self.line_index >= len(self.lines):
            self.current_line = None
        else:
            self.current_line = self.lines[self.line_index]

    def is_blankline(self):
        whitespace = self.peek_whitespace()
        if whitespace is None:
            return True
        return self.peek_char(skip=len(whitespace)) is None

    def take_char(self):
        if self.index >= len(self.current_line):
            return None
        self.index += 1
        return self.current_line[self.index-1]

    def take_chars(self, num):
        ret = ""
        for i in range(num):
            char = self.take_char()
            if char is None:
                return None
            ret += char
        return ret

    def peek_char(self, skip=0):
        if self.index + skip >= len(self.current_line):
            return None
        return self.current_line[self.index + skip]

    def parse_char(self, char):
        actual = self.peek_char()
        if actual is None:
            self.throw_eol(char)
        if actual == char:
            self.take_char()
            return char
        self.throw_expecting_error(char, actual)

    def parse_indent(self):
        """Parse the indent from the start of the line."""
        # FIXME: should just peek the whitespace
        new_indent = self.parse_whitespace(None, require=False)
        # FIXME: These checks should probably come after we check whether
        # any change in indent is legal at this point:
        # "Indents of 3 spaces aren't allowed" -> make it 2 spaces
        # -> "oh, you aren't allowed to indent at that point anyway"
        if "\t" in new_indent:
            self.throw_parse_error("Indents may not be done by tabs")
        if (len(new_indent) % 2 != 0):
            self.throw_parse_error("Indent not a multiple of two spaces")
        new_indent_level = len(new_indent) // 2
        if new_indent_level != self.current_indent_level:
            old_indent_level = self.current_indent_level
            self.current_indent_level = new_indent_level
            if (new_indent_level > old_indent_level and
                    new_indent_level - old_indent_level != 1):
               self.throw_parse_error(
                    "Indented by more than two spaces at once")
            return old_indent_level
        return None

    def parse_whitespace(self, looking_for, require=True, instruction=None):
        if require:
            actual = self.peek_char()
            if actual is None:
                kwargs = {}
                if instruction is not None:
                    kwargs = {
                        "cls": InstructionParseError,
                        "instruction": instruction,
                        }
                self.throw_parse_error(
                    "End of line while looking for %s" % looking_for, **kwargs)
            if actual not in self.whitespace_chars:
                self.throw_parse_error(
                    "Expecting whitespace before %s, got '%s'." %
                    (looking_for, actual))
        ret = ""
        actual = self.peek_char()
        while actual is not None and actual in self.whitespace_chars:
            self.take_char()
            ret += actual
            actual = self.peek_char()
        return ret

    def peek_whitespace(self):
        ret = ""
        char = self.peek_char()
        if char is None:
            return char
        count = 0
        while char is not None and char in self.whitespace_chars:
            ret += char
            count += 1
            char = self.peek_char(skip=count)
        return ret

    def parse_word(self, expected, require_whitespace=True):
        self.parse_whitespace("'%s'" % expected, require=require_whitespace)
        length = len(expected)
        actual = self.peek_to_whitespace()
        if actual == expected:
            self.take_chars(length)
            return expected
        if actual is None:
            self.throw_eol(expected)
        self.throw_expecting_error(expected, actual)

    def peek_to_whitespace(self):
        ret = ""
        char = self.peek_char()
        if char is None:
            return char
        count = 0
        while char is not None and char not in self.whitespace_chars:
            ret += char
            count += 1
            char = self.peek_char(skip=count)
        return ret

    def take_to_whitespace(self, looking_for, instruction=None):
        text = self.peek_to_whitespace()
        if text is None:
            kwargs = {}
            if instruction is not None:
                kwargs = {
                    "cls": InstructionParseError,
                    "instruction": instruction,
                    }
            self.throw_parse_error(
                "End of line while looking for %s" % looking_for, **kwargs)
        self.take_chars(len(text))
        return text

    def peek_float(self, looking_for):
        self.parse_whitespace(looking_for)
        ret = self._parse_integer()
        conv_fn = int
        if ret == "":
            self.throw_parse_error(
                "Expecting a float, got '%s'" % self.peek_to_whitespace())
        if self.peek_char(skip=len(ret)) == ".":
            conv_fn = float
            ret2 = self._parse_integer(skip=(len(ret) + 1))
            if ret2 == "":
                self.throw_parse_error(
                    "Expecting a float, got '%s'" % self.peek_to_whitespace())
            ret += "." + ret2
        try:
            fl = conv_fn(ret)
        except ValueError:
            self.throw_parse_error("Expecting a float, got '%s'" % ret)
        return (fl, ret)

    def _parse_integer(self, skip=0):
        i = skip
        ret = ""
        while True:
            char = self.peek_char(skip=i)
            if char not in self.digit_chars:
                break
            ret += char
            i += 1
        return ret

    def parse_integer(self):
        ret = self._parse_integer()
        if ret == "":
            self.throw_parse_error(
                "Expected an integer, found %s" % self.peek_to_whitespace())
        self.take_chars(len(ret))
        return ret

    def take_to_newline(self):
        text = self.current_line[self.index:]
        self.index += len(text)
        return text

    def parse_comment_line(self):
        whitespace = self.peek_whitespace()
        if whitespace is None:
            return ""
        if self.peek_char(skip=len(whitespace)) is None:
            return ""
        if self.peek_char(skip=len(whitespace)) != "#":
            return None
        self.parse_whitespace(None, require=False)
        comment = self.current_line[self.index:]
        self.index += len(comment)
        return comment


def parse_recipe(recipe_file, safe=False):
    parser = RecipeParser(recipe_file)
    if safe:
        permitted_instructions = SAFE_INSTRUCTIONS
    else:
        permitted_instructions = None
    return parser.parse(permitted_instructions=permitted_instructions)