+sub open_main_gitattrs () {
+ confess 'internal error no maindir' unless defined $maindir;
+ my $gai = new IO::File "$maindir_gitcommon/info/attributes"
+ or $!==ENOENT
+ or die "open $maindir_gitcommon/info/attributes: $!";
+ return $gai;
+}
+
+our $gitattrs_ourmacro_re = qr{^\[attr\]dgit-defuse-attrs\s};
+
+sub is_gitattrs_setup () {
+ # return values:
+ # trueish
+ # 1: gitattributes set up and should be left alone
+ # falseish
+ # 0: there is a dgit-defuse-attrs but it needs fixing
+ # undef: there is none
+ my $gai = open_main_gitattrs();
+ return 0 unless $gai;
+ while (<$gai>) {
+ next unless m{$gitattrs_ourmacro_re};
+ return 1 if m{\s-working-tree-encoding\s};
+ printdebug "is_gitattrs_setup: found old macro\n";
+ return 0;
+ }
+ $gai->error and die $!;
+ printdebug "is_gitattrs_setup: found nothing\n";
+ return undef;
+}
+
+sub setup_gitattrs (;$) {
+ my ($always) = @_;
+ return unless $always || access_cfg_bool(1, 'setup-gitattributes');
+
+ my $already = is_gitattrs_setup();
+ if ($already) {
+ progress <<END;
+[attr]dgit-defuse-attrs already found, and proper, in .git/info/attributes
+ not doing further gitattributes setup
+END
+ return;
+ }
+ my $new = "[attr]dgit-defuse-attrs $negate_harmful_gitattrs";
+ my $af = "$maindir_gitcommon/info/attributes";
+ ensuredir "$maindir_gitcommon/info";
+
+ open GAO, "> $af.new" or die $!;
+ print GAO <<END or die $! unless defined $already;
+* dgit-defuse-attrs
+$new
+# ^ see GITATTRIBUTES in dgit(7) and dgit setup-new-tree in dgit(1)
+END
+ my $gai = open_main_gitattrs();
+ if ($gai) {
+ while (<$gai>) {
+ if (m{$gitattrs_ourmacro_re}) {
+ die unless defined $already;
+ $_ = $new;
+ }
+ chomp;
+ print GAO $_, "\n" or die $!;
+ }
+ $gai->error and die $!;
+ }
+ close GAO or die $!;
+ rename "$af.new", "$af" or die "install $af: $!";
+}
+