Don't print an error message for empty courses
[nci.git] / nci-list-courses.c
blob98ee9a273683bf93aadc4cb07742e7d545a760bf
1 /*
2 * Copyright (c) 2016-2019 S. Gilles <sgilles@math.umd.edu>
4 * Permission to use, copy, modify, and/or distribute this software
5 * for any purpose with or without fee is hereby granted, provided
6 * that the above copyright notice and this permission notice appear
7 * in all copies.
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
10 * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
11 * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
12 * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
13 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
14 * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
15 * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
16 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 #include <errno.h>
19 #include <locale.h>
20 #include <stdint.h>
21 #include <stdio.h>
22 #include <stdlib.h>
24 #include <curl/curl.h>
25 #include <yajl_parse.h>
27 #include "macros.h"
28 #include "util.h"
30 static int
31 list_courses(const char *url_base, const char *auth_token)
33 size_t j = 0;
34 int ret = EINVAL;
35 size_t len = 0;
36 char *built_uri = 0;
37 const char *fn_courses[] = { "id", "name", 0 };
38 map courses = { 0 };
39 char **courses_ids = 0;
40 char **c = 0;
41 size_t courses_num = 0;
43 len = snprintf(0, 0, "%s/api/v1/courses?per_page=9999", url_base);
45 if (len + 1 < len) {
46 ret = errno = EOVERFLOW;
47 perror(L(""));
48 goto cleanup;
51 if (!(built_uri = malloc(len + 1))) {
52 ret = errno;
53 perror(L("malloc"));
54 goto cleanup;
57 sprintf(built_uri, "%s/api/v1/courses?per_page=9999", url_base);
59 if ((ret = key_value_extract(built_uri, auth_token, fn_courses, 0,
60 &courses))) {
61 goto cleanup;
64 map_get_keys(&courses, &courses_ids, &courses_num);
66 for (j = 0; j < courses_num; ++j) {
67 c = map_get(&courses, courses_ids[j]);
69 if (c[0]) {
70 printf("%s %s\n", courses_ids[j], c[0]);
74 cleanup:
75 free(courses_ids);
76 map_clean(&courses);
77 free(built_uri);
79 return ret;
82 int
83 main(void)
85 int ret = EINVAL;
86 char *url_base = 0;
87 char *auth_token = 0;
89 setlocale(LC_ALL, "");
90 curl_global_init(CURL_GLOBAL_DEFAULT);
92 if (!(url_base = get_url_base())) {
93 ret = ENOENT;
95 /* Error should have already been printed */
96 goto cleanup;
99 if (!(auth_token = get_auth_token())) {
100 ret = ENOENT;
102 /* Error should have already been printed */
103 goto cleanup;
106 if ((ret = list_courses(url_base, auth_token))) {
107 goto cleanup;
110 ret = 0;
111 cleanup:
112 free(url_base);
113 free(auth_token);
114 curl_global_cleanup();
116 return ret;