~emersion/mrsh

5a5f1adf781a436a36d5ea03ed1af43688ff6ebe — Simon Ser 8 months ago b73d3a4
shell/task/word: add parameter leading hash op
2 files changed, 22 insertions(+), 3 deletions(-)

M shell/task/word.c
M test/word.sh
M shell/task/word.c => shell/task/word.c +21 -2
@@ 148,7 148,8 @@ static void assign_word_or_null(struct mrsh_word *word,
}

/* Fill either result_str or result_word */
static int apply_parameter_op(struct mrsh_word_parameter *wp, const char *str,
static int apply_parameter_op(struct context *ctx,
		struct mrsh_word_parameter *wp, const char *str,
		char **result_str, struct mrsh_word **result_word) {
	switch (wp->op) {
	case MRSH_PARAM_NONE:


@@ 173,6 174,24 @@ static int apply_parameter_op(struct mrsh_word_parameter *wp, const char *str,
		}
		return 0;
	case MRSH_PARAM_LEADING_HASH: // String Length
		if (str == NULL && (ctx->state->options & MRSH_OPT_NOUNSET)) {
			return 0;
		}
		if (strcmp(wp->name, "*") == 0 || strcmp(wp->name, "@") == 0) {
			fprintf(stderr, "%s: using the string length operator on $%s "
				"is undefined behaviour\n",
				ctx->state->frame->argv[0], wp->name);
			return TASK_STATUS_ERROR;
		}

		int len = 0;
		if (str != NULL) {
			len = strlen(str);
		}
		char len_str[32];
		snprintf(len_str, sizeof(len_str), "%d", len);
		*result_str = strdup(len_str);
		return 0;
	case MRSH_PARAM_PERCENT: // Remove Smallest Suffix Pattern
	case MRSH_PARAM_DPERCENT: // Remove Largest Suffix Pattern
	case MRSH_PARAM_HASH: // Remove Smallest Prefix Pattern


@@ 209,7 228,7 @@ int run_word(struct context *ctx, struct mrsh_word **word_ptr,
		}
		char *result_str = NULL;
		struct mrsh_word *result_word = NULL;
		ret = apply_parameter_op(wp, value, &result_str, &result_word);
		ret = apply_parameter_op(ctx, wp, value, &result_str, &result_word);
		if (ret < 0) {
			return ret;
		}

M test/word.sh => test/word.sh +1 -1
@@ 19,7 19,7 @@ echo ${a:-BAD} ${idontexist:-GOOD} ${null:-GOOD} ${idontexist:-}
echo ${a-BAD} ${idontexist-GOOD} ${null-BAD} ${null-}
echo ${a:+GOOD} ${idontexist:+BAD} ${null:+BAD} ${idontexist:+}
echo ${a+GOOD} ${idontexist+BAD} ${null-GOOD} ${null+}
#echo ${#hello}
echo ${#hello} ${#null} ${#idontexist}

echo ""
echo "Command Substitution"