Skip to content

Commit

Permalink
parser: add a function for default values
Browse files Browse the repository at this point in the history
fixes #142
  • Loading branch information
acrisci committed Jun 22, 2019
1 parent b56df07 commit fd0b4ab
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
26 changes: 24 additions & 2 deletions playerctl/playerctl-formatter.c
Expand Up @@ -255,8 +255,6 @@ static GList *tokenize_format(const char *format, GError **error) {
}
i += 1;

} else if (format[i] == '}' && i < len + 1 && format[i + 1] == '}') {
assert(FALSE && "TODO");
} else {
buf[buf_len++] = format[i];
}
Expand Down Expand Up @@ -365,6 +363,29 @@ static gchar *helperfn_markup_escape(struct token *token, GVariant **args, int n
return escaped;
}

static gchar *helperfn_default(struct token *token, GVariant **args, int nargs, GError **error) {
if (nargs != 2) {
g_set_error(error, playerctl_formatter_error_quark(), 1,
"function default takes exactly two arguments (got %d)", nargs);
return NULL;
}

if (args[0] == NULL && args[1] == NULL) {
return g_strdup("");
}

if (args[0] == NULL) {
return pctl_print_gvariant(args[1]);
} else {
gchar *printed = pctl_print_gvariant(args[0]);
if (g_strcmp0(printed, "") == 0) {
g_free(printed);
return pctl_print_gvariant(args[1]);
}
return printed;
}
}

static gchar *helperfn_emoji(struct token *token, GVariant **args, int nargs, GError **error) {
g_warning("The emoji() helper function is undocumented and experimental and will change in a "
"future release.");
Expand Down Expand Up @@ -423,6 +444,7 @@ struct template_helper {
{"uc", &helperfn_uc},
{"duration", &helperfn_duration},
{"markup_escape", &helperfn_markup_escape},
{"default", &helperfn_default},
// EXPERIMENTAL
{"emoji", &helperfn_emoji},
};
Expand Down
14 changes: 14 additions & 0 deletions test/test_format.py
Expand Up @@ -51,3 +51,17 @@ async def test_format(bus_address):
'metadata --format \'@{{ uc( "hi" ) }} - {{uc( lc( "HO" ) ) }} . {{lc( uc( title ) ) }}@\''
)
assert cmd.stdout == '@HI - HO . a title@'

cmd = await playerctl.run(
'metadata --format \'{{default(xesam:missing, artist)}}\'')
assert cmd.stdout == ARTIST

cmd = await playerctl.run(
'metadata --format \'{{default(title, artist)}}\'')
assert cmd.stdout == TITLE

cmd = await playerctl.run('metadata --format \'{{default("", "ok")}}\'')
assert cmd.stdout == 'ok'

cmd = await playerctl.run('metadata --format \'{{default("ok", "not")}}\'')
assert cmd.stdout == 'ok'

0 comments on commit fd0b4ab

Please sign in to comment.