mpd_edit_playlist.c (1765B)
1 #define _POSIX_C_SOURCE 200809L 2 3 #include "mpd_common.h" 4 5 #include <string.h> 6 7 static void usage(FILE *file, const char *program) { 8 fprintf(file, "Usage: %s [--force] PLAYLIST\n", program); 9 } 10 11 int main(int argc, char **argv) { 12 bool force = false; 13 const char *playlist = NULL; 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], "--force") == 0) { 20 force = true; 21 } else if (argv[i][0] == '-') { 22 usage(stderr, argv[0]); 23 return 2; 24 } else if (playlist == NULL) { 25 playlist = argv[i]; 26 } else { 27 usage(stderr, argv[0]); 28 return 2; 29 } 30 } 31 if (playlist == NULL) { 32 usage(stderr, argv[0]); 33 return 2; 34 } 35 36 struct mt_strvec original; 37 struct mt_strvec edited; 38 mt_strvec_init(&original); 39 mt_strvec_init(&edited); 40 41 struct mpd_connection *connection = mt_connect(); 42 if (connection == NULL) 43 return 1; 44 bool ok = mt_read_playlist(connection, playlist, &original); 45 mpd_connection_free(connection); 46 for (size_t i = 0; ok && i < original.len; i++) 47 ok = mt_strvec_push(&edited, original.items[i]); 48 if (!ok && edited.len != original.len) 49 perror("mpd: copy stored playlist"); 50 51 if (ok) 52 ok = mt_edit_lines(&edited); 53 if (ok) { 54 connection = mt_connect(); 55 if (connection == NULL) { 56 ok = false; 57 } else { 58 ok = mt_replace_playlist(connection, playlist, &edited, &original, force); 59 mpd_connection_free(connection); 60 } 61 } 62 if (ok) 63 printf("Playlist %s replaced with %zu track%s.\n", playlist, edited.len, 64 edited.len == 1U ? "" : "s"); 65 66 mt_strvec_clear(&original); 67 mt_strvec_clear(&edited); 68 return ok ? 0 : 1; 69 }