1 /* ui-blob.c: show blob content
3 * Copyright (C) 2008 Lars Hjemli
4 * Copyright (C) 2010 Jason A. Donenfeld <Jason@zx2c4.com>
6 * Licensed under GNU General Public License v2
7 * (see COPYING for full license text)
13 #include "ui-shared.h"
15 struct walk_tree_context {
16 const char *match_path;
17 unsigned char *matched_sha1;
21 static int walk_tree(const unsigned char *sha1, const char *base, int baselen,
22 const char *pathname, unsigned mode, int stage, void *cbdata)
24 struct walk_tree_context *walk_tree_ctx = cbdata;
26 if (strncmp(base, walk_tree_ctx->match_path, baselen)
27 || strcmp(walk_tree_ctx->match_path + baselen, pathname))
28 return READ_TREE_RECURSIVE;
29 memmove(walk_tree_ctx->matched_sha1, sha1, 20);
30 walk_tree_ctx->found_path = 1;
34 int cgit_ref_path_exists(const char *path, const char *ref)
36 unsigned char sha1[20];
38 struct pathspec_item path_items = {
42 struct pathspec paths = {
46 struct walk_tree_context walk_tree_ctx = {
52 if (get_sha1(ref, sha1))
54 if (sha1_object_info(sha1, &size) != OBJ_COMMIT)
56 read_tree_recursive(lookup_commit_reference(sha1)->tree, "", 0, 0, &paths, walk_tree, &walk_tree_ctx);
57 return walk_tree_ctx.found_path;
60 int cgit_print_file(char *path, const char *head)
62 unsigned char sha1[20];
63 enum object_type type;
66 struct commit *commit;
67 struct pathspec_item path_items = {
71 struct pathspec paths = {
75 struct walk_tree_context walk_tree_ctx = {
81 if (get_sha1(head, sha1))
83 type = sha1_object_info(sha1, &size);
84 if (type == OBJ_COMMIT && path) {
85 commit = lookup_commit_reference(sha1);
86 read_tree_recursive(commit->tree, "", 0, 0, &paths, walk_tree, &walk_tree_ctx);
87 if (!walk_tree_ctx.found_path)
89 type = sha1_object_info(sha1, &size);
93 buf = read_sha1_file(sha1, &type, &size);
101 void cgit_print_blob(const char *hex, char *path, const char *head)
103 unsigned char sha1[20];
104 enum object_type type;
107 struct commit *commit;
108 struct pathspec_item path_items = {
110 .len = path ? strlen(path) : 0
112 struct pathspec paths = {
116 struct walk_tree_context walk_tree_ctx = {
118 .matched_sha1 = sha1,
122 if (get_sha1_hex(hex, sha1)) {
123 cgit_print_error("Bad hex value: %s", hex);
127 if (get_sha1(head, sha1)) {
128 cgit_print_error("Bad ref: %s", head);
133 type = sha1_object_info(sha1, &size);
135 if ((!hex) && type == OBJ_COMMIT && path) {
136 commit = lookup_commit_reference(sha1);
137 read_tree_recursive(commit->tree, "", 0, 0, &paths, walk_tree, &walk_tree_ctx);
138 type = sha1_object_info(sha1,&size);
141 if (type == OBJ_BAD) {
142 cgit_print_error("Bad object name: %s", hex);
146 buf = read_sha1_file(sha1, &type, &size);
148 cgit_print_error("Error reading object %s", hex);
153 ctx.page.mimetype = ctx.qry.mimetype;
154 if (!ctx.page.mimetype) {
155 if (buffer_is_binary(buf, size))
156 ctx.page.mimetype = "application/octet-stream";
158 ctx.page.mimetype = "text/plain";
160 ctx.page.filename = path;
161 cgit_print_http_headers(&ctx);