xref: /openbsd-src/usr.bin/libtool/LT/Exec.pm (revision f41ccc36c98bb70900c901ba8385dbb26f3cea97)
1# $OpenBSD: Exec.pm,v 1.6 2023/07/06 08:29:26 espie Exp $
2
3# Copyright (c) 2007-2010 Steven Mestdagh <steven@openbsd.org>
4# Copyright (c) 2012 Marc Espie <espie@openbsd.org>
5#
6# Permission to use, copy, modify, and distribute this software for any
7# purpose with or without fee is hereby granted, provided that the above
8# copyright notice and this permission notice appear in all copies.
9#
10# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
18use v5.36;
19
20package LT::Exec;
21use LT::Trace;
22use LT::Util;
23
24# OO singleton
25my $dry = 0;
26my $verbose = 0;
27my $performed = 0;
28
29sub performed($)
30{
31	return $performed;
32}
33
34sub dry_run($)
35{
36	$dry = 1;
37}
38
39sub verbose_run($)
40{
41	$verbose = 1;
42}
43
44sub silent_run($)
45{
46	$verbose = 0;
47}
48
49sub new($class)
50{
51	bless {}, $class;
52}
53
54sub chdir($self, $dir)
55{
56	my $class = ref($self) || $self;
57	bless {dir => $dir}, $class;
58}
59
60sub compile($self, @l)
61{
62	$self->command("compile", @l);
63}
64
65sub execute($self, @l)
66{
67	$self->command("execute", @l);
68}
69
70sub install($self, @l)
71{
72	$self->command("install", @l);
73}
74
75sub link($self, @l)
76{
77	$self->command("link", @l);
78}
79
80sub command_run($self, @l)
81{
82	if ($self->{dir}) {
83		tprint {"cd $self->{dir} && "};
84	}
85	tsay { "@l" };
86	my $pid = fork();
87	if (!defined $pid) {
88		die "Couldn't fork while running @l\n";
89	}
90	if ($pid == 0) {
91		if ($self->{dir}) {
92			CORE::chdir($self->{dir}) or die "Can't chdir to $self->{dir}\n";
93		}
94		exec(@l);
95		die "Exec failed @l\n";
96	} else {
97		my $kid = waitpid($pid, 0);
98		if ($? != 0) {
99			shortdie "Error while executing @l\n";
100		}
101	}
102}
103
104sub shell($self, @cmds)
105{
106	# create an object "on the run"
107	if (!ref($self)) {
108		$self = $self->new;
109	}
110	for my $c (@cmds) {
111		say $c if $verbose || $dry;
112		if (!$dry) {
113			$self->command_run($c);
114	        }
115	}
116	$performed++;
117}
118
119sub command($self, $mode, @l)
120{
121	# create an object "on the run"
122	if (!ref($self)) {
123		$self = $self->new;
124	}
125	if ($mode eq "compile"){
126		say "@l" if $verbose || $dry;
127	} else {
128		say "libtool: $mode: @l" if $verbose || $dry;
129	}
130	if (!$dry) {
131		$self->command_run(@l);
132	}
133	$performed++;
134}
135
1361;
137