~emersion/mrsh

f4f0d8228a4e3bd11a4728b96dfa53e13f6f5296 — delthas 3 years ago b4af69a
Implement pwd builtin
5 files changed, 28 insertions(+), 1 deletions(-)

M builtin/builtin.c
A builtin/pwd.c
M include/builtin.h
M main.c
M meson.build
M builtin/builtin.c => builtin/builtin.c +1 -0
@@ 22,6 22,7 @@ static const struct builtin builtins[] = {
	{ "exit", builtin_exit, true },
	{ "export", builtin_export, true },
	{ "false", builtin_false, false },
	{ "pwd", builtin_pwd, false },
	{ "readonly", builtin_export, true },
	{ "set", builtin_set, true },
	{ "shift", builtin_shift, true },

A builtin/pwd.c => builtin/pwd.c +18 -0
@@ 0,0 1,18 @@
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <mrsh/shell.h>
#include "builtin.h"

// usage: pwd [-L|-P]

int builtin_pwd(struct mrsh_state *state, int argc, char *argv[]) {
	// TODO `-P` and `-L`
	const char *pwd = mrsh_env_get(state, "PWD", NULL);
	if (pwd == NULL) {
		fprintf(stderr, "pwd: Cannot return current directory as PWD was unset\n");
		return EXIT_FAILURE;
	}
	puts(pwd);
	return EXIT_SUCCESS;
}

M include/builtin.h => include/builtin.h +1 -0
@@ 14,6 14,7 @@ int builtin_colon(struct mrsh_state *state, int argc, char *argv[]);
int builtin_exit(struct mrsh_state *state, int argc, char *argv[]);
int builtin_export(struct mrsh_state *state, int argc, char *argv[]);
int builtin_eval(struct mrsh_state *state, int argc, char *argv[]);
int builtin_pwd(struct mrsh_state *state, int argc, char *argv[]);
int builtin_shift(struct mrsh_state *state, int argc, char *argv[]);
int builtin_source(struct mrsh_state *state, int argc, char *argv[]);
int builtin_times(struct mrsh_state *state, int argc, char *argv[]);

M main.c => main.c +7 -1
@@ 88,7 88,13 @@ int main(int argc, char *argv[]) {
		source_profile(&state);
	}

	// TODO: set PWD
	// TODO check if path is well-formed, has . or .., and handle symbolic links
	const char *pwd = mrsh_env_get(&state, "PWD", NULL);
	if (pwd == NULL || strlen(pwd) >= PATH_MAX) {
		char cwd[PATH_MAX];
		getcwd(cwd, PATH_MAX);
		mrsh_env_set(&state, "PWD", cwd, MRSH_VAR_ATTRIB_EXPORT);
	}

	struct mrsh_parser *parser = mrsh_parser_create(state.input);
	mrsh_parser_set_alias(parser, get_alias, &state);

M meson.build => meson.build +1 -0
@@ 39,6 39,7 @@ lib_mrsh = library(
		'builtin/eval.c',
		'builtin/exit.c',
		'builtin/export.c',
		'builtin/pwd.c',
		'builtin/set.c',
		'builtin/shift.c',
		'builtin/source.c',