toolbox/lint-all-readme.pl: new utility to check readme data
[girocco.git] / toolbox / projtool.pl
blob2d16bc9468f1134bc5095d90e0598c506d1ab33e
1 #!/usr/bin/perl
3 # projtool.pl - command line Girocco project maintenance tool
4 # Copyright (C) 2016,2017,2020 Kyle J. McKay. All rights reserved.
5 # License GPLv2+: GNU GPL version 2 or later.
6 # www.gnu.org/licenses/gpl-2.0.html
7 # This is free software: you are free to change and redistribute it.
8 # There is NO WARRANTY, to the extent permitted by law.
10 use strict;
11 use warnings;
12 use vars qw($VERSION);
13 BEGIN {*VERSION = \'1.0.3'}
14 use File::Basename;
15 use Digest::MD5 qw(md5_hex);
16 use IO::Socket;
17 use Cwd qw(realpath);
18 use POSIX qw(strftime);
19 use lib "__BASEDIR__";
20 use Girocco::Config;
21 use Girocco::Util;
22 use Girocco::HashUtil;
23 use Girocco::CLIUtil;
24 use Girocco::Project;
25 use Girocco::User;
27 exit(&main(@ARGV)||0);
29 our $help;
30 BEGIN {my @a; /^(.*)$/s && push(@a, $1) foreach @ARGV; @ARGV=@a;}
31 BEGIN {$help = <<'HELP'}
32 Usage: %s [<global option>...] <command> <options>
34 global options:
35 -q | --quiet suppress warning messages
36 -p | --pager force output to be paginated
37 --no-pager never paginate output
39 help [<command>]
40 show full help or just for <command> if given
42 list [--verbose] [--sort=lcname|name|owner|gid|no] [--owner] [<regexp>]
43 list all projects (default is --sort=lcname)
44 limit to project names matching <regex> if given
45 match <regex> against owner instead of project name with --owner
47 create [--force] [--no-alternates] [--orphan] [<option>...] <project>
48 create new project <project> (prompted)
49 <option> can be:
50 --no-alternates skip setup of objects/info/alternates
51 --orphan allow creation of subproject w/o a parent
52 -p use mkdir -p during --orphan creation
53 --no-password set password crypt to invalid value "unknown"
54 --no-owner leave the gitweb.owner config unset
55 --mirror=<url> create a mirror from <url>
56 --full-mirror mirror all refs
57 --push[=<list>] create a push project
58 --desc=<string> specify project description w/o prompt
59 --homepage=<url> specify project homepage URL w/o prompt
60 --defaults do no interactive prompting at all
61 Using --no-password skips the prompts for password, using
62 --no-owner skips the prompt for owner and using --mirror=<url>
63 or --push[=<list>] skips the prompts for mirror URL and
64 heads-only and push users. With --defaults if neither
65 --mirror=<url> nor --push[=<list>] is given then --push will
66 be implied. Using --desc=<string> will force a specific
67 description (including an empty string) and skip the prompt for
68 it. Otherwise a non-empty default description will always be
69 supplied in lieu of an empty or omitted description.
71 adopt [--force] [--type=mirror|push] [<option>...] <project> [<users>]
72 adopt project <project>
73 type of project is guessed if --type=<type> omitted
74 <users> is same as <newuserslist> for setusers command
75 <option> can be:
76 --dry-run do all the checks but don't perform adoption
77 --verbose show project info dump (useful with --dry-run)
78 --no-users no push users at all (<users> must be omitted)
79 --no-owner leave the gitweb.owner config totally unchanged
80 --owner=<val> set the gitweb.owner config to <val>
81 Both --no-owner and --owner=<val> may NOT be given, with neither
82 take owner from preexisting gitweb.owner else use admin setting.
83 For mirrors <users> is ignored otherwise if no <users> and no
84 --no-users option the push users list will consist of the single
85 user name matching the owner or empty if none or more than one.
86 With --dry-run <project> can be an absolute path to a git dir.
88 remove [--force] [--really-delete] [--keep-forks] <project>
89 remove project <project>
90 do not move to _recyclebin with --really-delete (just rm -rf)
91 remove projects with forks (by keeping forks) using --keep-forks
93 prune [--quiet] (--force | --dry-run) [<project>...]
94 check to see if any projects (default is all projects) are
95 missing the associated project directory on disk.
96 Requires either --force or --dry-run option to operate.
97 With --dry-run only show what would be done.
98 With --prune actually remove any extraneous project(s).
99 With --dry-run exit code is non-zero if any action needed.
100 With --quiet, suppress output message, if any.
102 show <project>
103 show project <project>
105 listheads <project>
106 list all available heads for <project> and indicate current head
108 listtags [--verbose] <project>
109 list all ctags on project <project>
111 deltags <project> [-i] <tagstodel>
112 remove any ctags on project <project> present in <tagstodel>
113 <tagstodel> is space or comma separated list of tags to remove
114 with -i match against <tagstodel> without regard to letter case
116 addtags <project> <tagstoadd>
117 add ctags to project <project>
118 <tagstoadd> is space or comma separated list of tags to add
120 chpass [--force] <project> [random | unknown]
121 change project <project> password (prompted)
122 with "random" set to random password
123 with "unknown" set password hash to invalid value "unknown"
125 checkpw <project>
126 check project <project> password for a match (prompted)
128 gc [--force | --auto] [--redelta | --recompress] <project>
129 run the gc.sh script on project <project>
130 with --auto let the gc.sh script decide what to do
131 with --force cause a full gc to take place (force_gc=1)
132 with neither --auto nor --force do a mini or if needed a full gc
133 (in other words just touch .needsgc and run gc.sh)
134 with --redelta a full gc will use pack-objects --no-reuse-delta
135 with --recompress a full gc uses pack-objects --no-reuse-object
136 (--no-reuse-delta and --no-reuse-object are accepted as aliases)
137 unless the global --quiet option is given show_progress=1 is used
139 update [--force] [--quiet | --summary] <project>
140 run the update.sh script on project <project>
141 with --force cause a fetch to always take place (force_update=1)
142 with --quiet only show errors (show_progress is left unset)
143 with --summary show progress and ref summary (show_progress=1)
144 with neither --quiet nor --summary show it all (show_progress=2)
146 remirror [--force] <project>
147 initiate a remirror of project <project>
149 [set]owner [--force] <project> <newowner>
150 set project <project> owner to <newowner>
151 without "set" and only 1 arg, just show current project owner
153 [set]desc [--force] <project> <newdesc>
154 set project <project> description to <newdesc>
155 without "set" and only 1 arg, just show current project desc
157 [set]readme [--force] [--format=<readmetype>] <project> [<newsetting>]
158 set project <project> readme to <newsetting>
159 <readmetype> is markdown|plain|html (default is no change)
160 <newsetting> is automatic|suppressed|-|[@]filename
161 with "set" <readmetype> and/or <newsetting> is required
162 without "set" and only 2 args, just show current readme setting
164 [set]head <project> <newhead>
165 set project <project> HEAD symbolic ref to <newhead>
166 without "set" and only 1 arg, just show current project HEAD
168 [set]bool [--force] <project> <flagname> <boolvalue>
169 set project <project> boolean <flagname> to <boolvalue>
170 <flagname> is cleanmirror|reverseorder|summaryonly|statusupdtaes
171 without "set" and only 2 args, just show current flag value
173 [set]hooks [--force] <project> local | global | <path>
174 set project <project> hookspath to local, global or <path>
175 without "set" and only 1 arg, just show current hookspath
177 [set]autogchack <project> <boolvalue> | unset
178 set project <project> autogchack to <boolvalue> or "unset" it
179 without "set" just show current autogchack setting if enabled
180 with "set" autogchack must be enabled in Config.pm for the
181 type of project and maintain-auto-gc-hack.sh is always run
183 [set]url [--force] <project> <urlname> <newurlvalue>
184 set project <project> url <urlname> to <newurlvalue>
185 <urlname> is baseurl|homepage|notifyjson
186 without "set" and only 2 args, just show current url value
188 [set]msgs [--force] <project> <msgsname> <eaddrlist>
189 set project <project> msgs <msgsname> to <addrlist>
190 <msgsname> is notifymail|notifytag
191 <eaddrlist> is space or comma separated list of email addresses
192 without "set" and only 2 args, just show current msgs value
194 [set]users [--force] <project> <newuserslist>
195 set push project <project> users list to <newuserslist>
196 <newuserslist> is space or comma separated list of user names
197 without "set" and only 1 arg, just show current users list
199 [set]jsontype <project> <newjsontype>
200 set project <project> JSON Content-Type to <newjsontype>
201 <newjsontype> is x-www-form-urlencoded or json
202 without "set" and only 1 arg, just show current jsontype
204 [set]jsonsecret <project> <newjsonsecret>
205 set project <project> JSON secret to <newjsonsecret>
206 <newjsonsecret> is a string (empty string disables signatures)
207 without "set" and only 1 arg, just show current jsonsecret
209 get <project> <fieldname>
210 show project <project> field <fieldname>
211 <fieldname> is owner|desc|readme|head|hooks|users|jsontype
212 or jsonsecret|<flagname>|autogchack|<urlname>|<msgsname>
214 set [--force] <project> <fieldname> <newfieldvalue>
215 set project <project> field <fieldname> to <newfieldvalue>
216 <fieldname> same as for get
217 <newfieldvalue> same as for corresponding set... command
218 HELP
220 our $quiet;
221 our $usepager;
222 our $setopt;
223 sub die_usage {
224 my $sub = shift || diename;
225 if ($sub) {
226 die "Invalid arguments to $sub command -- try \"help\"\n";
227 } else {
228 die "Invalid arguments -- try \"help\"\n";
232 sub get_readme_len {
233 my $rm = shift;
234 defined($rm) or $rm = '';
235 return "length " . length($rm);
238 sub get_readme_desc {
239 my $rm = shift;
240 defined($rm) or $rm = '';
241 if (length($rm)) {
242 my $test = $rm;
243 $test =~ s/<!--(?:[^-]|(?:-(?!-)))*-->//gs;
244 $test =~ s/\s+//s;
245 return $test eq '' ? "suppressed" : "length " . length($rm);
246 } else {
247 return "automatic";
251 sub get_ctag_counts {
252 my $project = shift;
253 my $compact = shift;
254 my @ctags = ();
255 foreach ($project->get_ctag_names) {
256 my $val = 0;
257 my $ct;
258 if (open $ct, '<', $project->{path}."/ctags/$_") {
259 my $count = <$ct>;
260 close $ct;
261 defined $count or $count = '';
262 chomp $count;
263 $val = $count =~ /^[1-9]\d*$/ ? $count : 1;
265 if ($compact) {
266 if ($val == 1) {
267 push(@ctags, $_);
268 } elsif ($val > 1) {
269 push(@ctags, $_."(".$val.")");
271 } else {
272 push(@ctags, [$_, $val]) if $val;
275 @ctags;
278 sub get_clean_project {
279 my $project = get_project(@_);
280 delete $project->{loaded};
281 delete $project->{base_path};
282 delete $project->{ccrypt};
283 /^orig/i || !defined($project->{$_}) and delete $project->{$_} foreach keys %$project;
284 $project->{owner} = $project->{email}; delete $project->{email};
285 $project->{homepage} = $project->{hp}; delete $project->{hp};
286 $project->{baseurl} = $project->{url}; delete $project->{url};
287 if (defined($project->{path}) && $project->{path} ne "") {
288 my $rp = realpath($project->{path});
289 defined($rp) && $rp ne "" and $project->{realpath} = $rp;
290 if (-f "$rp/objects/info/packs") {
291 my $ipt = (stat _)[9];
292 defined($ipt) and $project->{infopackstime} =
293 strftime("%Y-%m-%d %H:%M:%S %z", localtime($ipt));
296 my $owner = $project->{owner};
297 if ($owner) {
298 $owner = lc($owner);
299 my @owner_users = map {$owner eq lc($$_[4]) ? $$_[1] : ()} get_all_users;
300 $project->{owner_users} = \@owner_users if @owner_users;
302 my $projname = $project->{name};
303 my @forks = grep {$$_[1] =~ m,^$projname/,} get_all_projects;
304 $project->{has_forks} = 1 if @forks;
305 $project->{has_alternates} = 1 if $project->has_alternates;
306 my @bundles = $project->bundles;
307 for (my $i = 0; $i < @bundles; ++$i) {
308 my $secs = $bundles[$i]->[0];
309 $bundles[$i]->[0] = strftime("%Y-%m-%d %H:%M:%S %z", localtime($secs));
310 my $sz = $bundles[$i]->[2];
311 1 while $sz =~ s/(?<=\d)(\d{3})(?:,|$)/,$1/g;
312 $bundles[$i]->[2] = $sz;
314 delete $project->{bundles};
315 $project->{bundles} = \@bundles if @bundles;
316 $project->{mirror} = 0 unless $project->{mirror};
317 $project->{is_empty} = 1 if $project->is_empty;
318 delete $project->{showpush} unless $project->{showpush};
319 delete $project->{users} if $project->{mirror};
320 delete $project->{baseurl} unless $project->{mirror};
321 delete $project->{banged} unless $project->{mirror};
322 delete $project->{lastrefresh} unless $project->{mirror};
323 delete $project->{cleanmirror} unless $project->{mirror};
324 delete $project->{statusupdates} unless $project->{mirror};
325 delete $project->{lastparentgc} unless $projname =~ m,/,;
326 unless ($project->{banged}) {
327 delete $project->{bangcount};
328 delete $project->{bangfirstfail};
329 delete $project->{bangmessagesent};
331 my $projhook = $project->_has_notifyhook;
332 if (defined($projhook) && $projhook ne "") {
333 $project->{notifyhook} = $projhook;
334 } else {
335 delete $project->{notifyhook};
337 $project->{README} = get_readme_desc($project->{README}) if exists($project->{README});
338 $project->{READMEDATA} = get_readme_len($project->{READMEDATA}) if exists($project->{READMEDATA});
339 my @tags = get_ctag_counts($project, 1);
340 $project->{tags} = \@tags if @tags;
341 my $projconfig = read_config_file_hash($project->{path}."/config");
342 if (defined($projconfig) && defined($projconfig->{"core.hookspath"})) {
343 my $ahp = $projconfig->{"core.hookspath"};
344 my $rahp = realpath($ahp);
345 my $lhp = $project->{path}."/hooks";
346 my $rlhp = realpath($lhp);
347 my $ghp = $Girocco::Config::reporoot."/_global/hooks";
348 my $rghp = realpath($ghp);
349 $project->{has_local_hooks} = 1 if
350 defined($rahp) && defined($rlhp) && $rahp eq $rlhp;
351 $project->{has_global_hooks} = 1 if
352 defined($rahp) && defined($rghp) && $rahp eq $rghp;
353 $project->{hookspath} = $ahp unless $ahp eq $lhp || $ahp eq $ghp;
355 $project;
358 sub clean_addrlist {
359 my %seen = ();
360 my @newlist = ();
361 foreach (split(/[,\s]+/, $_[0])) {
362 next unless $_;
363 $seen{lc($_)} = 1, push(@newlist, $_) unless $seen{lc($_)};
365 return join(($_[1]||","), @newlist);
368 sub valid_addrlist {
369 my $cleaned = clean_addrlist(join(" ", @_));
370 return 1 if $cleaned eq "";
371 valid_email_multi($cleaned) && length($cleaned) <= 512;
374 sub validate_users {
375 my ($userlist, $force, $nodie) = @_;
376 my @newusers = ();
377 my $badlist = 0;
378 my %seenuser = ();
379 my $mobok = $Girocco::Config::mob && $Girocco::Config::mob eq "mob";
380 my %users = map({($$_[1] => $_)} get_all_users);
381 foreach (split(/[\s,]+/, $userlist)) {
382 if (exists($users{$_}) || $_ eq "everyone" || ($mobok && $_ eq "mob")) {
383 $seenuser{$_}=1, push(@newusers, $_) unless $seenuser{$_};
384 next;
386 if (Girocco::User::does_exist($_, 1)) {
387 if ($force) {
388 $seenuser{$_}=1, push(@newusers, $_) unless $seenuser{$_};
389 } else {
390 $badlist = 1;
391 warn "refusing to allow questionable user \"$_\" without --force\n" unless $nodie && $quiet;
393 next;
395 $badlist = 1;
396 warn "invalid user: \"$_\"\n" unless $nodie && $quiet
398 die if $badlist && !$nodie;
399 return @newusers;
402 sub is_default_desc {
403 # "Unnamed repository; edit this file 'description' to name the repository."
404 # "Unnamed repository; edit this file to name it for gitweb."
405 local $_ = shift;
406 return 0 unless defined($_);
407 /Unnamed\s+repository;/i && /\s+edit\s+this\s+file\s+/i && /\s+to\s+name\s+/i;
410 sub valid_desc {
411 my $test = shift;
412 chomp $test;
413 return 0 if $test =~ /[\r\n]/;
414 $test =~ s/\s\s+/ /g;
415 $test =~ s/^\s+//;
416 $test =~ s/\s+$//;
417 return $test ne '';
420 sub clean_desc {
421 my $desc = shift;
422 defined($desc) or $desc = '';
423 chomp $desc;
424 $desc = to_utf8($desc, 1);
425 $desc =~ s/\s\s+/ /g;
426 $desc =~ s/^\s+//;
427 $desc =~ s/\s+$//;
428 return $desc;
431 sub parse_options {
432 Girocco::CLIUtil::_parse_options(
433 sub {
434 warn((($_[0]eq'?')?"unrecognized":"missing argument for")." option \"$_[1]\"\n")
435 unless $quiet;
436 die_usage;
437 }, @_);
440 sub cmd_list {
441 my %sortsub = (
442 lcname => sub {lc($$a[1]) cmp lc($$b[1])},
443 name => sub {$$a[1] cmp $$b[1]},
444 gid => sub {$$a[3] <=> $$b[3]},
445 owner => sub {lc($$a[4]) cmp lc($$b[4]) || lc($$a[1]) cmp lc($$b[1])},
446 no => sub {$$a[0] <=> $$b[0]},
448 my $sortopt = 'lcname';
449 my ($verbose, $owner);
450 parse_options(":sort" => \$sortopt, verbose => \$verbose, owner => \$owner);
451 my $regex;
452 if (@ARGV) {
453 my $val = shift @ARGV;
454 $regex = qr($val) or die "bad regex \"$val\"\n";
456 !@ARGV && exists($sortsub{$sortopt}) or die_usage;
457 my $sortsub = $sortsub{$sortopt};
458 my $grepsub = defined($regex) ? ($owner ? sub {$$_[4] =~ /$regex/} : sub {$$_[1] =~ /$regex/}) : sub {1};
459 my @projects = sort($sortsub grep {&$grepsub} get_all_projects);
460 if ($verbose) {
461 print map(sprintf("%s\n", join(":", (@$_)[1..5])), @projects);
462 } else {
463 print map(sprintf("%s: %s\n", $$_[1], $$_[5] =~ /^:/ ? "<mirror>" : $$_[5]), @projects);
465 return 0;
468 sub cmd_create {
469 my ($force, $noalternates, $orphanok, $optp, $nopasswd, $noowner, $defaults, $ispush, $pushusers,
470 $ismirror, $desc, $fullmirror, $homepage);
471 parse_options(
472 force => \$force, "no-alternates" => \$noalternates, orphan => \$orphanok, p => \$optp,
473 "no-password" => \$nopasswd, "no-owner" => \$noowner, defaults => \$defaults,
474 "push" => \$ispush, ":push" => \$pushusers, ":mirror" => \$ismirror, ":desc" => \$desc,
475 ":description" => \$desc, "full-mirror" => \$fullmirror, ":homepage" => \$homepage);
476 @ARGV == 1 or die_usage;
477 !defined($pushusers) || defined($ispush) or $ispush = 1;
478 defined($ismirror) && $ismirror =~ /^\s*$/ and die "--mirror url must not be empty\n";
479 die "--mirror and --push are mutually exclusive options\n" if $ismirror && $ispush;
480 die "--full-mirror requires use of --mirror=<url> option\n" if $fullmirror && !$ismirror;
481 !$defaults || defined($ispush) || defined($ismirror) or $ispush = 1;
482 !$defaults || defined($nopasswd) or $nopasswd = 1;
483 !$defaults || defined($noowner) or $noowner = 1;
484 !defined($ispush) || defined($pushusers) or $pushusers = "";
485 my $projname = $ARGV[0];
486 $projname =~ s/\.git$//i;
487 Girocco::Project::does_exist($projname, 1) and die "Project already exists: \"$projname\"\n";
488 if (!Girocco::Project::valid_name($projname, $orphanok, $optp)) {
489 warn "Refusing to create orphan project without --orphan\n"
490 if !$quiet && !$orphanok && Girocco::Project::valid_name($projname, 1, 1);
491 warn "Required orphan parent directory does not exist (use -p): ",
492 $Girocco::Config::reporoot.'/'.Girocco::Project::get_forkee_name($projname), "\n"
493 if !$quiet && $orphanok && Girocco::Project::valid_name($projname, 1, 1);
494 die "Invalid project name: \"$projname\"\n";
496 my ($forkee, $project) = ($projname =~ m#^(.*/)?([^/]+)$#);
497 my $newtype = $forkee ? 'fork' : 'project';
498 if (length($project) > 64) {
499 die "The $newtype name is longer than 64 characters. Do you really need that much?\n"
500 unless $force;
501 warn "Allowing $newtype name longer than 64 characters with --force\n" unless $quiet;
503 unless ($Girocco::Config::push || $Girocco::Config::mirror) {
504 die "Project creation disabled (no mirrors or push projects allowed)\n" unless $force;
505 warn "Continuing with --force even though both push and mirror projects are disabled\n" unless $quiet;
507 print "Enter settings for new project \"$projname\"\n" unless $defaults;
508 my %settings = ();
509 $settings{noalternates} = $noalternates;
510 if ($nopasswd) {
511 $settings{crypt} = "unknown";
512 } else {
513 my $np1 = prompt_noecho_nl_or_die("Admin password for project $projname (echo is off)");
514 $np1 ne "" or die "empty passwords are not permitted (brokenness will ensue)\n";
515 my $np2 = prompt_noecho_nl_or_die("Retype admin password for project $projname");
516 $np1 eq $np2 or die "Our high-paid security consultants have determined that\n" .
517 "the admin passwords you have entered do not match each other.\n";
518 $settings{crypt} = scrypt_sha1($np1);
520 my $owner = "";
521 unless ($noowner) {
522 $owner = prompt_or_die("Owner/email name for project $projname");
523 unless (valid_email($owner)) {
524 unless ($force) {
525 warn "Your email sure looks weird...?\n";
526 redo;
528 warn "Allowing invalid email with --force\n" unless $quiet;
530 if (length($owner) > 96) {
531 unless ($force) {
532 warn "Your email is longer than 96 characters. Do you really need that much?\n";
533 redo;
535 warn "Allowing email longer than 96 characters with --force\n" unless $quiet;
538 $settings{email} = $owner;
539 my $baseurl = "";
540 my $checkmirror = sub {
541 my $checkurl = shift;
542 unless (valid_repo_url($checkurl)) {
543 unless ($force) {
544 warn "Invalid mirror URL: \"$checkurl\"\n";
545 return undef;
547 warn "Allowing invalid mirror URL with --force\n" unless $quiet;
549 if ($Girocco::Config::restrict_mirror_hosts) {
550 my $mh = extract_url_hostname($checkurl);
551 unless (is_dns_hostname($mh)) {
552 unless ($force) {
553 warn "Invalid non-DNS mirror URL: \"$checkurl\"\n";
554 return undef;
556 warn "Allowing non-DNS mirror URL with --force\n" unless $quiet;
558 if (is_our_hostname($mh)) {
559 unless ($force) {
560 warn "Invalid same-host mirror URL: \"$checkurl\"\n";
561 return undef;
563 warn "Allowing same-host mirror URL with --force\n" unless $quiet;
566 return $checkurl;
568 if ($ispush || $ismirror) {
569 !$ispush || $force || $Girocco::Config::push or
570 die "Push projects are disabled, create a mirror (or use --force)\n";
571 !$ismirror || $force || $Girocco::Config::mirror or
572 die "Mirror projects are disabled, create a push project (or use --force)\n";
573 if ($ismirror) {
574 &$checkmirror($ismirror) or die "Invalid --mirror URL\n";
575 $baseurl = $ismirror;
576 $settings{url} = $baseurl;
577 $settings{cleanmirror} = $fullmirror ? 0 : 1;
578 } else {
579 my @newusers = ();
580 if ($pushusers !~ /^[\s,]*$/) {
581 eval {@newusers = validate_users($pushusers, $force); 1;} or
582 die "Invalid --push user list\n";
584 $settings{users} = \@newusers;
586 } elsif ($force || $Girocco::Config::mirror) {{
587 if ($force || $Girocco::Config::push) {
588 $baseurl = prompt_or_die("URL to mirror from (leave blank for push project)", "");
589 } else {{
590 $baseurl = prompt_or_die("URL to mirror from");
591 unless ($baseurl ne "") {
592 warn "Push projects are disabled, you must enter a mirror URL (or use --force)\n";
593 redo;
596 if ($baseurl ne "") {
597 &$checkmirror($baseurl) or redo;
598 $settings{url} = $baseurl;
599 $settings{cleanmirror} =
600 ynprompt_or_die("Mirror only heads, tags and notes (Y/n)", "Yes");
603 my $mirror = ($baseurl eq "") ? 0 : 1;
604 my $checkdesc = sub {
605 my $d = shift;
606 if (length($d) > 1024) {
607 unless ($force) {
608 warn "Short description length greater than 1024 characters!\n";
609 return undef;
611 warn "Allowing short description length greater than 1024 characters\n" unless $quiet;
613 return $d;
615 if (defined($desc)) {
616 $desc =~ s/^\s+//; $desc =~ s/\s+$//;
617 $desc eq "" || &$checkdesc($desc) or
618 die "Invalid --desc description\n";
619 } elsif (!$defaults) {
620 $desc = prompt_or_die("Short description", "");
621 $desc =~ s/^\s+//; $desc =~ s/\s+$//;
622 $desc eq "" || &$checkdesc($desc) or redo;
623 $desc = undef if $desc eq "";
625 defined($desc) or $desc = $mirror ? "Mirror of $baseurl" : "Push project $projname";
626 $settings{desc} = $desc;
627 my $checkhp = sub {
628 my $hpurl = shift;
629 unless (valid_web_url($hpurl)) {
630 unless ($force) {
631 warn "Invalid home page URL: \"$hpurl\"\n";
632 return undef;
634 warn "Allowing invalid home page URL with --force\n" unless $quiet;
636 return $hpurl;
638 if (defined($homepage)) {
639 $homepage =~ s/^\s+//; $homepage =~ s/\s+$//;
640 $homepage eq "" || &$checkhp($homepage) or
641 die "Invalid --homepage URL\n";
642 } elsif (!$defaults) {
643 $homepage = prompt_or_die("Home page URL", "");
644 $homepage =~ s/^\s+//; $homepage =~ s/\s+$//;
645 $homepage eq "" || &$checkhp($homepage) or redo;
646 $homepage = undef if $homepage eq "";
648 $settings{hp} = $homepage;
649 my $jsonurl = "";
650 if (!$defaults) {
651 $jsonurl = prompt_or_die("JSON notify POST URL", "");
652 if ($jsonurl ne "" && !valid_web_url($jsonurl)) {
653 unless ($force) {
654 warn "Invalid JSON notify POST URL: \$jsonurl\"\n";
655 redo;
657 warn "Allowing invalid JSON notify POST URL with --force\n" unless $quiet;
660 $settings{notifyjson} = $jsonurl;
661 my $commitaddrs = "";
662 if (!$defaults) {
663 $commitaddrs = clean_addrlist(prompt_or_die("Commit notify email addr(s)", ""));
664 if ($commitaddrs ne "" && !valid_addrlist($commitaddrs)) {
665 unless ($force) {
666 warn"invalid commit notify email address list (use --force to accept): \"$commitaddrs\"\n";
667 redo;
669 warn "using invalid commit notify email address list with --force\n" unless $quiet;
672 $settings{notifymail} = $commitaddrs;
673 $settings{reverseorder} = 1;
674 $settings{reverseorder} = ynprompt_or_die("Oldest-to-newest commit order in emails", "Yes")
675 if !$defaults && $commitaddrs ne "";
676 $settings{summaryonly} = ynprompt_or_die("Summary only (no diff) in emails", "No")
677 if !$defaults && $commitaddrs ne "";
678 my $tagaddrs = "";
679 if (!$defaults) {
680 $tagaddrs = clean_addrlist(prompt_or_die("Tag notify email addr(s)", ""));
681 if ($tagaddrs ne "" && !valid_addrlist($tagaddrs)) {
682 unless ($force) {
683 warn"invalid tag notify email address list (use --force to accept): \"$tagaddrs\"\n";
684 redo;
686 warn "using invalid tag notify email address list with --force\n" unless $quiet;
689 $settings{notifytag} = $tagaddrs;
690 if (!$mirror && !$ispush) {
691 my @newusers = ();
693 my $userlist = prompt_or_die("Push users", join(",", @newusers));
694 eval {@newusers = validate_users($userlist, $force); 1;} or redo;
696 $settings{users} = \@newusers;
698 my $newproj = Girocco::Project->ghost($projname, $mirror, $orphanok, $optp)
699 or die "Girocco::Project->ghost call failed\n";
700 my ($k, $v);
701 $newproj->{$k} = $v while ($k, $v) = each(%settings);
702 my $killowner = sub {
703 system($Girocco::Config::git_bin, '--git-dir='.$newproj->{path},
704 'config', '--unset', "gitweb.owner");
706 if ($mirror) {
707 $newproj->premirror or die "Girocco::Project->premirror failed\n";
708 !$noowner or &$killowner;
709 $newproj->clone or die "Girocco::Project->clone failed\n";
710 warn "Project $projname created and cloning successfully initiated.\n"
711 unless $quiet;
712 } else {
713 $newproj->conjure or die "Girocco::Project->conjure failed\n";
714 !$noowner or &$killowner;
715 warn "New push project fork is empty due to use of --no-alternates\n"
716 if !$quiet && $projname =~ m,/, && $noalternates;
717 warn "Project $projname successfully created.\n" unless $quiet;
719 return 0;
722 sub git_config {
723 my $gd = shift;
724 system($Girocco::Config::git_bin, "--git-dir=$gd", 'config', @_) == 0
725 or die "\"git --git-dir='$gd' config ".join(" ", @_)."\" failed.\n";
728 sub cmd_adopt {
729 my ($force, $type, $nousers, $dryrun, $noowner, $owner, $users, $verbose);
730 parse_options(force => \$force, ":type" => \$type, "no-users" => \$nousers, "dry-run" => \$dryrun,
731 "no-owner" => \$noowner,":owner" => \$owner, quiet => \$quiet, q =>\$quiet, verbose => \$verbose);
732 @ARGV or die "Please give project name on command line.\n";
733 my $projname = shift @ARGV;
734 (!$noowner || !defined($owner)) && (!$nousers || !@ARGV) or die_usage;
735 !defined($type) || $type eq "mirror" || $type eq "push" or die_usage;
736 defined($type) or $type = "";
737 my $projdir;
738 if ($dryrun && $projname =~ m,^/[^.\s/\\:], && is_git_dir(realpath($projname))) {
739 $projdir = realpath($projname);
740 $projname = $projdir;
741 $projname =~ s/\.git$//i;
742 $projname =~ s,/+$,,;
743 $projname =~ s,^.*/,,;
744 $projname ne "" or $projname = $projdir;
745 } else {
746 $projname =~ s/\.git$//i;
747 $projname ne "" or die "Invalid project name \"\".\n";
748 unless (Girocco::Project::does_exist($projname, 1)) {
749 Girocco::Project::valid_name($projname, 1, 1)
750 or die "Invalid project name \"$projname\".\n";
751 die "No such project to adopt: $projname\n";
753 defined(Girocco::Project->load($projname))
754 and die "Project already known (no need to adopt): $projname\n";
755 $projdir = $Girocco::Config::reporoot . "/" . $projname . ".git";
756 is_git_dir($projdir) or die "Not a git directory: \"$projdir\"\n";
758 my $config = read_config_file($projdir . "/config");
759 my %config = ();
760 %config = map {($$_[0], defined($$_[1])?$$_[1]:"true")} @$config if defined($config);
761 git_bool($config{"core.bare"}) or die "Not a bare git repository: \"$projdir\"\n";
762 defined(read_HEAD_symref($projdir)) or die "Project with non-symbolic HEAD ref: \"$projdir\"\n";
763 @ARGV and $users = [validate_users(join(" ", @ARGV), $force, 1)];
764 my $desc = "";
765 if (-e "$projdir/description") {
766 open my $fd, '<', "$projdir/description" or die "Cannot open \"$projdir/description\": $!\n";
768 local $/;
769 $desc = <$fd>;
771 close $fd;
772 defined $desc or $desc = "";
773 chomp $desc;
774 $desc = to_utf8($desc, 1);
775 is_default_desc($desc) and $desc = "";
776 if ($desc ne "" && !valid_desc($desc)) {
777 die "invalid 'description' file contents (use --force to accept): \"$desc\"\n"
778 unless $force;
779 warn "using invalid 'description' file contents with --force\n" unless $quiet;
781 $desc = clean_desc($desc);
782 if (length($desc) > 1024) {
783 die "description longer than 1024 chars (use --force to accept): \"$desc\"\n"
784 unless $force;
785 warn "using longer than 1024 char description with --force\n" unless $quiet;
788 my $readme = "";
789 my $origreadme = "";
790 my $readmedata = "";
791 my $origreadmedata = "";
792 my $readmetype = Girocco::Project::_normalize_rmtype($config{"girocco.readmetype"},1);
793 if (-e "$projdir/README.html") {
794 open my $fd, '<', "$projdir/README.html" or die "Cannot open \"$projdir/README.html\": $!\n";
796 local $/;
797 $readme = <$fd>;
799 close $fd;
800 defined $readme or $readme = "";
801 $readme = to_utf8($readme, 1);
802 $readme =~ s/\r\n?/\n/gs;
803 $readme =~ s/^\s+//s;
804 $readme =~ s/\s+$//s;
805 $readme eq "" or $readme .= "\n";
806 $origreadme = $readme;
807 if (-e "$projdir/README.dat") {
808 open my $fd2, '<', "$projdir/README.dat" or die "Cannot open \"$projdir/README.dat\": $!\n";
810 local $/;
811 $readmedata = <$fd2>;
813 close $fd2;
814 defined $readmedata or $readmedata = "";
815 $readmedata = to_utf8($readmedata, 1);
816 $readmedata =~ s/\r\n?/\n/gs;
817 $readmedata =~ s/^\s+//s;
818 $readmedata =~ s/\s+$//s;
819 $readmedata eq "" or $readmedata .= "\n";
820 $origreadmedata = $readmedata;
822 !$readmetype && length($readme) && !length($readmedata) and do {
823 # the old HTML format
824 $readmetype = 'HTML';
825 $readmedata = $readme;
827 if (length($readmedata) > 8192) {
828 die "readme greater than 8192 chars is too long (use --force to override)\n"
829 unless $force;
830 warn "using readme greater than 8192 chars with --force\n" unless $quiet;
833 my $dummy = {READMEDATA => $readmedata, rmtype => $readmetype, name => $projname};
834 my ($cnt, $err) = Girocco::Project::_lint_readme($dummy, 0);
835 if ($cnt) {
836 my $msg = "README: $cnt error";
837 $msg .= "s" unless $cnt == 1;
838 print STDERR "$msg\n", "-" x length($msg), "\n", $err
839 unless $force && $quiet;
840 exit(255) unless $force && $readmetype eq 'HTML';
841 warn "$projname: using invalid raw HTML with --force\n" unless $quiet;
842 } else {
843 $readme = $dummy->{README};
847 $readmetype or $readmetype = Girocco::Project::_normalize_rmtype(""); # use default type
848 # Inspect any remotes now
849 # Yes, Virginia, remote urls can be multi-valued
850 my %remotes = ();
851 foreach (@$config) {
852 my ($k,$v) = @$_;
853 next unless $k =~ /^remote\.([^\/].*?)\.([^.]+)$/; # remote name cannot start with "/"
854 my ($name, $subkey) = ($1, $2);
855 $remotes{$name}->{skip} = git_bool($v,1), next if $subkey eq "skipdefaultupdate" || $subkey eq "skipfetchall";
856 $remotes{$name}->{mirror} = git_bool($v,1), next if $subkey eq "mirror"; # we might want this
857 $remotes{$name}->{vcs} = $v, next if defined($v) && $v !~ /^\s*$/ && $subkey eq "vcs";
858 push(@{$remotes{$name}->{$subkey}}, $v), next if defined($v) && $v !~ /^\s*$/ &&
859 ($subkey eq "url" || $subkey eq "fetch" || $subkey eq "push" || $subkey eq "pushurl");
861 # remotes.default is the default remote group to fetch for "git remote update" otherwise --all
862 # the remote names in a group are separated by runs of [ \t\n] characters
863 # remote names "", ".", ".." and any name starting with "/" are invalid
864 # a remote with no url or vcs setting is not considered valid
865 my @check = ();
866 my $usingall = 0;
867 if (exists($config{"remotes.default"})) {
868 foreach (split(/[ \t\n]+/, $config{"remotes.default"})) {
869 next unless exists($remotes{$_});
870 my $rmt = $remotes{$_};
871 next if !exists($rmt->{url}) && !$rmt->{vcs};
872 push(@check, $_);
874 } else {
875 $usingall = 1;
876 my %seenrmt = ();
877 foreach (@$config) {
878 my ($k,$v) = @$_;
879 next unless $k =~ /^remote\.([^\/].*?)\.[^.]+$/;
880 next if $seenrmt{$1};
881 $seenrmt{$1} = 1;
882 next unless exists($remotes{$1});
883 my $rmt = $remotes{$1};
884 next if $rmt->{skip} || (!exists($rmt->{url}) && !$rmt->{vcs});
885 push(@check, $1);
888 my @needskip = (); # remotes that need skipDefaultUpdate set to true
889 my $foundvcs = 0;
890 my $foundfetch = 0;
891 my $foundfetchwithmirror = 0;
892 foreach (@check) {
893 my $rmt = $remotes{$_};
894 push(@needskip, $_) if $usingall && !exists($rmt->{fetch});
895 next unless exists($rmt->{fetch});
896 ++$foundfetch;
897 ++$foundfetchwithmirror if $rmt->{mirror};
898 ++$foundvcs if $rmt->{vcs} || (exists($rmt->{url}) && $rmt->{url}->[0] =~ /^[a-zA-Z0-9][a-zA-Z0-9+.-]*::/);
900 # if we have $foundvcs then we need to explicitly set fetch.prune to false
901 # if we have $foundfetch > 1 then we need to explicitly set fetch.prune to false
902 my $neednoprune = !exists($config{"fetch.prune"}) && ($foundvcs || $foundfetch > 1);
903 my $baseurl = "";
904 my $needfakeorigin = 0; # if true we need to set remote.origin.skipDefaultUpdate = true
905 # if remote "origin" exists we always pick up its first url or use ""
906 if (exists($remotes{origin})) {
907 my $rmt = $remotes{origin};
908 $baseurl = exists($rmt->{url}) ? $rmt->{url}->[0] : "";
909 $needfakeorigin = !exists($rmt->{url}) && !$rmt->{vcs} && !$rmt->{skip};
910 } else {
911 $needfakeorigin = 1;
912 # get the first url of the @check remotes
913 foreach (@check) {
914 my $rmt = $remotes{$_};
915 next unless exists($rmt->{url});
916 next unless defined($rmt->{url}->[0]) && $rmt->{url}->[0] ne "";
917 $baseurl = $rmt->{url}->[0];
918 last;
921 my $makemirror = $type eq "mirror" || ($type eq "" && $foundfetch);
923 # If we have $foundfetch we want to make a mirror but complain if
924 # we $foundfetchwithmirror as well unless we have --type=mirror.
925 # Warn if we have --type=push and $foundfetch and !$foundfetchwithmirror.
926 # Warn if we need to set fetch.prune=false when making a mirror
927 # Warn if we need to create remote.origin.skipDefaultUpdate when making a mirror
928 # Complain if @needskip AND !$usingall (warn with --force but don't set skip)
929 # Warn if $usingall and any @needskip (and set them) if making a mirror
930 # Warn if making a mirror and $baseurl eq ""
931 # Warn if we have --type=mirror and !$foundfetch
933 if ($makemirror) {
934 warn "No base URL to mirror from for adopted \"$projname\"\n" unless $quiet || $baseurl ne "";
935 warn "Adopting mirror \"$projname\" without any fetch remotes\n" unless $quiet || $foundfetch;
936 if ($foundfetchwithmirror) {
937 warn "Refusing to adopt mirror \"$projname\" with active remote.<name>.mirror=true remote(s)\n".
938 "(Use --type=mirror to override)\n"
939 unless $type eq "mirror";
940 exit(255) unless $type eq "mirror" || $dryrun;
941 warn "Adopting mirror \"$projname\" with active remote.<name>.mirror=true remotes\n"
942 unless $quiet || $type ne "mirror";
944 warn "Setting explicit fetch.prune=false for adoption of mirror \"$projname\"\n"
945 if !$quiet && $neednoprune;
946 warn "Setting remote.origin.skipDefaultUpdate=true for adoption of mirror \"$projname\"\n"
947 if !$quiet && $needfakeorigin;
948 if (!$usingall && @needskip) {
949 warn "Refusing to adopt mirror empty fetch remote(s) (override with --force)\n"
950 unless $force;
951 exit(255) unless $force || $dryrun;
952 warn "Adopting mirror with empty fetch remote(s) with --force\n"
953 unless $quiet || !$force;
955 warn "Will set skipDefaultUpdate=true on non-fetch remote(s)\n" if !$quiet && $usingall && @needskip;
956 warn "Adopting mirror with base URL \"$baseurl\"\n" unless $quiet || $baseurl eq "";
957 } else {
958 warn "Adopting push \"$projname\" but active non-mirror remotes are present\n"
959 if !$quiet && $foundfetch && !$foundfetchwithmirror;
962 if (!$noowner && !defined($owner)) {
963 # Select the owner
964 $owner = $config{"gitweb.owner"};
965 if (!defined($owner) || $owner eq "") {
966 $owner = $Girocco::Config::admin;
967 warn "Using owner \"$owner\" for adopted project\n" unless $quiet;
970 if (!$nousers && !$makemirror && !defined($users)) {
971 # select user list for push project
972 my $findowner = $owner;
973 defined($findowner) or $findowner = $config{"gitweb.owner"};
974 $findowner = lc($findowner) if defined($findowner);
975 my @owner_users = ();
976 @owner_users = map {$findowner eq lc($$_[4]) ? $$_[1] : ()} get_all_users
977 if defined($findowner) && $findowner ne "";
978 defined($findowner) or $findowner = "";
979 if (@owner_users <= 1) {
980 $users = \@owner_users;
981 warn "No users found that match owner \"$findowner\"\n" unless @owner_users || $quiet;
982 } else {
983 $users = [];
984 warn "Found ".scalar(@owner_users)." users for owner \"$findowner\" (" .
985 join(" ", @owner_users) . ") not setting any\n" unless $quiet;
988 defined($users) or $users = [];
990 # Warn if we preserve an existing receive.denyNonFastForwards or receive.denyDeleteCurrent setting
991 # Complain if core.logallrefupdates or logs subdir exists and contains any files (allow with --force
992 # and warn about preserving the setting)
994 warn "Preserving existing receive.denyNonFastForwards=true\n"
995 if !$quiet && git_bool($config{"receive.denynonfastforwards"});
996 warn "Preserving existing receive.denyDeleteCurrent=$config{'receive.denydeletecurrent'}\n"
997 if !$quiet && exists($config{"receive.denydeletecurrent"}) &&
998 $config{"receive.denydeletecurrent"} ne "warn";
1000 my $reflogfiles = Girocco::Project::_contains_files("$projdir/logs");
1001 my $reflogactive = git_bool($config{"core.logallrefupdates"});
1002 if ($reflogactive || $reflogfiles) {
1003 warn "Refusing to adopt \"$projname\" with active ref logs without --force\n" if $reflogfiles && !$force;
1004 warn "Refusing to adopt \"$projname\" with core.logAllRefUpdates=true without --force\n" if $reflogactive && !$force;
1005 exit(255) unless $force || $dryrun;
1006 warn "Adopting \"$projname\" with active ref logs with --force\n" unless $quiet || ($reflogfiles && !$force);
1007 warn "Adopting \"$projname\" with core.logAllRefUpdates=true with --force\n" unless $quiet || ($reflogactive && !$force);
1010 return 0 if $dryrun && !$verbose;
1012 my $newproj = eval {Girocco::Project->ghost($projname, $makemirror, 1, $dryrun)};
1013 defined($newproj) or die "Girocco::Project::ghost failed: $@\n";
1014 $newproj->{desc} = $desc;
1015 $newproj->{README} = $readme;
1016 $newproj->{READMEDATA} = $readmedata;
1017 $newproj->{rmtype} = $readmetype;
1018 $newproj->{url} = $baseurl if $makemirror || exists($config{"gitweb.baseurl"});
1019 $newproj->{email} = $owner if defined($owner);
1020 $newproj->{users} = $users;
1021 $newproj->{crypt} = "unknown";
1022 $newproj->{reverseorder} = 1 unless exists($config{"hooks.reverseorder"});
1023 $newproj->{summaryonly} = 1 unless exists($config{"hooks.summaryonly"});
1024 my $dummy = bless {}, "Girocco::Project";
1025 $dummy->{path} = "$projdir";
1026 $dummy->{configfilehash} = \%config;
1027 $dummy->_properties_load;
1028 delete $dummy->{origurl};
1029 foreach my $k (keys(%$dummy)) {
1030 $newproj->{$k} = $dummy->{$k}
1031 if exists($dummy->{$k}) && !exists($newproj->{$k});
1034 if ($verbose) {
1035 use Data::Dumper;
1036 my %info = %$newproj;
1037 $info{README} = get_readme_desc($info{README}) if exists($info{README});
1038 my $d = Data::Dumper->new([\%info], ['*'.$newproj->{name}]);
1039 $d->Sortkeys(sub {[sort({lc($a) cmp lc($b)} keys %{$_[0]})]});
1040 print $d->Dump([\%info], ['*'.$newproj->{name}]);
1042 return 0 if $dryrun;
1044 # Make any changes as needed for @needskip, $neednoprune and $needfakeorigin
1045 if ($makemirror) {
1046 git_config($projdir, "fetch.prune", "false") if $neednoprune;
1047 git_config($projdir, "remote.origin.skipDefaultUpdate", "true") if $needfakeorigin;
1048 if ($usingall && @needskip) {
1049 git_config($projdir, "remote.$_.skipDefaultUpdate", "true") foreach @needskip;
1053 # Write out any README.dat/README.html changes before the actual Adoption
1054 # Otherwise they will get stepped on. The Girocco::Project::adopt function
1055 # does not know how to validate README.html during adoption like the above code does.
1056 if ($readmedata ne $origreadmedata) {
1057 open my $fd, '>', "$projdir/README.dat" or die "Cannot write \"$projdir/README.dat\": $!\n";
1058 print $fd $readmedata or die "Error writing \"$projdir/README.dat\": $!\n";
1059 close $fd or die "Error closing \"$projdir/README.dat\": $!\n";
1061 if ($readme ne $origreadme || ! -e "$projdir/README.html") {
1062 open my $fd, '>', "$projdir/README.html" or die "Cannot write \"$projdir/README.html\": $!\n";
1063 print $fd $readme or die "Error writing \"$projdir/README.html\": $!\n";
1064 close $fd or die "Error closing \"$projdir/README.html\": $!\n";
1066 git_config($projdir, "girocco.rmtype", $readmetype);
1068 # Perform the actual adoption
1069 $newproj->adopt or die "Girocco::Project::adopt failed\n";
1071 # Perhaps restore core.logAllRefUpdates, receive.denyNonFastForwards and receive.denyDeleteCurrent
1072 git_config($projdir, "receive.denyNonFastForwards", "true")
1073 if git_bool($config{"receive.denynonfastforwards"});
1074 git_config($projdir, "receive.denyDeleteCurrent", $config{"receive.denydeletecurrent"})
1075 if exists($config{"receive.denydeletecurrent"}) &&
1076 $config{"receive.denydeletecurrent"} ne "warn";
1077 git_config($projdir, "core.logAllRefUpdates", "true")
1078 if $reflogactive;
1080 # Success
1081 if ($makemirror) {
1082 warn "Mirror project \"$projname\" successfully adopted.\n" unless $quiet;
1083 } else {
1084 warn "Push project \"$projname\" successfully adopted.\n" unless $quiet;
1086 return 0;
1089 sub cmd_remove {
1090 my ($force, $reallydel, $keepforks);
1091 parse_options(force => \$force, "really-delete" => \$reallydel,
1092 "keep-forks" => \$keepforks, quiet => \$quiet, q =>\$quiet);
1093 @ARGV or die "Please give project name on command line.\n";
1094 @ARGV == 1 or die_usage;
1095 my $project = get_project($ARGV[0]);
1096 my $projname = $project->{name};
1097 my $isempty = !$project->{mirror} && $project->is_empty;
1098 if (!$project->{mirror} && !$isempty && $reallydel) {
1099 die "refusing to remove and delete non-empty push project without --force: $projname\n" unless $force;
1100 warn "allowing removal and deletion of non-empty push project with --force\n" unless $quiet;
1102 my $altwarn;
1103 my $removenogc;
1104 if ($project->has_forks) {
1105 die "refusing to remove project with forks (use --keep-forks): $projname\n" unless $keepforks;
1106 warn "allowing removal of forked project while preserving its forks with --keep-forks\n" unless $quiet;
1107 # Run pseudo GC on that repository so that objects don't get lost within forks
1108 my $basedir = $Girocco::Config::basedir;
1109 my $projdir = $project->{path};
1110 warn "We have to run pseudo GC on the repo so that the forks don't lose data. Hang on...\n" unless $quiet;
1111 my $nogcrunning = sub {
1112 die "Error: GC appears to be currently running on $projname\n"
1113 if -e "$projdir/gc.pid" || -e "$projdir/.gc_in_progress";
1115 &$nogcrunning;
1116 $removenogc = ! -e "$projdir/.nogc";
1117 recreate_file("$projdir/.nogc") if $removenogc;
1118 die "unable to create \"$projdir/.nogc\"\n" unless -e "$projdir/.nogc";
1119 delete $ENV{show_progress};
1120 $ENV{'show_progress'} = 1 unless $quiet;
1121 sleep 2; # *cough*
1122 &$nogcrunning;
1123 system("$basedir/toolbox/perform-pre-gc-linking.sh", "--include-packs", $projname) == 0
1124 or die "Running pseudo GC on project $projname failed\n";
1125 $altwarn = 1;
1127 my $archived;
1128 if (!$project->{mirror} && !$isempty && !$reallydel) {
1129 $archived = $project->archive_and_delete;
1130 unlink("$archived/.nogc") if $removenogc && defined($archived) && $archived ne "";
1131 } else {
1132 $project->delete;
1134 warn "Project '$projname' removed from $Girocco::Config::name" .
1135 ($archived ? ", backup in '$archived'" : "") .".\n" unless $quiet;
1136 warn "Retained forks may now have unwanted objects/info/alternates lines\n" if $altwarn && !$quiet;
1137 return 0;
1140 sub cmd_prune {
1141 my ($force, $dryrun);
1142 parse_options(force => \$force, "dry-run" => \$dryrun, "quiet" => \$quiet);
1143 ($force && !$dryrun) || (!$force && $dryrun) or die_usage;
1144 my @projs = @ARGV;
1145 my @allprojs = sort({lc($a) cmp lc($b)} Girocco::Project::get_full_list());
1146 my %allprojs = map({$_ => 1} @allprojs);
1147 my %seen = ();
1148 @projs or @projs = @allprojs;
1149 my $bd = $Girocco::Config::reporoot.'/';
1150 my @remove = ();
1151 foreach (@projs) {
1152 !$seen{$_} && $allprojs{$_} or next;
1153 $seen{$_} = 1;
1154 my $pd = $bd . $_ . '.git';
1155 if (! -e $pd) {
1156 warn "$_: no such directory: $pd\n" unless $quiet;
1157 push(@remove, $_);
1158 } elsif (! -d _) {
1159 warn "$_: exists but not directory: $pd\n" unless $quiet;
1160 push(@remove, $_);
1163 warn "\n" if @remove && !$quiet;
1164 if ($dryrun) {
1165 return 0 unless @remove;
1166 my $msg = "Would remove ".scalar(@remove). " project";
1167 @remove == 1 or $msg .= "s";
1168 $msg .= ":\n";
1169 $msg .= join("", map("\t$_\n", @remove));
1170 print $msg unless $quiet;
1171 return 1;
1173 my $msg = "Removed ".scalar(@remove). " project";
1174 @remove == 1 or $msg .= "s";
1175 $msg .= ":\n";
1176 $msg .= join("", map("\t$_\n", @remove));
1177 my %remove = map({$_ => 1} @remove);
1178 filedb_atomic_edit(jailed_file('/etc/group'), sub {
1179 !exists($remove{(split /:/)[0]}) and return $_;
1181 print $msg unless $quiet;
1182 return 0;
1185 sub cmd_show {
1186 use Data::Dumper;
1187 @ARGV == 1 or die_usage;
1188 my $project = get_clean_project($ARGV[0]);
1189 my %info = %$project;
1190 my $d = Data::Dumper->new([\%info], ['*'.$project->{name}]);
1191 $d->Sortkeys(sub {[sort({lc($a) cmp lc($b)} keys %{$_[0]})]});
1192 print $d->Dump([\%info], ['*'.$project->{name}]);
1193 return 0;
1196 sub cmd_listheads {
1197 @ARGV == 1 or die_usage;
1198 my $project = get_project($ARGV[0]);
1199 my @heads = sort({lc($a) cmp lc($b)} $project->get_heads);
1200 my $cur = $project->{HEAD};
1201 defined($cur) or $cur = '';
1202 my $curmark = '*';
1203 my $headhash = get_git("--git-dir=$project->{path}", 'rev-parse', '--quiet', '--verify', 'HEAD');
1204 defined($headhash) or $headhash = '';
1205 chomp $headhash;
1206 $headhash or $curmark = '!';
1207 foreach (@heads) {
1208 my $mark = $_ eq $cur ? $curmark : ' ';
1209 print "$mark $_\n";
1211 return 0;
1214 sub cmd_listtags {
1215 my $vcnt = 0;
1216 shift(@ARGV), $vcnt=1 if @ARGV && ($ARGV[0] eq '--verbose' || $ARGV[0] eq '-v');
1217 @ARGV == 1 or die_usage;
1218 my $project = get_project($ARGV[0]);
1219 if ($vcnt) {
1220 print map("$$_[0]\t$$_[1]\n", get_ctag_counts($project));
1221 } else {
1222 print map("$_\n", $project->get_ctag_names);
1224 return 0;
1227 sub cmd_deltags {
1228 my $ic = 0;
1229 shift(@ARGV), $ic=1 if @ARGV && $ARGV[0] =~ /^(?:--?ignore-case|-i)$/i;
1230 @ARGV >= 2 or die_usage;
1231 my $project = get_project(shift @ARGV);
1232 my %curtags;
1233 if ($ic) {
1234 push(@{$curtags{lc($_)}}, $_) foreach $project->get_ctag_names;
1235 } else {
1236 push(@{$curtags{$_}}, $_) foreach $project->get_ctag_names;
1238 my @deltags = ();
1239 my %seentag = ();
1240 my $ctags = join(" ", @ARGV);
1241 $ctags = lc($ctags) if $ic;
1242 foreach (split(/[\s,]+/, $ctags)) {
1243 next unless exists($curtags{$_});
1244 $seentag{$_}=1, push(@deltags, $_) unless $seentag{$_};
1246 if (!@deltags) {
1247 warn $project->{name}, ": skipping removal of only non-existent tags\n" unless $quiet;
1248 } else {
1249 # Avoid touching anything other than the ctags
1250 foreach my $tg (@deltags) {
1251 $project->delete_ctag($_) foreach @{$curtags{$tg}};
1253 $project->_set_changed;
1254 $project->_set_forkchange;
1255 warn $project->{name}, ": specified tags have been removed\n" unless $quiet;
1257 return 0;
1260 sub cmd_addtags {
1261 @ARGV >= 2 or die_usage;
1262 my $project = get_project(shift @ARGV);
1263 my $ctags = join(" ", @ARGV);
1264 $ctags =~ /[^, a-zA-Z0-9:.+#_-]/ and
1265 die "Content tag(s) \"$ctags\" contain(s) evil character(s).\n";
1266 my $oldmask = umask();
1267 umask($oldmask & ~0060);
1268 my $changed = 0;
1269 foreach (split(/[\s,]+/, $ctags)) {
1270 ++$changed if $project->add_ctag($_, 1);
1272 if ($changed) {
1273 $project->_set_changed;
1274 $project->_set_forkchange;
1276 umask($oldmask);
1277 my $cnt = ($changed == 1) ? "1 content tag has" : $changed . " content tags have";
1278 warn $project->{name}, ": $cnt been added/updated\n" unless $quiet;
1279 return 0;
1282 sub _get_random_val {
1283 my $p = shift;
1284 my $md5;
1286 no warnings;
1287 $md5 = md5_hex(time . $$ . rand() . join(':',%$p));
1289 $md5;
1292 sub cmd_chpass {
1293 my $force = 0;
1294 shift(@ARGV), $force=1 if @ARGV && $ARGV[0] eq '--force';
1295 my $random = undef;
1296 pop(@ARGV), $random=lc($ARGV[1]) if @ARGV==2 && $ARGV[1] =~ /^(?:random|unknown)$/i;
1297 @ARGV == 1 or die_usage;
1298 my $project = get_project($ARGV[0]);
1299 die "refusing to change locked password of project \"$ARGV[0]\" without --force\n"
1300 if $project->is_password_locked;
1301 my ($newpw, $rmsg);
1302 if ($random) {
1303 if ($random eq "random") {
1304 die "refusing to set random password without --force\n" unless $force;
1305 $rmsg = "set to random value";
1306 $newpw = _get_random_val($project);
1307 } else {
1308 die "refusing to set password hash to '$random' without --force\n" unless $force;
1309 $rmsg = "hash set to '$random'";
1310 $newpw = $random;
1312 } else {
1313 $rmsg = "updated";
1314 if (-t STDIN) {
1315 print "Changing admin password for project $ARGV[0]\n";
1316 my $np1 = prompt_noecho_nl_or_die("New password for project $ARGV[0] (echo is off)");
1317 $np1 ne "" or die "empty passwords are not permitted (brokenness will ensue)\n";
1318 my $np2 = prompt_noecho_nl_or_die("Retype new password for project $ARGV[0]");
1319 $np1 eq $np2 or die "Our high-paid security consultants have determined that\n" .
1320 "the admin passwords you have entered do not match each other.\n";
1321 $newpw = $np1;
1322 } else {
1323 $newpw = <STDIN>;
1324 defined($newpw) or die "missing new password on STDIN\n";
1325 chomp($newpw);
1328 $newpw ne "" or die "empty passwords are not permitted (brokenness will ensue)\n";
1329 my $old = $project->{crypt};
1330 $project->{crypt} = (defined($random) && $random ne "random") ? $newpw : scrypt_sha1($newpw);
1331 if (defined($old) && $old eq $project->{crypt}) {
1332 warn $project->{name}, ": skipping update of password hash to same value\n" unless $quiet;
1333 } else {
1334 # Avoid touching anything other than the password hash
1335 $project->_group_update;
1336 warn $project->{name}, ": admin password $rmsg (new hash stored)\n" unless $quiet;
1338 return 0;
1341 sub cmd_checkpw {
1342 @ARGV == 1 or die_usage;
1343 my $project = get_project($ARGV[0]);
1344 my $pwhash = $project->{crypt};
1345 defined($pwhash) or $pwhash = "";
1346 if ($pwhash eq "") {
1347 warn $project->{name}, ": no password required\n" unless $quiet;
1348 return 0;
1350 if ($project->is_password_locked) {
1351 warn $project->{name}, ": password is locked\n" unless $quiet;
1352 exit 1;
1354 my $checkpw;
1355 if (-t STDIN) {
1356 $checkpw = prompt_noecho_nl_or_die("Admin password for project $ARGV[0] (echo is off)");
1357 $checkpw ne "" or warn "checking for empty password as hash (very unlikely)\n" unless $quiet;
1358 } else {
1359 $checkpw = <STDIN>;
1360 defined($checkpw) or die "missing admin password on STDIN\n";
1361 chomp($checkpw);
1363 unless (Girocco::CLIUtil::check_passwd_match($pwhash, $checkpw)) {
1364 warn "password check failure\n" unless $quiet;
1365 exit 1;
1367 warn "admin password match\n" unless $quiet;
1368 return 0;
1371 sub cmd_gc {
1372 my ($force, $auto, $redelta, $recompress);
1373 parse_options(force => \$force, quiet => \$quiet, q => \$quiet, auto => \$auto,
1374 redelta => \$redelta, "no-reuse-delta" => \$redelta, aggressive => \$force,
1375 recompress => \$recompress, "no-reuse-object" => $recompress);
1376 $force && $auto and die "--force and --auto are mutually exclusive options\n";
1377 @ARGV or die "Please give project name on command line.\n";
1378 @ARGV == 1 or die_usage;
1379 my $project = get_project($ARGV[0]);
1380 delete $ENV{show_progress};
1381 delete $ENV{force_gc};
1382 $quiet or $ENV{"show_progress"} = 1;
1383 $force and $ENV{"force_gc"} = 1;
1384 if (!$auto && !$force && ! -e $project->{path}."/.needsgc") {
1385 open NEEDSGC, '>', $project->{path}."/.needsgc" and close NEEDSGC;
1387 my @args = ($Girocco::Config::basedir . "/jobd/gc.sh", $project->{name});
1388 $redelta && !$recompress and push(@args, "-f");
1389 $recompress and push(@args, "-F");
1390 my $lastgc = $project->{lastgc};
1391 system({$args[0]} @args) != 0 and return 1;
1392 # Do it again Sam, but only if lastgc was set, gc.sh succeeded and now it's not set
1393 if ($lastgc) {
1394 my $newlastgc = get_git("--git-dir=$project->{path}", 'config', '--get', 'gitweb.lastgc');
1395 if (!$newlastgc) {
1396 system({$args[0]} @args) != 0 and return 1;
1399 return 0;
1402 sub cmd_update {
1403 my ($force, $summary);
1404 parse_options(force => \$force, quiet => \$quiet, q => \$quiet, summary => \$summary);
1405 $quiet && $summary and die "--quiet and --summary are mutually exclusive options\n";
1406 @ARGV or die "Please give project name on command line.\n";
1407 @ARGV == 1 or die_usage;
1408 my $project = get_project($ARGV[0]);
1409 $project->{mirror} or die "Project \"$ARGV[0]\" is a push project, not a mirror project.\n";
1410 delete $ENV{show_progress};
1411 delete $ENV{force_update};
1412 if ($quiet) {
1413 $ENV{"show_progress"} = 0;
1414 } else {
1415 $ENV{"show_progress"} = ($summary ? 1 : 2);
1417 $force and $ENV{"force_update"} = 1;
1418 system($Girocco::Config::basedir . "/jobd/update.sh", $project->{name}) != 0 and return 1;
1419 return 0;
1422 sub cmd_remirror {
1423 my $force = 0;
1424 parse_options(force => \$force, quiet => \$quiet, q => \$quiet);
1425 @ARGV or die "Please give project name on command line.\n";
1426 @ARGV == 1 or die_usage;
1427 my $project = get_project($ARGV[0]);
1428 $project->{mirror} or die "Project \"$ARGV[0]\" is a push project, not a mirror project.\n";
1429 if ($project->{clone_in_progress} && !$project->{clone_failed}) {
1430 warn "Project \"$ARGV[0]\" already seems to have a clone underway at this moment.\n" unless $quiet && $force;
1431 exit(255) unless $force;
1432 yes_to_continue_or_die("Are you sure you want to force a remirror");
1434 unlink($project->_clonefail_path);
1435 unlink($project->_clonelog_path);
1436 recreate_file($project->_clonep_path);
1437 my $sock = IO::Socket::UNIX->new($Girocco::Config::chroot.'/etc/taskd.socket') or
1438 die "cannot connect to taskd.socket: $!\n";
1439 select((select($sock),$|=1)[0]);
1440 $sock->print("clone ".$project->{name}."\n");
1441 # Just ignore reply, we are going to succeed anyway and the I/O
1442 # would apparently get quite hairy.
1443 $sock->flush();
1444 sleep 2; # *cough*
1445 $sock->close();
1446 warn "Project \"$ARGV[0]\" remirror initiated.\n" unless $quiet;
1447 return 0;
1450 sub cmd_setowner {
1451 my $force = 0;
1452 shift(@ARGV), $force=1 if @ARGV && $ARGV[0] eq '--force';
1453 @ARGV == 2 || (@ARGV == 1 && !$force && !$setopt) or die_usage;
1454 my $project = get_project($ARGV[0]);
1455 if (@ARGV == 2 && !valid_email($ARGV[1])) {
1456 die "invalid owner/email (use --force to accept): \"$ARGV[1]\"\n"
1457 unless $force;
1458 warn "using invalid owner/email with --force\n" unless $quiet;
1460 if (@ARGV == 2 && length($ARGV[1]) > 96) {
1461 die "owner/email longer than 96 chars (use --force to accept): \"$ARGV[1]\"\n"
1462 unless $force;
1463 warn "using longer than 96 char owner/email with --force\n" unless $quiet;
1465 my $old = $project->{email};
1466 if (@ARGV == 1) {
1467 print "$old\n" if defined($old);
1468 return 0;
1470 if (defined($old) && $old eq $ARGV[1]) {
1471 warn $project->{name}, ": skipping update of owner/email to same value\n" unless $quiet;
1472 } else {
1473 # Avoid touching anything other than "gitweb.owner"
1474 $project->_property_fput("email", $ARGV[1]);
1475 $project->_update_index;
1476 $project->_set_changed;
1477 warn $project->{name}, ": owner/email updated to \"$ARGV[1]\"\n" unless $quiet;
1479 return 0;
1482 sub cmd_setdesc {
1483 my $force = 0;
1484 shift(@ARGV), $force=1 if @ARGV && $ARGV[0] eq '--force';
1485 @ARGV >= 2 || (@ARGV == 1 && !$force && !$setopt) or die_usage;
1486 my $project = get_project(shift @ARGV);
1487 if (@ARGV && !valid_desc(join(" ", @ARGV))) {
1488 die "invalid description (use --force to accept): \"".join(" ", @ARGV)."\"\n"
1489 unless $force;
1490 warn "using invalid description with --force\n" unless $quiet;
1492 my $desc = clean_desc(join(" ", @ARGV));
1493 if (@ARGV && length($desc) > 1024) {
1494 die "description longer than 1024 chars (use --force to accept): \"$desc\"\n"
1495 unless $force;
1496 warn "using longer than 1024 char description with --force\n" unless $quiet;
1498 my $old = $project->{desc};
1499 if (!@ARGV) {
1500 print "$old\n" if defined($old);
1501 return 0;
1503 if (defined($old) && $old eq $desc) {
1504 warn $project->{name}, ": skipping update of description to same value\n" unless $quiet;
1505 } else {
1506 # Avoid touching anything other than description file
1507 $project->_property_fput("desc", $desc);
1508 $project->_set_changed;
1509 warn $project->{name}, ": description updated to \"$desc\"\n" unless $quiet;
1511 return 0;
1514 sub cmd_setreadme {
1515 my ($force, $readmetype) = (0, undef);
1516 parse_options(force => \$force, ":type" => \$readmetype, ":format" => \$readmetype);
1517 @ARGV == 1 && defined($readmetype) and push(@ARGV, undef);
1518 @ARGV == 2 || (@ARGV == 1 && !$force && !defined($readmetype) && !$setopt) or die_usage;
1519 defined($readmetype) and $readmetype = Girocco::Project::_normalize_rmtype($readmetype,1);
1520 defined($readmetype) && !$readmetype and die_usage;
1521 my $project = get_project($ARGV[0]);
1522 my $old = $project->{READMEDATA};
1523 if (@ARGV == 1) {
1524 chomp $old if defined($old);
1525 print "$old\n" if defined($old) && $old ne "";
1526 return 0;
1528 $readmetype or $readmetype = $project->{rmtype};
1529 my ($new, $raw, $newname);
1530 $newname = '';
1531 if (!defined($ARGV[1])) {
1532 $new = $old;
1533 $newname = "original README data";
1534 $readmetype ne $project->{rmtype} && $new ne "" and $raw = 1;
1535 } elsif ($ARGV[1] eq "-") {
1536 local $/;
1537 $new = <STDIN>;
1538 $raw = 1;
1539 $newname = "contents of <STDIN>";
1540 } elsif (lc($ARGV[1]) eq "automatic" || lc($ARGV[1]) eq "auto") {
1541 $new = "";
1542 } elsif (lc($ARGV[1]) eq "suppressed" || lc($ARGV[1]) eq "suppress") {
1543 $new = "<!-- suppress -->";
1544 } else {
1545 my $fn = $ARGV[1];
1546 $fn =~ s/^\@//;
1547 die "missing filename for README\n" unless $fn ne "";
1548 die "no such file: \"$fn\"\n" unless -f $fn && -r $fn;
1549 open F, '<', $fn or die "cannot open \"$fn\" for reading: $!\n";
1550 local $/;
1551 $new = <F>;
1552 close F;
1553 $raw = 1;
1554 $newname = "contents of \"$fn\"";
1556 defined($new) or $new = '';
1557 my $origrmtype = $project->{rmtype};
1558 $project->{rmtype} = $readmetype;
1559 $project->{READMEDATA} = to_utf8($new, 1);
1560 $project->_cleanup_readme;
1561 if (length($project->{READMEDATA}) > 8192) {
1562 die "readme greater than 8192 chars is too long (use --force to override)\n"
1563 unless $force;
1564 warn "using readme greater than 8192 chars with --force\n" unless $quiet;
1566 if ($raw) {
1567 my ($cnt, $err) = $project->_lint_readme(0);
1568 if ($cnt) {
1569 my $msg = "README: $cnt error";
1570 $msg .= "s" unless $cnt == 1;
1571 print STDERR "$msg\n", "-" x length($msg), "\n", $err
1572 unless $force && $quiet;
1573 exit(255) unless $force && $project->{rmtype} eq 'HTML';
1574 warn $project->{name} . ": using invalid raw HTML with --force\n" unless $quiet;
1575 $project->{README} = $project->{READMEDATA};
1578 if (defined($old) && $old eq $project->{READMEDATA} && $readmetype eq $origrmtype && !$force) {
1579 warn $project->{name}, ": skipping update of README to same value\n" unless $quiet;
1580 } else {
1581 # Avoid touching anything other than README.html file
1582 $project->_property_fput("READMEDATA", $project->{READMEDATA}, 1);
1583 $project->_property_fput("README", $project->{README});
1584 $project->_property_fput("rmtype", $readmetype) if $readmetype ne $origrmtype;
1585 $project->_set_changed;
1586 my $desc = get_readme_desc($project->{README});
1587 if ($newname) {
1588 $newname .= " ($desc)";
1589 } else {
1590 $newname = $desc;
1592 warn $project->{name}, ": README $readmetype format updated to $newname\n" unless $quiet;
1594 return 0;
1597 sub valid_head {
1598 my ($proj, $newhead) = @_;
1599 my %okheads = map({($_ => 1)} $proj->get_heads);
1600 exists($okheads{$newhead});
1603 sub cmd_sethead {
1604 @ARGV == 2 || (@ARGV == 1 && !$setopt) or die_usage;
1605 my $project = get_project($ARGV[0]);
1606 if (@ARGV == 2 && !valid_head($project, $ARGV[1])) {
1607 die "invalid head (try \"@{[basename($0)]} listheads $ARGV[0]\"): \"$ARGV[1]\"\n";
1609 my $old = $project->{HEAD};
1610 if (@ARGV == 1) {
1611 print "$old\n" if defined($old);
1612 return 0;
1614 if (defined($old) && $old eq $ARGV[1]) {
1615 warn $project->{name}, ": skipping update of HEAD symref to same value\n" unless $quiet;
1616 } else {
1617 # Avoid touching anything other than the HEAD symref
1618 $project->set_HEAD($ARGV[1]);
1619 $project->_set_changed;
1620 warn $project->{name}, ": HEAD symref updated to \"refs/heads/$ARGV[1]\"\n" unless $quiet;
1622 return 0;
1625 sub cmd_sethooks {
1626 my $force = 0;
1627 shift(@ARGV), $force=1 if @ARGV && $ARGV[0] eq '--force';
1628 @ARGV == 2 || (@ARGV == 1 && !$force && !$setopt) or die_usage;
1629 my $project = get_project($ARGV[0]);
1630 my $projconfig = read_config_file_hash($project->{path}."/config");
1631 my $ghp = $Girocco::Config::reporoot."/_global/hooks";
1632 my $rghp = realpath($ghp);
1633 my $lhp = $project->{path}."/hooks";
1634 my $rlhp = realpath($lhp);
1635 my $ahp = "";
1636 my $rahp = undef;
1637 if (defined($projconfig) && defined($projconfig->{"core.hookspath"})) {
1638 $ahp = $projconfig->{"core.hookspath"};
1639 $rahp = realpath($ahp);
1641 if (@ARGV == 1) {
1642 if (defined($rahp) && $rahp ne "") {
1643 if ($rahp eq $rghp) {
1644 my $nc = ($ahp eq $ghp ? "" : " non-canonical");
1645 printf "%s \t(global%s)\n", $ahp, $nc;
1646 } elsif ($rahp eq $rlhp) {
1647 my $nc = ($ahp eq $lhp ? "" : " non-canonical");
1648 printf "%s \t(local%s)\n", $ahp, $nc;
1649 } elsif ($rahp ne $ahp) {
1650 print "$ahp \t($rahp)\n";
1651 } else {
1652 print "$ahp\n";
1654 } elsif ($ahp ne "") {
1655 print "$ahp \t(non-existent)\n";
1657 return 0;
1659 my $shp = $ARGV[1];
1660 if (lc($shp) eq "global") {
1661 $shp = $ghp;
1662 } elsif (lc($shp) eq "local") {
1663 $shp = $lhp;
1664 } elsif (substr($shp, 0, 2) eq "~/") {
1665 $shp = $ENV{"HOME"}.substr($shp,1);
1666 } elsif ($shp =~ m,^~([a-zA-Z_][a-zA-Z_0-9]*)((?:/.*)?)$,) {
1667 my $sfx = $2;
1668 my $hd = (getpwnam($1))[7];
1669 $shp = $hd . $sfx if defined($hd) && $hd ne "" && $hd ne "/" && -d $hd;
1671 $shp ne "" && -d $shp or die "no such directory: $ARGV[1]\n";
1672 my $rshp = realpath($shp);
1673 defined($rshp) && $rshp ne "" or die "could not realpath: $ARGV[1]\n";
1674 $rshp =~ m,^/[^/], or die "invalid hookspath: $rshp\n";
1675 die "refusing to switch from current non-global hookspath without --force\n"
1676 if !$force && defined($rahp) && $rahp ne "" && $rahp ne $rghp && $rshp ne $rahp;
1677 if (!$force && defined($rahp) && $rahp ne "") {
1678 if ($rshp eq $rahp && ($ahp eq $ghp || $ahp eq $lhp)) {
1679 warn $project->{name}, ": skipping update of hookspath to same effective value\n" unless $quiet;
1680 return 0;
1683 $rshp = $ghp if $rshp eq $rghp;
1684 $rshp = $lhp if $rshp eq $rlhp;
1685 if ($rshp eq $ahp) {
1686 warn $project->{name}, ": skipping update of hookspath to same value\n" unless $quiet;
1687 return 0;
1689 die "refusing to set neither local nor global hookspath without --force\n"
1690 if !$force && $rshp ne $ghp && $rshp ne $lhp;
1691 system($Girocco::Config::git_bin, '--git-dir='.$project->{path},
1692 'config', "core.hookspath", $rshp);
1693 my $newval = '"'.$rshp.'"';
1694 $newval = "global" if $rshp eq $ghp;
1695 $newval = "local" if $rshp eq $lhp;
1696 warn $project->{name}, ": hookspath set to $newval\n" unless $quiet;
1697 return 0;
1700 our %boolfields;
1701 BEGIN {
1702 %boolfields = (
1703 cleanmirror => 1,
1704 reverseorder => 0,
1705 summaryonly => 0,
1706 statusupdates => 1,
1710 sub cmd_setbool {
1711 my $force = 0;
1712 shift(@ARGV), $force=1 if @ARGV && $ARGV[0] eq '--force';
1713 @ARGV == 3 || (@ARGV == 2 && !$force && !$setopt) or die_usage;
1714 my $project = get_project($ARGV[0]);
1715 if (!exists($boolfields{$ARGV[1]})) {
1716 die "invalid boolean field name: \"$ARGV[1]\" -- try \"help\"\n";
1718 if (@ARGV == 3 && $boolfields{$ARGV[1]} && !$project->{mirror}) {
1719 die "invalid boolean field for non-mirror (use --force to accept): \"$ARGV[1]\"\n"
1720 unless $force;
1721 warn "using mirror field on non-mirror with --force\n" unless $quiet;
1723 if (@ARGV == 3 && !valid_bool($ARGV[2])) {
1724 die "invalid boolean value: \"$ARGV[2]\"\n";
1726 my $bool = clean_bool($ARGV[2]);
1727 my $old = $project->{$ARGV[1]};
1728 if (@ARGV == 2) {
1729 print "$old\n" if defined($old);
1730 return 0;
1732 if (defined($old) && $old eq $bool) {
1733 warn $project->{name}, ": skipping update of $ARGV[1] to same value\n" unless $quiet;
1734 } else {
1735 # Avoid touching anything other than $ARGV[1] field
1736 $project->_property_fput($ARGV[1], $bool);
1737 warn $project->{name}, ": $ARGV[1] updated to $bool\n" unless $quiet;
1739 return 0;
1742 sub cmd_setjsontype {
1743 @ARGV == 2 || (@ARGV == 1 && !$setopt) or die_usage;
1744 my $project = get_project($ARGV[0]);
1745 my $jsontype;
1746 if (@ARGV == 2) {
1747 my $jt = lc($ARGV[1]);
1748 index($jt, "/") >= 0 or $jt = "application/".$jt;
1749 $jt eq 'application/x-www-form-urlencoded' ||
1750 $jt eq 'application/json' or
1751 die "invalid jsontype value: \"$ARGV[1]\"\n";
1752 $jsontype = $jt;
1754 my $old = $project->{jsontype};
1755 if (@ARGV == 1) {
1756 print "$old\n" if defined($old);
1757 return 0;
1759 if (defined($old) && $old eq $jsontype) {
1760 warn $project->{name}, ": skipping update of jsontype to same value\n" unless $quiet;
1761 } else {
1762 # Avoid touching anything other than jsontype field
1763 $project->_property_fput('jsontype', $jsontype);
1764 warn $project->{name}, ": jsontype updated to $jsontype\n" unless $quiet;
1766 return 0;
1769 sub cmd_setjsonsecret {
1770 @ARGV == 2 || (@ARGV == 1 && !$setopt) or die_usage;
1771 my $project = get_project($ARGV[0]);
1772 my $jsonsecret;
1773 if (@ARGV == 2) {
1774 my $js = $ARGV[1];
1775 $js =~ s/^\s+//; $js =~ s/\s+$//;
1776 $jsonsecret = $js;
1778 my $old = $project->{jsonsecret};
1779 if (@ARGV == 1) {
1780 print "$old\n" if defined($old);
1781 return 0;
1783 if (defined($old) && $old eq $jsonsecret) {
1784 warn $project->{name}, ": skipping update of jsonsecret to same value\n" unless $quiet;
1785 } else {
1786 # Avoid touching anything other than jsonsecret field
1787 $project->_property_fput('jsonsecret', $jsonsecret);
1788 warn $project->{name}, ": jsonsecret updated to \"$jsonsecret\"\n" unless $quiet;
1790 return 0;
1793 sub cmd_setautogchack {
1794 @ARGV == 2 || (@ARGV == 1 && !$setopt) or die_usage;
1795 my $project = get_project($ARGV[0]);
1796 my $aghok = $Girocco::Config::autogchack &&
1797 ($project->{mirror} || $Girocco::Config::autogchack ne "mirror");
1798 my $old = defined($project->{autogchack}) ? clean_bool($project->{autogchack}) : "unset";
1799 if (@ARGV == 1) {
1800 print "$old\n" if $aghok;
1801 return 0;
1803 my $bool;
1804 if (lc($ARGV[1]) eq "unset") {
1805 $bool = "unset";
1806 } else {
1807 valid_bool($ARGV[1]) or die "invalid boolean value: \"$ARGV[1]\"\n";
1808 $bool = clean_bool($ARGV[1]);
1810 if (!$aghok) {
1811 die "\$Girocco::Config::autogchack is false\n" unless $Girocco::Config::autogchack;
1812 die "\$Girocco::Config::autogchack is only enabled for mirrors\n";
1814 if ($old eq $bool) {
1815 warn $project->{name}, ": autogchack value unchanged\n" unless $quiet;
1816 } else {
1817 if ($bool eq "unset") {
1818 system($Girocco::Config::git_bin, '--git-dir='.$project->{path},
1819 'config', '--unset', "girocco.autogchack");
1820 } else {
1821 system($Girocco::Config::git_bin, '--git-dir='.$project->{path},
1822 'config', '--bool', "girocco.autogchack", $bool);
1825 return system($Girocco::Config::basedir . "/jobd/maintain-auto-gc-hack.sh", $project->{name}) == 0
1826 ? 0 : 1;
1829 sub valid_url {
1830 my ($url, $type) = @_;
1831 $type ne 'baseurl' and return valid_web_url($url);
1832 valid_repo_url($url) or return 0;
1833 if ($Girocco::Config::restrict_mirror_hosts) {
1834 my $mh = extract_url_hostname($url);
1835 is_dns_hostname($mh) or return 0;
1836 !is_our_hostname($mh) or return 0;
1838 return 1;
1841 our %urlfields;
1842 BEGIN {
1843 %urlfields = (
1844 baseurl => ["url" , 1],
1845 homepage => ["hp" , 0],
1846 notifyjson => ["notifyjson", 0],
1850 sub cmd_seturl {
1851 my $force = 0;
1852 shift(@ARGV), $force=1 if @ARGV && $ARGV[0] eq '--force';
1853 @ARGV == 3 || (@ARGV == 2 && !$force && !$setopt) or die_usage;
1854 my $project = get_project($ARGV[0]);
1855 if (!exists($urlfields{$ARGV[1]})) {
1856 die "invalid URL field name: \"$ARGV[1]\" -- try \"help\"\n";
1858 if (@ARGV == 3 && ${$urlfields{$ARGV[1]}}[1] && !$project->{mirror}) {
1859 die "invalid URL field for non-mirror (use --force to accept): \"$ARGV[1]\"\n"
1860 unless $force;
1861 warn "using mirror field on non-mirror with --force\n" unless $quiet;
1863 if (@ARGV == 3 && !valid_url($ARGV[2], $ARGV[1])) {
1864 die "invalid URL (use --force to accept): \"$ARGV[2]\"\n"
1865 unless $force;
1866 warn "using invalid URL with --force\n" unless $quiet;
1868 my $old = $project->{${$urlfields{$ARGV[1]}}[0]};
1869 if (@ARGV == 2) {
1870 print "$old\n" if defined($old);
1871 return 0;
1873 if (defined($old) && $old eq $ARGV[2]) {
1874 warn $project->{name}, ": skipping update of $ARGV[1] to same value\n" unless $quiet;
1875 } else {
1876 # Avoid touching anything other than $ARGV[1]'s field
1877 $project->_property_fput(${$urlfields{$ARGV[1]}}[0], $ARGV[2]);
1878 if ($ARGV[1] eq "baseurl") {
1879 $project->{url} = $ARGV[2];
1880 $project->_set_bangagain;
1882 $project->_set_changed unless $ARGV[1] eq "notifyjson";
1883 warn $project->{name}, ": $ARGV[1] updated to $ARGV[2]\n" unless $quiet;
1885 return 0;
1888 our %msgsfields;
1889 BEGIN {
1890 %msgsfields = (
1891 notifymail => 1,
1892 notifytag => 1,
1896 sub cmd_setmsgs {
1897 my $force = 0;
1898 shift(@ARGV), $force=1 if @ARGV && $ARGV[0] eq '--force';
1899 @ARGV >= 3 || (@ARGV == 2 && !$force && !$setopt) or die_usage;
1900 my $project = get_project(shift @ARGV);
1901 my $field = shift @ARGV;
1902 if (!exists($msgsfields{$field})) {
1903 die "invalid msgs field name: \"$field\" -- try \"help\"\n";
1905 if (@ARGV && !valid_addrlist(@ARGV)) {
1906 die "invalid email address list (use --force to accept): \"".join(" ",@ARGV)."\"\n"
1907 unless $force;
1908 warn "using invalid email address list with --force\n" unless $quiet;
1910 my $old = $project->{$field};
1911 if (!@ARGV) {
1912 printf "%s\n", clean_addrlist($old, " ") if defined($old);
1913 return 0;
1915 my $newlist = clean_addrlist(join(" ",@ARGV));
1916 if (defined($old) && $old eq $newlist) {
1917 warn $project->{name}, ": skipping update of $field to same value\n" unless $quiet;
1918 } else {
1919 # Avoid touching anything other than $field's field
1920 $project->_property_fput($field, $newlist);
1921 warn $project->{name}, ": $field updated to \"$newlist\"\n" unless $quiet;
1923 return 0;
1926 sub cmd_setusers {
1927 my $force = 0;
1928 shift(@ARGV), $force=1 if @ARGV && $ARGV[0] eq '--force';
1929 @ARGV >= 2 || (@ARGV == 1 && !$force && !$setopt) or die_usage;
1930 my $project = get_project(shift @ARGV);
1931 my $projname = $project->{name};
1932 !@ARGV || !$project->{mirror} or die "cannot set users list for mirror project: \"$projname\"\n";
1933 my @newusers = ();
1934 if (@ARGV) {
1935 eval {@newusers = validate_users(join(" ", @ARGV), $force); 1;} or exit 255;
1936 die "refusing to set empty users list without --force\n" unless @newusers || $force;
1938 return 0 if !@ARGV && $project->{mirror};
1939 my $oldusers = $project->{users};
1940 if ($oldusers && ref($oldusers) eq "ARRAY") {
1941 $oldusers = join("\n", @$oldusers);
1942 } else {
1943 $oldusers = "";
1945 if (!@ARGV) {
1946 print "$oldusers\n" if $oldusers ne "";
1947 return 0;
1949 if ($oldusers eq join("\n", @newusers)) {
1950 warn "$projname: skipping update of users list to same value\n" unless $quiet;
1951 } else {
1952 # Avoid touching anything other than the users list
1953 $project->{users} = \@newusers;
1954 $project->_update_users;
1955 warn "$projname: users list updated to \"@{[join(',',@newusers)]}\"\n" unless $quiet;
1957 return 0;
1960 our %fieldnames;
1961 BEGIN {
1962 %fieldnames = (
1963 owner => [\&cmd_setowner, 0],
1964 desc => [\&cmd_setdesc, 0],
1965 description => [\&cmd_setdesc, 0],
1966 readme => [\&cmd_setreadme, 0],
1967 head => [\&cmd_sethead, 0],
1968 HEAD => [\&cmd_sethead, 0],
1969 hooks => [\&cmd_sethooks, 0],
1970 hookspath => [\&cmd_sethooks, 0],
1971 cleanmirror => [\&cmd_setbool, 1],
1972 reverseorder => [\&cmd_setbool, 1],
1973 summaryonly => [\&cmd_setbool, 1],
1974 statusupdates => [\&cmd_setbool, 1],
1975 autogchack => [\&cmd_setautogchack, 0],
1976 baseurl => [\&cmd_seturl, 1],
1977 homepage => [\&cmd_seturl, 1],
1978 notifyjson => [\&cmd_seturl, 1],
1979 jsontype => [\&cmd_setjsontype, 0],
1980 jsonsecret => [\&cmd_setjsonsecret, 0],
1981 notifymail => [\&cmd_setmsgs, 1],
1982 notifytag => [\&cmd_setmsgs, 1],
1983 users => [\&cmd_setusers, 0],
1987 sub do_getset {
1988 $setopt = shift;
1989 my @newargs = ();
1990 push(@newargs, shift) if @_ && $_[0] eq '--force';
1991 my $field = $_[1];
1992 (($setopt && @_ >= 3) || @_ == 2) && exists($fieldnames{$field}) or die_usage;
1993 push(@newargs, shift);
1994 shift unless ${$fieldnames{$field}}[1];
1995 push(@newargs, @_);
1996 diename(($setopt ? "set " : "get ") . $field);
1997 @ARGV = @newargs;
1998 &{${$fieldnames{$field}}[0]}(@ARGV);
2001 sub cmd_get {
2002 do_getset(0, @_);
2005 sub cmd_set {
2006 do_getset(1, @_);
2009 our %commands;
2010 BEGIN {
2011 %commands = (
2012 list => \&cmd_list,
2013 create => \&cmd_create,
2014 adopt => \&cmd_adopt,
2015 remove => \&cmd_remove,
2016 trash => \&cmd_remove,
2017 delete => \&cmd_remove,
2018 prune => \&cmd_prune,
2019 show => \&cmd_show,
2020 listheads => \&cmd_listheads,
2021 listtags => \&cmd_listtags,
2022 listctags => \&cmd_listtags,
2023 deltags => \&cmd_deltags,
2024 delctags => \&cmd_deltags,
2025 addtags => \&cmd_addtags,
2026 addctags => \&cmd_addtags,
2027 chpass => \&cmd_chpass,
2028 checkpw => \&cmd_checkpw,
2029 gc => \&cmd_gc,
2030 update => \&cmd_update,
2031 remirror => \&cmd_remirror,
2032 setowner => \&cmd_setowner,
2033 setdesc => \&cmd_setdesc,
2034 setdescription => \&cmd_setdesc,
2035 setreadme => \&cmd_setreadme,
2036 sethead => \&cmd_sethead,
2037 sethooks => \&cmd_sethooks,
2038 sethookspath => \&cmd_sethooks,
2039 setbool => \&cmd_setbool,
2040 setboolean => \&cmd_setbool,
2041 setflag => \&cmd_setbool,
2042 setautogchack => \&cmd_setautogchack,
2043 seturl => \&cmd_seturl,
2044 setjsontype => \&cmd_setjsontype,
2045 setjsonsecret => \&cmd_setjsonsecret,
2046 setmsgs => \&cmd_setmsgs,
2047 setusers => \&cmd_setusers,
2048 get => \&cmd_get,
2049 set => \&cmd_set,
2052 our %nopager;
2053 BEGIN { %nopager = (
2054 # 1 => pager never allowed
2055 # -1 => pager defaults to off instead of on
2056 create => 1,
2057 adopt => -1,
2058 remove => -1,
2059 trash => -1,
2060 delete => -1,
2061 prune => -1,
2062 deltags => -1,
2063 delctags => -1,
2064 addtags => -1,
2065 addctags => -1,
2066 chpass => 1,
2067 checkpw => 1,
2068 gc => -1,
2069 update => -1,
2070 remirror => -1,
2071 setowner => -1,
2072 setdesc => -1,
2073 setdescription => -1,
2074 setreadme => -1,
2075 sethead => -1,
2076 sethooks => -1,
2077 sethookspath => -1,
2078 setbool => -1,
2079 setboolean => -1,
2080 setflag => -1,
2081 setautogchack => -1,
2082 seturl => -1,
2083 setjsontype => -1,
2084 setjsonsecret => -1,
2085 setmsgs => -1,
2086 setusers => -1,
2087 set => -1,
2090 sub dohelp {
2091 my $cmd = shift;
2092 my $bn = basename($0);
2093 setup_pager_stdout($usepager);
2094 printf "%s version %s\n\n", $bn, $VERSION;
2095 if (defined($cmd) && $cmd ne '') {
2096 $cmd =~ s/^set(?=[a-zA-Z])//i;
2097 my $cmdhelp = '';
2098 my ($lastmt, $incmd);
2099 foreach (split('\n', sprintf($help, $bn))) {
2100 $lastmt || $incmd or $lastmt = /^\s*$/, next;
2101 $incmd = 1 if $lastmt && /^\s*(?:\[?set\]?)?$cmd\s/;
2102 last if $incmd && /^\s*$/;
2103 $incmd and $cmdhelp .= $_ . "\n";
2104 $lastmt = /^\s*$/;
2106 print $cmdhelp and exit 0 if $cmdhelp;
2108 printf $help, $bn;
2109 exit 0;
2112 sub main {
2113 local *ARGV = \@_;
2115 shift, $quiet=1, redo if @ARGV && $ARGV[0] =~ /^(?:-q|--quiet)$/i;
2116 shift, $usepager=1, redo if @ARGV && $ARGV[0] =~ /^(?:-p|--pager|--paginate)$/i;
2117 shift, $usepager=0, redo if @ARGV && $ARGV[0] =~ /^(?:--no-pager|--no-paginate)$/i;
2119 dohelp($ARGV[1]) if !@ARGV || @ARGV && $ARGV[0] =~ /^(?:-h|-?-help|help)$/i;
2120 my $command = shift;
2121 diename($command);
2122 $setopt = 1;
2123 if (!exists($commands{$command}) && exists($commands{"set".$command})) {
2124 $setopt = 0;
2125 $command = "set" . $command;
2127 exists($commands{$command}) or die "Unknown command \"$command\" -- try \"help\"\n";
2128 dohelp($command) if @ARGV && ($ARGV[0] =~ /^(?:-h|-?-help)$/i ||
2129 $ARGV[0] =~ /^help$/i && !Girocco::Project::does_exist("help",1));
2130 $nopager{$command} && $nopager{$command} > 0 and $usepager = 0;
2131 my $pgdfltoff = $nopager{$command} && $nopager{$command} < 0 ? 1 : 0;
2132 setup_pager_stdout($usepager, $pgdfltoff);
2133 &{$commands{$command}}(@ARGV);