cmd-ls.c (2567B)
1 /* 2 * Copyright (c) 2014 Mohamed Aslan <maslan@sce.carleton.ca> 3 * 4 * Permission to use, copy, modify, and distribute this software for any 5 * purpose with or without fee is hereby granted, provided that the above 6 * copyright notice and this permission notice appear in all copies. 7 * 8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 15 */ 16 17 #include <stdio.h> /* printf(3) */ 18 #include <stdlib.h> /* EXIT_SUCCESS */ 19 #include <string.h> /* strdup(3) */ 20 #include <unistd.h> /* getopt(3) */ 21 #include <sys/stat.h> /* S_ISDIR */ 22 23 #include "cmd.h" 24 #include "session.h" 25 26 #include "objects.h" 27 28 29 void 30 ls(struct session *s, struct dir* d, const char *prefix, int is_recursive) 31 { 32 char *nextprefix = NULL; 33 struct dir *child; 34 struct dirent *ent; 35 36 if (d == NULL) 37 return; 38 ent = d->children; 39 while (ent != NULL) { 40 if (S_ISDIR(ent->mode)) { 41 printf("%s%s/\n", prefix, ent->name); 42 if (is_recursive) { 43 asprintf(&nextprefix, "%s%s/", prefix, ent->name); 44 child = baseline_dir_new(); 45 s->db_ops->select_dir(s->db_ctx, ent->id, child); 46 ls(s, child, nextprefix, is_recursive); 47 baseline_dir_free(child); 48 free(nextprefix); 49 } 50 } 51 else { 52 printf("%s%s\n", prefix, ent->name); 53 } 54 ent = ent->next; 55 } 56 } 57 58 int 59 cmd_ls(int argc, char **argv) 60 { 61 char *head = NULL; 62 int ch; 63 int recursive = 0, explicit = 0; 64 struct session s; 65 struct commit *comm; 66 struct dir *dir; 67 68 baseline_session_begin(&s, 0); 69 70 /* parse command line options */ 71 while ((ch = getopt(argc, argv, "Rc:")) != -1) { 72 switch (ch) { 73 case 'R': 74 recursive = 1; 75 break; 76 case 'c': 77 explicit = 1; 78 head = strdup(optarg); 79 break; 80 default: 81 exit(EXIT_FAILURE); 82 } 83 } 84 argc -= optind; 85 argv += optind; 86 87 if (!explicit) { 88 s.db_ops->branch_get_head(s.db_ctx, s.branch, &head); 89 if (head == NULL) 90 goto ret; 91 } 92 93 comm = baseline_commit_new(); 94 s.db_ops->select_commit(s.db_ctx, head, comm); 95 96 dir = baseline_dir_new(); 97 s.db_ops->select_dir(s.db_ctx, comm->dir, dir); 98 99 printf("commit: %s\n", comm->id); 100 ls(&s, dir, "", recursive); 101 102 baseline_dir_free(dir); 103 104 ret: 105 baseline_session_end(&s); 106 return EXIT_SUCCESS; 107 } 108