Subject: Re: [PATCH v2 1/4] refs: add function to translate errors to strings

From: Junio C Hamano <[email-masked]>
Date: Thu, 15 May 2025 13:26:14 -0700

Karthik Nayak <[email-masked]> writes:

> diff --git a/builtin/update-ref.c b/builtin/update-ref.c
> index 2b1e336ba1..09b99143bf 100644
> --- a/builtin/update-ref.c
> +++ b/builtin/update-ref.c
> @@ -575,30 +575,7 @@ static void print_rejected_refs(const char *refname,
>  				void *cb_data UNUSED)
>  {
>  	struct strbuf sb = STRBUF_INIT;
> -	const char *reason = "";
> -
> -	switch (err) {
> -	case REF_TRANSACTION_ERROR_NAME_CONFLICT:
> -		reason = "refname conflict";
> -		break;
> -	case REF_TRANSACTION_ERROR_CREATE_EXISTS:
> -		reason = "reference already exists";
> -		break;
> -	case REF_TRANSACTION_ERROR_NONEXISTENT_REF:
> -		reason = "reference does not exist";
> -		break;
> -	case REF_TRANSACTION_ERROR_INCORRECT_OLD_VALUE:
> -		reason = "incorrect old value provided";
> -		break;
> -	case REF_TRANSACTION_ERROR_INVALID_NEW_VALUE:
> -		reason = "invalid new value provided";
> -		break;
> -	case REF_TRANSACTION_ERROR_EXPECTED_SYMREF:
> -		reason = "expected symref but found regular ref";
> -		break;
> -	default:
> -		reason = "unkown failure";
> -	}
> +	char *reason = ref_transaction_error_msg(err);
>  
>  	strbuf_addf(&sb, "rejected %s %s %s %s\n", refname,
>  		    new_oid ? oid_to_hex(new_oid) : new_target,
> @@ -606,6 +583,7 @@ static void print_rejected_refs(const char *refname,
>  		    reason);
>  
>  	fwrite(sb.buf, sb.len, 1, stdout);
> +	free(reason);
>  	strbuf_release(&sb);
>  }

Why free()?  Goes and reads on...

> +char *ref_transaction_error_msg(enum ref_transaction_error err)
> +{
> +	const char *reason = "";
> +
> +	switch (err) {
> +	case REF_TRANSACTION_ERROR_NAME_CONFLICT:
> +		reason = "refname conflict";
> +		break;
> +	case REF_TRANSACTION_ERROR_CREATE_EXISTS:
> +		reason = "reference already exists";
> +		break;
> +	case REF_TRANSACTION_ERROR_NONEXISTENT_REF:
> +		reason = "reference does not exist";
> +		break;
> +	case REF_TRANSACTION_ERROR_INCORRECT_OLD_VALUE:
> +		reason = "incorrect old value provided";
> +		break;
> +	case REF_TRANSACTION_ERROR_INVALID_NEW_VALUE:
> +		reason = "invalid new value provided";
> +		break;
> +	case REF_TRANSACTION_ERROR_EXPECTED_SYMREF:
> +		reason = "expected symref but found regular ref";
> +		break;
> +	default:
> +		reason = "unkown failure";
> +	}
> +
> +	return xstrdup(reason);
> +}

Why can't this return "const char *", without xstrdup()?