summaryrefslogtreecommitdiff
path: root/src/packages.c
blob: e89eb82d53caccfe7eef1ef96a42f0717efc51d0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include "packages.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#if defined(__linux__)
#include "distro.h"

/*const char *distroname;*/
#endif

const char *run_package_command(const char *command) {
  char buf[64];
  char *out = NULL;
  size_t outsize = 0;

  FILE *p = popen(command, "r");
  if (!p) {
    fprintf(stderr, "パッケージコマンドを実効に失敗: %s", command);
    return NULL;
  }

  while (fgets(buf, sizeof(buf), p) != NULL) {
    buf[strcspn(buf, "\n")] = '\0';

    size_t len = strlen(buf);
    char *nout = realloc(out, outsize + len + 1);
    if (nout == NULL) {
      perror("メモリの役割に失敗");
      free(out);
      pclose(p);
      return NULL;
    }

    out = nout;

    memccpy(out + outsize, buf, sizeof(buf), len);
    outsize += len;
    out[outsize] = '\0';
  }

  pclose(p);

  return out;
}

void display_packages() {
#if defined(__OpenBSD__) || defined(__NetBSD__)
  printf("%s (pkg_info)", run_package_command("pkg_info -a | wc -l | "
         "sed \"s/ //g\""));
#elif defined(__FreeBSD__) || defined(__DragonFly__)
  printf("%s (pkg)", run_package_command("pkg info -a | wc -l | "
         "sed \"s/ //g\""));
#elif defined(__linux__)
  if (access("/bin/xbps-query", F_OK) != -1) {
    printf("%s (xbps-query)", run_package_command("xbps-query -l | wc -l | "
           "sed \"s/ //g\""));
  } else if (access("/usr/bin/dpkg-query", F_OK) != -1) {
    printf("%s (dpkg)", run_package_command("dpkg-query -f '.\n' -W | wc -l | "
           "sed \"s/ //g\""));
  }
#endif
}