tools

various tools I have been using throughout the years
Log | Files | Refs | README | LICENSE

mpd_trim_queue.c (1724B)


      1 #define _POSIX_C_SOURCE 200809L
      2 
      3 #include "mpd_common.h"
      4 
      5 #include <limits.h>
      6 #include <string.h>
      7 
      8 static void usage(FILE *file, const char *program) {
      9   fprintf(file, "Usage: %s [--keep N]\n", program);
     10 }
     11 
     12 int main(int argc, char **argv) {
     13   size_t keep = 0U;
     14   for (int i = 1; i < argc; i++) {
     15     if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) {
     16       usage(stdout, argv[0]);
     17       return 0;
     18     }
     19     if (strcmp(argv[i], "--keep") == 0 && i + 1 < argc) {
     20       if (!mt_parse_size(argv[++i], &keep) || keep > UINT_MAX) {
     21         fprintf(stderr, "mpd: invalid --keep value\n");
     22         return 2;
     23       }
     24     } else {
     25       usage(stderr, argv[0]);
     26       return 2;
     27     }
     28   }
     29 
     30   struct mpd_connection *connection = mt_connect();
     31   if (connection == NULL)
     32     return 1;
     33   struct mt_player_state state;
     34   bool ok = mt_get_player_state(connection, &state);
     35   unsigned remove = 0U;
     36   if (ok && state.song_pos != UINT_MAX && state.song_pos > (unsigned)keep)
     37     remove = state.song_pos - (unsigned)keep;
     38   if (ok && remove > 0U) {
     39     enum mt_state_match match =
     40         mt_player_state_is(connection, state.queue_version, state.song_id);
     41     if (match == MT_STATE_CHANGED) {
     42       fprintf(stderr, "mpd: player or queue changed before trimming; retry the "
     43                       "command\n");
     44       ok = false;
     45     } else if (match == MT_STATE_ERROR) {
     46       ok = false;
     47     }
     48   }
     49   if (ok && remove > 0U && !mpd_run_delete_range(connection, 0U, remove)) {
     50     mt_report_error(connection, "trim played tracks");
     51     ok = false;
     52   }
     53   if (ok)
     54     printf("Removed %u played track%s.\n", remove, remove == 1U ? "" : "s");
     55 
     56   mt_player_state_clear(&state);
     57   mpd_connection_free(connection);
     58   return ok ? 0 : 1;
     59 }