2020-01-18 09:38:21 +01:00
/*
2020-09-16 18:56:00 +02:00
* Copyright ( c ) 2020 , the SerenityOS developers .
2020-01-18 09:38:21 +01:00
*
2021-04-22 01:24:48 -07:00
* SPDX - License - Identifier : BSD - 2 - Clause
2020-01-18 09:38:21 +01:00
*/
2021-04-03 13:57:31 -06:00
# include <LibCore/ArgsParser.h>
2020-09-16 18:56:00 +02:00
# include <LibCore/DirIterator.h>
2021-12-24 08:23:25 -08:00
# include <LibCore/System.h>
# include <LibMain/Main.h>
2020-09-16 18:56:00 +02:00
# include <stdlib.h>
2019-06-07 11:49:31 +02:00
# include <unistd.h>
2019-02-22 01:55:22 +01:00
2021-12-24 08:23:25 -08:00
ErrorOr < int > serenity_main ( Main : : Arguments arguments )
2019-02-22 01:55:22 +01:00
{
2021-12-24 08:23:25 -08:00
TRY ( Core : : System : : pledge ( " stdio rpath exec " ) ) ;
2020-02-18 13:19:10 +01:00
2021-04-03 13:57:31 -06:00
bool ignore_env = false ;
2022-07-11 20:42:03 +00:00
StringView split_string { } ;
2022-04-02 16:48:43 +01:00
Vector < String > values ;
2020-09-16 18:56:00 +02:00
2021-04-03 13:57:31 -06:00
Core : : ArgsParser args_parser ;
2021-06-07 21:27:21 +02:00
args_parser . set_stop_on_first_non_option ( true ) ;
2021-04-03 13:57:31 -06:00
args_parser . add_option ( ignore_env , " Start with an empty environment " , " ignore-environment " , ' i ' ) ;
args_parser . add_option ( split_string , " Process and split S into separate arguments; used to pass multiple arguments on shebang lines " , " split-string " , ' S ' , " S " ) ;
args_parser . add_positional_argument ( values , " Environment and commands " , " env/command " , Core : : ArgsParser : : Required : : No ) ;
2021-12-24 08:23:25 -08:00
args_parser . parse ( arguments ) ;
2021-04-03 13:57:31 -06:00
if ( ignore_env )
clearenv ( ) ;
size_t argv_start ;
for ( argv_start = 0 ; argv_start < values . size ( ) ; + + argv_start ) {
2022-04-02 16:48:43 +01:00
if ( values [ argv_start ] . contains ( ' = ' ) ) {
putenv ( const_cast < char * > ( values [ argv_start ] . characters ( ) ) ) ;
2020-09-16 18:56:00 +02:00
} else {
break ;
}
}
2022-04-02 16:48:43 +01:00
Vector < StringView > new_argv ;
2022-07-11 20:42:03 +00:00
if ( ! split_string . is_empty ( ) ) {
for ( auto view : split_string . split_view ( ' ' ) ) {
2022-04-02 16:48:43 +01:00
new_argv . append ( view ) ;
2021-04-03 13:57:31 -06:00
}
}
for ( size_t i = argv_start ; i < values . size ( ) ; + + i ) {
new_argv . append ( values [ i ] ) ;
}
if ( new_argv . size ( ) = = 0 ) {
2020-09-16 18:56:00 +02:00
for ( auto entry = environ ; * entry ! = nullptr ; + + entry )
2021-05-31 15:43:25 +01:00
outln ( " {} " , * entry ) ;
2020-09-16 18:56:00 +02:00
return 0 ;
}
2022-04-02 16:48:43 +01:00
TRY ( Core : : System : : exec ( new_argv [ 0 ] , new_argv , Core : : System : : SearchInPath : : Yes ) ) ;
2020-09-16 18:56:00 +02:00
return 1 ;
2019-02-22 01:55:22 +01:00
}